PackageManagerService.java revision a9aa24974ee4620b42a0573189b68c9af50926c5
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 } else { 7976 String[] abiList = (cpuAbiOverride != null) ? 7977 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7978 7979 // Enable gross and lame hacks for apps that are built with old 7980 // SDK tools. We must scan their APKs for renderscript bitcode and 7981 // not launch them if it's present. Don't bother checking on devices 7982 // that don't have 64 bit support. 7983 boolean needsRenderScriptOverride = false; 7984 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7985 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7986 abiList = Build.SUPPORTED_32_BIT_ABIS; 7987 needsRenderScriptOverride = true; 7988 } 7989 7990 final int copyRet; 7991 if (extractLibs) { 7992 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7993 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7994 } else { 7995 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7996 } 7997 7998 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7999 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 8000 "Error unpackaging native libs for app, errorCode=" + copyRet); 8001 } 8002 8003 if (copyRet >= 0) { 8004 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 8005 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 8006 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 8007 } else if (needsRenderScriptOverride) { 8008 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 8009 } 8010 } 8011 } catch (IOException ioe) { 8012 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 8013 } finally { 8014 IoUtils.closeQuietly(handle); 8015 } 8016 8017 // Now that we've calculated the ABIs and determined if it's an internal app, 8018 // we will go ahead and populate the nativeLibraryPath. 8019 setNativeLibraryPaths(pkg); 8020 } 8021 8022 /** 8023 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 8024 * i.e, so that all packages can be run inside a single process if required. 8025 * 8026 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 8027 * this function will either try and make the ABI for all packages in {@code packagesForUser} 8028 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 8029 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 8030 * updating a package that belongs to a shared user. 8031 * 8032 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 8033 * adds unnecessary complexity. 8034 */ 8035 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 8036 PackageParser.Package scannedPackage, boolean bootComplete) { 8037 String requiredInstructionSet = null; 8038 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 8039 requiredInstructionSet = VMRuntime.getInstructionSet( 8040 scannedPackage.applicationInfo.primaryCpuAbi); 8041 } 8042 8043 PackageSetting requirer = null; 8044 for (PackageSetting ps : packagesForUser) { 8045 // If packagesForUser contains scannedPackage, we skip it. This will happen 8046 // when scannedPackage is an update of an existing package. Without this check, 8047 // we will never be able to change the ABI of any package belonging to a shared 8048 // user, even if it's compatible with other packages. 8049 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8050 if (ps.primaryCpuAbiString == null) { 8051 continue; 8052 } 8053 8054 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 8055 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 8056 // We have a mismatch between instruction sets (say arm vs arm64) warn about 8057 // this but there's not much we can do. 8058 String errorMessage = "Instruction set mismatch, " 8059 + ((requirer == null) ? "[caller]" : requirer) 8060 + " requires " + requiredInstructionSet + " whereas " + ps 8061 + " requires " + instructionSet; 8062 Slog.w(TAG, errorMessage); 8063 } 8064 8065 if (requiredInstructionSet == null) { 8066 requiredInstructionSet = instructionSet; 8067 requirer = ps; 8068 } 8069 } 8070 } 8071 8072 if (requiredInstructionSet != null) { 8073 String adjustedAbi; 8074 if (requirer != null) { 8075 // requirer != null implies that either scannedPackage was null or that scannedPackage 8076 // did not require an ABI, in which case we have to adjust scannedPackage to match 8077 // the ABI of the set (which is the same as requirer's ABI) 8078 adjustedAbi = requirer.primaryCpuAbiString; 8079 if (scannedPackage != null) { 8080 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 8081 } 8082 } else { 8083 // requirer == null implies that we're updating all ABIs in the set to 8084 // match scannedPackage. 8085 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 8086 } 8087 8088 for (PackageSetting ps : packagesForUser) { 8089 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8090 if (ps.primaryCpuAbiString != null) { 8091 continue; 8092 } 8093 8094 ps.primaryCpuAbiString = adjustedAbi; 8095 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 8096 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 8097 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi); 8098 try { 8099 mInstaller.rmdex(ps.codePathString, 8100 getDexCodeInstructionSet(getPreferredInstructionSet())); 8101 } catch (InstallerException ignored) { 8102 } 8103 } 8104 } 8105 } 8106 } 8107 } 8108 8109 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 8110 synchronized (mPackages) { 8111 mResolverReplaced = true; 8112 // Set up information for custom user intent resolution activity. 8113 mResolveActivity.applicationInfo = pkg.applicationInfo; 8114 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 8115 mResolveActivity.packageName = pkg.applicationInfo.packageName; 8116 mResolveActivity.processName = pkg.applicationInfo.packageName; 8117 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8118 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8119 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8120 mResolveActivity.theme = 0; 8121 mResolveActivity.exported = true; 8122 mResolveActivity.enabled = true; 8123 mResolveInfo.activityInfo = mResolveActivity; 8124 mResolveInfo.priority = 0; 8125 mResolveInfo.preferredOrder = 0; 8126 mResolveInfo.match = 0; 8127 mResolveComponentName = mCustomResolverComponentName; 8128 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 8129 mResolveComponentName); 8130 } 8131 } 8132 8133 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 8134 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 8135 8136 // Set up information for ephemeral installer activity 8137 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 8138 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 8139 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 8140 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 8141 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8142 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8143 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8144 mEphemeralInstallerActivity.theme = 0; 8145 mEphemeralInstallerActivity.exported = true; 8146 mEphemeralInstallerActivity.enabled = true; 8147 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 8148 mEphemeralInstallerInfo.priority = 0; 8149 mEphemeralInstallerInfo.preferredOrder = 0; 8150 mEphemeralInstallerInfo.match = 0; 8151 8152 if (DEBUG_EPHEMERAL) { 8153 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 8154 } 8155 } 8156 8157 private static String calculateBundledApkRoot(final String codePathString) { 8158 final File codePath = new File(codePathString); 8159 final File codeRoot; 8160 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 8161 codeRoot = Environment.getRootDirectory(); 8162 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 8163 codeRoot = Environment.getOemDirectory(); 8164 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 8165 codeRoot = Environment.getVendorDirectory(); 8166 } else { 8167 // Unrecognized code path; take its top real segment as the apk root: 8168 // e.g. /something/app/blah.apk => /something 8169 try { 8170 File f = codePath.getCanonicalFile(); 8171 File parent = f.getParentFile(); // non-null because codePath is a file 8172 File tmp; 8173 while ((tmp = parent.getParentFile()) != null) { 8174 f = parent; 8175 parent = tmp; 8176 } 8177 codeRoot = f; 8178 Slog.w(TAG, "Unrecognized code path " 8179 + codePath + " - using " + codeRoot); 8180 } catch (IOException e) { 8181 // Can't canonicalize the code path -- shenanigans? 8182 Slog.w(TAG, "Can't canonicalize code path " + codePath); 8183 return Environment.getRootDirectory().getPath(); 8184 } 8185 } 8186 return codeRoot.getPath(); 8187 } 8188 8189 /** 8190 * Derive and set the location of native libraries for the given package, 8191 * which varies depending on where and how the package was installed. 8192 */ 8193 private void setNativeLibraryPaths(PackageParser.Package pkg) { 8194 final ApplicationInfo info = pkg.applicationInfo; 8195 final String codePath = pkg.codePath; 8196 final File codeFile = new File(codePath); 8197 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 8198 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 8199 8200 info.nativeLibraryRootDir = null; 8201 info.nativeLibraryRootRequiresIsa = false; 8202 info.nativeLibraryDir = null; 8203 info.secondaryNativeLibraryDir = null; 8204 8205 if (isApkFile(codeFile)) { 8206 // Monolithic install 8207 if (bundledApp) { 8208 // If "/system/lib64/apkname" exists, assume that is the per-package 8209 // native library directory to use; otherwise use "/system/lib/apkname". 8210 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 8211 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 8212 getPrimaryInstructionSet(info)); 8213 8214 // This is a bundled system app so choose the path based on the ABI. 8215 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 8216 // is just the default path. 8217 final String apkName = deriveCodePathName(codePath); 8218 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 8219 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 8220 apkName).getAbsolutePath(); 8221 8222 if (info.secondaryCpuAbi != null) { 8223 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 8224 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 8225 secondaryLibDir, apkName).getAbsolutePath(); 8226 } 8227 } else if (asecApp) { 8228 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 8229 .getAbsolutePath(); 8230 } else { 8231 final String apkName = deriveCodePathName(codePath); 8232 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 8233 .getAbsolutePath(); 8234 } 8235 8236 info.nativeLibraryRootRequiresIsa = false; 8237 info.nativeLibraryDir = info.nativeLibraryRootDir; 8238 } else { 8239 // Cluster install 8240 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 8241 info.nativeLibraryRootRequiresIsa = true; 8242 8243 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 8244 getPrimaryInstructionSet(info)).getAbsolutePath(); 8245 8246 if (info.secondaryCpuAbi != null) { 8247 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 8248 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 8249 } 8250 } 8251 } 8252 8253 /** 8254 * Calculate the abis and roots for a bundled app. These can uniquely 8255 * be determined from the contents of the system partition, i.e whether 8256 * it contains 64 or 32 bit shared libraries etc. We do not validate any 8257 * of this information, and instead assume that the system was built 8258 * sensibly. 8259 */ 8260 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 8261 PackageSetting pkgSetting) { 8262 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 8263 8264 // If "/system/lib64/apkname" exists, assume that is the per-package 8265 // native library directory to use; otherwise use "/system/lib/apkname". 8266 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 8267 setBundledAppAbi(pkg, apkRoot, apkName); 8268 // pkgSetting might be null during rescan following uninstall of updates 8269 // to a bundled app, so accommodate that possibility. The settings in 8270 // that case will be established later from the parsed package. 8271 // 8272 // If the settings aren't null, sync them up with what we've just derived. 8273 // note that apkRoot isn't stored in the package settings. 8274 if (pkgSetting != null) { 8275 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8276 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8277 } 8278 } 8279 8280 /** 8281 * Deduces the ABI of a bundled app and sets the relevant fields on the 8282 * parsed pkg object. 8283 * 8284 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 8285 * under which system libraries are installed. 8286 * @param apkName the name of the installed package. 8287 */ 8288 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 8289 final File codeFile = new File(pkg.codePath); 8290 8291 final boolean has64BitLibs; 8292 final boolean has32BitLibs; 8293 if (isApkFile(codeFile)) { 8294 // Monolithic install 8295 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 8296 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 8297 } else { 8298 // Cluster install 8299 final File rootDir = new File(codeFile, LIB_DIR_NAME); 8300 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 8301 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 8302 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 8303 has64BitLibs = (new File(rootDir, isa)).exists(); 8304 } else { 8305 has64BitLibs = false; 8306 } 8307 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 8308 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 8309 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 8310 has32BitLibs = (new File(rootDir, isa)).exists(); 8311 } else { 8312 has32BitLibs = false; 8313 } 8314 } 8315 8316 if (has64BitLibs && !has32BitLibs) { 8317 // The package has 64 bit libs, but not 32 bit libs. Its primary 8318 // ABI should be 64 bit. We can safely assume here that the bundled 8319 // native libraries correspond to the most preferred ABI in the list. 8320 8321 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8322 pkg.applicationInfo.secondaryCpuAbi = null; 8323 } else if (has32BitLibs && !has64BitLibs) { 8324 // The package has 32 bit libs but not 64 bit libs. Its primary 8325 // ABI should be 32 bit. 8326 8327 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8328 pkg.applicationInfo.secondaryCpuAbi = null; 8329 } else if (has32BitLibs && has64BitLibs) { 8330 // The application has both 64 and 32 bit bundled libraries. We check 8331 // here that the app declares multiArch support, and warn if it doesn't. 8332 // 8333 // We will be lenient here and record both ABIs. The primary will be the 8334 // ABI that's higher on the list, i.e, a device that's configured to prefer 8335 // 64 bit apps will see a 64 bit primary ABI, 8336 8337 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 8338 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 8339 } 8340 8341 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 8342 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8343 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8344 } else { 8345 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8346 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8347 } 8348 } else { 8349 pkg.applicationInfo.primaryCpuAbi = null; 8350 pkg.applicationInfo.secondaryCpuAbi = null; 8351 } 8352 } 8353 8354 private void killApplication(String pkgName, int appId, String reason) { 8355 // Request the ActivityManager to kill the process(only for existing packages) 8356 // so that we do not end up in a confused state while the user is still using the older 8357 // version of the application while the new one gets installed. 8358 IActivityManager am = ActivityManagerNative.getDefault(); 8359 if (am != null) { 8360 try { 8361 am.killApplicationWithAppId(pkgName, appId, reason); 8362 } catch (RemoteException e) { 8363 } 8364 } 8365 } 8366 8367 void removePackageLI(PackageSetting ps, boolean chatty) { 8368 if (DEBUG_INSTALL) { 8369 if (chatty) 8370 Log.d(TAG, "Removing package " + ps.name); 8371 } 8372 8373 // writer 8374 synchronized (mPackages) { 8375 mPackages.remove(ps.name); 8376 final PackageParser.Package pkg = ps.pkg; 8377 if (pkg != null) { 8378 cleanPackageDataStructuresLILPw(pkg, chatty); 8379 } 8380 } 8381 } 8382 8383 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 8384 if (DEBUG_INSTALL) { 8385 if (chatty) 8386 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 8387 } 8388 8389 // writer 8390 synchronized (mPackages) { 8391 mPackages.remove(pkg.applicationInfo.packageName); 8392 cleanPackageDataStructuresLILPw(pkg, chatty); 8393 } 8394 } 8395 8396 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 8397 int N = pkg.providers.size(); 8398 StringBuilder r = null; 8399 int i; 8400 for (i=0; i<N; i++) { 8401 PackageParser.Provider p = pkg.providers.get(i); 8402 mProviders.removeProvider(p); 8403 if (p.info.authority == null) { 8404 8405 /* There was another ContentProvider with this authority when 8406 * this app was installed so this authority is null, 8407 * Ignore it as we don't have to unregister the provider. 8408 */ 8409 continue; 8410 } 8411 String names[] = p.info.authority.split(";"); 8412 for (int j = 0; j < names.length; j++) { 8413 if (mProvidersByAuthority.get(names[j]) == p) { 8414 mProvidersByAuthority.remove(names[j]); 8415 if (DEBUG_REMOVE) { 8416 if (chatty) 8417 Log.d(TAG, "Unregistered content provider: " + names[j] 8418 + ", className = " + p.info.name + ", isSyncable = " 8419 + p.info.isSyncable); 8420 } 8421 } 8422 } 8423 if (DEBUG_REMOVE && chatty) { 8424 if (r == null) { 8425 r = new StringBuilder(256); 8426 } else { 8427 r.append(' '); 8428 } 8429 r.append(p.info.name); 8430 } 8431 } 8432 if (r != null) { 8433 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 8434 } 8435 8436 N = pkg.services.size(); 8437 r = null; 8438 for (i=0; i<N; i++) { 8439 PackageParser.Service s = pkg.services.get(i); 8440 mServices.removeService(s); 8441 if (chatty) { 8442 if (r == null) { 8443 r = new StringBuilder(256); 8444 } else { 8445 r.append(' '); 8446 } 8447 r.append(s.info.name); 8448 } 8449 } 8450 if (r != null) { 8451 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 8452 } 8453 8454 N = pkg.receivers.size(); 8455 r = null; 8456 for (i=0; i<N; i++) { 8457 PackageParser.Activity a = pkg.receivers.get(i); 8458 mReceivers.removeActivity(a, "receiver"); 8459 if (DEBUG_REMOVE && chatty) { 8460 if (r == null) { 8461 r = new StringBuilder(256); 8462 } else { 8463 r.append(' '); 8464 } 8465 r.append(a.info.name); 8466 } 8467 } 8468 if (r != null) { 8469 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 8470 } 8471 8472 N = pkg.activities.size(); 8473 r = null; 8474 for (i=0; i<N; i++) { 8475 PackageParser.Activity a = pkg.activities.get(i); 8476 mActivities.removeActivity(a, "activity"); 8477 if (DEBUG_REMOVE && chatty) { 8478 if (r == null) { 8479 r = new StringBuilder(256); 8480 } else { 8481 r.append(' '); 8482 } 8483 r.append(a.info.name); 8484 } 8485 } 8486 if (r != null) { 8487 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 8488 } 8489 8490 N = pkg.permissions.size(); 8491 r = null; 8492 for (i=0; i<N; i++) { 8493 PackageParser.Permission p = pkg.permissions.get(i); 8494 BasePermission bp = mSettings.mPermissions.get(p.info.name); 8495 if (bp == null) { 8496 bp = mSettings.mPermissionTrees.get(p.info.name); 8497 } 8498 if (bp != null && bp.perm == p) { 8499 bp.perm = null; 8500 if (DEBUG_REMOVE && chatty) { 8501 if (r == null) { 8502 r = new StringBuilder(256); 8503 } else { 8504 r.append(' '); 8505 } 8506 r.append(p.info.name); 8507 } 8508 } 8509 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8510 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 8511 if (appOpPkgs != null) { 8512 appOpPkgs.remove(pkg.packageName); 8513 } 8514 } 8515 } 8516 if (r != null) { 8517 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8518 } 8519 8520 N = pkg.requestedPermissions.size(); 8521 r = null; 8522 for (i=0; i<N; i++) { 8523 String perm = pkg.requestedPermissions.get(i); 8524 BasePermission bp = mSettings.mPermissions.get(perm); 8525 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8526 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 8527 if (appOpPkgs != null) { 8528 appOpPkgs.remove(pkg.packageName); 8529 if (appOpPkgs.isEmpty()) { 8530 mAppOpPermissionPackages.remove(perm); 8531 } 8532 } 8533 } 8534 } 8535 if (r != null) { 8536 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8537 } 8538 8539 N = pkg.instrumentation.size(); 8540 r = null; 8541 for (i=0; i<N; i++) { 8542 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8543 mInstrumentation.remove(a.getComponentName()); 8544 if (DEBUG_REMOVE && chatty) { 8545 if (r == null) { 8546 r = new StringBuilder(256); 8547 } else { 8548 r.append(' '); 8549 } 8550 r.append(a.info.name); 8551 } 8552 } 8553 if (r != null) { 8554 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 8555 } 8556 8557 r = null; 8558 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8559 // Only system apps can hold shared libraries. 8560 if (pkg.libraryNames != null) { 8561 for (i=0; i<pkg.libraryNames.size(); i++) { 8562 String name = pkg.libraryNames.get(i); 8563 SharedLibraryEntry cur = mSharedLibraries.get(name); 8564 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 8565 mSharedLibraries.remove(name); 8566 if (DEBUG_REMOVE && chatty) { 8567 if (r == null) { 8568 r = new StringBuilder(256); 8569 } else { 8570 r.append(' '); 8571 } 8572 r.append(name); 8573 } 8574 } 8575 } 8576 } 8577 } 8578 if (r != null) { 8579 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 8580 } 8581 } 8582 8583 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 8584 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 8585 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 8586 return true; 8587 } 8588 } 8589 return false; 8590 } 8591 8592 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 8593 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 8594 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 8595 8596 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 8597 int flags) { 8598 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 8599 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 8600 } 8601 8602 private void updatePermissionsLPw(String changingPkg, 8603 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 8604 // Make sure there are no dangling permission trees. 8605 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 8606 while (it.hasNext()) { 8607 final BasePermission bp = it.next(); 8608 if (bp.packageSetting == null) { 8609 // We may not yet have parsed the package, so just see if 8610 // we still know about its settings. 8611 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8612 } 8613 if (bp.packageSetting == null) { 8614 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 8615 + " from package " + bp.sourcePackage); 8616 it.remove(); 8617 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8618 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8619 Slog.i(TAG, "Removing old permission tree: " + bp.name 8620 + " from package " + bp.sourcePackage); 8621 flags |= UPDATE_PERMISSIONS_ALL; 8622 it.remove(); 8623 } 8624 } 8625 } 8626 8627 // Make sure all dynamic permissions have been assigned to a package, 8628 // and make sure there are no dangling permissions. 8629 it = mSettings.mPermissions.values().iterator(); 8630 while (it.hasNext()) { 8631 final BasePermission bp = it.next(); 8632 if (bp.type == BasePermission.TYPE_DYNAMIC) { 8633 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 8634 + bp.name + " pkg=" + bp.sourcePackage 8635 + " info=" + bp.pendingInfo); 8636 if (bp.packageSetting == null && bp.pendingInfo != null) { 8637 final BasePermission tree = findPermissionTreeLP(bp.name); 8638 if (tree != null && tree.perm != null) { 8639 bp.packageSetting = tree.packageSetting; 8640 bp.perm = new PackageParser.Permission(tree.perm.owner, 8641 new PermissionInfo(bp.pendingInfo)); 8642 bp.perm.info.packageName = tree.perm.info.packageName; 8643 bp.perm.info.name = bp.name; 8644 bp.uid = tree.uid; 8645 } 8646 } 8647 } 8648 if (bp.packageSetting == null) { 8649 // We may not yet have parsed the package, so just see if 8650 // we still know about its settings. 8651 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8652 } 8653 if (bp.packageSetting == null) { 8654 Slog.w(TAG, "Removing dangling permission: " + bp.name 8655 + " from package " + bp.sourcePackage); 8656 it.remove(); 8657 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8658 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8659 Slog.i(TAG, "Removing old permission: " + bp.name 8660 + " from package " + bp.sourcePackage); 8661 flags |= UPDATE_PERMISSIONS_ALL; 8662 it.remove(); 8663 } 8664 } 8665 } 8666 8667 // Now update the permissions for all packages, in particular 8668 // replace the granted permissions of the system packages. 8669 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 8670 for (PackageParser.Package pkg : mPackages.values()) { 8671 if (pkg != pkgInfo) { 8672 // Only replace for packages on requested volume 8673 final String volumeUuid = getVolumeUuidForPackage(pkg); 8674 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 8675 && Objects.equals(replaceVolumeUuid, volumeUuid); 8676 grantPermissionsLPw(pkg, replace, changingPkg); 8677 } 8678 } 8679 } 8680 8681 if (pkgInfo != null) { 8682 // Only replace for packages on requested volume 8683 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 8684 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 8685 && Objects.equals(replaceVolumeUuid, volumeUuid); 8686 grantPermissionsLPw(pkgInfo, replace, changingPkg); 8687 } 8688 } 8689 8690 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 8691 String packageOfInterest) { 8692 // IMPORTANT: There are two types of permissions: install and runtime. 8693 // Install time permissions are granted when the app is installed to 8694 // all device users and users added in the future. Runtime permissions 8695 // are granted at runtime explicitly to specific users. Normal and signature 8696 // protected permissions are install time permissions. Dangerous permissions 8697 // are install permissions if the app's target SDK is Lollipop MR1 or older, 8698 // otherwise they are runtime permissions. This function does not manage 8699 // runtime permissions except for the case an app targeting Lollipop MR1 8700 // being upgraded to target a newer SDK, in which case dangerous permissions 8701 // are transformed from install time to runtime ones. 8702 8703 final PackageSetting ps = (PackageSetting) pkg.mExtras; 8704 if (ps == null) { 8705 return; 8706 } 8707 8708 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 8709 8710 PermissionsState permissionsState = ps.getPermissionsState(); 8711 PermissionsState origPermissions = permissionsState; 8712 8713 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 8714 8715 boolean runtimePermissionsRevoked = false; 8716 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 8717 8718 boolean changedInstallPermission = false; 8719 8720 if (replace) { 8721 ps.installPermissionsFixed = false; 8722 if (!ps.isSharedUser()) { 8723 origPermissions = new PermissionsState(permissionsState); 8724 permissionsState.reset(); 8725 } else { 8726 // We need to know only about runtime permission changes since the 8727 // calling code always writes the install permissions state but 8728 // the runtime ones are written only if changed. The only cases of 8729 // changed runtime permissions here are promotion of an install to 8730 // runtime and revocation of a runtime from a shared user. 8731 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 8732 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 8733 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 8734 runtimePermissionsRevoked = true; 8735 } 8736 } 8737 } 8738 8739 permissionsState.setGlobalGids(mGlobalGids); 8740 8741 final int N = pkg.requestedPermissions.size(); 8742 for (int i=0; i<N; i++) { 8743 final String name = pkg.requestedPermissions.get(i); 8744 final BasePermission bp = mSettings.mPermissions.get(name); 8745 8746 if (DEBUG_INSTALL) { 8747 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 8748 } 8749 8750 if (bp == null || bp.packageSetting == null) { 8751 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8752 Slog.w(TAG, "Unknown permission " + name 8753 + " in package " + pkg.packageName); 8754 } 8755 continue; 8756 } 8757 8758 final String perm = bp.name; 8759 boolean allowedSig = false; 8760 int grant = GRANT_DENIED; 8761 8762 // Keep track of app op permissions. 8763 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8764 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 8765 if (pkgs == null) { 8766 pkgs = new ArraySet<>(); 8767 mAppOpPermissionPackages.put(bp.name, pkgs); 8768 } 8769 pkgs.add(pkg.packageName); 8770 } 8771 8772 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 8773 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 8774 >= Build.VERSION_CODES.M; 8775 switch (level) { 8776 case PermissionInfo.PROTECTION_NORMAL: { 8777 // For all apps normal permissions are install time ones. 8778 grant = GRANT_INSTALL; 8779 } break; 8780 8781 case PermissionInfo.PROTECTION_DANGEROUS: { 8782 // If a permission review is required for legacy apps we represent 8783 // their permissions as always granted runtime ones since we need 8784 // to keep the review required permission flag per user while an 8785 // install permission's state is shared across all users. 8786 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 8787 // For legacy apps dangerous permissions are install time ones. 8788 grant = GRANT_INSTALL; 8789 } else if (origPermissions.hasInstallPermission(bp.name)) { 8790 // For legacy apps that became modern, install becomes runtime. 8791 grant = GRANT_UPGRADE; 8792 } else if (mPromoteSystemApps 8793 && isSystemApp(ps) 8794 && mExistingSystemPackages.contains(ps.name)) { 8795 // For legacy system apps, install becomes runtime. 8796 // We cannot check hasInstallPermission() for system apps since those 8797 // permissions were granted implicitly and not persisted pre-M. 8798 grant = GRANT_UPGRADE; 8799 } else { 8800 // For modern apps keep runtime permissions unchanged. 8801 grant = GRANT_RUNTIME; 8802 } 8803 } break; 8804 8805 case PermissionInfo.PROTECTION_SIGNATURE: { 8806 // For all apps signature permissions are install time ones. 8807 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 8808 if (allowedSig) { 8809 grant = GRANT_INSTALL; 8810 } 8811 } break; 8812 } 8813 8814 if (DEBUG_INSTALL) { 8815 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 8816 } 8817 8818 if (grant != GRANT_DENIED) { 8819 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 8820 // If this is an existing, non-system package, then 8821 // we can't add any new permissions to it. 8822 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 8823 // Except... if this is a permission that was added 8824 // to the platform (note: need to only do this when 8825 // updating the platform). 8826 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 8827 grant = GRANT_DENIED; 8828 } 8829 } 8830 } 8831 8832 switch (grant) { 8833 case GRANT_INSTALL: { 8834 // Revoke this as runtime permission to handle the case of 8835 // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps 8836 for (int userId : UserManagerService.getInstance().getUserIds()) { 8837 if (origPermissions.getRuntimePermissionState( 8838 bp.name, userId) != null) { 8839 // Revoke the runtime permission and clear the flags. 8840 origPermissions.revokeRuntimePermission(bp, userId); 8841 origPermissions.updatePermissionFlags(bp, userId, 8842 PackageManager.MASK_PERMISSION_FLAGS, 0); 8843 // If we revoked a permission permission, we have to write. 8844 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8845 changedRuntimePermissionUserIds, userId); 8846 } 8847 } 8848 // Grant an install permission. 8849 if (permissionsState.grantInstallPermission(bp) != 8850 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8851 changedInstallPermission = true; 8852 } 8853 } break; 8854 8855 case GRANT_RUNTIME: { 8856 // Grant previously granted runtime permissions. 8857 for (int userId : UserManagerService.getInstance().getUserIds()) { 8858 PermissionState permissionState = origPermissions 8859 .getRuntimePermissionState(bp.name, userId); 8860 int flags = permissionState != null 8861 ? permissionState.getFlags() : 0; 8862 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8863 if (permissionsState.grantRuntimePermission(bp, userId) == 8864 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8865 // If we cannot put the permission as it was, we have to write. 8866 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8867 changedRuntimePermissionUserIds, userId); 8868 } 8869 // If the app supports runtime permissions no need for a review. 8870 if (Build.PERMISSIONS_REVIEW_REQUIRED 8871 && appSupportsRuntimePermissions 8872 && (flags & PackageManager 8873 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 8874 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 8875 // Since we changed the flags, we have to write. 8876 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8877 changedRuntimePermissionUserIds, userId); 8878 } 8879 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 8880 && !appSupportsRuntimePermissions) { 8881 // For legacy apps that need a permission review, every new 8882 // runtime permission is granted but it is pending a review. 8883 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 8884 permissionsState.grantRuntimePermission(bp, userId); 8885 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 8886 // We changed the permission and flags, hence have to write. 8887 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8888 changedRuntimePermissionUserIds, userId); 8889 } 8890 } 8891 // Propagate the permission flags. 8892 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 8893 } 8894 } break; 8895 8896 case GRANT_UPGRADE: { 8897 // Grant runtime permissions for a previously held install permission. 8898 PermissionState permissionState = origPermissions 8899 .getInstallPermissionState(bp.name); 8900 final int flags = permissionState != null ? permissionState.getFlags() : 0; 8901 8902 if (origPermissions.revokeInstallPermission(bp) 8903 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 8904 // We will be transferring the permission flags, so clear them. 8905 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 8906 PackageManager.MASK_PERMISSION_FLAGS, 0); 8907 changedInstallPermission = true; 8908 } 8909 8910 // If the permission is not to be promoted to runtime we ignore it and 8911 // also its other flags as they are not applicable to install permissions. 8912 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 8913 for (int userId : currentUserIds) { 8914 if (permissionsState.grantRuntimePermission(bp, userId) != 8915 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8916 // Transfer the permission flags. 8917 permissionsState.updatePermissionFlags(bp, userId, 8918 flags, flags); 8919 // If we granted the permission, we have to write. 8920 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8921 changedRuntimePermissionUserIds, userId); 8922 } 8923 } 8924 } 8925 } break; 8926 8927 default: { 8928 if (packageOfInterest == null 8929 || packageOfInterest.equals(pkg.packageName)) { 8930 Slog.w(TAG, "Not granting permission " + perm 8931 + " to package " + pkg.packageName 8932 + " because it was previously installed without"); 8933 } 8934 } break; 8935 } 8936 } else { 8937 if (permissionsState.revokeInstallPermission(bp) != 8938 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8939 // Also drop the permission flags. 8940 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 8941 PackageManager.MASK_PERMISSION_FLAGS, 0); 8942 changedInstallPermission = true; 8943 Slog.i(TAG, "Un-granting permission " + perm 8944 + " from package " + pkg.packageName 8945 + " (protectionLevel=" + bp.protectionLevel 8946 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8947 + ")"); 8948 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 8949 // Don't print warning for app op permissions, since it is fine for them 8950 // not to be granted, there is a UI for the user to decide. 8951 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8952 Slog.w(TAG, "Not granting permission " + perm 8953 + " to package " + pkg.packageName 8954 + " (protectionLevel=" + bp.protectionLevel 8955 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8956 + ")"); 8957 } 8958 } 8959 } 8960 } 8961 8962 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 8963 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 8964 // This is the first that we have heard about this package, so the 8965 // permissions we have now selected are fixed until explicitly 8966 // changed. 8967 ps.installPermissionsFixed = true; 8968 } 8969 8970 // Persist the runtime permissions state for users with changes. If permissions 8971 // were revoked because no app in the shared user declares them we have to 8972 // write synchronously to avoid losing runtime permissions state. 8973 for (int userId : changedRuntimePermissionUserIds) { 8974 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 8975 } 8976 8977 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8978 } 8979 8980 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8981 boolean allowed = false; 8982 final int NP = PackageParser.NEW_PERMISSIONS.length; 8983 for (int ip=0; ip<NP; ip++) { 8984 final PackageParser.NewPermissionInfo npi 8985 = PackageParser.NEW_PERMISSIONS[ip]; 8986 if (npi.name.equals(perm) 8987 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8988 allowed = true; 8989 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8990 + pkg.packageName); 8991 break; 8992 } 8993 } 8994 return allowed; 8995 } 8996 8997 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 8998 BasePermission bp, PermissionsState origPermissions) { 8999 boolean allowed; 9000 allowed = (compareSignatures( 9001 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 9002 == PackageManager.SIGNATURE_MATCH) 9003 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 9004 == PackageManager.SIGNATURE_MATCH); 9005 if (!allowed && (bp.protectionLevel 9006 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 9007 if (isSystemApp(pkg)) { 9008 // For updated system applications, a system permission 9009 // is granted only if it had been defined by the original application. 9010 if (pkg.isUpdatedSystemApp()) { 9011 final PackageSetting sysPs = mSettings 9012 .getDisabledSystemPkgLPr(pkg.packageName); 9013 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 9014 // If the original was granted this permission, we take 9015 // that grant decision as read and propagate it to the 9016 // update. 9017 if (sysPs.isPrivileged()) { 9018 allowed = true; 9019 } 9020 } else { 9021 // The system apk may have been updated with an older 9022 // version of the one on the data partition, but which 9023 // granted a new system permission that it didn't have 9024 // before. In this case we do want to allow the app to 9025 // now get the new permission if the ancestral apk is 9026 // privileged to get it. 9027 if (sysPs.pkg != null && sysPs.isPrivileged()) { 9028 for (int j=0; 9029 j<sysPs.pkg.requestedPermissions.size(); j++) { 9030 if (perm.equals( 9031 sysPs.pkg.requestedPermissions.get(j))) { 9032 allowed = true; 9033 break; 9034 } 9035 } 9036 } 9037 } 9038 } else { 9039 allowed = isPrivilegedApp(pkg); 9040 } 9041 } 9042 } 9043 if (!allowed) { 9044 if (!allowed && (bp.protectionLevel 9045 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 9046 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 9047 // If this was a previously normal/dangerous permission that got moved 9048 // to a system permission as part of the runtime permission redesign, then 9049 // we still want to blindly grant it to old apps. 9050 allowed = true; 9051 } 9052 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 9053 && pkg.packageName.equals(mRequiredInstallerPackage)) { 9054 // If this permission is to be granted to the system installer and 9055 // this app is an installer, then it gets the permission. 9056 allowed = true; 9057 } 9058 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 9059 && pkg.packageName.equals(mRequiredVerifierPackage)) { 9060 // If this permission is to be granted to the system verifier and 9061 // this app is a verifier, then it gets the permission. 9062 allowed = true; 9063 } 9064 if (!allowed && (bp.protectionLevel 9065 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 9066 && isSystemApp(pkg)) { 9067 // Any pre-installed system app is allowed to get this permission. 9068 allowed = true; 9069 } 9070 if (!allowed && (bp.protectionLevel 9071 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 9072 // For development permissions, a development permission 9073 // is granted only if it was already granted. 9074 allowed = origPermissions.hasInstallPermission(perm); 9075 } 9076 } 9077 return allowed; 9078 } 9079 9080 final class ActivityIntentResolver 9081 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 9082 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9083 boolean defaultOnly, int userId) { 9084 if (!sUserManager.exists(userId)) return null; 9085 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9086 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9087 } 9088 9089 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9090 int userId) { 9091 if (!sUserManager.exists(userId)) return null; 9092 mFlags = flags; 9093 return super.queryIntent(intent, resolvedType, 9094 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9095 } 9096 9097 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9098 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 9099 if (!sUserManager.exists(userId)) return null; 9100 if (packageActivities == null) { 9101 return null; 9102 } 9103 mFlags = flags; 9104 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9105 final int N = packageActivities.size(); 9106 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 9107 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 9108 9109 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 9110 for (int i = 0; i < N; ++i) { 9111 intentFilters = packageActivities.get(i).intents; 9112 if (intentFilters != null && intentFilters.size() > 0) { 9113 PackageParser.ActivityIntentInfo[] array = 9114 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 9115 intentFilters.toArray(array); 9116 listCut.add(array); 9117 } 9118 } 9119 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9120 } 9121 9122 public final void addActivity(PackageParser.Activity a, String type) { 9123 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 9124 mActivities.put(a.getComponentName(), a); 9125 if (DEBUG_SHOW_INFO) 9126 Log.v( 9127 TAG, " " + type + " " + 9128 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 9129 if (DEBUG_SHOW_INFO) 9130 Log.v(TAG, " Class=" + a.info.name); 9131 final int NI = a.intents.size(); 9132 for (int j=0; j<NI; j++) { 9133 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 9134 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 9135 intent.setPriority(0); 9136 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 9137 + a.className + " with priority > 0, forcing to 0"); 9138 } 9139 if (DEBUG_SHOW_INFO) { 9140 Log.v(TAG, " IntentFilter:"); 9141 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9142 } 9143 if (!intent.debugCheck()) { 9144 Log.w(TAG, "==> For Activity " + a.info.name); 9145 } 9146 addFilter(intent); 9147 } 9148 } 9149 9150 public final void removeActivity(PackageParser.Activity a, String type) { 9151 mActivities.remove(a.getComponentName()); 9152 if (DEBUG_SHOW_INFO) { 9153 Log.v(TAG, " " + type + " " 9154 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 9155 : a.info.name) + ":"); 9156 Log.v(TAG, " Class=" + a.info.name); 9157 } 9158 final int NI = a.intents.size(); 9159 for (int j=0; j<NI; j++) { 9160 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 9161 if (DEBUG_SHOW_INFO) { 9162 Log.v(TAG, " IntentFilter:"); 9163 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9164 } 9165 removeFilter(intent); 9166 } 9167 } 9168 9169 @Override 9170 protected boolean allowFilterResult( 9171 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 9172 ActivityInfo filterAi = filter.activity.info; 9173 for (int i=dest.size()-1; i>=0; i--) { 9174 ActivityInfo destAi = dest.get(i).activityInfo; 9175 if (destAi.name == filterAi.name 9176 && destAi.packageName == filterAi.packageName) { 9177 return false; 9178 } 9179 } 9180 return true; 9181 } 9182 9183 @Override 9184 protected ActivityIntentInfo[] newArray(int size) { 9185 return new ActivityIntentInfo[size]; 9186 } 9187 9188 @Override 9189 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 9190 if (!sUserManager.exists(userId)) return true; 9191 PackageParser.Package p = filter.activity.owner; 9192 if (p != null) { 9193 PackageSetting ps = (PackageSetting)p.mExtras; 9194 if (ps != null) { 9195 // System apps are never considered stopped for purposes of 9196 // filtering, because there may be no way for the user to 9197 // actually re-launch them. 9198 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 9199 && ps.getStopped(userId); 9200 } 9201 } 9202 return false; 9203 } 9204 9205 @Override 9206 protected boolean isPackageForFilter(String packageName, 9207 PackageParser.ActivityIntentInfo info) { 9208 return packageName.equals(info.activity.owner.packageName); 9209 } 9210 9211 @Override 9212 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 9213 int match, int userId) { 9214 if (!sUserManager.exists(userId)) return null; 9215 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 9216 return null; 9217 } 9218 final PackageParser.Activity activity = info.activity; 9219 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 9220 if (ps == null) { 9221 return null; 9222 } 9223 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 9224 ps.readUserState(userId), userId); 9225 if (ai == null) { 9226 return null; 9227 } 9228 final ResolveInfo res = new ResolveInfo(); 9229 res.activityInfo = ai; 9230 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9231 res.filter = info; 9232 } 9233 if (info != null) { 9234 res.handleAllWebDataURI = info.handleAllWebDataURI(); 9235 } 9236 res.priority = info.getPriority(); 9237 res.preferredOrder = activity.owner.mPreferredOrder; 9238 //System.out.println("Result: " + res.activityInfo.className + 9239 // " = " + res.priority); 9240 res.match = match; 9241 res.isDefault = info.hasDefault; 9242 res.labelRes = info.labelRes; 9243 res.nonLocalizedLabel = info.nonLocalizedLabel; 9244 if (userNeedsBadging(userId)) { 9245 res.noResourceId = true; 9246 } else { 9247 res.icon = info.icon; 9248 } 9249 res.iconResourceId = info.icon; 9250 res.system = res.activityInfo.applicationInfo.isSystemApp(); 9251 return res; 9252 } 9253 9254 @Override 9255 protected void sortResults(List<ResolveInfo> results) { 9256 Collections.sort(results, mResolvePrioritySorter); 9257 } 9258 9259 @Override 9260 protected void dumpFilter(PrintWriter out, String prefix, 9261 PackageParser.ActivityIntentInfo filter) { 9262 out.print(prefix); out.print( 9263 Integer.toHexString(System.identityHashCode(filter.activity))); 9264 out.print(' '); 9265 filter.activity.printComponentShortName(out); 9266 out.print(" filter "); 9267 out.println(Integer.toHexString(System.identityHashCode(filter))); 9268 } 9269 9270 @Override 9271 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 9272 return filter.activity; 9273 } 9274 9275 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9276 PackageParser.Activity activity = (PackageParser.Activity)label; 9277 out.print(prefix); out.print( 9278 Integer.toHexString(System.identityHashCode(activity))); 9279 out.print(' '); 9280 activity.printComponentShortName(out); 9281 if (count > 1) { 9282 out.print(" ("); out.print(count); out.print(" filters)"); 9283 } 9284 out.println(); 9285 } 9286 9287// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9288// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9289// final List<ResolveInfo> retList = Lists.newArrayList(); 9290// while (i.hasNext()) { 9291// final ResolveInfo resolveInfo = i.next(); 9292// if (isEnabledLP(resolveInfo.activityInfo)) { 9293// retList.add(resolveInfo); 9294// } 9295// } 9296// return retList; 9297// } 9298 9299 // Keys are String (activity class name), values are Activity. 9300 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 9301 = new ArrayMap<ComponentName, PackageParser.Activity>(); 9302 private int mFlags; 9303 } 9304 9305 private final class ServiceIntentResolver 9306 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 9307 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9308 boolean defaultOnly, int userId) { 9309 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9310 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9311 } 9312 9313 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9314 int userId) { 9315 if (!sUserManager.exists(userId)) return null; 9316 mFlags = flags; 9317 return super.queryIntent(intent, resolvedType, 9318 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9319 } 9320 9321 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9322 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 9323 if (!sUserManager.exists(userId)) return null; 9324 if (packageServices == null) { 9325 return null; 9326 } 9327 mFlags = flags; 9328 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9329 final int N = packageServices.size(); 9330 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 9331 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 9332 9333 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 9334 for (int i = 0; i < N; ++i) { 9335 intentFilters = packageServices.get(i).intents; 9336 if (intentFilters != null && intentFilters.size() > 0) { 9337 PackageParser.ServiceIntentInfo[] array = 9338 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 9339 intentFilters.toArray(array); 9340 listCut.add(array); 9341 } 9342 } 9343 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9344 } 9345 9346 public final void addService(PackageParser.Service s) { 9347 mServices.put(s.getComponentName(), s); 9348 if (DEBUG_SHOW_INFO) { 9349 Log.v(TAG, " " 9350 + (s.info.nonLocalizedLabel != null 9351 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9352 Log.v(TAG, " Class=" + s.info.name); 9353 } 9354 final int NI = s.intents.size(); 9355 int j; 9356 for (j=0; j<NI; j++) { 9357 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9358 if (DEBUG_SHOW_INFO) { 9359 Log.v(TAG, " IntentFilter:"); 9360 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9361 } 9362 if (!intent.debugCheck()) { 9363 Log.w(TAG, "==> For Service " + s.info.name); 9364 } 9365 addFilter(intent); 9366 } 9367 } 9368 9369 public final void removeService(PackageParser.Service s) { 9370 mServices.remove(s.getComponentName()); 9371 if (DEBUG_SHOW_INFO) { 9372 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 9373 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9374 Log.v(TAG, " Class=" + s.info.name); 9375 } 9376 final int NI = s.intents.size(); 9377 int j; 9378 for (j=0; j<NI; j++) { 9379 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9380 if (DEBUG_SHOW_INFO) { 9381 Log.v(TAG, " IntentFilter:"); 9382 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9383 } 9384 removeFilter(intent); 9385 } 9386 } 9387 9388 @Override 9389 protected boolean allowFilterResult( 9390 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 9391 ServiceInfo filterSi = filter.service.info; 9392 for (int i=dest.size()-1; i>=0; i--) { 9393 ServiceInfo destAi = dest.get(i).serviceInfo; 9394 if (destAi.name == filterSi.name 9395 && destAi.packageName == filterSi.packageName) { 9396 return false; 9397 } 9398 } 9399 return true; 9400 } 9401 9402 @Override 9403 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 9404 return new PackageParser.ServiceIntentInfo[size]; 9405 } 9406 9407 @Override 9408 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 9409 if (!sUserManager.exists(userId)) return true; 9410 PackageParser.Package p = filter.service.owner; 9411 if (p != null) { 9412 PackageSetting ps = (PackageSetting)p.mExtras; 9413 if (ps != null) { 9414 // System apps are never considered stopped for purposes of 9415 // filtering, because there may be no way for the user to 9416 // actually re-launch them. 9417 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9418 && ps.getStopped(userId); 9419 } 9420 } 9421 return false; 9422 } 9423 9424 @Override 9425 protected boolean isPackageForFilter(String packageName, 9426 PackageParser.ServiceIntentInfo info) { 9427 return packageName.equals(info.service.owner.packageName); 9428 } 9429 9430 @Override 9431 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 9432 int match, int userId) { 9433 if (!sUserManager.exists(userId)) return null; 9434 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 9435 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 9436 return null; 9437 } 9438 final PackageParser.Service service = info.service; 9439 PackageSetting ps = (PackageSetting) service.owner.mExtras; 9440 if (ps == null) { 9441 return null; 9442 } 9443 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 9444 ps.readUserState(userId), userId); 9445 if (si == null) { 9446 return null; 9447 } 9448 final ResolveInfo res = new ResolveInfo(); 9449 res.serviceInfo = si; 9450 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9451 res.filter = filter; 9452 } 9453 res.priority = info.getPriority(); 9454 res.preferredOrder = service.owner.mPreferredOrder; 9455 res.match = match; 9456 res.isDefault = info.hasDefault; 9457 res.labelRes = info.labelRes; 9458 res.nonLocalizedLabel = info.nonLocalizedLabel; 9459 res.icon = info.icon; 9460 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 9461 return res; 9462 } 9463 9464 @Override 9465 protected void sortResults(List<ResolveInfo> results) { 9466 Collections.sort(results, mResolvePrioritySorter); 9467 } 9468 9469 @Override 9470 protected void dumpFilter(PrintWriter out, String prefix, 9471 PackageParser.ServiceIntentInfo filter) { 9472 out.print(prefix); out.print( 9473 Integer.toHexString(System.identityHashCode(filter.service))); 9474 out.print(' '); 9475 filter.service.printComponentShortName(out); 9476 out.print(" filter "); 9477 out.println(Integer.toHexString(System.identityHashCode(filter))); 9478 } 9479 9480 @Override 9481 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 9482 return filter.service; 9483 } 9484 9485 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9486 PackageParser.Service service = (PackageParser.Service)label; 9487 out.print(prefix); out.print( 9488 Integer.toHexString(System.identityHashCode(service))); 9489 out.print(' '); 9490 service.printComponentShortName(out); 9491 if (count > 1) { 9492 out.print(" ("); out.print(count); out.print(" filters)"); 9493 } 9494 out.println(); 9495 } 9496 9497// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9498// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9499// final List<ResolveInfo> retList = Lists.newArrayList(); 9500// while (i.hasNext()) { 9501// final ResolveInfo resolveInfo = (ResolveInfo) i; 9502// if (isEnabledLP(resolveInfo.serviceInfo)) { 9503// retList.add(resolveInfo); 9504// } 9505// } 9506// return retList; 9507// } 9508 9509 // Keys are String (activity class name), values are Activity. 9510 private final ArrayMap<ComponentName, PackageParser.Service> mServices 9511 = new ArrayMap<ComponentName, PackageParser.Service>(); 9512 private int mFlags; 9513 }; 9514 9515 private final class ProviderIntentResolver 9516 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 9517 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9518 boolean defaultOnly, int userId) { 9519 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9520 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9521 } 9522 9523 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9524 int userId) { 9525 if (!sUserManager.exists(userId)) 9526 return null; 9527 mFlags = flags; 9528 return super.queryIntent(intent, resolvedType, 9529 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9530 } 9531 9532 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9533 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 9534 if (!sUserManager.exists(userId)) 9535 return null; 9536 if (packageProviders == null) { 9537 return null; 9538 } 9539 mFlags = flags; 9540 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 9541 final int N = packageProviders.size(); 9542 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 9543 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 9544 9545 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 9546 for (int i = 0; i < N; ++i) { 9547 intentFilters = packageProviders.get(i).intents; 9548 if (intentFilters != null && intentFilters.size() > 0) { 9549 PackageParser.ProviderIntentInfo[] array = 9550 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 9551 intentFilters.toArray(array); 9552 listCut.add(array); 9553 } 9554 } 9555 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9556 } 9557 9558 public final void addProvider(PackageParser.Provider p) { 9559 if (mProviders.containsKey(p.getComponentName())) { 9560 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 9561 return; 9562 } 9563 9564 mProviders.put(p.getComponentName(), p); 9565 if (DEBUG_SHOW_INFO) { 9566 Log.v(TAG, " " 9567 + (p.info.nonLocalizedLabel != null 9568 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9569 Log.v(TAG, " Class=" + p.info.name); 9570 } 9571 final int NI = p.intents.size(); 9572 int j; 9573 for (j = 0; j < NI; j++) { 9574 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9575 if (DEBUG_SHOW_INFO) { 9576 Log.v(TAG, " IntentFilter:"); 9577 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9578 } 9579 if (!intent.debugCheck()) { 9580 Log.w(TAG, "==> For Provider " + p.info.name); 9581 } 9582 addFilter(intent); 9583 } 9584 } 9585 9586 public final void removeProvider(PackageParser.Provider p) { 9587 mProviders.remove(p.getComponentName()); 9588 if (DEBUG_SHOW_INFO) { 9589 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 9590 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9591 Log.v(TAG, " Class=" + p.info.name); 9592 } 9593 final int NI = p.intents.size(); 9594 int j; 9595 for (j = 0; j < NI; j++) { 9596 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9597 if (DEBUG_SHOW_INFO) { 9598 Log.v(TAG, " IntentFilter:"); 9599 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9600 } 9601 removeFilter(intent); 9602 } 9603 } 9604 9605 @Override 9606 protected boolean allowFilterResult( 9607 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 9608 ProviderInfo filterPi = filter.provider.info; 9609 for (int i = dest.size() - 1; i >= 0; i--) { 9610 ProviderInfo destPi = dest.get(i).providerInfo; 9611 if (destPi.name == filterPi.name 9612 && destPi.packageName == filterPi.packageName) { 9613 return false; 9614 } 9615 } 9616 return true; 9617 } 9618 9619 @Override 9620 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 9621 return new PackageParser.ProviderIntentInfo[size]; 9622 } 9623 9624 @Override 9625 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 9626 if (!sUserManager.exists(userId)) 9627 return true; 9628 PackageParser.Package p = filter.provider.owner; 9629 if (p != null) { 9630 PackageSetting ps = (PackageSetting) p.mExtras; 9631 if (ps != null) { 9632 // System apps are never considered stopped for purposes of 9633 // filtering, because there may be no way for the user to 9634 // actually re-launch them. 9635 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9636 && ps.getStopped(userId); 9637 } 9638 } 9639 return false; 9640 } 9641 9642 @Override 9643 protected boolean isPackageForFilter(String packageName, 9644 PackageParser.ProviderIntentInfo info) { 9645 return packageName.equals(info.provider.owner.packageName); 9646 } 9647 9648 @Override 9649 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 9650 int match, int userId) { 9651 if (!sUserManager.exists(userId)) 9652 return null; 9653 final PackageParser.ProviderIntentInfo info = filter; 9654 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 9655 return null; 9656 } 9657 final PackageParser.Provider provider = info.provider; 9658 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 9659 if (ps == null) { 9660 return null; 9661 } 9662 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 9663 ps.readUserState(userId), userId); 9664 if (pi == null) { 9665 return null; 9666 } 9667 final ResolveInfo res = new ResolveInfo(); 9668 res.providerInfo = pi; 9669 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 9670 res.filter = filter; 9671 } 9672 res.priority = info.getPriority(); 9673 res.preferredOrder = provider.owner.mPreferredOrder; 9674 res.match = match; 9675 res.isDefault = info.hasDefault; 9676 res.labelRes = info.labelRes; 9677 res.nonLocalizedLabel = info.nonLocalizedLabel; 9678 res.icon = info.icon; 9679 res.system = res.providerInfo.applicationInfo.isSystemApp(); 9680 return res; 9681 } 9682 9683 @Override 9684 protected void sortResults(List<ResolveInfo> results) { 9685 Collections.sort(results, mResolvePrioritySorter); 9686 } 9687 9688 @Override 9689 protected void dumpFilter(PrintWriter out, String prefix, 9690 PackageParser.ProviderIntentInfo filter) { 9691 out.print(prefix); 9692 out.print( 9693 Integer.toHexString(System.identityHashCode(filter.provider))); 9694 out.print(' '); 9695 filter.provider.printComponentShortName(out); 9696 out.print(" filter "); 9697 out.println(Integer.toHexString(System.identityHashCode(filter))); 9698 } 9699 9700 @Override 9701 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 9702 return filter.provider; 9703 } 9704 9705 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9706 PackageParser.Provider provider = (PackageParser.Provider)label; 9707 out.print(prefix); out.print( 9708 Integer.toHexString(System.identityHashCode(provider))); 9709 out.print(' '); 9710 provider.printComponentShortName(out); 9711 if (count > 1) { 9712 out.print(" ("); out.print(count); out.print(" filters)"); 9713 } 9714 out.println(); 9715 } 9716 9717 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 9718 = new ArrayMap<ComponentName, PackageParser.Provider>(); 9719 private int mFlags; 9720 } 9721 9722 private static final class EphemeralIntentResolver 9723 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 9724 @Override 9725 protected EphemeralResolveIntentInfo[] newArray(int size) { 9726 return new EphemeralResolveIntentInfo[size]; 9727 } 9728 9729 @Override 9730 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 9731 return true; 9732 } 9733 9734 @Override 9735 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 9736 int userId) { 9737 if (!sUserManager.exists(userId)) { 9738 return null; 9739 } 9740 return info.getEphemeralResolveInfo(); 9741 } 9742 } 9743 9744 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 9745 new Comparator<ResolveInfo>() { 9746 public int compare(ResolveInfo r1, ResolveInfo r2) { 9747 int v1 = r1.priority; 9748 int v2 = r2.priority; 9749 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 9750 if (v1 != v2) { 9751 return (v1 > v2) ? -1 : 1; 9752 } 9753 v1 = r1.preferredOrder; 9754 v2 = r2.preferredOrder; 9755 if (v1 != v2) { 9756 return (v1 > v2) ? -1 : 1; 9757 } 9758 if (r1.isDefault != r2.isDefault) { 9759 return r1.isDefault ? -1 : 1; 9760 } 9761 v1 = r1.match; 9762 v2 = r2.match; 9763 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 9764 if (v1 != v2) { 9765 return (v1 > v2) ? -1 : 1; 9766 } 9767 if (r1.system != r2.system) { 9768 return r1.system ? -1 : 1; 9769 } 9770 if (r1.activityInfo != null) { 9771 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 9772 } 9773 if (r1.serviceInfo != null) { 9774 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 9775 } 9776 if (r1.providerInfo != null) { 9777 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 9778 } 9779 return 0; 9780 } 9781 }; 9782 9783 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 9784 new Comparator<ProviderInfo>() { 9785 public int compare(ProviderInfo p1, ProviderInfo p2) { 9786 final int v1 = p1.initOrder; 9787 final int v2 = p2.initOrder; 9788 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 9789 } 9790 }; 9791 9792 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 9793 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 9794 final int[] userIds) { 9795 mHandler.post(new Runnable() { 9796 @Override 9797 public void run() { 9798 try { 9799 final IActivityManager am = ActivityManagerNative.getDefault(); 9800 if (am == null) return; 9801 final int[] resolvedUserIds; 9802 if (userIds == null) { 9803 resolvedUserIds = am.getRunningUserIds(); 9804 } else { 9805 resolvedUserIds = userIds; 9806 } 9807 for (int id : resolvedUserIds) { 9808 final Intent intent = new Intent(action, 9809 pkg != null ? Uri.fromParts("package", pkg, null) : null); 9810 if (extras != null) { 9811 intent.putExtras(extras); 9812 } 9813 if (targetPkg != null) { 9814 intent.setPackage(targetPkg); 9815 } 9816 // Modify the UID when posting to other users 9817 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 9818 if (uid > 0 && UserHandle.getUserId(uid) != id) { 9819 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 9820 intent.putExtra(Intent.EXTRA_UID, uid); 9821 } 9822 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 9823 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 9824 if (DEBUG_BROADCASTS) { 9825 RuntimeException here = new RuntimeException("here"); 9826 here.fillInStackTrace(); 9827 Slog.d(TAG, "Sending to user " + id + ": " 9828 + intent.toShortString(false, true, false, false) 9829 + " " + intent.getExtras(), here); 9830 } 9831 am.broadcastIntent(null, intent, null, finishedReceiver, 9832 0, null, null, null, android.app.AppOpsManager.OP_NONE, 9833 null, finishedReceiver != null, false, id); 9834 } 9835 } catch (RemoteException ex) { 9836 } 9837 } 9838 }); 9839 } 9840 9841 /** 9842 * Check if the external storage media is available. This is true if there 9843 * is a mounted external storage medium or if the external storage is 9844 * emulated. 9845 */ 9846 private boolean isExternalMediaAvailable() { 9847 return mMediaMounted || Environment.isExternalStorageEmulated(); 9848 } 9849 9850 @Override 9851 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 9852 // writer 9853 synchronized (mPackages) { 9854 if (!isExternalMediaAvailable()) { 9855 // If the external storage is no longer mounted at this point, 9856 // the caller may not have been able to delete all of this 9857 // packages files and can not delete any more. Bail. 9858 return null; 9859 } 9860 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 9861 if (lastPackage != null) { 9862 pkgs.remove(lastPackage); 9863 } 9864 if (pkgs.size() > 0) { 9865 return pkgs.get(0); 9866 } 9867 } 9868 return null; 9869 } 9870 9871 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 9872 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 9873 userId, andCode ? 1 : 0, packageName); 9874 if (mSystemReady) { 9875 msg.sendToTarget(); 9876 } else { 9877 if (mPostSystemReadyMessages == null) { 9878 mPostSystemReadyMessages = new ArrayList<>(); 9879 } 9880 mPostSystemReadyMessages.add(msg); 9881 } 9882 } 9883 9884 void startCleaningPackages() { 9885 // reader 9886 synchronized (mPackages) { 9887 if (!isExternalMediaAvailable()) { 9888 return; 9889 } 9890 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 9891 return; 9892 } 9893 } 9894 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 9895 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 9896 IActivityManager am = ActivityManagerNative.getDefault(); 9897 if (am != null) { 9898 try { 9899 am.startService(null, intent, null, mContext.getOpPackageName(), 9900 UserHandle.USER_SYSTEM); 9901 } catch (RemoteException e) { 9902 } 9903 } 9904 } 9905 9906 @Override 9907 public void installPackage(String originPath, IPackageInstallObserver2 observer, 9908 int installFlags, String installerPackageName, VerificationParams verificationParams, 9909 String packageAbiOverride) { 9910 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 9911 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 9912 } 9913 9914 @Override 9915 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 9916 int installFlags, String installerPackageName, VerificationParams verificationParams, 9917 String packageAbiOverride, int userId) { 9918 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 9919 9920 final int callingUid = Binder.getCallingUid(); 9921 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 9922 9923 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9924 try { 9925 if (observer != null) { 9926 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 9927 } 9928 } catch (RemoteException re) { 9929 } 9930 return; 9931 } 9932 9933 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 9934 installFlags |= PackageManager.INSTALL_FROM_ADB; 9935 9936 } else { 9937 // Caller holds INSTALL_PACKAGES permission, so we're less strict 9938 // about installerPackageName. 9939 9940 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 9941 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 9942 } 9943 9944 UserHandle user; 9945 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 9946 user = UserHandle.ALL; 9947 } else { 9948 user = new UserHandle(userId); 9949 } 9950 9951 // Only system components can circumvent runtime permissions when installing. 9952 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 9953 && mContext.checkCallingOrSelfPermission(Manifest.permission 9954 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 9955 throw new SecurityException("You need the " 9956 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 9957 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 9958 } 9959 9960 verificationParams.setInstallerUid(callingUid); 9961 9962 final File originFile = new File(originPath); 9963 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 9964 9965 final Message msg = mHandler.obtainMessage(INIT_COPY); 9966 final InstallParams params = new InstallParams(origin, null, observer, installFlags, 9967 installerPackageName, null, verificationParams, user, packageAbiOverride, null); 9968 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 9969 msg.obj = params; 9970 9971 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 9972 System.identityHashCode(msg.obj)); 9973 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 9974 System.identityHashCode(msg.obj)); 9975 9976 mHandler.sendMessage(msg); 9977 } 9978 9979 void installStage(String packageName, File stagedDir, String stagedCid, 9980 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 9981 String installerPackageName, int installerUid, UserHandle user) { 9982 if (DEBUG_EPHEMERAL) { 9983 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 9984 Slog.d(TAG, "Ephemeral install of " + packageName); 9985 } 9986 } 9987 final VerificationParams verifParams = new VerificationParams( 9988 null, sessionParams.originatingUri, sessionParams.referrerUri, 9989 sessionParams.originatingUid); 9990 verifParams.setInstallerUid(installerUid); 9991 9992 final OriginInfo origin; 9993 if (stagedDir != null) { 9994 origin = OriginInfo.fromStagedFile(stagedDir); 9995 } else { 9996 origin = OriginInfo.fromStagedContainer(stagedCid); 9997 } 9998 9999 final Message msg = mHandler.obtainMessage(INIT_COPY); 10000 final InstallParams params = new InstallParams(origin, null, observer, 10001 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 10002 verifParams, user, sessionParams.abiOverride, 10003 sessionParams.grantedRuntimePermissions); 10004 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 10005 msg.obj = params; 10006 10007 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 10008 System.identityHashCode(msg.obj)); 10009 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 10010 System.identityHashCode(msg.obj)); 10011 10012 mHandler.sendMessage(msg); 10013 } 10014 10015 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 10016 Bundle extras = new Bundle(1); 10017 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 10018 10019 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 10020 packageName, extras, 0, null, null, new int[] {userId}); 10021 try { 10022 IActivityManager am = ActivityManagerNative.getDefault(); 10023 final boolean isSystem = 10024 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 10025 if (isSystem && am.isUserRunning(userId, 0)) { 10026 // The just-installed/enabled app is bundled on the system, so presumed 10027 // to be able to run automatically without needing an explicit launch. 10028 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 10029 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 10030 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 10031 .setPackage(packageName); 10032 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 10033 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 10034 } 10035 } catch (RemoteException e) { 10036 // shouldn't happen 10037 Slog.w(TAG, "Unable to bootstrap installed package", e); 10038 } 10039 } 10040 10041 @Override 10042 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 10043 int userId) { 10044 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10045 PackageSetting pkgSetting; 10046 final int uid = Binder.getCallingUid(); 10047 enforceCrossUserPermission(uid, userId, true, true, 10048 "setApplicationHiddenSetting for user " + userId); 10049 10050 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 10051 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 10052 return false; 10053 } 10054 10055 long callingId = Binder.clearCallingIdentity(); 10056 try { 10057 boolean sendAdded = false; 10058 boolean sendRemoved = false; 10059 // writer 10060 synchronized (mPackages) { 10061 pkgSetting = mSettings.mPackages.get(packageName); 10062 if (pkgSetting == null) { 10063 return false; 10064 } 10065 if (pkgSetting.getHidden(userId) != hidden) { 10066 pkgSetting.setHidden(hidden, userId); 10067 mSettings.writePackageRestrictionsLPr(userId); 10068 if (hidden) { 10069 sendRemoved = true; 10070 } else { 10071 sendAdded = true; 10072 } 10073 } 10074 } 10075 if (sendAdded) { 10076 sendPackageAddedForUser(packageName, pkgSetting, userId); 10077 return true; 10078 } 10079 if (sendRemoved) { 10080 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 10081 "hiding pkg"); 10082 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 10083 return true; 10084 } 10085 } finally { 10086 Binder.restoreCallingIdentity(callingId); 10087 } 10088 return false; 10089 } 10090 10091 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 10092 int userId) { 10093 final PackageRemovedInfo info = new PackageRemovedInfo(); 10094 info.removedPackage = packageName; 10095 info.removedUsers = new int[] {userId}; 10096 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 10097 info.sendBroadcast(false, false, false); 10098 } 10099 10100 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 10101 if (pkgList.length > 0) { 10102 Bundle extras = new Bundle(1); 10103 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 10104 10105 sendPackageBroadcast( 10106 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 10107 : Intent.ACTION_PACKAGES_UNSUSPENDED, 10108 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 10109 new int[] {userId}); 10110 } 10111 } 10112 10113 /** 10114 * Returns true if application is not found or there was an error. Otherwise it returns 10115 * the hidden state of the package for the given user. 10116 */ 10117 @Override 10118 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 10119 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10120 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 10121 false, "getApplicationHidden for user " + userId); 10122 PackageSetting pkgSetting; 10123 long callingId = Binder.clearCallingIdentity(); 10124 try { 10125 // writer 10126 synchronized (mPackages) { 10127 pkgSetting = mSettings.mPackages.get(packageName); 10128 if (pkgSetting == null) { 10129 return true; 10130 } 10131 return pkgSetting.getHidden(userId); 10132 } 10133 } finally { 10134 Binder.restoreCallingIdentity(callingId); 10135 } 10136 } 10137 10138 /** 10139 * @hide 10140 */ 10141 @Override 10142 public int installExistingPackageAsUser(String packageName, int userId) { 10143 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 10144 null); 10145 PackageSetting pkgSetting; 10146 final int uid = Binder.getCallingUid(); 10147 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 10148 + userId); 10149 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 10150 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 10151 } 10152 10153 long callingId = Binder.clearCallingIdentity(); 10154 try { 10155 boolean installed = false; 10156 10157 // writer 10158 synchronized (mPackages) { 10159 pkgSetting = mSettings.mPackages.get(packageName); 10160 if (pkgSetting == null) { 10161 return PackageManager.INSTALL_FAILED_INVALID_URI; 10162 } 10163 if (!pkgSetting.getInstalled(userId)) { 10164 pkgSetting.setInstalled(true, userId); 10165 pkgSetting.setHidden(false, userId); 10166 mSettings.writePackageRestrictionsLPr(userId); 10167 if (pkgSetting.pkg != null) { 10168 prepareAppDataAfterInstall(pkgSetting.pkg); 10169 } 10170 installed = true; 10171 } 10172 } 10173 10174 if (installed) { 10175 sendPackageAddedForUser(packageName, pkgSetting, userId); 10176 } 10177 } finally { 10178 Binder.restoreCallingIdentity(callingId); 10179 } 10180 10181 return PackageManager.INSTALL_SUCCEEDED; 10182 } 10183 10184 boolean isUserRestricted(int userId, String restrictionKey) { 10185 Bundle restrictions = sUserManager.getUserRestrictions(userId); 10186 if (restrictions.getBoolean(restrictionKey, false)) { 10187 Log.w(TAG, "User is restricted: " + restrictionKey); 10188 return true; 10189 } 10190 return false; 10191 } 10192 10193 @Override 10194 public boolean setPackageSuspendedAsUser(String packageName, boolean suspended, int userId) { 10195 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10196 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, true, 10197 "setPackageSuspended for user " + userId); 10198 10199 // TODO: investigate and add more restrictions for suspending crucial packages. 10200 if (isPackageDeviceAdmin(packageName, userId)) { 10201 Slog.w(TAG, "Not suspending/un-suspending package \"" + packageName 10202 + "\": has active device admin"); 10203 return false; 10204 } 10205 10206 long callingId = Binder.clearCallingIdentity(); 10207 try { 10208 boolean changed = false; 10209 boolean success = false; 10210 int appId = -1; 10211 synchronized (mPackages) { 10212 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 10213 if (pkgSetting != null) { 10214 if (pkgSetting.getSuspended(userId) != suspended) { 10215 pkgSetting.setSuspended(suspended, userId); 10216 mSettings.writePackageRestrictionsLPr(userId); 10217 appId = pkgSetting.appId; 10218 changed = true; 10219 } 10220 success = true; 10221 } 10222 } 10223 10224 if (changed) { 10225 sendPackagesSuspendedForUser(new String[]{packageName}, userId, suspended); 10226 if (suspended) { 10227 killApplication(packageName, UserHandle.getUid(userId, appId), 10228 "suspending package"); 10229 } 10230 } 10231 return success; 10232 } finally { 10233 Binder.restoreCallingIdentity(callingId); 10234 } 10235 } 10236 10237 @Override 10238 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 10239 mContext.enforceCallingOrSelfPermission( 10240 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10241 "Only package verification agents can verify applications"); 10242 10243 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 10244 final PackageVerificationResponse response = new PackageVerificationResponse( 10245 verificationCode, Binder.getCallingUid()); 10246 msg.arg1 = id; 10247 msg.obj = response; 10248 mHandler.sendMessage(msg); 10249 } 10250 10251 @Override 10252 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 10253 long millisecondsToDelay) { 10254 mContext.enforceCallingOrSelfPermission( 10255 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10256 "Only package verification agents can extend verification timeouts"); 10257 10258 final PackageVerificationState state = mPendingVerification.get(id); 10259 final PackageVerificationResponse response = new PackageVerificationResponse( 10260 verificationCodeAtTimeout, Binder.getCallingUid()); 10261 10262 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 10263 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 10264 } 10265 if (millisecondsToDelay < 0) { 10266 millisecondsToDelay = 0; 10267 } 10268 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 10269 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 10270 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 10271 } 10272 10273 if ((state != null) && !state.timeoutExtended()) { 10274 state.extendTimeout(); 10275 10276 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 10277 msg.arg1 = id; 10278 msg.obj = response; 10279 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 10280 } 10281 } 10282 10283 private void broadcastPackageVerified(int verificationId, Uri packageUri, 10284 int verificationCode, UserHandle user) { 10285 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 10286 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 10287 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10288 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10289 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 10290 10291 mContext.sendBroadcastAsUser(intent, user, 10292 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 10293 } 10294 10295 private ComponentName matchComponentForVerifier(String packageName, 10296 List<ResolveInfo> receivers) { 10297 ActivityInfo targetReceiver = null; 10298 10299 final int NR = receivers.size(); 10300 for (int i = 0; i < NR; i++) { 10301 final ResolveInfo info = receivers.get(i); 10302 if (info.activityInfo == null) { 10303 continue; 10304 } 10305 10306 if (packageName.equals(info.activityInfo.packageName)) { 10307 targetReceiver = info.activityInfo; 10308 break; 10309 } 10310 } 10311 10312 if (targetReceiver == null) { 10313 return null; 10314 } 10315 10316 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 10317 } 10318 10319 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 10320 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 10321 if (pkgInfo.verifiers.length == 0) { 10322 return null; 10323 } 10324 10325 final int N = pkgInfo.verifiers.length; 10326 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 10327 for (int i = 0; i < N; i++) { 10328 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 10329 10330 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 10331 receivers); 10332 if (comp == null) { 10333 continue; 10334 } 10335 10336 final int verifierUid = getUidForVerifier(verifierInfo); 10337 if (verifierUid == -1) { 10338 continue; 10339 } 10340 10341 if (DEBUG_VERIFY) { 10342 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 10343 + " with the correct signature"); 10344 } 10345 sufficientVerifiers.add(comp); 10346 verificationState.addSufficientVerifier(verifierUid); 10347 } 10348 10349 return sufficientVerifiers; 10350 } 10351 10352 private int getUidForVerifier(VerifierInfo verifierInfo) { 10353 synchronized (mPackages) { 10354 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 10355 if (pkg == null) { 10356 return -1; 10357 } else if (pkg.mSignatures.length != 1) { 10358 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10359 + " has more than one signature; ignoring"); 10360 return -1; 10361 } 10362 10363 /* 10364 * If the public key of the package's signature does not match 10365 * our expected public key, then this is a different package and 10366 * we should skip. 10367 */ 10368 10369 final byte[] expectedPublicKey; 10370 try { 10371 final Signature verifierSig = pkg.mSignatures[0]; 10372 final PublicKey publicKey = verifierSig.getPublicKey(); 10373 expectedPublicKey = publicKey.getEncoded(); 10374 } catch (CertificateException e) { 10375 return -1; 10376 } 10377 10378 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 10379 10380 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 10381 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10382 + " does not have the expected public key; ignoring"); 10383 return -1; 10384 } 10385 10386 return pkg.applicationInfo.uid; 10387 } 10388 } 10389 10390 @Override 10391 public void finishPackageInstall(int token) { 10392 enforceSystemOrRoot("Only the system is allowed to finish installs"); 10393 10394 if (DEBUG_INSTALL) { 10395 Slog.v(TAG, "BM finishing package install for " + token); 10396 } 10397 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10398 10399 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10400 mHandler.sendMessage(msg); 10401 } 10402 10403 /** 10404 * Get the verification agent timeout. 10405 * 10406 * @return verification timeout in milliseconds 10407 */ 10408 private long getVerificationTimeout() { 10409 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 10410 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 10411 DEFAULT_VERIFICATION_TIMEOUT); 10412 } 10413 10414 /** 10415 * Get the default verification agent response code. 10416 * 10417 * @return default verification response code 10418 */ 10419 private int getDefaultVerificationResponse() { 10420 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10421 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 10422 DEFAULT_VERIFICATION_RESPONSE); 10423 } 10424 10425 /** 10426 * Check whether or not package verification has been enabled. 10427 * 10428 * @return true if verification should be performed 10429 */ 10430 private boolean isVerificationEnabled(int userId, int installFlags) { 10431 if (!DEFAULT_VERIFY_ENABLE) { 10432 return false; 10433 } 10434 // Ephemeral apps don't get the full verification treatment 10435 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 10436 if (DEBUG_EPHEMERAL) { 10437 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 10438 } 10439 return false; 10440 } 10441 10442 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 10443 10444 // Check if installing from ADB 10445 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 10446 // Do not run verification in a test harness environment 10447 if (ActivityManager.isRunningInTestHarness()) { 10448 return false; 10449 } 10450 if (ensureVerifyAppsEnabled) { 10451 return true; 10452 } 10453 // Check if the developer does not want package verification for ADB installs 10454 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10455 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 10456 return false; 10457 } 10458 } 10459 10460 if (ensureVerifyAppsEnabled) { 10461 return true; 10462 } 10463 10464 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10465 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 10466 } 10467 10468 @Override 10469 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 10470 throws RemoteException { 10471 mContext.enforceCallingOrSelfPermission( 10472 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 10473 "Only intentfilter verification agents can verify applications"); 10474 10475 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 10476 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 10477 Binder.getCallingUid(), verificationCode, failedDomains); 10478 msg.arg1 = id; 10479 msg.obj = response; 10480 mHandler.sendMessage(msg); 10481 } 10482 10483 @Override 10484 public int getIntentVerificationStatus(String packageName, int userId) { 10485 synchronized (mPackages) { 10486 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 10487 } 10488 } 10489 10490 @Override 10491 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 10492 mContext.enforceCallingOrSelfPermission( 10493 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10494 10495 boolean result = false; 10496 synchronized (mPackages) { 10497 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 10498 } 10499 if (result) { 10500 scheduleWritePackageRestrictionsLocked(userId); 10501 } 10502 return result; 10503 } 10504 10505 @Override 10506 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 10507 synchronized (mPackages) { 10508 return mSettings.getIntentFilterVerificationsLPr(packageName); 10509 } 10510 } 10511 10512 @Override 10513 public List<IntentFilter> getAllIntentFilters(String packageName) { 10514 if (TextUtils.isEmpty(packageName)) { 10515 return Collections.<IntentFilter>emptyList(); 10516 } 10517 synchronized (mPackages) { 10518 PackageParser.Package pkg = mPackages.get(packageName); 10519 if (pkg == null || pkg.activities == null) { 10520 return Collections.<IntentFilter>emptyList(); 10521 } 10522 final int count = pkg.activities.size(); 10523 ArrayList<IntentFilter> result = new ArrayList<>(); 10524 for (int n=0; n<count; n++) { 10525 PackageParser.Activity activity = pkg.activities.get(n); 10526 if (activity.intents != null && activity.intents.size() > 0) { 10527 result.addAll(activity.intents); 10528 } 10529 } 10530 return result; 10531 } 10532 } 10533 10534 @Override 10535 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 10536 mContext.enforceCallingOrSelfPermission( 10537 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10538 10539 synchronized (mPackages) { 10540 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 10541 if (packageName != null) { 10542 result |= updateIntentVerificationStatus(packageName, 10543 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 10544 userId); 10545 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 10546 packageName, userId); 10547 } 10548 return result; 10549 } 10550 } 10551 10552 @Override 10553 public String getDefaultBrowserPackageName(int userId) { 10554 synchronized (mPackages) { 10555 return mSettings.getDefaultBrowserPackageNameLPw(userId); 10556 } 10557 } 10558 10559 /** 10560 * Get the "allow unknown sources" setting. 10561 * 10562 * @return the current "allow unknown sources" setting 10563 */ 10564 private int getUnknownSourcesSettings() { 10565 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10566 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 10567 -1); 10568 } 10569 10570 @Override 10571 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 10572 final int uid = Binder.getCallingUid(); 10573 // writer 10574 synchronized (mPackages) { 10575 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 10576 if (targetPackageSetting == null) { 10577 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 10578 } 10579 10580 PackageSetting installerPackageSetting; 10581 if (installerPackageName != null) { 10582 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 10583 if (installerPackageSetting == null) { 10584 throw new IllegalArgumentException("Unknown installer package: " 10585 + installerPackageName); 10586 } 10587 } else { 10588 installerPackageSetting = null; 10589 } 10590 10591 Signature[] callerSignature; 10592 Object obj = mSettings.getUserIdLPr(uid); 10593 if (obj != null) { 10594 if (obj instanceof SharedUserSetting) { 10595 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 10596 } else if (obj instanceof PackageSetting) { 10597 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 10598 } else { 10599 throw new SecurityException("Bad object " + obj + " for uid " + uid); 10600 } 10601 } else { 10602 throw new SecurityException("Unknown calling UID: " + uid); 10603 } 10604 10605 // Verify: can't set installerPackageName to a package that is 10606 // not signed with the same cert as the caller. 10607 if (installerPackageSetting != null) { 10608 if (compareSignatures(callerSignature, 10609 installerPackageSetting.signatures.mSignatures) 10610 != PackageManager.SIGNATURE_MATCH) { 10611 throw new SecurityException( 10612 "Caller does not have same cert as new installer package " 10613 + installerPackageName); 10614 } 10615 } 10616 10617 // Verify: if target already has an installer package, it must 10618 // be signed with the same cert as the caller. 10619 if (targetPackageSetting.installerPackageName != null) { 10620 PackageSetting setting = mSettings.mPackages.get( 10621 targetPackageSetting.installerPackageName); 10622 // If the currently set package isn't valid, then it's always 10623 // okay to change it. 10624 if (setting != null) { 10625 if (compareSignatures(callerSignature, 10626 setting.signatures.mSignatures) 10627 != PackageManager.SIGNATURE_MATCH) { 10628 throw new SecurityException( 10629 "Caller does not have same cert as old installer package " 10630 + targetPackageSetting.installerPackageName); 10631 } 10632 } 10633 } 10634 10635 // Okay! 10636 targetPackageSetting.installerPackageName = installerPackageName; 10637 scheduleWriteSettingsLocked(); 10638 } 10639 } 10640 10641 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 10642 // Queue up an async operation since the package installation may take a little while. 10643 mHandler.post(new Runnable() { 10644 public void run() { 10645 mHandler.removeCallbacks(this); 10646 // Result object to be returned 10647 PackageInstalledInfo res = new PackageInstalledInfo(); 10648 res.returnCode = currentStatus; 10649 res.uid = -1; 10650 res.pkg = null; 10651 res.removedInfo = new PackageRemovedInfo(); 10652 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10653 args.doPreInstall(res.returnCode); 10654 synchronized (mInstallLock) { 10655 installPackageTracedLI(args, res); 10656 } 10657 args.doPostInstall(res.returnCode, res.uid); 10658 } 10659 10660 // A restore should be performed at this point if (a) the install 10661 // succeeded, (b) the operation is not an update, and (c) the new 10662 // package has not opted out of backup participation. 10663 final boolean update = res.removedInfo.removedPackage != null; 10664 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 10665 boolean doRestore = !update 10666 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 10667 10668 // Set up the post-install work request bookkeeping. This will be used 10669 // and cleaned up by the post-install event handling regardless of whether 10670 // there's a restore pass performed. Token values are >= 1. 10671 int token; 10672 if (mNextInstallToken < 0) mNextInstallToken = 1; 10673 token = mNextInstallToken++; 10674 10675 PostInstallData data = new PostInstallData(args, res); 10676 mRunningInstalls.put(token, data); 10677 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 10678 10679 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 10680 // Pass responsibility to the Backup Manager. It will perform a 10681 // restore if appropriate, then pass responsibility back to the 10682 // Package Manager to run the post-install observer callbacks 10683 // and broadcasts. 10684 IBackupManager bm = IBackupManager.Stub.asInterface( 10685 ServiceManager.getService(Context.BACKUP_SERVICE)); 10686 if (bm != null) { 10687 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 10688 + " to BM for possible restore"); 10689 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10690 try { 10691 // TODO: http://b/22388012 10692 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 10693 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 10694 } else { 10695 doRestore = false; 10696 } 10697 } catch (RemoteException e) { 10698 // can't happen; the backup manager is local 10699 } catch (Exception e) { 10700 Slog.e(TAG, "Exception trying to enqueue restore", e); 10701 doRestore = false; 10702 } 10703 } else { 10704 Slog.e(TAG, "Backup Manager not found!"); 10705 doRestore = false; 10706 } 10707 } 10708 10709 if (!doRestore) { 10710 // No restore possible, or the Backup Manager was mysteriously not 10711 // available -- just fire the post-install work request directly. 10712 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 10713 10714 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 10715 10716 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10717 mHandler.sendMessage(msg); 10718 } 10719 } 10720 }); 10721 } 10722 10723 private abstract class HandlerParams { 10724 private static final int MAX_RETRIES = 4; 10725 10726 /** 10727 * Number of times startCopy() has been attempted and had a non-fatal 10728 * error. 10729 */ 10730 private int mRetries = 0; 10731 10732 /** User handle for the user requesting the information or installation. */ 10733 private final UserHandle mUser; 10734 String traceMethod; 10735 int traceCookie; 10736 10737 HandlerParams(UserHandle user) { 10738 mUser = user; 10739 } 10740 10741 UserHandle getUser() { 10742 return mUser; 10743 } 10744 10745 HandlerParams setTraceMethod(String traceMethod) { 10746 this.traceMethod = traceMethod; 10747 return this; 10748 } 10749 10750 HandlerParams setTraceCookie(int traceCookie) { 10751 this.traceCookie = traceCookie; 10752 return this; 10753 } 10754 10755 final boolean startCopy() { 10756 boolean res; 10757 try { 10758 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 10759 10760 if (++mRetries > MAX_RETRIES) { 10761 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 10762 mHandler.sendEmptyMessage(MCS_GIVE_UP); 10763 handleServiceError(); 10764 return false; 10765 } else { 10766 handleStartCopy(); 10767 res = true; 10768 } 10769 } catch (RemoteException e) { 10770 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 10771 mHandler.sendEmptyMessage(MCS_RECONNECT); 10772 res = false; 10773 } 10774 handleReturnCode(); 10775 return res; 10776 } 10777 10778 final void serviceError() { 10779 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 10780 handleServiceError(); 10781 handleReturnCode(); 10782 } 10783 10784 abstract void handleStartCopy() throws RemoteException; 10785 abstract void handleServiceError(); 10786 abstract void handleReturnCode(); 10787 } 10788 10789 class MeasureParams extends HandlerParams { 10790 private final PackageStats mStats; 10791 private boolean mSuccess; 10792 10793 private final IPackageStatsObserver mObserver; 10794 10795 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 10796 super(new UserHandle(stats.userHandle)); 10797 mObserver = observer; 10798 mStats = stats; 10799 } 10800 10801 @Override 10802 public String toString() { 10803 return "MeasureParams{" 10804 + Integer.toHexString(System.identityHashCode(this)) 10805 + " " + mStats.packageName + "}"; 10806 } 10807 10808 @Override 10809 void handleStartCopy() throws RemoteException { 10810 synchronized (mInstallLock) { 10811 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 10812 } 10813 10814 if (mSuccess) { 10815 final boolean mounted; 10816 if (Environment.isExternalStorageEmulated()) { 10817 mounted = true; 10818 } else { 10819 final String status = Environment.getExternalStorageState(); 10820 mounted = (Environment.MEDIA_MOUNTED.equals(status) 10821 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 10822 } 10823 10824 if (mounted) { 10825 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 10826 10827 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 10828 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 10829 10830 mStats.externalDataSize = calculateDirectorySize(mContainerService, 10831 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 10832 10833 // Always subtract cache size, since it's a subdirectory 10834 mStats.externalDataSize -= mStats.externalCacheSize; 10835 10836 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 10837 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 10838 10839 mStats.externalObbSize = calculateDirectorySize(mContainerService, 10840 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 10841 } 10842 } 10843 } 10844 10845 @Override 10846 void handleReturnCode() { 10847 if (mObserver != null) { 10848 try { 10849 mObserver.onGetStatsCompleted(mStats, mSuccess); 10850 } catch (RemoteException e) { 10851 Slog.i(TAG, "Observer no longer exists."); 10852 } 10853 } 10854 } 10855 10856 @Override 10857 void handleServiceError() { 10858 Slog.e(TAG, "Could not measure application " + mStats.packageName 10859 + " external storage"); 10860 } 10861 } 10862 10863 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 10864 throws RemoteException { 10865 long result = 0; 10866 for (File path : paths) { 10867 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 10868 } 10869 return result; 10870 } 10871 10872 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 10873 for (File path : paths) { 10874 try { 10875 mcs.clearDirectory(path.getAbsolutePath()); 10876 } catch (RemoteException e) { 10877 } 10878 } 10879 } 10880 10881 static class OriginInfo { 10882 /** 10883 * Location where install is coming from, before it has been 10884 * copied/renamed into place. This could be a single monolithic APK 10885 * file, or a cluster directory. This location may be untrusted. 10886 */ 10887 final File file; 10888 final String cid; 10889 10890 /** 10891 * Flag indicating that {@link #file} or {@link #cid} has already been 10892 * staged, meaning downstream users don't need to defensively copy the 10893 * contents. 10894 */ 10895 final boolean staged; 10896 10897 /** 10898 * Flag indicating that {@link #file} or {@link #cid} is an already 10899 * installed app that is being moved. 10900 */ 10901 final boolean existing; 10902 10903 final String resolvedPath; 10904 final File resolvedFile; 10905 10906 static OriginInfo fromNothing() { 10907 return new OriginInfo(null, null, false, false); 10908 } 10909 10910 static OriginInfo fromUntrustedFile(File file) { 10911 return new OriginInfo(file, null, false, false); 10912 } 10913 10914 static OriginInfo fromExistingFile(File file) { 10915 return new OriginInfo(file, null, false, true); 10916 } 10917 10918 static OriginInfo fromStagedFile(File file) { 10919 return new OriginInfo(file, null, true, false); 10920 } 10921 10922 static OriginInfo fromStagedContainer(String cid) { 10923 return new OriginInfo(null, cid, true, false); 10924 } 10925 10926 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 10927 this.file = file; 10928 this.cid = cid; 10929 this.staged = staged; 10930 this.existing = existing; 10931 10932 if (cid != null) { 10933 resolvedPath = PackageHelper.getSdDir(cid); 10934 resolvedFile = new File(resolvedPath); 10935 } else if (file != null) { 10936 resolvedPath = file.getAbsolutePath(); 10937 resolvedFile = file; 10938 } else { 10939 resolvedPath = null; 10940 resolvedFile = null; 10941 } 10942 } 10943 } 10944 10945 static class MoveInfo { 10946 final int moveId; 10947 final String fromUuid; 10948 final String toUuid; 10949 final String packageName; 10950 final String dataAppName; 10951 final int appId; 10952 final String seinfo; 10953 final int targetSdkVersion; 10954 10955 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 10956 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 10957 this.moveId = moveId; 10958 this.fromUuid = fromUuid; 10959 this.toUuid = toUuid; 10960 this.packageName = packageName; 10961 this.dataAppName = dataAppName; 10962 this.appId = appId; 10963 this.seinfo = seinfo; 10964 this.targetSdkVersion = targetSdkVersion; 10965 } 10966 } 10967 10968 class InstallParams extends HandlerParams { 10969 final OriginInfo origin; 10970 final MoveInfo move; 10971 final IPackageInstallObserver2 observer; 10972 int installFlags; 10973 final String installerPackageName; 10974 final String volumeUuid; 10975 final VerificationParams verificationParams; 10976 private InstallArgs mArgs; 10977 private int mRet; 10978 final String packageAbiOverride; 10979 final String[] grantedRuntimePermissions; 10980 10981 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10982 int installFlags, String installerPackageName, String volumeUuid, 10983 VerificationParams verificationParams, UserHandle user, String packageAbiOverride, 10984 String[] grantedPermissions) { 10985 super(user); 10986 this.origin = origin; 10987 this.move = move; 10988 this.observer = observer; 10989 this.installFlags = installFlags; 10990 this.installerPackageName = installerPackageName; 10991 this.volumeUuid = volumeUuid; 10992 this.verificationParams = verificationParams; 10993 this.packageAbiOverride = packageAbiOverride; 10994 this.grantedRuntimePermissions = grantedPermissions; 10995 } 10996 10997 @Override 10998 public String toString() { 10999 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 11000 + " file=" + origin.file + " cid=" + origin.cid + "}"; 11001 } 11002 11003 private int installLocationPolicy(PackageInfoLite pkgLite) { 11004 String packageName = pkgLite.packageName; 11005 int installLocation = pkgLite.installLocation; 11006 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11007 // reader 11008 synchronized (mPackages) { 11009 PackageParser.Package pkg = mPackages.get(packageName); 11010 if (pkg != null) { 11011 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 11012 // Check for downgrading. 11013 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 11014 try { 11015 checkDowngrade(pkg, pkgLite); 11016 } catch (PackageManagerException e) { 11017 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 11018 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 11019 } 11020 } 11021 // Check for updated system application. 11022 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 11023 if (onSd) { 11024 Slog.w(TAG, "Cannot install update to system app on sdcard"); 11025 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 11026 } 11027 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11028 } else { 11029 if (onSd) { 11030 // Install flag overrides everything. 11031 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11032 } 11033 // If current upgrade specifies particular preference 11034 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 11035 // Application explicitly specified internal. 11036 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11037 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 11038 // App explictly prefers external. Let policy decide 11039 } else { 11040 // Prefer previous location 11041 if (isExternal(pkg)) { 11042 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11043 } 11044 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11045 } 11046 } 11047 } else { 11048 // Invalid install. Return error code 11049 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 11050 } 11051 } 11052 } 11053 // All the special cases have been taken care of. 11054 // Return result based on recommended install location. 11055 if (onSd) { 11056 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11057 } 11058 return pkgLite.recommendedInstallLocation; 11059 } 11060 11061 /* 11062 * Invoke remote method to get package information and install 11063 * location values. Override install location based on default 11064 * policy if needed and then create install arguments based 11065 * on the install location. 11066 */ 11067 public void handleStartCopy() throws RemoteException { 11068 int ret = PackageManager.INSTALL_SUCCEEDED; 11069 11070 // If we're already staged, we've firmly committed to an install location 11071 if (origin.staged) { 11072 if (origin.file != null) { 11073 installFlags |= PackageManager.INSTALL_INTERNAL; 11074 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 11075 } else if (origin.cid != null) { 11076 installFlags |= PackageManager.INSTALL_EXTERNAL; 11077 installFlags &= ~PackageManager.INSTALL_INTERNAL; 11078 } else { 11079 throw new IllegalStateException("Invalid stage location"); 11080 } 11081 } 11082 11083 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11084 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 11085 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 11086 PackageInfoLite pkgLite = null; 11087 11088 if (onInt && onSd) { 11089 // Check if both bits are set. 11090 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 11091 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11092 } else if (onSd && ephemeral) { 11093 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 11094 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11095 } else { 11096 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 11097 packageAbiOverride); 11098 11099 if (DEBUG_EPHEMERAL && ephemeral) { 11100 Slog.v(TAG, "pkgLite for install: " + pkgLite); 11101 } 11102 11103 /* 11104 * If we have too little free space, try to free cache 11105 * before giving up. 11106 */ 11107 if (!origin.staged && pkgLite.recommendedInstallLocation 11108 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 11109 // TODO: focus freeing disk space on the target device 11110 final StorageManager storage = StorageManager.from(mContext); 11111 final long lowThreshold = storage.getStorageLowBytes( 11112 Environment.getDataDirectory()); 11113 11114 final long sizeBytes = mContainerService.calculateInstalledSize( 11115 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 11116 11117 try { 11118 mInstaller.freeCache(null, sizeBytes + lowThreshold); 11119 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 11120 installFlags, packageAbiOverride); 11121 } catch (InstallerException e) { 11122 Slog.w(TAG, "Failed to free cache", e); 11123 } 11124 11125 /* 11126 * The cache free must have deleted the file we 11127 * downloaded to install. 11128 * 11129 * TODO: fix the "freeCache" call to not delete 11130 * the file we care about. 11131 */ 11132 if (pkgLite.recommendedInstallLocation 11133 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 11134 pkgLite.recommendedInstallLocation 11135 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 11136 } 11137 } 11138 } 11139 11140 if (ret == PackageManager.INSTALL_SUCCEEDED) { 11141 int loc = pkgLite.recommendedInstallLocation; 11142 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 11143 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11144 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 11145 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 11146 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 11147 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11148 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 11149 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 11150 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 11151 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 11152 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 11153 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 11154 } else { 11155 // Override with defaults if needed. 11156 loc = installLocationPolicy(pkgLite); 11157 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 11158 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 11159 } else if (!onSd && !onInt) { 11160 // Override install location with flags 11161 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 11162 // Set the flag to install on external media. 11163 installFlags |= PackageManager.INSTALL_EXTERNAL; 11164 installFlags &= ~PackageManager.INSTALL_INTERNAL; 11165 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 11166 if (DEBUG_EPHEMERAL) { 11167 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 11168 } 11169 installFlags |= PackageManager.INSTALL_EPHEMERAL; 11170 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 11171 |PackageManager.INSTALL_INTERNAL); 11172 } else { 11173 // Make sure the flag for installing on external 11174 // media is unset 11175 installFlags |= PackageManager.INSTALL_INTERNAL; 11176 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 11177 } 11178 } 11179 } 11180 } 11181 11182 final InstallArgs args = createInstallArgs(this); 11183 mArgs = args; 11184 11185 if (ret == PackageManager.INSTALL_SUCCEEDED) { 11186 // TODO: http://b/22976637 11187 // Apps installed for "all" users use the device owner to verify the app 11188 UserHandle verifierUser = getUser(); 11189 if (verifierUser == UserHandle.ALL) { 11190 verifierUser = UserHandle.SYSTEM; 11191 } 11192 11193 /* 11194 * Determine if we have any installed package verifiers. If we 11195 * do, then we'll defer to them to verify the packages. 11196 */ 11197 final int requiredUid = mRequiredVerifierPackage == null ? -1 11198 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 11199 verifierUser.getIdentifier()); 11200 if (!origin.existing && requiredUid != -1 11201 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 11202 final Intent verification = new Intent( 11203 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 11204 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 11205 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 11206 PACKAGE_MIME_TYPE); 11207 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11208 11209 // Query all live verifiers based on current user state 11210 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 11211 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 11212 11213 if (DEBUG_VERIFY) { 11214 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 11215 + verification.toString() + " with " + pkgLite.verifiers.length 11216 + " optional verifiers"); 11217 } 11218 11219 final int verificationId = mPendingVerificationToken++; 11220 11221 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11222 11223 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 11224 installerPackageName); 11225 11226 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 11227 installFlags); 11228 11229 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 11230 pkgLite.packageName); 11231 11232 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 11233 pkgLite.versionCode); 11234 11235 if (verificationParams != null) { 11236 if (verificationParams.getVerificationURI() != null) { 11237 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 11238 verificationParams.getVerificationURI()); 11239 } 11240 if (verificationParams.getOriginatingURI() != null) { 11241 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 11242 verificationParams.getOriginatingURI()); 11243 } 11244 if (verificationParams.getReferrer() != null) { 11245 verification.putExtra(Intent.EXTRA_REFERRER, 11246 verificationParams.getReferrer()); 11247 } 11248 if (verificationParams.getOriginatingUid() >= 0) { 11249 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 11250 verificationParams.getOriginatingUid()); 11251 } 11252 if (verificationParams.getInstallerUid() >= 0) { 11253 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 11254 verificationParams.getInstallerUid()); 11255 } 11256 } 11257 11258 final PackageVerificationState verificationState = new PackageVerificationState( 11259 requiredUid, args); 11260 11261 mPendingVerification.append(verificationId, verificationState); 11262 11263 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 11264 receivers, verificationState); 11265 11266 /* 11267 * If any sufficient verifiers were listed in the package 11268 * manifest, attempt to ask them. 11269 */ 11270 if (sufficientVerifiers != null) { 11271 final int N = sufficientVerifiers.size(); 11272 if (N == 0) { 11273 Slog.i(TAG, "Additional verifiers required, but none installed."); 11274 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 11275 } else { 11276 for (int i = 0; i < N; i++) { 11277 final ComponentName verifierComponent = sufficientVerifiers.get(i); 11278 11279 final Intent sufficientIntent = new Intent(verification); 11280 sufficientIntent.setComponent(verifierComponent); 11281 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 11282 } 11283 } 11284 } 11285 11286 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 11287 mRequiredVerifierPackage, receivers); 11288 if (ret == PackageManager.INSTALL_SUCCEEDED 11289 && mRequiredVerifierPackage != null) { 11290 Trace.asyncTraceBegin( 11291 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 11292 /* 11293 * Send the intent to the required verification agent, 11294 * but only start the verification timeout after the 11295 * target BroadcastReceivers have run. 11296 */ 11297 verification.setComponent(requiredVerifierComponent); 11298 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 11299 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11300 new BroadcastReceiver() { 11301 @Override 11302 public void onReceive(Context context, Intent intent) { 11303 final Message msg = mHandler 11304 .obtainMessage(CHECK_PENDING_VERIFICATION); 11305 msg.arg1 = verificationId; 11306 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 11307 } 11308 }, null, 0, null, null); 11309 11310 /* 11311 * We don't want the copy to proceed until verification 11312 * succeeds, so null out this field. 11313 */ 11314 mArgs = null; 11315 } 11316 } else { 11317 /* 11318 * No package verification is enabled, so immediately start 11319 * the remote call to initiate copy using temporary file. 11320 */ 11321 ret = args.copyApk(mContainerService, true); 11322 } 11323 } 11324 11325 mRet = ret; 11326 } 11327 11328 @Override 11329 void handleReturnCode() { 11330 // If mArgs is null, then MCS couldn't be reached. When it 11331 // reconnects, it will try again to install. At that point, this 11332 // will succeed. 11333 if (mArgs != null) { 11334 processPendingInstall(mArgs, mRet); 11335 } 11336 } 11337 11338 @Override 11339 void handleServiceError() { 11340 mArgs = createInstallArgs(this); 11341 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11342 } 11343 11344 public boolean isForwardLocked() { 11345 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11346 } 11347 } 11348 11349 /** 11350 * Used during creation of InstallArgs 11351 * 11352 * @param installFlags package installation flags 11353 * @return true if should be installed on external storage 11354 */ 11355 private static boolean installOnExternalAsec(int installFlags) { 11356 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 11357 return false; 11358 } 11359 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 11360 return true; 11361 } 11362 return false; 11363 } 11364 11365 /** 11366 * Used during creation of InstallArgs 11367 * 11368 * @param installFlags package installation flags 11369 * @return true if should be installed as forward locked 11370 */ 11371 private static boolean installForwardLocked(int installFlags) { 11372 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11373 } 11374 11375 private InstallArgs createInstallArgs(InstallParams params) { 11376 if (params.move != null) { 11377 return new MoveInstallArgs(params); 11378 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 11379 return new AsecInstallArgs(params); 11380 } else { 11381 return new FileInstallArgs(params); 11382 } 11383 } 11384 11385 /** 11386 * Create args that describe an existing installed package. Typically used 11387 * when cleaning up old installs, or used as a move source. 11388 */ 11389 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 11390 String resourcePath, String[] instructionSets) { 11391 final boolean isInAsec; 11392 if (installOnExternalAsec(installFlags)) { 11393 /* Apps on SD card are always in ASEC containers. */ 11394 isInAsec = true; 11395 } else if (installForwardLocked(installFlags) 11396 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 11397 /* 11398 * Forward-locked apps are only in ASEC containers if they're the 11399 * new style 11400 */ 11401 isInAsec = true; 11402 } else { 11403 isInAsec = false; 11404 } 11405 11406 if (isInAsec) { 11407 return new AsecInstallArgs(codePath, instructionSets, 11408 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 11409 } else { 11410 return new FileInstallArgs(codePath, resourcePath, instructionSets); 11411 } 11412 } 11413 11414 static abstract class InstallArgs { 11415 /** @see InstallParams#origin */ 11416 final OriginInfo origin; 11417 /** @see InstallParams#move */ 11418 final MoveInfo move; 11419 11420 final IPackageInstallObserver2 observer; 11421 // Always refers to PackageManager flags only 11422 final int installFlags; 11423 final String installerPackageName; 11424 final String volumeUuid; 11425 final UserHandle user; 11426 final String abiOverride; 11427 final String[] installGrantPermissions; 11428 /** If non-null, drop an async trace when the install completes */ 11429 final String traceMethod; 11430 final int traceCookie; 11431 11432 // The list of instruction sets supported by this app. This is currently 11433 // only used during the rmdex() phase to clean up resources. We can get rid of this 11434 // if we move dex files under the common app path. 11435 /* nullable */ String[] instructionSets; 11436 11437 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 11438 int installFlags, String installerPackageName, String volumeUuid, 11439 UserHandle user, String[] instructionSets, 11440 String abiOverride, String[] installGrantPermissions, 11441 String traceMethod, int traceCookie) { 11442 this.origin = origin; 11443 this.move = move; 11444 this.installFlags = installFlags; 11445 this.observer = observer; 11446 this.installerPackageName = installerPackageName; 11447 this.volumeUuid = volumeUuid; 11448 this.user = user; 11449 this.instructionSets = instructionSets; 11450 this.abiOverride = abiOverride; 11451 this.installGrantPermissions = installGrantPermissions; 11452 this.traceMethod = traceMethod; 11453 this.traceCookie = traceCookie; 11454 } 11455 11456 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 11457 abstract int doPreInstall(int status); 11458 11459 /** 11460 * Rename package into final resting place. All paths on the given 11461 * scanned package should be updated to reflect the rename. 11462 */ 11463 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 11464 abstract int doPostInstall(int status, int uid); 11465 11466 /** @see PackageSettingBase#codePathString */ 11467 abstract String getCodePath(); 11468 /** @see PackageSettingBase#resourcePathString */ 11469 abstract String getResourcePath(); 11470 11471 // Need installer lock especially for dex file removal. 11472 abstract void cleanUpResourcesLI(); 11473 abstract boolean doPostDeleteLI(boolean delete); 11474 11475 /** 11476 * Called before the source arguments are copied. This is used mostly 11477 * for MoveParams when it needs to read the source file to put it in the 11478 * destination. 11479 */ 11480 int doPreCopy() { 11481 return PackageManager.INSTALL_SUCCEEDED; 11482 } 11483 11484 /** 11485 * Called after the source arguments are copied. This is used mostly for 11486 * MoveParams when it needs to read the source file to put it in the 11487 * destination. 11488 * 11489 * @return 11490 */ 11491 int doPostCopy(int uid) { 11492 return PackageManager.INSTALL_SUCCEEDED; 11493 } 11494 11495 protected boolean isFwdLocked() { 11496 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11497 } 11498 11499 protected boolean isExternalAsec() { 11500 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11501 } 11502 11503 protected boolean isEphemeral() { 11504 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 11505 } 11506 11507 UserHandle getUser() { 11508 return user; 11509 } 11510 } 11511 11512 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 11513 if (!allCodePaths.isEmpty()) { 11514 if (instructionSets == null) { 11515 throw new IllegalStateException("instructionSet == null"); 11516 } 11517 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 11518 for (String codePath : allCodePaths) { 11519 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 11520 try { 11521 mInstaller.rmdex(codePath, dexCodeInstructionSet); 11522 } catch (InstallerException ignored) { 11523 } 11524 } 11525 } 11526 } 11527 } 11528 11529 /** 11530 * Logic to handle installation of non-ASEC applications, including copying 11531 * and renaming logic. 11532 */ 11533 class FileInstallArgs extends InstallArgs { 11534 private File codeFile; 11535 private File resourceFile; 11536 11537 // Example topology: 11538 // /data/app/com.example/base.apk 11539 // /data/app/com.example/split_foo.apk 11540 // /data/app/com.example/lib/arm/libfoo.so 11541 // /data/app/com.example/lib/arm64/libfoo.so 11542 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 11543 11544 /** New install */ 11545 FileInstallArgs(InstallParams params) { 11546 super(params.origin, params.move, params.observer, params.installFlags, 11547 params.installerPackageName, params.volumeUuid, 11548 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11549 params.grantedRuntimePermissions, 11550 params.traceMethod, params.traceCookie); 11551 if (isFwdLocked()) { 11552 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 11553 } 11554 } 11555 11556 /** Existing install */ 11557 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 11558 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 11559 null, null, null, 0); 11560 this.codeFile = (codePath != null) ? new File(codePath) : null; 11561 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 11562 } 11563 11564 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11565 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 11566 try { 11567 return doCopyApk(imcs, temp); 11568 } finally { 11569 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11570 } 11571 } 11572 11573 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11574 if (origin.staged) { 11575 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 11576 codeFile = origin.file; 11577 resourceFile = origin.file; 11578 return PackageManager.INSTALL_SUCCEEDED; 11579 } 11580 11581 try { 11582 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 11583 final File tempDir = 11584 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 11585 codeFile = tempDir; 11586 resourceFile = tempDir; 11587 } catch (IOException e) { 11588 Slog.w(TAG, "Failed to create copy file: " + e); 11589 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11590 } 11591 11592 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 11593 @Override 11594 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 11595 if (!FileUtils.isValidExtFilename(name)) { 11596 throw new IllegalArgumentException("Invalid filename: " + name); 11597 } 11598 try { 11599 final File file = new File(codeFile, name); 11600 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 11601 O_RDWR | O_CREAT, 0644); 11602 Os.chmod(file.getAbsolutePath(), 0644); 11603 return new ParcelFileDescriptor(fd); 11604 } catch (ErrnoException e) { 11605 throw new RemoteException("Failed to open: " + e.getMessage()); 11606 } 11607 } 11608 }; 11609 11610 int ret = PackageManager.INSTALL_SUCCEEDED; 11611 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 11612 if (ret != PackageManager.INSTALL_SUCCEEDED) { 11613 Slog.e(TAG, "Failed to copy package"); 11614 return ret; 11615 } 11616 11617 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 11618 NativeLibraryHelper.Handle handle = null; 11619 try { 11620 handle = NativeLibraryHelper.Handle.create(codeFile); 11621 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 11622 abiOverride); 11623 } catch (IOException e) { 11624 Slog.e(TAG, "Copying native libraries failed", e); 11625 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11626 } finally { 11627 IoUtils.closeQuietly(handle); 11628 } 11629 11630 return ret; 11631 } 11632 11633 int doPreInstall(int status) { 11634 if (status != PackageManager.INSTALL_SUCCEEDED) { 11635 cleanUp(); 11636 } 11637 return status; 11638 } 11639 11640 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11641 if (status != PackageManager.INSTALL_SUCCEEDED) { 11642 cleanUp(); 11643 return false; 11644 } 11645 11646 final File targetDir = codeFile.getParentFile(); 11647 final File beforeCodeFile = codeFile; 11648 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 11649 11650 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 11651 try { 11652 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 11653 } catch (ErrnoException e) { 11654 Slog.w(TAG, "Failed to rename", e); 11655 return false; 11656 } 11657 11658 if (!SELinux.restoreconRecursive(afterCodeFile)) { 11659 Slog.w(TAG, "Failed to restorecon"); 11660 return false; 11661 } 11662 11663 // Reflect the rename internally 11664 codeFile = afterCodeFile; 11665 resourceFile = afterCodeFile; 11666 11667 // Reflect the rename in scanned details 11668 pkg.codePath = afterCodeFile.getAbsolutePath(); 11669 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11670 pkg.baseCodePath); 11671 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11672 pkg.splitCodePaths); 11673 11674 // Reflect the rename in app info 11675 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11676 pkg.applicationInfo.setCodePath(pkg.codePath); 11677 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11678 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11679 pkg.applicationInfo.setResourcePath(pkg.codePath); 11680 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11681 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11682 11683 return true; 11684 } 11685 11686 int doPostInstall(int status, int uid) { 11687 if (status != PackageManager.INSTALL_SUCCEEDED) { 11688 cleanUp(); 11689 } 11690 return status; 11691 } 11692 11693 @Override 11694 String getCodePath() { 11695 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11696 } 11697 11698 @Override 11699 String getResourcePath() { 11700 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11701 } 11702 11703 private boolean cleanUp() { 11704 if (codeFile == null || !codeFile.exists()) { 11705 return false; 11706 } 11707 11708 removeCodePathLI(codeFile); 11709 11710 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 11711 resourceFile.delete(); 11712 } 11713 11714 return true; 11715 } 11716 11717 void cleanUpResourcesLI() { 11718 // Try enumerating all code paths before deleting 11719 List<String> allCodePaths = Collections.EMPTY_LIST; 11720 if (codeFile != null && codeFile.exists()) { 11721 try { 11722 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11723 allCodePaths = pkg.getAllCodePaths(); 11724 } catch (PackageParserException e) { 11725 // Ignored; we tried our best 11726 } 11727 } 11728 11729 cleanUp(); 11730 removeDexFiles(allCodePaths, instructionSets); 11731 } 11732 11733 boolean doPostDeleteLI(boolean delete) { 11734 // XXX err, shouldn't we respect the delete flag? 11735 cleanUpResourcesLI(); 11736 return true; 11737 } 11738 } 11739 11740 private boolean isAsecExternal(String cid) { 11741 final String asecPath = PackageHelper.getSdFilesystem(cid); 11742 return !asecPath.startsWith(mAsecInternalPath); 11743 } 11744 11745 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 11746 PackageManagerException { 11747 if (copyRet < 0) { 11748 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 11749 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 11750 throw new PackageManagerException(copyRet, message); 11751 } 11752 } 11753 } 11754 11755 /** 11756 * Extract the MountService "container ID" from the full code path of an 11757 * .apk. 11758 */ 11759 static String cidFromCodePath(String fullCodePath) { 11760 int eidx = fullCodePath.lastIndexOf("/"); 11761 String subStr1 = fullCodePath.substring(0, eidx); 11762 int sidx = subStr1.lastIndexOf("/"); 11763 return subStr1.substring(sidx+1, eidx); 11764 } 11765 11766 /** 11767 * Logic to handle installation of ASEC applications, including copying and 11768 * renaming logic. 11769 */ 11770 class AsecInstallArgs extends InstallArgs { 11771 static final String RES_FILE_NAME = "pkg.apk"; 11772 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 11773 11774 String cid; 11775 String packagePath; 11776 String resourcePath; 11777 11778 /** New install */ 11779 AsecInstallArgs(InstallParams params) { 11780 super(params.origin, params.move, params.observer, params.installFlags, 11781 params.installerPackageName, params.volumeUuid, 11782 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11783 params.grantedRuntimePermissions, 11784 params.traceMethod, params.traceCookie); 11785 } 11786 11787 /** Existing install */ 11788 AsecInstallArgs(String fullCodePath, String[] instructionSets, 11789 boolean isExternal, boolean isForwardLocked) { 11790 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 11791 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 11792 instructionSets, null, null, null, 0); 11793 // Hackily pretend we're still looking at a full code path 11794 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 11795 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 11796 } 11797 11798 // Extract cid from fullCodePath 11799 int eidx = fullCodePath.lastIndexOf("/"); 11800 String subStr1 = fullCodePath.substring(0, eidx); 11801 int sidx = subStr1.lastIndexOf("/"); 11802 cid = subStr1.substring(sidx+1, eidx); 11803 setMountPath(subStr1); 11804 } 11805 11806 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 11807 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 11808 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 11809 instructionSets, null, null, null, 0); 11810 this.cid = cid; 11811 setMountPath(PackageHelper.getSdDir(cid)); 11812 } 11813 11814 void createCopyFile() { 11815 cid = mInstallerService.allocateExternalStageCidLegacy(); 11816 } 11817 11818 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11819 if (origin.staged && origin.cid != null) { 11820 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 11821 cid = origin.cid; 11822 setMountPath(PackageHelper.getSdDir(cid)); 11823 return PackageManager.INSTALL_SUCCEEDED; 11824 } 11825 11826 if (temp) { 11827 createCopyFile(); 11828 } else { 11829 /* 11830 * Pre-emptively destroy the container since it's destroyed if 11831 * copying fails due to it existing anyway. 11832 */ 11833 PackageHelper.destroySdDir(cid); 11834 } 11835 11836 final String newMountPath = imcs.copyPackageToContainer( 11837 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 11838 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 11839 11840 if (newMountPath != null) { 11841 setMountPath(newMountPath); 11842 return PackageManager.INSTALL_SUCCEEDED; 11843 } else { 11844 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11845 } 11846 } 11847 11848 @Override 11849 String getCodePath() { 11850 return packagePath; 11851 } 11852 11853 @Override 11854 String getResourcePath() { 11855 return resourcePath; 11856 } 11857 11858 int doPreInstall(int status) { 11859 if (status != PackageManager.INSTALL_SUCCEEDED) { 11860 // Destroy container 11861 PackageHelper.destroySdDir(cid); 11862 } else { 11863 boolean mounted = PackageHelper.isContainerMounted(cid); 11864 if (!mounted) { 11865 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 11866 Process.SYSTEM_UID); 11867 if (newMountPath != null) { 11868 setMountPath(newMountPath); 11869 } else { 11870 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11871 } 11872 } 11873 } 11874 return status; 11875 } 11876 11877 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11878 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 11879 String newMountPath = null; 11880 if (PackageHelper.isContainerMounted(cid)) { 11881 // Unmount the container 11882 if (!PackageHelper.unMountSdDir(cid)) { 11883 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 11884 return false; 11885 } 11886 } 11887 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11888 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 11889 " which might be stale. Will try to clean up."); 11890 // Clean up the stale container and proceed to recreate. 11891 if (!PackageHelper.destroySdDir(newCacheId)) { 11892 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 11893 return false; 11894 } 11895 // Successfully cleaned up stale container. Try to rename again. 11896 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11897 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 11898 + " inspite of cleaning it up."); 11899 return false; 11900 } 11901 } 11902 if (!PackageHelper.isContainerMounted(newCacheId)) { 11903 Slog.w(TAG, "Mounting container " + newCacheId); 11904 newMountPath = PackageHelper.mountSdDir(newCacheId, 11905 getEncryptKey(), Process.SYSTEM_UID); 11906 } else { 11907 newMountPath = PackageHelper.getSdDir(newCacheId); 11908 } 11909 if (newMountPath == null) { 11910 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 11911 return false; 11912 } 11913 Log.i(TAG, "Succesfully renamed " + cid + 11914 " to " + newCacheId + 11915 " at new path: " + newMountPath); 11916 cid = newCacheId; 11917 11918 final File beforeCodeFile = new File(packagePath); 11919 setMountPath(newMountPath); 11920 final File afterCodeFile = new File(packagePath); 11921 11922 // Reflect the rename in scanned details 11923 pkg.codePath = afterCodeFile.getAbsolutePath(); 11924 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11925 pkg.baseCodePath); 11926 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11927 pkg.splitCodePaths); 11928 11929 // Reflect the rename in app info 11930 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11931 pkg.applicationInfo.setCodePath(pkg.codePath); 11932 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11933 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11934 pkg.applicationInfo.setResourcePath(pkg.codePath); 11935 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11936 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11937 11938 return true; 11939 } 11940 11941 private void setMountPath(String mountPath) { 11942 final File mountFile = new File(mountPath); 11943 11944 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 11945 if (monolithicFile.exists()) { 11946 packagePath = monolithicFile.getAbsolutePath(); 11947 if (isFwdLocked()) { 11948 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 11949 } else { 11950 resourcePath = packagePath; 11951 } 11952 } else { 11953 packagePath = mountFile.getAbsolutePath(); 11954 resourcePath = packagePath; 11955 } 11956 } 11957 11958 int doPostInstall(int status, int uid) { 11959 if (status != PackageManager.INSTALL_SUCCEEDED) { 11960 cleanUp(); 11961 } else { 11962 final int groupOwner; 11963 final String protectedFile; 11964 if (isFwdLocked()) { 11965 groupOwner = UserHandle.getSharedAppGid(uid); 11966 protectedFile = RES_FILE_NAME; 11967 } else { 11968 groupOwner = -1; 11969 protectedFile = null; 11970 } 11971 11972 if (uid < Process.FIRST_APPLICATION_UID 11973 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 11974 Slog.e(TAG, "Failed to finalize " + cid); 11975 PackageHelper.destroySdDir(cid); 11976 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11977 } 11978 11979 boolean mounted = PackageHelper.isContainerMounted(cid); 11980 if (!mounted) { 11981 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 11982 } 11983 } 11984 return status; 11985 } 11986 11987 private void cleanUp() { 11988 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 11989 11990 // Destroy secure container 11991 PackageHelper.destroySdDir(cid); 11992 } 11993 11994 private List<String> getAllCodePaths() { 11995 final File codeFile = new File(getCodePath()); 11996 if (codeFile != null && codeFile.exists()) { 11997 try { 11998 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11999 return pkg.getAllCodePaths(); 12000 } catch (PackageParserException e) { 12001 // Ignored; we tried our best 12002 } 12003 } 12004 return Collections.EMPTY_LIST; 12005 } 12006 12007 void cleanUpResourcesLI() { 12008 // Enumerate all code paths before deleting 12009 cleanUpResourcesLI(getAllCodePaths()); 12010 } 12011 12012 private void cleanUpResourcesLI(List<String> allCodePaths) { 12013 cleanUp(); 12014 removeDexFiles(allCodePaths, instructionSets); 12015 } 12016 12017 String getPackageName() { 12018 return getAsecPackageName(cid); 12019 } 12020 12021 boolean doPostDeleteLI(boolean delete) { 12022 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 12023 final List<String> allCodePaths = getAllCodePaths(); 12024 boolean mounted = PackageHelper.isContainerMounted(cid); 12025 if (mounted) { 12026 // Unmount first 12027 if (PackageHelper.unMountSdDir(cid)) { 12028 mounted = false; 12029 } 12030 } 12031 if (!mounted && delete) { 12032 cleanUpResourcesLI(allCodePaths); 12033 } 12034 return !mounted; 12035 } 12036 12037 @Override 12038 int doPreCopy() { 12039 if (isFwdLocked()) { 12040 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 12041 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 12042 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12043 } 12044 } 12045 12046 return PackageManager.INSTALL_SUCCEEDED; 12047 } 12048 12049 @Override 12050 int doPostCopy(int uid) { 12051 if (isFwdLocked()) { 12052 if (uid < Process.FIRST_APPLICATION_UID 12053 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 12054 RES_FILE_NAME)) { 12055 Slog.e(TAG, "Failed to finalize " + cid); 12056 PackageHelper.destroySdDir(cid); 12057 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12058 } 12059 } 12060 12061 return PackageManager.INSTALL_SUCCEEDED; 12062 } 12063 } 12064 12065 /** 12066 * Logic to handle movement of existing installed applications. 12067 */ 12068 class MoveInstallArgs extends InstallArgs { 12069 private File codeFile; 12070 private File resourceFile; 12071 12072 /** New install */ 12073 MoveInstallArgs(InstallParams params) { 12074 super(params.origin, params.move, params.observer, params.installFlags, 12075 params.installerPackageName, params.volumeUuid, 12076 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 12077 params.grantedRuntimePermissions, 12078 params.traceMethod, params.traceCookie); 12079 } 12080 12081 int copyApk(IMediaContainerService imcs, boolean temp) { 12082 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 12083 + move.fromUuid + " to " + move.toUuid); 12084 synchronized (mInstaller) { 12085 try { 12086 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 12087 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 12088 } catch (InstallerException e) { 12089 Slog.w(TAG, "Failed to move app", e); 12090 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12091 } 12092 } 12093 12094 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 12095 resourceFile = codeFile; 12096 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 12097 12098 return PackageManager.INSTALL_SUCCEEDED; 12099 } 12100 12101 int doPreInstall(int status) { 12102 if (status != PackageManager.INSTALL_SUCCEEDED) { 12103 cleanUp(move.toUuid); 12104 } 12105 return status; 12106 } 12107 12108 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12109 if (status != PackageManager.INSTALL_SUCCEEDED) { 12110 cleanUp(move.toUuid); 12111 return false; 12112 } 12113 12114 // Reflect the move in app info 12115 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 12116 pkg.applicationInfo.setCodePath(pkg.codePath); 12117 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 12118 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 12119 pkg.applicationInfo.setResourcePath(pkg.codePath); 12120 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 12121 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 12122 12123 return true; 12124 } 12125 12126 int doPostInstall(int status, int uid) { 12127 if (status == PackageManager.INSTALL_SUCCEEDED) { 12128 cleanUp(move.fromUuid); 12129 } else { 12130 cleanUp(move.toUuid); 12131 } 12132 return status; 12133 } 12134 12135 @Override 12136 String getCodePath() { 12137 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 12138 } 12139 12140 @Override 12141 String getResourcePath() { 12142 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 12143 } 12144 12145 private boolean cleanUp(String volumeUuid) { 12146 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 12147 move.dataAppName); 12148 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 12149 synchronized (mInstallLock) { 12150 // Clean up both app data and code 12151 removeDataDirsLI(volumeUuid, move.packageName); 12152 removeCodePathLI(codeFile); 12153 } 12154 return true; 12155 } 12156 12157 void cleanUpResourcesLI() { 12158 throw new UnsupportedOperationException(); 12159 } 12160 12161 boolean doPostDeleteLI(boolean delete) { 12162 throw new UnsupportedOperationException(); 12163 } 12164 } 12165 12166 static String getAsecPackageName(String packageCid) { 12167 int idx = packageCid.lastIndexOf("-"); 12168 if (idx == -1) { 12169 return packageCid; 12170 } 12171 return packageCid.substring(0, idx); 12172 } 12173 12174 // Utility method used to create code paths based on package name and available index. 12175 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 12176 String idxStr = ""; 12177 int idx = 1; 12178 // Fall back to default value of idx=1 if prefix is not 12179 // part of oldCodePath 12180 if (oldCodePath != null) { 12181 String subStr = oldCodePath; 12182 // Drop the suffix right away 12183 if (suffix != null && subStr.endsWith(suffix)) { 12184 subStr = subStr.substring(0, subStr.length() - suffix.length()); 12185 } 12186 // If oldCodePath already contains prefix find out the 12187 // ending index to either increment or decrement. 12188 int sidx = subStr.lastIndexOf(prefix); 12189 if (sidx != -1) { 12190 subStr = subStr.substring(sidx + prefix.length()); 12191 if (subStr != null) { 12192 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 12193 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 12194 } 12195 try { 12196 idx = Integer.parseInt(subStr); 12197 if (idx <= 1) { 12198 idx++; 12199 } else { 12200 idx--; 12201 } 12202 } catch(NumberFormatException e) { 12203 } 12204 } 12205 } 12206 } 12207 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 12208 return prefix + idxStr; 12209 } 12210 12211 private File getNextCodePath(File targetDir, String packageName) { 12212 int suffix = 1; 12213 File result; 12214 do { 12215 result = new File(targetDir, packageName + "-" + suffix); 12216 suffix++; 12217 } while (result.exists()); 12218 return result; 12219 } 12220 12221 // Utility method that returns the relative package path with respect 12222 // to the installation directory. Like say for /data/data/com.test-1.apk 12223 // string com.test-1 is returned. 12224 static String deriveCodePathName(String codePath) { 12225 if (codePath == null) { 12226 return null; 12227 } 12228 final File codeFile = new File(codePath); 12229 final String name = codeFile.getName(); 12230 if (codeFile.isDirectory()) { 12231 return name; 12232 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 12233 final int lastDot = name.lastIndexOf('.'); 12234 return name.substring(0, lastDot); 12235 } else { 12236 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 12237 return null; 12238 } 12239 } 12240 12241 static class PackageInstalledInfo { 12242 String name; 12243 int uid; 12244 // The set of users that originally had this package installed. 12245 int[] origUsers; 12246 // The set of users that now have this package installed. 12247 int[] newUsers; 12248 PackageParser.Package pkg; 12249 int returnCode; 12250 String returnMsg; 12251 PackageRemovedInfo removedInfo; 12252 12253 public void setError(int code, String msg) { 12254 returnCode = code; 12255 returnMsg = msg; 12256 Slog.w(TAG, msg); 12257 } 12258 12259 public void setError(String msg, PackageParserException e) { 12260 returnCode = e.error; 12261 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 12262 Slog.w(TAG, msg, e); 12263 } 12264 12265 public void setError(String msg, PackageManagerException e) { 12266 returnCode = e.error; 12267 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 12268 Slog.w(TAG, msg, e); 12269 } 12270 12271 // In some error cases we want to convey more info back to the observer 12272 String origPackage; 12273 String origPermission; 12274 } 12275 12276 /* 12277 * Install a non-existing package. 12278 */ 12279 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 12280 UserHandle user, String installerPackageName, String volumeUuid, 12281 PackageInstalledInfo res) { 12282 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 12283 12284 // Remember this for later, in case we need to rollback this install 12285 String pkgName = pkg.packageName; 12286 12287 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 12288 // TODO: b/23350563 12289 final boolean dataDirExists = Environment 12290 .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists(); 12291 12292 synchronized(mPackages) { 12293 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 12294 // A package with the same name is already installed, though 12295 // it has been renamed to an older name. The package we 12296 // are trying to install should be installed as an update to 12297 // the existing one, but that has not been requested, so bail. 12298 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 12299 + " without first uninstalling package running as " 12300 + mSettings.mRenamedPackages.get(pkgName)); 12301 return; 12302 } 12303 if (mPackages.containsKey(pkgName)) { 12304 // Don't allow installation over an existing package with the same name. 12305 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 12306 + " without first uninstalling."); 12307 return; 12308 } 12309 } 12310 12311 try { 12312 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 12313 System.currentTimeMillis(), user); 12314 12315 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 12316 prepareAppDataAfterInstall(newPackage); 12317 12318 // delete the partially installed application. the data directory will have to be 12319 // restored if it was already existing 12320 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12321 // remove package from internal structures. Note that we want deletePackageX to 12322 // delete the package data and cache directories that it created in 12323 // scanPackageLocked, unless those directories existed before we even tried to 12324 // install. 12325 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 12326 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 12327 res.removedInfo, true); 12328 } 12329 12330 } catch (PackageManagerException e) { 12331 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12332 } 12333 12334 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12335 } 12336 12337 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 12338 // Can't rotate keys during boot or if sharedUser. 12339 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 12340 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 12341 return false; 12342 } 12343 // app is using upgradeKeySets; make sure all are valid 12344 KeySetManagerService ksms = mSettings.mKeySetManagerService; 12345 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 12346 for (int i = 0; i < upgradeKeySets.length; i++) { 12347 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 12348 Slog.wtf(TAG, "Package " 12349 + (oldPs.name != null ? oldPs.name : "<null>") 12350 + " contains upgrade-key-set reference to unknown key-set: " 12351 + upgradeKeySets[i] 12352 + " reverting to signatures check."); 12353 return false; 12354 } 12355 } 12356 return true; 12357 } 12358 12359 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 12360 // Upgrade keysets are being used. Determine if new package has a superset of the 12361 // required keys. 12362 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 12363 KeySetManagerService ksms = mSettings.mKeySetManagerService; 12364 for (int i = 0; i < upgradeKeySets.length; i++) { 12365 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 12366 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 12367 return true; 12368 } 12369 } 12370 return false; 12371 } 12372 12373 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 12374 UserHandle user, String installerPackageName, String volumeUuid, 12375 PackageInstalledInfo res) { 12376 final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 12377 12378 final PackageParser.Package oldPackage; 12379 final String pkgName = pkg.packageName; 12380 final int[] allUsers; 12381 final boolean[] perUserInstalled; 12382 12383 // First find the old package info and check signatures 12384 synchronized(mPackages) { 12385 oldPackage = mPackages.get(pkgName); 12386 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 12387 if (isEphemeral && !oldIsEphemeral) { 12388 // can't downgrade from full to ephemeral 12389 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 12390 res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 12391 return; 12392 } 12393 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 12394 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12395 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12396 if(!checkUpgradeKeySetLP(ps, pkg)) { 12397 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 12398 "New package not signed by keys specified by upgrade-keysets: " 12399 + pkgName); 12400 return; 12401 } 12402 } else { 12403 // default to original signature matching 12404 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 12405 != PackageManager.SIGNATURE_MATCH) { 12406 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 12407 "New package has a different signature: " + pkgName); 12408 return; 12409 } 12410 } 12411 12412 // In case of rollback, remember per-user/profile install state 12413 allUsers = sUserManager.getUserIds(); 12414 perUserInstalled = new boolean[allUsers.length]; 12415 for (int i = 0; i < allUsers.length; i++) { 12416 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12417 } 12418 } 12419 12420 boolean sysPkg = (isSystemApp(oldPackage)); 12421 if (sysPkg) { 12422 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 12423 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 12424 } else { 12425 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 12426 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 12427 } 12428 } 12429 12430 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 12431 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 12432 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 12433 String volumeUuid, PackageInstalledInfo res) { 12434 String pkgName = deletedPackage.packageName; 12435 boolean deletedPkg = true; 12436 boolean updatedSettings = false; 12437 12438 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 12439 + deletedPackage); 12440 long origUpdateTime; 12441 if (pkg.mExtras != null) { 12442 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 12443 } else { 12444 origUpdateTime = 0; 12445 } 12446 12447 // First delete the existing package while retaining the data directory 12448 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 12449 res.removedInfo, true)) { 12450 // If the existing package wasn't successfully deleted 12451 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 12452 deletedPkg = false; 12453 } else { 12454 // Successfully deleted the old package; proceed with replace. 12455 12456 // If deleted package lived in a container, give users a chance to 12457 // relinquish resources before killing. 12458 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 12459 if (DEBUG_INSTALL) { 12460 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 12461 } 12462 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 12463 final ArrayList<String> pkgList = new ArrayList<String>(1); 12464 pkgList.add(deletedPackage.applicationInfo.packageName); 12465 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 12466 } 12467 12468 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 12469 try { 12470 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 12471 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 12472 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12473 perUserInstalled, res, user); 12474 prepareAppDataAfterInstall(newPackage); 12475 updatedSettings = true; 12476 } catch (PackageManagerException e) { 12477 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12478 } 12479 } 12480 12481 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12482 // remove package from internal structures. Note that we want deletePackageX to 12483 // delete the package data and cache directories that it created in 12484 // scanPackageLocked, unless those directories existed before we even tried to 12485 // install. 12486 if(updatedSettings) { 12487 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 12488 deletePackageLI( 12489 pkgName, null, true, allUsers, perUserInstalled, 12490 PackageManager.DELETE_KEEP_DATA, 12491 res.removedInfo, true); 12492 } 12493 // Since we failed to install the new package we need to restore the old 12494 // package that we deleted. 12495 if (deletedPkg) { 12496 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 12497 File restoreFile = new File(deletedPackage.codePath); 12498 // Parse old package 12499 boolean oldExternal = isExternal(deletedPackage); 12500 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 12501 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 12502 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 12503 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 12504 try { 12505 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 12506 null); 12507 } catch (PackageManagerException e) { 12508 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 12509 + e.getMessage()); 12510 return; 12511 } 12512 // Restore of old package succeeded. Update permissions. 12513 // writer 12514 synchronized (mPackages) { 12515 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 12516 UPDATE_PERMISSIONS_ALL); 12517 // can downgrade to reader 12518 mSettings.writeLPr(); 12519 } 12520 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 12521 } 12522 } 12523 } 12524 12525 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 12526 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 12527 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 12528 String volumeUuid, PackageInstalledInfo res) { 12529 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 12530 + ", old=" + deletedPackage); 12531 boolean disabledSystem = false; 12532 boolean updatedSettings = false; 12533 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 12534 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 12535 != 0) { 12536 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12537 } 12538 String packageName = deletedPackage.packageName; 12539 if (packageName == null) { 12540 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12541 "Attempt to delete null packageName."); 12542 return; 12543 } 12544 PackageParser.Package oldPkg; 12545 PackageSetting oldPkgSetting; 12546 // reader 12547 synchronized (mPackages) { 12548 oldPkg = mPackages.get(packageName); 12549 oldPkgSetting = mSettings.mPackages.get(packageName); 12550 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 12551 (oldPkgSetting == null)) { 12552 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12553 "Couldn't find package " + packageName + " information"); 12554 return; 12555 } 12556 } 12557 12558 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 12559 12560 res.removedInfo.uid = oldPkg.applicationInfo.uid; 12561 res.removedInfo.removedPackage = packageName; 12562 // Remove existing system package 12563 removePackageLI(oldPkgSetting, true); 12564 // writer 12565 synchronized (mPackages) { 12566 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 12567 if (!disabledSystem && deletedPackage != null) { 12568 // We didn't need to disable the .apk as a current system package, 12569 // which means we are replacing another update that is already 12570 // installed. We need to make sure to delete the older one's .apk. 12571 res.removedInfo.args = createInstallArgsForExisting(0, 12572 deletedPackage.applicationInfo.getCodePath(), 12573 deletedPackage.applicationInfo.getResourcePath(), 12574 getAppDexInstructionSets(deletedPackage.applicationInfo)); 12575 } else { 12576 res.removedInfo.args = null; 12577 } 12578 } 12579 12580 // Successfully disabled the old package. Now proceed with re-installation 12581 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 12582 12583 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12584 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 12585 12586 PackageParser.Package newPackage = null; 12587 try { 12588 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 12589 if (newPackage.mExtras != null) { 12590 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 12591 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 12592 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 12593 12594 // is the update attempting to change shared user? that isn't going to work... 12595 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 12596 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 12597 "Forbidding shared user change from " + oldPkgSetting.sharedUser 12598 + " to " + newPkgSetting.sharedUser); 12599 updatedSettings = true; 12600 } 12601 } 12602 12603 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12604 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12605 perUserInstalled, res, user); 12606 prepareAppDataAfterInstall(newPackage); 12607 updatedSettings = true; 12608 } 12609 12610 } catch (PackageManagerException e) { 12611 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12612 } 12613 12614 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12615 // Re installation failed. Restore old information 12616 // Remove new pkg information 12617 if (newPackage != null) { 12618 removeInstalledPackageLI(newPackage, true); 12619 } 12620 // Add back the old system package 12621 try { 12622 scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 12623 } catch (PackageManagerException e) { 12624 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 12625 } 12626 // Restore the old system information in Settings 12627 synchronized (mPackages) { 12628 if (disabledSystem) { 12629 mSettings.enableSystemPackageLPw(packageName); 12630 } 12631 if (updatedSettings) { 12632 mSettings.setInstallerPackageName(packageName, 12633 oldPkgSetting.installerPackageName); 12634 } 12635 mSettings.writeLPr(); 12636 } 12637 } 12638 } 12639 12640 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 12641 // Collect all used permissions in the UID 12642 ArraySet<String> usedPermissions = new ArraySet<>(); 12643 final int packageCount = su.packages.size(); 12644 for (int i = 0; i < packageCount; i++) { 12645 PackageSetting ps = su.packages.valueAt(i); 12646 if (ps.pkg == null) { 12647 continue; 12648 } 12649 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 12650 for (int j = 0; j < requestedPermCount; j++) { 12651 String permission = ps.pkg.requestedPermissions.get(j); 12652 BasePermission bp = mSettings.mPermissions.get(permission); 12653 if (bp != null) { 12654 usedPermissions.add(permission); 12655 } 12656 } 12657 } 12658 12659 PermissionsState permissionsState = su.getPermissionsState(); 12660 // Prune install permissions 12661 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 12662 final int installPermCount = installPermStates.size(); 12663 for (int i = installPermCount - 1; i >= 0; i--) { 12664 PermissionState permissionState = installPermStates.get(i); 12665 if (!usedPermissions.contains(permissionState.getName())) { 12666 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 12667 if (bp != null) { 12668 permissionsState.revokeInstallPermission(bp); 12669 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 12670 PackageManager.MASK_PERMISSION_FLAGS, 0); 12671 } 12672 } 12673 } 12674 12675 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 12676 12677 // Prune runtime permissions 12678 for (int userId : allUserIds) { 12679 List<PermissionState> runtimePermStates = permissionsState 12680 .getRuntimePermissionStates(userId); 12681 final int runtimePermCount = runtimePermStates.size(); 12682 for (int i = runtimePermCount - 1; i >= 0; i--) { 12683 PermissionState permissionState = runtimePermStates.get(i); 12684 if (!usedPermissions.contains(permissionState.getName())) { 12685 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 12686 if (bp != null) { 12687 permissionsState.revokeRuntimePermission(bp, userId); 12688 permissionsState.updatePermissionFlags(bp, userId, 12689 PackageManager.MASK_PERMISSION_FLAGS, 0); 12690 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 12691 runtimePermissionChangedUserIds, userId); 12692 } 12693 } 12694 } 12695 } 12696 12697 return runtimePermissionChangedUserIds; 12698 } 12699 12700 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 12701 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 12702 UserHandle user) { 12703 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 12704 12705 String pkgName = newPackage.packageName; 12706 synchronized (mPackages) { 12707 //write settings. the installStatus will be incomplete at this stage. 12708 //note that the new package setting would have already been 12709 //added to mPackages. It hasn't been persisted yet. 12710 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 12711 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 12712 mSettings.writeLPr(); 12713 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12714 } 12715 12716 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 12717 synchronized (mPackages) { 12718 updatePermissionsLPw(newPackage.packageName, newPackage, 12719 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 12720 ? UPDATE_PERMISSIONS_ALL : 0)); 12721 // For system-bundled packages, we assume that installing an upgraded version 12722 // of the package implies that the user actually wants to run that new code, 12723 // so we enable the package. 12724 PackageSetting ps = mSettings.mPackages.get(pkgName); 12725 if (ps != null) { 12726 if (isSystemApp(newPackage)) { 12727 // NB: implicit assumption that system package upgrades apply to all users 12728 if (DEBUG_INSTALL) { 12729 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 12730 } 12731 if (res.origUsers != null) { 12732 for (int userHandle : res.origUsers) { 12733 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 12734 userHandle, installerPackageName); 12735 } 12736 } 12737 // Also convey the prior install/uninstall state 12738 if (allUsers != null && perUserInstalled != null) { 12739 for (int i = 0; i < allUsers.length; i++) { 12740 if (DEBUG_INSTALL) { 12741 Slog.d(TAG, " user " + allUsers[i] 12742 + " => " + perUserInstalled[i]); 12743 } 12744 ps.setInstalled(perUserInstalled[i], allUsers[i]); 12745 } 12746 // these install state changes will be persisted in the 12747 // upcoming call to mSettings.writeLPr(). 12748 } 12749 } 12750 // It's implied that when a user requests installation, they want the app to be 12751 // installed and enabled. 12752 int userId = user.getIdentifier(); 12753 if (userId != UserHandle.USER_ALL) { 12754 ps.setInstalled(true, userId); 12755 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 12756 } 12757 } 12758 res.name = pkgName; 12759 res.uid = newPackage.applicationInfo.uid; 12760 res.pkg = newPackage; 12761 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 12762 mSettings.setInstallerPackageName(pkgName, installerPackageName); 12763 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12764 //to update install status 12765 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 12766 mSettings.writeLPr(); 12767 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12768 } 12769 12770 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12771 } 12772 12773 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 12774 try { 12775 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 12776 installPackageLI(args, res); 12777 } finally { 12778 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12779 } 12780 } 12781 12782 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 12783 final int installFlags = args.installFlags; 12784 final String installerPackageName = args.installerPackageName; 12785 final String volumeUuid = args.volumeUuid; 12786 final File tmpPackageFile = new File(args.getCodePath()); 12787 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 12788 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 12789 || (args.volumeUuid != null)); 12790 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 12791 boolean replace = false; 12792 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 12793 if (args.move != null) { 12794 // moving a complete application; perfom an initial scan on the new install location 12795 scanFlags |= SCAN_INITIAL; 12796 } 12797 // Result object to be returned 12798 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12799 12800 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 12801 12802 // Sanity check 12803 if (ephemeral && (forwardLocked || onExternal)) { 12804 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 12805 + " external=" + onExternal); 12806 res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 12807 return; 12808 } 12809 12810 // Retrieve PackageSettings and parse package 12811 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 12812 | PackageParser.PARSE_ENFORCE_CODE 12813 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 12814 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 12815 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0); 12816 PackageParser pp = new PackageParser(); 12817 pp.setSeparateProcesses(mSeparateProcesses); 12818 pp.setDisplayMetrics(mMetrics); 12819 12820 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 12821 final PackageParser.Package pkg; 12822 try { 12823 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 12824 } catch (PackageParserException e) { 12825 res.setError("Failed parse during installPackageLI", e); 12826 return; 12827 } finally { 12828 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12829 } 12830 12831 // Mark that we have an install time CPU ABI override. 12832 pkg.cpuAbiOverride = args.abiOverride; 12833 12834 String pkgName = res.name = pkg.packageName; 12835 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 12836 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 12837 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 12838 return; 12839 } 12840 } 12841 12842 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 12843 try { 12844 pp.collectCertificates(pkg, parseFlags); 12845 } catch (PackageParserException e) { 12846 res.setError("Failed collect during installPackageLI", e); 12847 return; 12848 } finally { 12849 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12850 } 12851 12852 // Get rid of all references to package scan path via parser. 12853 pp = null; 12854 String oldCodePath = null; 12855 boolean systemApp = false; 12856 synchronized (mPackages) { 12857 // Check if installing already existing package 12858 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12859 String oldName = mSettings.mRenamedPackages.get(pkgName); 12860 if (pkg.mOriginalPackages != null 12861 && pkg.mOriginalPackages.contains(oldName) 12862 && mPackages.containsKey(oldName)) { 12863 // This package is derived from an original package, 12864 // and this device has been updating from that original 12865 // name. We must continue using the original name, so 12866 // rename the new package here. 12867 pkg.setPackageName(oldName); 12868 pkgName = pkg.packageName; 12869 replace = true; 12870 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 12871 + oldName + " pkgName=" + pkgName); 12872 } else if (mPackages.containsKey(pkgName)) { 12873 // This package, under its official name, already exists 12874 // on the device; we should replace it. 12875 replace = true; 12876 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 12877 } 12878 12879 // Prevent apps opting out from runtime permissions 12880 if (replace) { 12881 PackageParser.Package oldPackage = mPackages.get(pkgName); 12882 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 12883 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 12884 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 12885 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 12886 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 12887 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 12888 + " doesn't support runtime permissions but the old" 12889 + " target SDK " + oldTargetSdk + " does."); 12890 return; 12891 } 12892 } 12893 } 12894 12895 PackageSetting ps = mSettings.mPackages.get(pkgName); 12896 if (ps != null) { 12897 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 12898 12899 // Quick sanity check that we're signed correctly if updating; 12900 // we'll check this again later when scanning, but we want to 12901 // bail early here before tripping over redefined permissions. 12902 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12903 if (!checkUpgradeKeySetLP(ps, pkg)) { 12904 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 12905 + pkg.packageName + " upgrade keys do not match the " 12906 + "previously installed version"); 12907 return; 12908 } 12909 } else { 12910 try { 12911 verifySignaturesLP(ps, pkg); 12912 } catch (PackageManagerException e) { 12913 res.setError(e.error, e.getMessage()); 12914 return; 12915 } 12916 } 12917 12918 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 12919 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 12920 systemApp = (ps.pkg.applicationInfo.flags & 12921 ApplicationInfo.FLAG_SYSTEM) != 0; 12922 } 12923 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12924 } 12925 12926 // Check whether the newly-scanned package wants to define an already-defined perm 12927 int N = pkg.permissions.size(); 12928 for (int i = N-1; i >= 0; i--) { 12929 PackageParser.Permission perm = pkg.permissions.get(i); 12930 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 12931 if (bp != null) { 12932 // If the defining package is signed with our cert, it's okay. This 12933 // also includes the "updating the same package" case, of course. 12934 // "updating same package" could also involve key-rotation. 12935 final boolean sigsOk; 12936 if (bp.sourcePackage.equals(pkg.packageName) 12937 && (bp.packageSetting instanceof PackageSetting) 12938 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 12939 scanFlags))) { 12940 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 12941 } else { 12942 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 12943 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 12944 } 12945 if (!sigsOk) { 12946 // If the owning package is the system itself, we log but allow 12947 // install to proceed; we fail the install on all other permission 12948 // redefinitions. 12949 if (!bp.sourcePackage.equals("android")) { 12950 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 12951 + pkg.packageName + " attempting to redeclare permission " 12952 + perm.info.name + " already owned by " + bp.sourcePackage); 12953 res.origPermission = perm.info.name; 12954 res.origPackage = bp.sourcePackage; 12955 return; 12956 } else { 12957 Slog.w(TAG, "Package " + pkg.packageName 12958 + " attempting to redeclare system permission " 12959 + perm.info.name + "; ignoring new declaration"); 12960 pkg.permissions.remove(i); 12961 } 12962 } 12963 } 12964 } 12965 12966 } 12967 12968 if (systemApp) { 12969 if (onExternal) { 12970 // Abort update; system app can't be replaced with app on sdcard 12971 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 12972 "Cannot install updates to system apps on sdcard"); 12973 return; 12974 } else if (ephemeral) { 12975 // Abort update; system app can't be replaced with an ephemeral app 12976 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 12977 "Cannot update a system app with an ephemeral app"); 12978 return; 12979 } 12980 } 12981 12982 if (args.move != null) { 12983 // We did an in-place move, so dex is ready to roll 12984 scanFlags |= SCAN_NO_DEX; 12985 scanFlags |= SCAN_MOVE; 12986 12987 synchronized (mPackages) { 12988 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12989 if (ps == null) { 12990 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 12991 "Missing settings for moved package " + pkgName); 12992 } 12993 12994 // We moved the entire application as-is, so bring over the 12995 // previously derived ABI information. 12996 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 12997 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 12998 } 12999 13000 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 13001 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 13002 scanFlags |= SCAN_NO_DEX; 13003 13004 try { 13005 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 13006 true /* extract libs */); 13007 } catch (PackageManagerException pme) { 13008 Slog.e(TAG, "Error deriving application ABI", pme); 13009 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 13010 return; 13011 } 13012 13013 // Extract package to save the VM unzipping the APK in memory during 13014 // launch. Only do this if profile-guided compilation is enabled because 13015 // otherwise BackgroundDexOptService will not dexopt the package later. 13016 if (mUseJitProfiles) { 13017 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 13018 // Do not run PackageDexOptimizer through the local performDexOpt 13019 // method because `pkg` is not in `mPackages` yet. 13020 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instructionSets */, 13021 false /* inclDependencies */, false /* useProfiles */, 13022 true /* extractOnly */); 13023 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13024 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 13025 String msg = "Extracking package failed for " + pkgName; 13026 res.setError(INSTALL_FAILED_DEXOPT, msg); 13027 return; 13028 } 13029 } 13030 } 13031 13032 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 13033 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 13034 return; 13035 } 13036 13037 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 13038 13039 if (replace) { 13040 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 13041 installerPackageName, volumeUuid, res); 13042 } else { 13043 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 13044 args.user, installerPackageName, volumeUuid, res); 13045 } 13046 synchronized (mPackages) { 13047 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13048 if (ps != null) { 13049 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 13050 } 13051 } 13052 } 13053 13054 private void startIntentFilterVerifications(int userId, boolean replacing, 13055 PackageParser.Package pkg) { 13056 if (mIntentFilterVerifierComponent == null) { 13057 Slog.w(TAG, "No IntentFilter verification will not be done as " 13058 + "there is no IntentFilterVerifier available!"); 13059 return; 13060 } 13061 13062 final int verifierUid = getPackageUid( 13063 mIntentFilterVerifierComponent.getPackageName(), 13064 MATCH_DEBUG_TRIAGED_MISSING, 13065 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 13066 13067 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 13068 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 13069 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 13070 mHandler.sendMessage(msg); 13071 } 13072 13073 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 13074 PackageParser.Package pkg) { 13075 int size = pkg.activities.size(); 13076 if (size == 0) { 13077 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 13078 "No activity, so no need to verify any IntentFilter!"); 13079 return; 13080 } 13081 13082 final boolean hasDomainURLs = hasDomainURLs(pkg); 13083 if (!hasDomainURLs) { 13084 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 13085 "No domain URLs, so no need to verify any IntentFilter!"); 13086 return; 13087 } 13088 13089 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 13090 + " if any IntentFilter from the " + size 13091 + " Activities needs verification ..."); 13092 13093 int count = 0; 13094 final String packageName = pkg.packageName; 13095 13096 synchronized (mPackages) { 13097 // If this is a new install and we see that we've already run verification for this 13098 // package, we have nothing to do: it means the state was restored from backup. 13099 if (!replacing) { 13100 IntentFilterVerificationInfo ivi = 13101 mSettings.getIntentFilterVerificationLPr(packageName); 13102 if (ivi != null) { 13103 if (DEBUG_DOMAIN_VERIFICATION) { 13104 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 13105 + ivi.getStatusString()); 13106 } 13107 return; 13108 } 13109 } 13110 13111 // If any filters need to be verified, then all need to be. 13112 boolean needToVerify = false; 13113 for (PackageParser.Activity a : pkg.activities) { 13114 for (ActivityIntentInfo filter : a.intents) { 13115 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 13116 if (DEBUG_DOMAIN_VERIFICATION) { 13117 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 13118 } 13119 needToVerify = true; 13120 break; 13121 } 13122 } 13123 } 13124 13125 if (needToVerify) { 13126 final int verificationId = mIntentFilterVerificationToken++; 13127 for (PackageParser.Activity a : pkg.activities) { 13128 for (ActivityIntentInfo filter : a.intents) { 13129 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 13130 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 13131 "Verification needed for IntentFilter:" + filter.toString()); 13132 mIntentFilterVerifier.addOneIntentFilterVerification( 13133 verifierUid, userId, verificationId, filter, packageName); 13134 count++; 13135 } 13136 } 13137 } 13138 } 13139 } 13140 13141 if (count > 0) { 13142 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 13143 + " IntentFilter verification" + (count > 1 ? "s" : "") 13144 + " for userId:" + userId); 13145 mIntentFilterVerifier.startVerifications(userId); 13146 } else { 13147 if (DEBUG_DOMAIN_VERIFICATION) { 13148 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 13149 } 13150 } 13151 } 13152 13153 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 13154 final ComponentName cn = filter.activity.getComponentName(); 13155 final String packageName = cn.getPackageName(); 13156 13157 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 13158 packageName); 13159 if (ivi == null) { 13160 return true; 13161 } 13162 int status = ivi.getStatus(); 13163 switch (status) { 13164 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 13165 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 13166 return true; 13167 13168 default: 13169 // Nothing to do 13170 return false; 13171 } 13172 } 13173 13174 private static boolean isMultiArch(ApplicationInfo info) { 13175 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 13176 } 13177 13178 private static boolean isExternal(PackageParser.Package pkg) { 13179 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 13180 } 13181 13182 private static boolean isExternal(PackageSetting ps) { 13183 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 13184 } 13185 13186 private static boolean isEphemeral(PackageParser.Package pkg) { 13187 return pkg.applicationInfo.isEphemeralApp(); 13188 } 13189 13190 private static boolean isEphemeral(PackageSetting ps) { 13191 return ps.pkg != null && isEphemeral(ps.pkg); 13192 } 13193 13194 private static boolean isSystemApp(PackageParser.Package pkg) { 13195 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 13196 } 13197 13198 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 13199 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 13200 } 13201 13202 private static boolean hasDomainURLs(PackageParser.Package pkg) { 13203 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 13204 } 13205 13206 private static boolean isSystemApp(PackageSetting ps) { 13207 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 13208 } 13209 13210 private static boolean isUpdatedSystemApp(PackageSetting ps) { 13211 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 13212 } 13213 13214 private int packageFlagsToInstallFlags(PackageSetting ps) { 13215 int installFlags = 0; 13216 if (isEphemeral(ps)) { 13217 installFlags |= PackageManager.INSTALL_EPHEMERAL; 13218 } 13219 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 13220 // This existing package was an external ASEC install when we have 13221 // the external flag without a UUID 13222 installFlags |= PackageManager.INSTALL_EXTERNAL; 13223 } 13224 if (ps.isForwardLocked()) { 13225 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 13226 } 13227 return installFlags; 13228 } 13229 13230 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 13231 if (isExternal(pkg)) { 13232 if (TextUtils.isEmpty(pkg.volumeUuid)) { 13233 return StorageManager.UUID_PRIMARY_PHYSICAL; 13234 } else { 13235 return pkg.volumeUuid; 13236 } 13237 } else { 13238 return StorageManager.UUID_PRIVATE_INTERNAL; 13239 } 13240 } 13241 13242 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 13243 if (isExternal(pkg)) { 13244 if (TextUtils.isEmpty(pkg.volumeUuid)) { 13245 return mSettings.getExternalVersion(); 13246 } else { 13247 return mSettings.findOrCreateVersion(pkg.volumeUuid); 13248 } 13249 } else { 13250 return mSettings.getInternalVersion(); 13251 } 13252 } 13253 13254 private void deleteTempPackageFiles() { 13255 final FilenameFilter filter = new FilenameFilter() { 13256 public boolean accept(File dir, String name) { 13257 return name.startsWith("vmdl") && name.endsWith(".tmp"); 13258 } 13259 }; 13260 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 13261 file.delete(); 13262 } 13263 } 13264 13265 @Override 13266 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 13267 int flags) { 13268 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 13269 flags); 13270 } 13271 13272 @Override 13273 public void deletePackage(final String packageName, 13274 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 13275 mContext.enforceCallingOrSelfPermission( 13276 android.Manifest.permission.DELETE_PACKAGES, null); 13277 Preconditions.checkNotNull(packageName); 13278 Preconditions.checkNotNull(observer); 13279 final int uid = Binder.getCallingUid(); 13280 final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0; 13281 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 13282 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 13283 mContext.enforceCallingOrSelfPermission( 13284 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 13285 "deletePackage for user " + userId); 13286 } 13287 13288 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 13289 try { 13290 observer.onPackageDeleted(packageName, 13291 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 13292 } catch (RemoteException re) { 13293 } 13294 return; 13295 } 13296 13297 for (int currentUserId : users) { 13298 if (getBlockUninstallForUser(packageName, currentUserId)) { 13299 try { 13300 observer.onPackageDeleted(packageName, 13301 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 13302 } catch (RemoteException re) { 13303 } 13304 return; 13305 } 13306 } 13307 13308 if (DEBUG_REMOVE) { 13309 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 13310 } 13311 // Queue up an async operation since the package deletion may take a little while. 13312 mHandler.post(new Runnable() { 13313 public void run() { 13314 mHandler.removeCallbacks(this); 13315 final int returnCode = deletePackageX(packageName, userId, flags); 13316 try { 13317 observer.onPackageDeleted(packageName, returnCode, null); 13318 } catch (RemoteException e) { 13319 Log.i(TAG, "Observer no longer exists."); 13320 } //end catch 13321 } //end run 13322 }); 13323 } 13324 13325 private boolean isPackageDeviceAdmin(String packageName, int userId) { 13326 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 13327 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 13328 try { 13329 if (dpm != null) { 13330 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 13331 /* callingUserOnly =*/ false); 13332 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 13333 : deviceOwnerComponentName.getPackageName(); 13334 // Does the package contains the device owner? 13335 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 13336 // this check is probably not needed, since DO should be registered as a device 13337 // admin on some user too. (Original bug for this: b/17657954) 13338 if (packageName.equals(deviceOwnerPackageName)) { 13339 return true; 13340 } 13341 // Does it contain a device admin for any user? 13342 int[] users; 13343 if (userId == UserHandle.USER_ALL) { 13344 users = sUserManager.getUserIds(); 13345 } else { 13346 users = new int[]{userId}; 13347 } 13348 for (int i = 0; i < users.length; ++i) { 13349 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 13350 return true; 13351 } 13352 } 13353 } 13354 } catch (RemoteException e) { 13355 } 13356 return false; 13357 } 13358 13359 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 13360 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 13361 } 13362 13363 /** 13364 * This method is an internal method that could be get invoked either 13365 * to delete an installed package or to clean up a failed installation. 13366 * After deleting an installed package, a broadcast is sent to notify any 13367 * listeners that the package has been installed. For cleaning up a failed 13368 * installation, the broadcast is not necessary since the package's 13369 * installation wouldn't have sent the initial broadcast either 13370 * The key steps in deleting a package are 13371 * deleting the package information in internal structures like mPackages, 13372 * deleting the packages base directories through installd 13373 * updating mSettings to reflect current status 13374 * persisting settings for later use 13375 * sending a broadcast if necessary 13376 */ 13377 private int deletePackageX(String packageName, int userId, int flags) { 13378 final PackageRemovedInfo info = new PackageRemovedInfo(); 13379 final boolean res; 13380 13381 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 13382 ? UserHandle.ALL : new UserHandle(userId); 13383 13384 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 13385 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 13386 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 13387 } 13388 13389 boolean removedForAllUsers = false; 13390 boolean systemUpdate = false; 13391 13392 PackageParser.Package uninstalledPkg; 13393 13394 // for the uninstall-updates case and restricted profiles, remember the per- 13395 // userhandle installed state 13396 int[] allUsers; 13397 boolean[] perUserInstalled; 13398 synchronized (mPackages) { 13399 uninstalledPkg = mPackages.get(packageName); 13400 PackageSetting ps = mSettings.mPackages.get(packageName); 13401 allUsers = sUserManager.getUserIds(); 13402 perUserInstalled = new boolean[allUsers.length]; 13403 for (int i = 0; i < allUsers.length; i++) { 13404 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 13405 } 13406 } 13407 13408 synchronized (mInstallLock) { 13409 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 13410 res = deletePackageLI(packageName, removeForUser, 13411 true, allUsers, perUserInstalled, 13412 flags | REMOVE_CHATTY, info, true); 13413 systemUpdate = info.isRemovedPackageSystemUpdate; 13414 synchronized (mPackages) { 13415 if (res) { 13416 if (!systemUpdate && mPackages.get(packageName) == null) { 13417 removedForAllUsers = true; 13418 } 13419 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPkg); 13420 } 13421 } 13422 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 13423 + " removedForAllUsers=" + removedForAllUsers); 13424 } 13425 13426 if (res) { 13427 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 13428 13429 // If the removed package was a system update, the old system package 13430 // was re-enabled; we need to broadcast this information 13431 if (systemUpdate) { 13432 Bundle extras = new Bundle(1); 13433 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 13434 ? info.removedAppId : info.uid); 13435 extras.putBoolean(Intent.EXTRA_REPLACING, true); 13436 13437 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 13438 extras, 0, null, null, null); 13439 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 13440 extras, 0, null, null, null); 13441 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 13442 null, 0, packageName, null, null); 13443 } 13444 } 13445 // Force a gc here. 13446 Runtime.getRuntime().gc(); 13447 // Delete the resources here after sending the broadcast to let 13448 // other processes clean up before deleting resources. 13449 if (info.args != null) { 13450 synchronized (mInstallLock) { 13451 info.args.doPostDeleteLI(true); 13452 } 13453 } 13454 13455 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 13456 } 13457 13458 class PackageRemovedInfo { 13459 String removedPackage; 13460 int uid = -1; 13461 int removedAppId = -1; 13462 int[] removedUsers = null; 13463 boolean isRemovedPackageSystemUpdate = false; 13464 // Clean up resources deleted packages. 13465 InstallArgs args = null; 13466 13467 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 13468 Bundle extras = new Bundle(1); 13469 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 13470 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 13471 if (replacing) { 13472 extras.putBoolean(Intent.EXTRA_REPLACING, true); 13473 } 13474 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 13475 if (removedPackage != null) { 13476 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 13477 extras, 0, null, null, removedUsers); 13478 if (fullRemove && !replacing) { 13479 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 13480 extras, 0, null, null, removedUsers); 13481 } 13482 } 13483 if (removedAppId >= 0) { 13484 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 13485 removedUsers); 13486 } 13487 } 13488 } 13489 13490 /* 13491 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 13492 * flag is not set, the data directory is removed as well. 13493 * make sure this flag is set for partially installed apps. If not its meaningless to 13494 * delete a partially installed application. 13495 */ 13496 private void removePackageDataLI(PackageSetting ps, 13497 int[] allUserHandles, boolean[] perUserInstalled, 13498 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 13499 String packageName = ps.name; 13500 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 13501 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 13502 // Retrieve object to delete permissions for shared user later on 13503 final PackageSetting deletedPs; 13504 // reader 13505 synchronized (mPackages) { 13506 deletedPs = mSettings.mPackages.get(packageName); 13507 if (outInfo != null) { 13508 outInfo.removedPackage = packageName; 13509 outInfo.removedUsers = deletedPs != null 13510 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 13511 : null; 13512 } 13513 } 13514 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 13515 removeDataDirsLI(ps.volumeUuid, packageName); 13516 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 13517 } 13518 // writer 13519 synchronized (mPackages) { 13520 if (deletedPs != null) { 13521 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 13522 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 13523 clearDefaultBrowserIfNeeded(packageName); 13524 if (outInfo != null) { 13525 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 13526 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 13527 } 13528 updatePermissionsLPw(deletedPs.name, null, 0); 13529 if (deletedPs.sharedUser != null) { 13530 // Remove permissions associated with package. Since runtime 13531 // permissions are per user we have to kill the removed package 13532 // or packages running under the shared user of the removed 13533 // package if revoking the permissions requested only by the removed 13534 // package is successful and this causes a change in gids. 13535 for (int userId : UserManagerService.getInstance().getUserIds()) { 13536 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 13537 userId); 13538 if (userIdToKill == UserHandle.USER_ALL 13539 || userIdToKill >= UserHandle.USER_SYSTEM) { 13540 // If gids changed for this user, kill all affected packages. 13541 mHandler.post(new Runnable() { 13542 @Override 13543 public void run() { 13544 // This has to happen with no lock held. 13545 killApplication(deletedPs.name, deletedPs.appId, 13546 KILL_APP_REASON_GIDS_CHANGED); 13547 } 13548 }); 13549 break; 13550 } 13551 } 13552 } 13553 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 13554 } 13555 // make sure to preserve per-user disabled state if this removal was just 13556 // a downgrade of a system app to the factory package 13557 if (allUserHandles != null && perUserInstalled != null) { 13558 if (DEBUG_REMOVE) { 13559 Slog.d(TAG, "Propagating install state across downgrade"); 13560 } 13561 for (int i = 0; i < allUserHandles.length; i++) { 13562 if (DEBUG_REMOVE) { 13563 Slog.d(TAG, " user " + allUserHandles[i] 13564 + " => " + perUserInstalled[i]); 13565 } 13566 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13567 } 13568 } 13569 } 13570 // can downgrade to reader 13571 if (writeSettings) { 13572 // Save settings now 13573 mSettings.writeLPr(); 13574 } 13575 } 13576 if (outInfo != null) { 13577 // A user ID was deleted here. Go through all users and remove it 13578 // from KeyStore. 13579 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 13580 } 13581 } 13582 13583 static boolean locationIsPrivileged(File path) { 13584 try { 13585 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 13586 .getCanonicalPath(); 13587 return path.getCanonicalPath().startsWith(privilegedAppDir); 13588 } catch (IOException e) { 13589 Slog.e(TAG, "Unable to access code path " + path); 13590 } 13591 return false; 13592 } 13593 13594 /* 13595 * Tries to delete system package. 13596 */ 13597 private boolean deleteSystemPackageLI(PackageSetting newPs, 13598 int[] allUserHandles, boolean[] perUserInstalled, 13599 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 13600 final boolean applyUserRestrictions 13601 = (allUserHandles != null) && (perUserInstalled != null); 13602 PackageSetting disabledPs = null; 13603 // Confirm if the system package has been updated 13604 // An updated system app can be deleted. This will also have to restore 13605 // the system pkg from system partition 13606 // reader 13607 synchronized (mPackages) { 13608 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 13609 } 13610 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 13611 + " disabledPs=" + disabledPs); 13612 if (disabledPs == null) { 13613 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 13614 return false; 13615 } else if (DEBUG_REMOVE) { 13616 Slog.d(TAG, "Deleting system pkg from data partition"); 13617 } 13618 if (DEBUG_REMOVE) { 13619 if (applyUserRestrictions) { 13620 Slog.d(TAG, "Remembering install states:"); 13621 for (int i = 0; i < allUserHandles.length; i++) { 13622 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 13623 } 13624 } 13625 } 13626 // Delete the updated package 13627 outInfo.isRemovedPackageSystemUpdate = true; 13628 if (disabledPs.versionCode < newPs.versionCode) { 13629 // Delete data for downgrades 13630 flags &= ~PackageManager.DELETE_KEEP_DATA; 13631 } else { 13632 // Preserve data by setting flag 13633 flags |= PackageManager.DELETE_KEEP_DATA; 13634 } 13635 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 13636 allUserHandles, perUserInstalled, outInfo, writeSettings); 13637 if (!ret) { 13638 return false; 13639 } 13640 // writer 13641 synchronized (mPackages) { 13642 // Reinstate the old system package 13643 mSettings.enableSystemPackageLPw(newPs.name); 13644 // Remove any native libraries from the upgraded package. 13645 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 13646 } 13647 // Install the system package 13648 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 13649 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 13650 if (locationIsPrivileged(disabledPs.codePath)) { 13651 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 13652 } 13653 13654 final PackageParser.Package newPkg; 13655 try { 13656 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 13657 } catch (PackageManagerException e) { 13658 Slog.w(TAG, "Failed to restore system package " + newPs.name + ": " + e.getMessage()); 13659 return false; 13660 } 13661 13662 prepareAppDataAfterInstall(newPkg); 13663 13664 // writer 13665 synchronized (mPackages) { 13666 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 13667 13668 // Propagate the permissions state as we do not want to drop on the floor 13669 // runtime permissions. The update permissions method below will take 13670 // care of removing obsolete permissions and grant install permissions. 13671 ps.getPermissionsState().copyFrom(newPs.getPermissionsState()); 13672 updatePermissionsLPw(newPkg.packageName, newPkg, 13673 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 13674 13675 if (applyUserRestrictions) { 13676 if (DEBUG_REMOVE) { 13677 Slog.d(TAG, "Propagating install state across reinstall"); 13678 } 13679 for (int i = 0; i < allUserHandles.length; i++) { 13680 if (DEBUG_REMOVE) { 13681 Slog.d(TAG, " user " + allUserHandles[i] 13682 + " => " + perUserInstalled[i]); 13683 } 13684 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13685 13686 mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false); 13687 } 13688 // Regardless of writeSettings we need to ensure that this restriction 13689 // state propagation is persisted 13690 mSettings.writeAllUsersPackageRestrictionsLPr(); 13691 } 13692 // can downgrade to reader here 13693 if (writeSettings) { 13694 mSettings.writeLPr(); 13695 } 13696 } 13697 return true; 13698 } 13699 13700 private boolean deleteInstalledPackageLI(PackageSetting ps, 13701 boolean deleteCodeAndResources, int flags, 13702 int[] allUserHandles, boolean[] perUserInstalled, 13703 PackageRemovedInfo outInfo, boolean writeSettings) { 13704 if (outInfo != null) { 13705 outInfo.uid = ps.appId; 13706 } 13707 13708 // Delete package data from internal structures and also remove data if flag is set 13709 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 13710 13711 // Delete application code and resources 13712 if (deleteCodeAndResources && (outInfo != null)) { 13713 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 13714 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 13715 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 13716 } 13717 return true; 13718 } 13719 13720 @Override 13721 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 13722 int userId) { 13723 mContext.enforceCallingOrSelfPermission( 13724 android.Manifest.permission.DELETE_PACKAGES, null); 13725 synchronized (mPackages) { 13726 PackageSetting ps = mSettings.mPackages.get(packageName); 13727 if (ps == null) { 13728 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 13729 return false; 13730 } 13731 if (!ps.getInstalled(userId)) { 13732 // Can't block uninstall for an app that is not installed or enabled. 13733 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 13734 return false; 13735 } 13736 ps.setBlockUninstall(blockUninstall, userId); 13737 mSettings.writePackageRestrictionsLPr(userId); 13738 } 13739 return true; 13740 } 13741 13742 @Override 13743 public boolean getBlockUninstallForUser(String packageName, int userId) { 13744 synchronized (mPackages) { 13745 PackageSetting ps = mSettings.mPackages.get(packageName); 13746 if (ps == null) { 13747 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 13748 return false; 13749 } 13750 return ps.getBlockUninstall(userId); 13751 } 13752 } 13753 13754 @Override 13755 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 13756 int callingUid = Binder.getCallingUid(); 13757 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 13758 throw new SecurityException( 13759 "setRequiredForSystemUser can only be run by the system or root"); 13760 } 13761 synchronized (mPackages) { 13762 PackageSetting ps = mSettings.mPackages.get(packageName); 13763 if (ps == null) { 13764 Log.w(TAG, "Package doesn't exist: " + packageName); 13765 return false; 13766 } 13767 if (systemUserApp) { 13768 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 13769 } else { 13770 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 13771 } 13772 mSettings.writeLPr(); 13773 } 13774 return true; 13775 } 13776 13777 /* 13778 * This method handles package deletion in general 13779 */ 13780 private boolean deletePackageLI(String packageName, UserHandle user, 13781 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 13782 int flags, PackageRemovedInfo outInfo, 13783 boolean writeSettings) { 13784 if (packageName == null) { 13785 Slog.w(TAG, "Attempt to delete null packageName."); 13786 return false; 13787 } 13788 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 13789 PackageSetting ps; 13790 boolean dataOnly = false; 13791 int removeUser = -1; 13792 int appId = -1; 13793 synchronized (mPackages) { 13794 ps = mSettings.mPackages.get(packageName); 13795 if (ps == null) { 13796 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13797 return false; 13798 } 13799 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 13800 && user.getIdentifier() != UserHandle.USER_ALL) { 13801 // The caller is asking that the package only be deleted for a single 13802 // user. To do this, we just mark its uninstalled state and delete 13803 // its data. If this is a system app, we only allow this to happen if 13804 // they have set the special DELETE_SYSTEM_APP which requests different 13805 // semantics than normal for uninstalling system apps. 13806 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 13807 final int userId = user.getIdentifier(); 13808 ps.setUserState(userId, 13809 COMPONENT_ENABLED_STATE_DEFAULT, 13810 false, //installed 13811 true, //stopped 13812 true, //notLaunched 13813 false, //hidden 13814 false, //suspended 13815 null, null, null, 13816 false, // blockUninstall 13817 ps.readUserState(userId).domainVerificationStatus, 0); 13818 if (!isSystemApp(ps)) { 13819 // Do not uninstall the APK if an app should be cached 13820 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 13821 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 13822 // Other user still have this package installed, so all 13823 // we need to do is clear this user's data and save that 13824 // it is uninstalled. 13825 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 13826 removeUser = user.getIdentifier(); 13827 appId = ps.appId; 13828 scheduleWritePackageRestrictionsLocked(removeUser); 13829 } else { 13830 // We need to set it back to 'installed' so the uninstall 13831 // broadcasts will be sent correctly. 13832 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 13833 ps.setInstalled(true, user.getIdentifier()); 13834 } 13835 } else { 13836 // This is a system app, so we assume that the 13837 // other users still have this package installed, so all 13838 // we need to do is clear this user's data and save that 13839 // it is uninstalled. 13840 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 13841 removeUser = user.getIdentifier(); 13842 appId = ps.appId; 13843 scheduleWritePackageRestrictionsLocked(removeUser); 13844 } 13845 } 13846 } 13847 13848 if (removeUser >= 0) { 13849 // From above, we determined that we are deleting this only 13850 // for a single user. Continue the work here. 13851 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 13852 if (outInfo != null) { 13853 outInfo.removedPackage = packageName; 13854 outInfo.removedAppId = appId; 13855 outInfo.removedUsers = new int[] {removeUser}; 13856 } 13857 // TODO: triage flags as part of 26466827 13858 final int installerFlags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE; 13859 try { 13860 mInstaller.destroyAppData(ps.volumeUuid, packageName, removeUser, installerFlags); 13861 } catch (InstallerException e) { 13862 Slog.w(TAG, "Failed to delete app data", e); 13863 } 13864 removeKeystoreDataIfNeeded(removeUser, appId); 13865 schedulePackageCleaning(packageName, removeUser, false); 13866 synchronized (mPackages) { 13867 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 13868 scheduleWritePackageRestrictionsLocked(removeUser); 13869 } 13870 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser); 13871 } 13872 return true; 13873 } 13874 13875 if (dataOnly) { 13876 // Delete application data first 13877 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 13878 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 13879 return true; 13880 } 13881 13882 boolean ret = false; 13883 if (isSystemApp(ps)) { 13884 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 13885 // When an updated system application is deleted we delete the existing resources as well and 13886 // fall back to existing code in system partition 13887 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 13888 flags, outInfo, writeSettings); 13889 } else { 13890 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 13891 // Kill application pre-emptively especially for apps on sd. 13892 killApplication(packageName, ps.appId, "uninstall pkg"); 13893 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 13894 allUserHandles, perUserInstalled, 13895 outInfo, writeSettings); 13896 } 13897 13898 return ret; 13899 } 13900 13901 private final static class ClearStorageConnection implements ServiceConnection { 13902 IMediaContainerService mContainerService; 13903 13904 @Override 13905 public void onServiceConnected(ComponentName name, IBinder service) { 13906 synchronized (this) { 13907 mContainerService = IMediaContainerService.Stub.asInterface(service); 13908 notifyAll(); 13909 } 13910 } 13911 13912 @Override 13913 public void onServiceDisconnected(ComponentName name) { 13914 } 13915 } 13916 13917 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 13918 final boolean mounted; 13919 if (Environment.isExternalStorageEmulated()) { 13920 mounted = true; 13921 } else { 13922 final String status = Environment.getExternalStorageState(); 13923 13924 mounted = status.equals(Environment.MEDIA_MOUNTED) 13925 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 13926 } 13927 13928 if (!mounted) { 13929 return; 13930 } 13931 13932 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 13933 int[] users; 13934 if (userId == UserHandle.USER_ALL) { 13935 users = sUserManager.getUserIds(); 13936 } else { 13937 users = new int[] { userId }; 13938 } 13939 final ClearStorageConnection conn = new ClearStorageConnection(); 13940 if (mContext.bindServiceAsUser( 13941 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 13942 try { 13943 for (int curUser : users) { 13944 long timeout = SystemClock.uptimeMillis() + 5000; 13945 synchronized (conn) { 13946 long now = SystemClock.uptimeMillis(); 13947 while (conn.mContainerService == null && now < timeout) { 13948 try { 13949 conn.wait(timeout - now); 13950 } catch (InterruptedException e) { 13951 } 13952 } 13953 } 13954 if (conn.mContainerService == null) { 13955 return; 13956 } 13957 13958 final UserEnvironment userEnv = new UserEnvironment(curUser); 13959 clearDirectory(conn.mContainerService, 13960 userEnv.buildExternalStorageAppCacheDirs(packageName)); 13961 if (allData) { 13962 clearDirectory(conn.mContainerService, 13963 userEnv.buildExternalStorageAppDataDirs(packageName)); 13964 clearDirectory(conn.mContainerService, 13965 userEnv.buildExternalStorageAppMediaDirs(packageName)); 13966 } 13967 } 13968 } finally { 13969 mContext.unbindService(conn); 13970 } 13971 } 13972 } 13973 13974 @Override 13975 public void clearApplicationUserData(final String packageName, 13976 final IPackageDataObserver observer, final int userId) { 13977 mContext.enforceCallingOrSelfPermission( 13978 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 13979 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 13980 // Queue up an async operation since the package deletion may take a little while. 13981 mHandler.post(new Runnable() { 13982 public void run() { 13983 mHandler.removeCallbacks(this); 13984 final boolean succeeded; 13985 synchronized (mInstallLock) { 13986 succeeded = clearApplicationUserDataLI(packageName, userId); 13987 } 13988 clearExternalStorageDataSync(packageName, userId, true); 13989 if (succeeded) { 13990 // invoke DeviceStorageMonitor's update method to clear any notifications 13991 DeviceStorageMonitorInternal 13992 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13993 if (dsm != null) { 13994 dsm.checkMemory(); 13995 } 13996 } 13997 if(observer != null) { 13998 try { 13999 observer.onRemoveCompleted(packageName, succeeded); 14000 } catch (RemoteException e) { 14001 Log.i(TAG, "Observer no longer exists."); 14002 } 14003 } //end if observer 14004 } //end run 14005 }); 14006 } 14007 14008 private boolean clearApplicationUserDataLI(String packageName, int userId) { 14009 if (packageName == null) { 14010 Slog.w(TAG, "Attempt to delete null packageName."); 14011 return false; 14012 } 14013 14014 // Try finding details about the requested package 14015 PackageParser.Package pkg; 14016 synchronized (mPackages) { 14017 pkg = mPackages.get(packageName); 14018 if (pkg == null) { 14019 final PackageSetting ps = mSettings.mPackages.get(packageName); 14020 if (ps != null) { 14021 pkg = ps.pkg; 14022 } 14023 } 14024 14025 if (pkg == null) { 14026 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 14027 return false; 14028 } 14029 14030 PackageSetting ps = (PackageSetting) pkg.mExtras; 14031 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 14032 } 14033 14034 // Always delete data directories for package, even if we found no other 14035 // record of app. This helps users recover from UID mismatches without 14036 // resorting to a full data wipe. 14037 // TODO: triage flags as part of 26466827 14038 final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE; 14039 try { 14040 mInstaller.clearAppData(pkg.volumeUuid, packageName, userId, flags); 14041 } catch (InstallerException e) { 14042 Slog.w(TAG, "Couldn't remove cache files for package " + packageName, e); 14043 return false; 14044 } 14045 14046 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 14047 removeKeystoreDataIfNeeded(userId, appId); 14048 14049 // Create a native library symlink only if we have native libraries 14050 // and if the native libraries are 32 bit libraries. We do not provide 14051 // this symlink for 64 bit libraries. 14052 if (pkg.applicationInfo.primaryCpuAbi != null && 14053 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 14054 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 14055 try { 14056 mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 14057 nativeLibPath, userId); 14058 } catch (InstallerException e) { 14059 Slog.w(TAG, "Failed linking native library dir", e); 14060 return false; 14061 } 14062 } 14063 14064 return true; 14065 } 14066 14067 /** 14068 * Reverts user permission state changes (permissions and flags) in 14069 * all packages for a given user. 14070 * 14071 * @param userId The device user for which to do a reset. 14072 */ 14073 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 14074 final int packageCount = mPackages.size(); 14075 for (int i = 0; i < packageCount; i++) { 14076 PackageParser.Package pkg = mPackages.valueAt(i); 14077 PackageSetting ps = (PackageSetting) pkg.mExtras; 14078 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 14079 } 14080 } 14081 14082 /** 14083 * Reverts user permission state changes (permissions and flags). 14084 * 14085 * @param ps The package for which to reset. 14086 * @param userId The device user for which to do a reset. 14087 */ 14088 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 14089 final PackageSetting ps, final int userId) { 14090 if (ps.pkg == null) { 14091 return; 14092 } 14093 14094 // These are flags that can change base on user actions. 14095 final int userSettableMask = FLAG_PERMISSION_USER_SET 14096 | FLAG_PERMISSION_USER_FIXED 14097 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 14098 | FLAG_PERMISSION_REVIEW_REQUIRED; 14099 14100 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 14101 | FLAG_PERMISSION_POLICY_FIXED; 14102 14103 boolean writeInstallPermissions = false; 14104 boolean writeRuntimePermissions = false; 14105 14106 final int permissionCount = ps.pkg.requestedPermissions.size(); 14107 for (int i = 0; i < permissionCount; i++) { 14108 String permission = ps.pkg.requestedPermissions.get(i); 14109 14110 BasePermission bp = mSettings.mPermissions.get(permission); 14111 if (bp == null) { 14112 continue; 14113 } 14114 14115 // If shared user we just reset the state to which only this app contributed. 14116 if (ps.sharedUser != null) { 14117 boolean used = false; 14118 final int packageCount = ps.sharedUser.packages.size(); 14119 for (int j = 0; j < packageCount; j++) { 14120 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 14121 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 14122 && pkg.pkg.requestedPermissions.contains(permission)) { 14123 used = true; 14124 break; 14125 } 14126 } 14127 if (used) { 14128 continue; 14129 } 14130 } 14131 14132 PermissionsState permissionsState = ps.getPermissionsState(); 14133 14134 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 14135 14136 // Always clear the user settable flags. 14137 final boolean hasInstallState = permissionsState.getInstallPermissionState( 14138 bp.name) != null; 14139 // If permission review is enabled and this is a legacy app, mark the 14140 // permission as requiring a review as this is the initial state. 14141 int flags = 0; 14142 if (Build.PERMISSIONS_REVIEW_REQUIRED 14143 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 14144 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 14145 } 14146 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 14147 if (hasInstallState) { 14148 writeInstallPermissions = true; 14149 } else { 14150 writeRuntimePermissions = true; 14151 } 14152 } 14153 14154 // Below is only runtime permission handling. 14155 if (!bp.isRuntime()) { 14156 continue; 14157 } 14158 14159 // Never clobber system or policy. 14160 if ((oldFlags & policyOrSystemFlags) != 0) { 14161 continue; 14162 } 14163 14164 // If this permission was granted by default, make sure it is. 14165 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 14166 if (permissionsState.grantRuntimePermission(bp, userId) 14167 != PERMISSION_OPERATION_FAILURE) { 14168 writeRuntimePermissions = true; 14169 } 14170 // If permission review is enabled the permissions for a legacy apps 14171 // are represented as constantly granted runtime ones, so don't revoke. 14172 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 14173 // Otherwise, reset the permission. 14174 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 14175 switch (revokeResult) { 14176 case PERMISSION_OPERATION_SUCCESS: { 14177 writeRuntimePermissions = true; 14178 } break; 14179 14180 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 14181 writeRuntimePermissions = true; 14182 final int appId = ps.appId; 14183 mHandler.post(new Runnable() { 14184 @Override 14185 public void run() { 14186 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 14187 } 14188 }); 14189 } break; 14190 } 14191 } 14192 } 14193 14194 // Synchronously write as we are taking permissions away. 14195 if (writeRuntimePermissions) { 14196 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 14197 } 14198 14199 // Synchronously write as we are taking permissions away. 14200 if (writeInstallPermissions) { 14201 mSettings.writeLPr(); 14202 } 14203 } 14204 14205 /** 14206 * Remove entries from the keystore daemon. Will only remove it if the 14207 * {@code appId} is valid. 14208 */ 14209 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 14210 if (appId < 0) { 14211 return; 14212 } 14213 14214 final KeyStore keyStore = KeyStore.getInstance(); 14215 if (keyStore != null) { 14216 if (userId == UserHandle.USER_ALL) { 14217 for (final int individual : sUserManager.getUserIds()) { 14218 keyStore.clearUid(UserHandle.getUid(individual, appId)); 14219 } 14220 } else { 14221 keyStore.clearUid(UserHandle.getUid(userId, appId)); 14222 } 14223 } else { 14224 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 14225 } 14226 } 14227 14228 @Override 14229 public void deleteApplicationCacheFiles(final String packageName, 14230 final IPackageDataObserver observer) { 14231 mContext.enforceCallingOrSelfPermission( 14232 android.Manifest.permission.DELETE_CACHE_FILES, null); 14233 // Queue up an async operation since the package deletion may take a little while. 14234 final int userId = UserHandle.getCallingUserId(); 14235 mHandler.post(new Runnable() { 14236 public void run() { 14237 mHandler.removeCallbacks(this); 14238 final boolean succeded; 14239 synchronized (mInstallLock) { 14240 succeded = deleteApplicationCacheFilesLI(packageName, userId); 14241 } 14242 clearExternalStorageDataSync(packageName, userId, false); 14243 if (observer != null) { 14244 try { 14245 observer.onRemoveCompleted(packageName, succeded); 14246 } catch (RemoteException e) { 14247 Log.i(TAG, "Observer no longer exists."); 14248 } 14249 } //end if observer 14250 } //end run 14251 }); 14252 } 14253 14254 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 14255 if (packageName == null) { 14256 Slog.w(TAG, "Attempt to delete null packageName."); 14257 return false; 14258 } 14259 PackageParser.Package p; 14260 synchronized (mPackages) { 14261 p = mPackages.get(packageName); 14262 } 14263 if (p == null) { 14264 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 14265 return false; 14266 } 14267 final ApplicationInfo applicationInfo = p.applicationInfo; 14268 if (applicationInfo == null) { 14269 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 14270 return false; 14271 } 14272 // TODO: triage flags as part of 26466827 14273 final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE; 14274 try { 14275 mInstaller.clearAppData(p.volumeUuid, packageName, userId, 14276 flags | Installer.FLAG_CLEAR_CACHE_ONLY); 14277 } catch (InstallerException e) { 14278 Slog.w(TAG, "Couldn't remove cache files for package " 14279 + packageName + " u" + userId, e); 14280 return false; 14281 } 14282 return true; 14283 } 14284 14285 @Override 14286 public void getPackageSizeInfo(final String packageName, int userHandle, 14287 final IPackageStatsObserver observer) { 14288 mContext.enforceCallingOrSelfPermission( 14289 android.Manifest.permission.GET_PACKAGE_SIZE, null); 14290 if (packageName == null) { 14291 throw new IllegalArgumentException("Attempt to get size of null packageName"); 14292 } 14293 14294 PackageStats stats = new PackageStats(packageName, userHandle); 14295 14296 /* 14297 * Queue up an async operation since the package measurement may take a 14298 * little while. 14299 */ 14300 Message msg = mHandler.obtainMessage(INIT_COPY); 14301 msg.obj = new MeasureParams(stats, observer); 14302 mHandler.sendMessage(msg); 14303 } 14304 14305 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 14306 PackageStats pStats) { 14307 if (packageName == null) { 14308 Slog.w(TAG, "Attempt to get size of null packageName."); 14309 return false; 14310 } 14311 PackageParser.Package p; 14312 boolean dataOnly = false; 14313 String libDirRoot = null; 14314 String asecPath = null; 14315 PackageSetting ps = null; 14316 synchronized (mPackages) { 14317 p = mPackages.get(packageName); 14318 ps = mSettings.mPackages.get(packageName); 14319 if(p == null) { 14320 dataOnly = true; 14321 if((ps == null) || (ps.pkg == null)) { 14322 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 14323 return false; 14324 } 14325 p = ps.pkg; 14326 } 14327 if (ps != null) { 14328 libDirRoot = ps.legacyNativeLibraryPathString; 14329 } 14330 if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) { 14331 final long token = Binder.clearCallingIdentity(); 14332 try { 14333 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 14334 if (secureContainerId != null) { 14335 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 14336 } 14337 } finally { 14338 Binder.restoreCallingIdentity(token); 14339 } 14340 } 14341 } 14342 String publicSrcDir = null; 14343 if(!dataOnly) { 14344 final ApplicationInfo applicationInfo = p.applicationInfo; 14345 if (applicationInfo == null) { 14346 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 14347 return false; 14348 } 14349 if (p.isForwardLocked()) { 14350 publicSrcDir = applicationInfo.getBaseResourcePath(); 14351 } 14352 } 14353 // TODO: extend to measure size of split APKs 14354 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 14355 // not just the first level. 14356 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 14357 // just the primary. 14358 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 14359 14360 String apkPath; 14361 File packageDir = new File(p.codePath); 14362 14363 if (packageDir.isDirectory() && p.canHaveOatDir()) { 14364 apkPath = packageDir.getAbsolutePath(); 14365 // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice 14366 if (libDirRoot != null && libDirRoot.startsWith(apkPath)) { 14367 libDirRoot = null; 14368 } 14369 } else { 14370 apkPath = p.baseCodePath; 14371 } 14372 14373 // TODO: triage flags as part of 26466827 14374 final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE; 14375 try { 14376 mInstaller.getAppSize(p.volumeUuid, packageName, userHandle, flags, apkPath, 14377 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 14378 } catch (InstallerException e) { 14379 return false; 14380 } 14381 14382 // Fix-up for forward-locked applications in ASEC containers. 14383 if (!isExternal(p)) { 14384 pStats.codeSize += pStats.externalCodeSize; 14385 pStats.externalCodeSize = 0L; 14386 } 14387 14388 return true; 14389 } 14390 14391 14392 @Override 14393 public void addPackageToPreferred(String packageName) { 14394 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 14395 } 14396 14397 @Override 14398 public void removePackageFromPreferred(String packageName) { 14399 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 14400 } 14401 14402 @Override 14403 public List<PackageInfo> getPreferredPackages(int flags) { 14404 return new ArrayList<PackageInfo>(); 14405 } 14406 14407 private int getUidTargetSdkVersionLockedLPr(int uid) { 14408 Object obj = mSettings.getUserIdLPr(uid); 14409 if (obj instanceof SharedUserSetting) { 14410 final SharedUserSetting sus = (SharedUserSetting) obj; 14411 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 14412 final Iterator<PackageSetting> it = sus.packages.iterator(); 14413 while (it.hasNext()) { 14414 final PackageSetting ps = it.next(); 14415 if (ps.pkg != null) { 14416 int v = ps.pkg.applicationInfo.targetSdkVersion; 14417 if (v < vers) vers = v; 14418 } 14419 } 14420 return vers; 14421 } else if (obj instanceof PackageSetting) { 14422 final PackageSetting ps = (PackageSetting) obj; 14423 if (ps.pkg != null) { 14424 return ps.pkg.applicationInfo.targetSdkVersion; 14425 } 14426 } 14427 return Build.VERSION_CODES.CUR_DEVELOPMENT; 14428 } 14429 14430 @Override 14431 public void addPreferredActivity(IntentFilter filter, int match, 14432 ComponentName[] set, ComponentName activity, int userId) { 14433 addPreferredActivityInternal(filter, match, set, activity, true, userId, 14434 "Adding preferred"); 14435 } 14436 14437 private void addPreferredActivityInternal(IntentFilter filter, int match, 14438 ComponentName[] set, ComponentName activity, boolean always, int userId, 14439 String opname) { 14440 // writer 14441 int callingUid = Binder.getCallingUid(); 14442 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 14443 if (filter.countActions() == 0) { 14444 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 14445 return; 14446 } 14447 synchronized (mPackages) { 14448 if (mContext.checkCallingOrSelfPermission( 14449 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14450 != PackageManager.PERMISSION_GRANTED) { 14451 if (getUidTargetSdkVersionLockedLPr(callingUid) 14452 < Build.VERSION_CODES.FROYO) { 14453 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 14454 + callingUid); 14455 return; 14456 } 14457 mContext.enforceCallingOrSelfPermission( 14458 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14459 } 14460 14461 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 14462 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 14463 + userId + ":"); 14464 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14465 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 14466 scheduleWritePackageRestrictionsLocked(userId); 14467 } 14468 } 14469 14470 @Override 14471 public void replacePreferredActivity(IntentFilter filter, int match, 14472 ComponentName[] set, ComponentName activity, int userId) { 14473 if (filter.countActions() != 1) { 14474 throw new IllegalArgumentException( 14475 "replacePreferredActivity expects filter to have only 1 action."); 14476 } 14477 if (filter.countDataAuthorities() != 0 14478 || filter.countDataPaths() != 0 14479 || filter.countDataSchemes() > 1 14480 || filter.countDataTypes() != 0) { 14481 throw new IllegalArgumentException( 14482 "replacePreferredActivity expects filter to have no data authorities, " + 14483 "paths, or types; and at most one scheme."); 14484 } 14485 14486 final int callingUid = Binder.getCallingUid(); 14487 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 14488 synchronized (mPackages) { 14489 if (mContext.checkCallingOrSelfPermission( 14490 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14491 != PackageManager.PERMISSION_GRANTED) { 14492 if (getUidTargetSdkVersionLockedLPr(callingUid) 14493 < Build.VERSION_CODES.FROYO) { 14494 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 14495 + Binder.getCallingUid()); 14496 return; 14497 } 14498 mContext.enforceCallingOrSelfPermission( 14499 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14500 } 14501 14502 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 14503 if (pir != null) { 14504 // Get all of the existing entries that exactly match this filter. 14505 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 14506 if (existing != null && existing.size() == 1) { 14507 PreferredActivity cur = existing.get(0); 14508 if (DEBUG_PREFERRED) { 14509 Slog.i(TAG, "Checking replace of preferred:"); 14510 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14511 if (!cur.mPref.mAlways) { 14512 Slog.i(TAG, " -- CUR; not mAlways!"); 14513 } else { 14514 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 14515 Slog.i(TAG, " -- CUR: mSet=" 14516 + Arrays.toString(cur.mPref.mSetComponents)); 14517 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 14518 Slog.i(TAG, " -- NEW: mMatch=" 14519 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 14520 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 14521 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 14522 } 14523 } 14524 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 14525 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 14526 && cur.mPref.sameSet(set)) { 14527 // Setting the preferred activity to what it happens to be already 14528 if (DEBUG_PREFERRED) { 14529 Slog.i(TAG, "Replacing with same preferred activity " 14530 + cur.mPref.mShortComponent + " for user " 14531 + userId + ":"); 14532 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14533 } 14534 return; 14535 } 14536 } 14537 14538 if (existing != null) { 14539 if (DEBUG_PREFERRED) { 14540 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 14541 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14542 } 14543 for (int i = 0; i < existing.size(); i++) { 14544 PreferredActivity pa = existing.get(i); 14545 if (DEBUG_PREFERRED) { 14546 Slog.i(TAG, "Removing existing preferred activity " 14547 + pa.mPref.mComponent + ":"); 14548 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 14549 } 14550 pir.removeFilter(pa); 14551 } 14552 } 14553 } 14554 addPreferredActivityInternal(filter, match, set, activity, true, userId, 14555 "Replacing preferred"); 14556 } 14557 } 14558 14559 @Override 14560 public void clearPackagePreferredActivities(String packageName) { 14561 final int uid = Binder.getCallingUid(); 14562 // writer 14563 synchronized (mPackages) { 14564 PackageParser.Package pkg = mPackages.get(packageName); 14565 if (pkg == null || pkg.applicationInfo.uid != uid) { 14566 if (mContext.checkCallingOrSelfPermission( 14567 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14568 != PackageManager.PERMISSION_GRANTED) { 14569 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 14570 < Build.VERSION_CODES.FROYO) { 14571 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 14572 + Binder.getCallingUid()); 14573 return; 14574 } 14575 mContext.enforceCallingOrSelfPermission( 14576 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14577 } 14578 } 14579 14580 int user = UserHandle.getCallingUserId(); 14581 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 14582 scheduleWritePackageRestrictionsLocked(user); 14583 } 14584 } 14585 } 14586 14587 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14588 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 14589 ArrayList<PreferredActivity> removed = null; 14590 boolean changed = false; 14591 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14592 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 14593 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14594 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 14595 continue; 14596 } 14597 Iterator<PreferredActivity> it = pir.filterIterator(); 14598 while (it.hasNext()) { 14599 PreferredActivity pa = it.next(); 14600 // Mark entry for removal only if it matches the package name 14601 // and the entry is of type "always". 14602 if (packageName == null || 14603 (pa.mPref.mComponent.getPackageName().equals(packageName) 14604 && pa.mPref.mAlways)) { 14605 if (removed == null) { 14606 removed = new ArrayList<PreferredActivity>(); 14607 } 14608 removed.add(pa); 14609 } 14610 } 14611 if (removed != null) { 14612 for (int j=0; j<removed.size(); j++) { 14613 PreferredActivity pa = removed.get(j); 14614 pir.removeFilter(pa); 14615 } 14616 changed = true; 14617 } 14618 } 14619 return changed; 14620 } 14621 14622 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14623 private void clearIntentFilterVerificationsLPw(int userId) { 14624 final int packageCount = mPackages.size(); 14625 for (int i = 0; i < packageCount; i++) { 14626 PackageParser.Package pkg = mPackages.valueAt(i); 14627 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 14628 } 14629 } 14630 14631 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14632 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 14633 if (userId == UserHandle.USER_ALL) { 14634 if (mSettings.removeIntentFilterVerificationLPw(packageName, 14635 sUserManager.getUserIds())) { 14636 for (int oneUserId : sUserManager.getUserIds()) { 14637 scheduleWritePackageRestrictionsLocked(oneUserId); 14638 } 14639 } 14640 } else { 14641 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 14642 scheduleWritePackageRestrictionsLocked(userId); 14643 } 14644 } 14645 } 14646 14647 void clearDefaultBrowserIfNeeded(String packageName) { 14648 for (int oneUserId : sUserManager.getUserIds()) { 14649 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 14650 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 14651 if (packageName.equals(defaultBrowserPackageName)) { 14652 setDefaultBrowserPackageName(null, oneUserId); 14653 } 14654 } 14655 } 14656 14657 @Override 14658 public void resetApplicationPreferences(int userId) { 14659 mContext.enforceCallingOrSelfPermission( 14660 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14661 // writer 14662 synchronized (mPackages) { 14663 final long identity = Binder.clearCallingIdentity(); 14664 try { 14665 clearPackagePreferredActivitiesLPw(null, userId); 14666 mSettings.applyDefaultPreferredAppsLPw(this, userId); 14667 // TODO: We have to reset the default SMS and Phone. This requires 14668 // significant refactoring to keep all default apps in the package 14669 // manager (cleaner but more work) or have the services provide 14670 // callbacks to the package manager to request a default app reset. 14671 applyFactoryDefaultBrowserLPw(userId); 14672 clearIntentFilterVerificationsLPw(userId); 14673 primeDomainVerificationsLPw(userId); 14674 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 14675 scheduleWritePackageRestrictionsLocked(userId); 14676 } finally { 14677 Binder.restoreCallingIdentity(identity); 14678 } 14679 } 14680 } 14681 14682 @Override 14683 public int getPreferredActivities(List<IntentFilter> outFilters, 14684 List<ComponentName> outActivities, String packageName) { 14685 14686 int num = 0; 14687 final int userId = UserHandle.getCallingUserId(); 14688 // reader 14689 synchronized (mPackages) { 14690 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 14691 if (pir != null) { 14692 final Iterator<PreferredActivity> it = pir.filterIterator(); 14693 while (it.hasNext()) { 14694 final PreferredActivity pa = it.next(); 14695 if (packageName == null 14696 || (pa.mPref.mComponent.getPackageName().equals(packageName) 14697 && pa.mPref.mAlways)) { 14698 if (outFilters != null) { 14699 outFilters.add(new IntentFilter(pa)); 14700 } 14701 if (outActivities != null) { 14702 outActivities.add(pa.mPref.mComponent); 14703 } 14704 } 14705 } 14706 } 14707 } 14708 14709 return num; 14710 } 14711 14712 @Override 14713 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 14714 int userId) { 14715 int callingUid = Binder.getCallingUid(); 14716 if (callingUid != Process.SYSTEM_UID) { 14717 throw new SecurityException( 14718 "addPersistentPreferredActivity can only be run by the system"); 14719 } 14720 if (filter.countActions() == 0) { 14721 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 14722 return; 14723 } 14724 synchronized (mPackages) { 14725 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 14726 ":"); 14727 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14728 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 14729 new PersistentPreferredActivity(filter, activity)); 14730 scheduleWritePackageRestrictionsLocked(userId); 14731 } 14732 } 14733 14734 @Override 14735 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 14736 int callingUid = Binder.getCallingUid(); 14737 if (callingUid != Process.SYSTEM_UID) { 14738 throw new SecurityException( 14739 "clearPackagePersistentPreferredActivities can only be run by the system"); 14740 } 14741 ArrayList<PersistentPreferredActivity> removed = null; 14742 boolean changed = false; 14743 synchronized (mPackages) { 14744 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 14745 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 14746 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 14747 .valueAt(i); 14748 if (userId != thisUserId) { 14749 continue; 14750 } 14751 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 14752 while (it.hasNext()) { 14753 PersistentPreferredActivity ppa = it.next(); 14754 // Mark entry for removal only if it matches the package name. 14755 if (ppa.mComponent.getPackageName().equals(packageName)) { 14756 if (removed == null) { 14757 removed = new ArrayList<PersistentPreferredActivity>(); 14758 } 14759 removed.add(ppa); 14760 } 14761 } 14762 if (removed != null) { 14763 for (int j=0; j<removed.size(); j++) { 14764 PersistentPreferredActivity ppa = removed.get(j); 14765 ppir.removeFilter(ppa); 14766 } 14767 changed = true; 14768 } 14769 } 14770 14771 if (changed) { 14772 scheduleWritePackageRestrictionsLocked(userId); 14773 } 14774 } 14775 } 14776 14777 /** 14778 * Common machinery for picking apart a restored XML blob and passing 14779 * it to a caller-supplied functor to be applied to the running system. 14780 */ 14781 private void restoreFromXml(XmlPullParser parser, int userId, 14782 String expectedStartTag, BlobXmlRestorer functor) 14783 throws IOException, XmlPullParserException { 14784 int type; 14785 while ((type = parser.next()) != XmlPullParser.START_TAG 14786 && type != XmlPullParser.END_DOCUMENT) { 14787 } 14788 if (type != XmlPullParser.START_TAG) { 14789 // oops didn't find a start tag?! 14790 if (DEBUG_BACKUP) { 14791 Slog.e(TAG, "Didn't find start tag during restore"); 14792 } 14793 return; 14794 } 14795Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 14796 // this is supposed to be TAG_PREFERRED_BACKUP 14797 if (!expectedStartTag.equals(parser.getName())) { 14798 if (DEBUG_BACKUP) { 14799 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 14800 } 14801 return; 14802 } 14803 14804 // skip interfering stuff, then we're aligned with the backing implementation 14805 while ((type = parser.next()) == XmlPullParser.TEXT) { } 14806Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 14807 functor.apply(parser, userId); 14808 } 14809 14810 private interface BlobXmlRestorer { 14811 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 14812 } 14813 14814 /** 14815 * Non-Binder method, support for the backup/restore mechanism: write the 14816 * full set of preferred activities in its canonical XML format. Returns the 14817 * XML output as a byte array, or null if there is none. 14818 */ 14819 @Override 14820 public byte[] getPreferredActivityBackup(int userId) { 14821 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14822 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 14823 } 14824 14825 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14826 try { 14827 final XmlSerializer serializer = new FastXmlSerializer(); 14828 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14829 serializer.startDocument(null, true); 14830 serializer.startTag(null, TAG_PREFERRED_BACKUP); 14831 14832 synchronized (mPackages) { 14833 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 14834 } 14835 14836 serializer.endTag(null, TAG_PREFERRED_BACKUP); 14837 serializer.endDocument(); 14838 serializer.flush(); 14839 } catch (Exception e) { 14840 if (DEBUG_BACKUP) { 14841 Slog.e(TAG, "Unable to write preferred activities for backup", e); 14842 } 14843 return null; 14844 } 14845 14846 return dataStream.toByteArray(); 14847 } 14848 14849 @Override 14850 public void restorePreferredActivities(byte[] backup, int userId) { 14851 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14852 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14853 } 14854 14855 try { 14856 final XmlPullParser parser = Xml.newPullParser(); 14857 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14858 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 14859 new BlobXmlRestorer() { 14860 @Override 14861 public void apply(XmlPullParser parser, int userId) 14862 throws XmlPullParserException, IOException { 14863 synchronized (mPackages) { 14864 mSettings.readPreferredActivitiesLPw(parser, userId); 14865 } 14866 } 14867 } ); 14868 } catch (Exception e) { 14869 if (DEBUG_BACKUP) { 14870 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14871 } 14872 } 14873 } 14874 14875 /** 14876 * Non-Binder method, support for the backup/restore mechanism: write the 14877 * default browser (etc) settings in its canonical XML format. Returns the default 14878 * browser XML representation as a byte array, or null if there is none. 14879 */ 14880 @Override 14881 public byte[] getDefaultAppsBackup(int userId) { 14882 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14883 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 14884 } 14885 14886 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14887 try { 14888 final XmlSerializer serializer = new FastXmlSerializer(); 14889 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14890 serializer.startDocument(null, true); 14891 serializer.startTag(null, TAG_DEFAULT_APPS); 14892 14893 synchronized (mPackages) { 14894 mSettings.writeDefaultAppsLPr(serializer, userId); 14895 } 14896 14897 serializer.endTag(null, TAG_DEFAULT_APPS); 14898 serializer.endDocument(); 14899 serializer.flush(); 14900 } catch (Exception e) { 14901 if (DEBUG_BACKUP) { 14902 Slog.e(TAG, "Unable to write default apps for backup", e); 14903 } 14904 return null; 14905 } 14906 14907 return dataStream.toByteArray(); 14908 } 14909 14910 @Override 14911 public void restoreDefaultApps(byte[] backup, int userId) { 14912 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14913 throw new SecurityException("Only the system may call restoreDefaultApps()"); 14914 } 14915 14916 try { 14917 final XmlPullParser parser = Xml.newPullParser(); 14918 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14919 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 14920 new BlobXmlRestorer() { 14921 @Override 14922 public void apply(XmlPullParser parser, int userId) 14923 throws XmlPullParserException, IOException { 14924 synchronized (mPackages) { 14925 mSettings.readDefaultAppsLPw(parser, userId); 14926 } 14927 } 14928 } ); 14929 } catch (Exception e) { 14930 if (DEBUG_BACKUP) { 14931 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 14932 } 14933 } 14934 } 14935 14936 @Override 14937 public byte[] getIntentFilterVerificationBackup(int userId) { 14938 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14939 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 14940 } 14941 14942 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14943 try { 14944 final XmlSerializer serializer = new FastXmlSerializer(); 14945 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14946 serializer.startDocument(null, true); 14947 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 14948 14949 synchronized (mPackages) { 14950 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 14951 } 14952 14953 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 14954 serializer.endDocument(); 14955 serializer.flush(); 14956 } catch (Exception e) { 14957 if (DEBUG_BACKUP) { 14958 Slog.e(TAG, "Unable to write default apps for backup", e); 14959 } 14960 return null; 14961 } 14962 14963 return dataStream.toByteArray(); 14964 } 14965 14966 @Override 14967 public void restoreIntentFilterVerification(byte[] backup, int userId) { 14968 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14969 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14970 } 14971 14972 try { 14973 final XmlPullParser parser = Xml.newPullParser(); 14974 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14975 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 14976 new BlobXmlRestorer() { 14977 @Override 14978 public void apply(XmlPullParser parser, int userId) 14979 throws XmlPullParserException, IOException { 14980 synchronized (mPackages) { 14981 mSettings.readAllDomainVerificationsLPr(parser, userId); 14982 mSettings.writeLPr(); 14983 } 14984 } 14985 } ); 14986 } catch (Exception e) { 14987 if (DEBUG_BACKUP) { 14988 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14989 } 14990 } 14991 } 14992 14993 @Override 14994 public byte[] getPermissionGrantBackup(int userId) { 14995 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14996 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 14997 } 14998 14999 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 15000 try { 15001 final XmlSerializer serializer = new FastXmlSerializer(); 15002 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 15003 serializer.startDocument(null, true); 15004 serializer.startTag(null, TAG_PERMISSION_BACKUP); 15005 15006 synchronized (mPackages) { 15007 serializeRuntimePermissionGrantsLPr(serializer, userId); 15008 } 15009 15010 serializer.endTag(null, TAG_PERMISSION_BACKUP); 15011 serializer.endDocument(); 15012 serializer.flush(); 15013 } catch (Exception e) { 15014 if (DEBUG_BACKUP) { 15015 Slog.e(TAG, "Unable to write default apps for backup", e); 15016 } 15017 return null; 15018 } 15019 15020 return dataStream.toByteArray(); 15021 } 15022 15023 @Override 15024 public void restorePermissionGrants(byte[] backup, int userId) { 15025 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15026 throw new SecurityException("Only the system may call restorePermissionGrants()"); 15027 } 15028 15029 try { 15030 final XmlPullParser parser = Xml.newPullParser(); 15031 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 15032 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 15033 new BlobXmlRestorer() { 15034 @Override 15035 public void apply(XmlPullParser parser, int userId) 15036 throws XmlPullParserException, IOException { 15037 synchronized (mPackages) { 15038 processRestoredPermissionGrantsLPr(parser, userId); 15039 } 15040 } 15041 } ); 15042 } catch (Exception e) { 15043 if (DEBUG_BACKUP) { 15044 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 15045 } 15046 } 15047 } 15048 15049 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 15050 throws IOException { 15051 serializer.startTag(null, TAG_ALL_GRANTS); 15052 15053 final int N = mSettings.mPackages.size(); 15054 for (int i = 0; i < N; i++) { 15055 final PackageSetting ps = mSettings.mPackages.valueAt(i); 15056 boolean pkgGrantsKnown = false; 15057 15058 PermissionsState packagePerms = ps.getPermissionsState(); 15059 15060 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 15061 final int grantFlags = state.getFlags(); 15062 // only look at grants that are not system/policy fixed 15063 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 15064 final boolean isGranted = state.isGranted(); 15065 // And only back up the user-twiddled state bits 15066 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 15067 final String packageName = mSettings.mPackages.keyAt(i); 15068 if (!pkgGrantsKnown) { 15069 serializer.startTag(null, TAG_GRANT); 15070 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 15071 pkgGrantsKnown = true; 15072 } 15073 15074 final boolean userSet = 15075 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 15076 final boolean userFixed = 15077 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 15078 final boolean revoke = 15079 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 15080 15081 serializer.startTag(null, TAG_PERMISSION); 15082 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 15083 if (isGranted) { 15084 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 15085 } 15086 if (userSet) { 15087 serializer.attribute(null, ATTR_USER_SET, "true"); 15088 } 15089 if (userFixed) { 15090 serializer.attribute(null, ATTR_USER_FIXED, "true"); 15091 } 15092 if (revoke) { 15093 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 15094 } 15095 serializer.endTag(null, TAG_PERMISSION); 15096 } 15097 } 15098 } 15099 15100 if (pkgGrantsKnown) { 15101 serializer.endTag(null, TAG_GRANT); 15102 } 15103 } 15104 15105 serializer.endTag(null, TAG_ALL_GRANTS); 15106 } 15107 15108 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 15109 throws XmlPullParserException, IOException { 15110 String pkgName = null; 15111 int outerDepth = parser.getDepth(); 15112 int type; 15113 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 15114 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 15115 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 15116 continue; 15117 } 15118 15119 final String tagName = parser.getName(); 15120 if (tagName.equals(TAG_GRANT)) { 15121 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 15122 if (DEBUG_BACKUP) { 15123 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 15124 } 15125 } else if (tagName.equals(TAG_PERMISSION)) { 15126 15127 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 15128 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 15129 15130 int newFlagSet = 0; 15131 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 15132 newFlagSet |= FLAG_PERMISSION_USER_SET; 15133 } 15134 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 15135 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 15136 } 15137 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 15138 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 15139 } 15140 if (DEBUG_BACKUP) { 15141 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 15142 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 15143 } 15144 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15145 if (ps != null) { 15146 // Already installed so we apply the grant immediately 15147 if (DEBUG_BACKUP) { 15148 Slog.v(TAG, " + already installed; applying"); 15149 } 15150 PermissionsState perms = ps.getPermissionsState(); 15151 BasePermission bp = mSettings.mPermissions.get(permName); 15152 if (bp != null) { 15153 if (isGranted) { 15154 perms.grantRuntimePermission(bp, userId); 15155 } 15156 if (newFlagSet != 0) { 15157 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 15158 } 15159 } 15160 } else { 15161 // Need to wait for post-restore install to apply the grant 15162 if (DEBUG_BACKUP) { 15163 Slog.v(TAG, " - not yet installed; saving for later"); 15164 } 15165 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 15166 isGranted, newFlagSet, userId); 15167 } 15168 } else { 15169 PackageManagerService.reportSettingsProblem(Log.WARN, 15170 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 15171 XmlUtils.skipCurrentTag(parser); 15172 } 15173 } 15174 15175 scheduleWriteSettingsLocked(); 15176 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 15177 } 15178 15179 @Override 15180 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 15181 int sourceUserId, int targetUserId, int flags) { 15182 mContext.enforceCallingOrSelfPermission( 15183 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 15184 int callingUid = Binder.getCallingUid(); 15185 enforceOwnerRights(ownerPackage, callingUid); 15186 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 15187 if (intentFilter.countActions() == 0) { 15188 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 15189 return; 15190 } 15191 synchronized (mPackages) { 15192 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 15193 ownerPackage, targetUserId, flags); 15194 CrossProfileIntentResolver resolver = 15195 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 15196 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 15197 // We have all those whose filter is equal. Now checking if the rest is equal as well. 15198 if (existing != null) { 15199 int size = existing.size(); 15200 for (int i = 0; i < size; i++) { 15201 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 15202 return; 15203 } 15204 } 15205 } 15206 resolver.addFilter(newFilter); 15207 scheduleWritePackageRestrictionsLocked(sourceUserId); 15208 } 15209 } 15210 15211 @Override 15212 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 15213 mContext.enforceCallingOrSelfPermission( 15214 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 15215 int callingUid = Binder.getCallingUid(); 15216 enforceOwnerRights(ownerPackage, callingUid); 15217 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 15218 synchronized (mPackages) { 15219 CrossProfileIntentResolver resolver = 15220 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 15221 ArraySet<CrossProfileIntentFilter> set = 15222 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 15223 for (CrossProfileIntentFilter filter : set) { 15224 if (filter.getOwnerPackage().equals(ownerPackage)) { 15225 resolver.removeFilter(filter); 15226 } 15227 } 15228 scheduleWritePackageRestrictionsLocked(sourceUserId); 15229 } 15230 } 15231 15232 // Enforcing that callingUid is owning pkg on userId 15233 private void enforceOwnerRights(String pkg, int callingUid) { 15234 // The system owns everything. 15235 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 15236 return; 15237 } 15238 int callingUserId = UserHandle.getUserId(callingUid); 15239 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 15240 if (pi == null) { 15241 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 15242 + callingUserId); 15243 } 15244 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 15245 throw new SecurityException("Calling uid " + callingUid 15246 + " does not own package " + pkg); 15247 } 15248 } 15249 15250 @Override 15251 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 15252 Intent intent = new Intent(Intent.ACTION_MAIN); 15253 intent.addCategory(Intent.CATEGORY_HOME); 15254 15255 final int callingUserId = UserHandle.getCallingUserId(); 15256 List<ResolveInfo> list = queryIntentActivities(intent, null, 15257 PackageManager.GET_META_DATA, callingUserId); 15258 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 15259 true, false, false, callingUserId); 15260 15261 allHomeCandidates.clear(); 15262 if (list != null) { 15263 for (ResolveInfo ri : list) { 15264 allHomeCandidates.add(ri); 15265 } 15266 } 15267 return (preferred == null || preferred.activityInfo == null) 15268 ? null 15269 : new ComponentName(preferred.activityInfo.packageName, 15270 preferred.activityInfo.name); 15271 } 15272 15273 @Override 15274 public void setApplicationEnabledSetting(String appPackageName, 15275 int newState, int flags, int userId, String callingPackage) { 15276 if (!sUserManager.exists(userId)) return; 15277 if (callingPackage == null) { 15278 callingPackage = Integer.toString(Binder.getCallingUid()); 15279 } 15280 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 15281 } 15282 15283 @Override 15284 public void setComponentEnabledSetting(ComponentName componentName, 15285 int newState, int flags, int userId) { 15286 if (!sUserManager.exists(userId)) return; 15287 setEnabledSetting(componentName.getPackageName(), 15288 componentName.getClassName(), newState, flags, userId, null); 15289 } 15290 15291 private void setEnabledSetting(final String packageName, String className, int newState, 15292 final int flags, int userId, String callingPackage) { 15293 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 15294 || newState == COMPONENT_ENABLED_STATE_ENABLED 15295 || newState == COMPONENT_ENABLED_STATE_DISABLED 15296 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 15297 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 15298 throw new IllegalArgumentException("Invalid new component state: " 15299 + newState); 15300 } 15301 PackageSetting pkgSetting; 15302 final int uid = Binder.getCallingUid(); 15303 final int permission = mContext.checkCallingOrSelfPermission( 15304 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 15305 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 15306 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 15307 boolean sendNow = false; 15308 boolean isApp = (className == null); 15309 String componentName = isApp ? packageName : className; 15310 int packageUid = -1; 15311 ArrayList<String> components; 15312 15313 // writer 15314 synchronized (mPackages) { 15315 pkgSetting = mSettings.mPackages.get(packageName); 15316 if (pkgSetting == null) { 15317 if (className == null) { 15318 throw new IllegalArgumentException("Unknown package: " + packageName); 15319 } 15320 throw new IllegalArgumentException( 15321 "Unknown component: " + packageName + "/" + className); 15322 } 15323 // Allow root and verify that userId is not being specified by a different user 15324 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 15325 throw new SecurityException( 15326 "Permission Denial: attempt to change component state from pid=" 15327 + Binder.getCallingPid() 15328 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 15329 } 15330 if (className == null) { 15331 // We're dealing with an application/package level state change 15332 if (pkgSetting.getEnabled(userId) == newState) { 15333 // Nothing to do 15334 return; 15335 } 15336 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 15337 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 15338 // Don't care about who enables an app. 15339 callingPackage = null; 15340 } 15341 pkgSetting.setEnabled(newState, userId, callingPackage); 15342 // pkgSetting.pkg.mSetEnabled = newState; 15343 } else { 15344 // We're dealing with a component level state change 15345 // First, verify that this is a valid class name. 15346 PackageParser.Package pkg = pkgSetting.pkg; 15347 if (pkg == null || !pkg.hasComponentClassName(className)) { 15348 if (pkg != null && 15349 pkg.applicationInfo.targetSdkVersion >= 15350 Build.VERSION_CODES.JELLY_BEAN) { 15351 throw new IllegalArgumentException("Component class " + className 15352 + " does not exist in " + packageName); 15353 } else { 15354 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 15355 + className + " does not exist in " + packageName); 15356 } 15357 } 15358 switch (newState) { 15359 case COMPONENT_ENABLED_STATE_ENABLED: 15360 if (!pkgSetting.enableComponentLPw(className, userId)) { 15361 return; 15362 } 15363 break; 15364 case COMPONENT_ENABLED_STATE_DISABLED: 15365 if (!pkgSetting.disableComponentLPw(className, userId)) { 15366 return; 15367 } 15368 break; 15369 case COMPONENT_ENABLED_STATE_DEFAULT: 15370 if (!pkgSetting.restoreComponentLPw(className, userId)) { 15371 return; 15372 } 15373 break; 15374 default: 15375 Slog.e(TAG, "Invalid new component state: " + newState); 15376 return; 15377 } 15378 } 15379 scheduleWritePackageRestrictionsLocked(userId); 15380 components = mPendingBroadcasts.get(userId, packageName); 15381 final boolean newPackage = components == null; 15382 if (newPackage) { 15383 components = new ArrayList<String>(); 15384 } 15385 if (!components.contains(componentName)) { 15386 components.add(componentName); 15387 } 15388 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 15389 sendNow = true; 15390 // Purge entry from pending broadcast list if another one exists already 15391 // since we are sending one right away. 15392 mPendingBroadcasts.remove(userId, packageName); 15393 } else { 15394 if (newPackage) { 15395 mPendingBroadcasts.put(userId, packageName, components); 15396 } 15397 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 15398 // Schedule a message 15399 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 15400 } 15401 } 15402 } 15403 15404 long callingId = Binder.clearCallingIdentity(); 15405 try { 15406 if (sendNow) { 15407 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 15408 sendPackageChangedBroadcast(packageName, 15409 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 15410 } 15411 } finally { 15412 Binder.restoreCallingIdentity(callingId); 15413 } 15414 } 15415 15416 private void sendPackageChangedBroadcast(String packageName, 15417 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 15418 if (DEBUG_INSTALL) 15419 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 15420 + componentNames); 15421 Bundle extras = new Bundle(4); 15422 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 15423 String nameList[] = new String[componentNames.size()]; 15424 componentNames.toArray(nameList); 15425 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 15426 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 15427 extras.putInt(Intent.EXTRA_UID, packageUid); 15428 // If this is not reporting a change of the overall package, then only send it 15429 // to registered receivers. We don't want to launch a swath of apps for every 15430 // little component state change. 15431 final int flags = !componentNames.contains(packageName) 15432 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 15433 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 15434 new int[] {UserHandle.getUserId(packageUid)}); 15435 } 15436 15437 @Override 15438 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 15439 if (!sUserManager.exists(userId)) return; 15440 final int uid = Binder.getCallingUid(); 15441 final int permission = mContext.checkCallingOrSelfPermission( 15442 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 15443 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 15444 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 15445 // writer 15446 synchronized (mPackages) { 15447 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 15448 allowedByPermission, uid, userId)) { 15449 scheduleWritePackageRestrictionsLocked(userId); 15450 } 15451 } 15452 } 15453 15454 @Override 15455 public String getInstallerPackageName(String packageName) { 15456 // reader 15457 synchronized (mPackages) { 15458 return mSettings.getInstallerPackageNameLPr(packageName); 15459 } 15460 } 15461 15462 @Override 15463 public int getApplicationEnabledSetting(String packageName, int userId) { 15464 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 15465 int uid = Binder.getCallingUid(); 15466 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 15467 // reader 15468 synchronized (mPackages) { 15469 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 15470 } 15471 } 15472 15473 @Override 15474 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 15475 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 15476 int uid = Binder.getCallingUid(); 15477 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 15478 // reader 15479 synchronized (mPackages) { 15480 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 15481 } 15482 } 15483 15484 @Override 15485 public void enterSafeMode() { 15486 enforceSystemOrRoot("Only the system can request entering safe mode"); 15487 15488 if (!mSystemReady) { 15489 mSafeMode = true; 15490 } 15491 } 15492 15493 @Override 15494 public void systemReady() { 15495 mSystemReady = true; 15496 15497 // Read the compatibilty setting when the system is ready. 15498 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 15499 mContext.getContentResolver(), 15500 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 15501 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 15502 if (DEBUG_SETTINGS) { 15503 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 15504 } 15505 15506 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 15507 15508 synchronized (mPackages) { 15509 // Verify that all of the preferred activity components actually 15510 // exist. It is possible for applications to be updated and at 15511 // that point remove a previously declared activity component that 15512 // had been set as a preferred activity. We try to clean this up 15513 // the next time we encounter that preferred activity, but it is 15514 // possible for the user flow to never be able to return to that 15515 // situation so here we do a sanity check to make sure we haven't 15516 // left any junk around. 15517 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 15518 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 15519 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 15520 removed.clear(); 15521 for (PreferredActivity pa : pir.filterSet()) { 15522 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 15523 removed.add(pa); 15524 } 15525 } 15526 if (removed.size() > 0) { 15527 for (int r=0; r<removed.size(); r++) { 15528 PreferredActivity pa = removed.get(r); 15529 Slog.w(TAG, "Removing dangling preferred activity: " 15530 + pa.mPref.mComponent); 15531 pir.removeFilter(pa); 15532 } 15533 mSettings.writePackageRestrictionsLPr( 15534 mSettings.mPreferredActivities.keyAt(i)); 15535 } 15536 } 15537 15538 for (int userId : UserManagerService.getInstance().getUserIds()) { 15539 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 15540 grantPermissionsUserIds = ArrayUtils.appendInt( 15541 grantPermissionsUserIds, userId); 15542 } 15543 } 15544 } 15545 sUserManager.systemReady(); 15546 15547 // If we upgraded grant all default permissions before kicking off. 15548 for (int userId : grantPermissionsUserIds) { 15549 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 15550 } 15551 15552 // Kick off any messages waiting for system ready 15553 if (mPostSystemReadyMessages != null) { 15554 for (Message msg : mPostSystemReadyMessages) { 15555 msg.sendToTarget(); 15556 } 15557 mPostSystemReadyMessages = null; 15558 } 15559 15560 // Watch for external volumes that come and go over time 15561 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15562 storage.registerListener(mStorageListener); 15563 15564 mInstallerService.systemReady(); 15565 mPackageDexOptimizer.systemReady(); 15566 15567 MountServiceInternal mountServiceInternal = LocalServices.getService( 15568 MountServiceInternal.class); 15569 mountServiceInternal.addExternalStoragePolicy( 15570 new MountServiceInternal.ExternalStorageMountPolicy() { 15571 @Override 15572 public int getMountMode(int uid, String packageName) { 15573 if (Process.isIsolated(uid)) { 15574 return Zygote.MOUNT_EXTERNAL_NONE; 15575 } 15576 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 15577 return Zygote.MOUNT_EXTERNAL_DEFAULT; 15578 } 15579 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 15580 return Zygote.MOUNT_EXTERNAL_DEFAULT; 15581 } 15582 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 15583 return Zygote.MOUNT_EXTERNAL_READ; 15584 } 15585 return Zygote.MOUNT_EXTERNAL_WRITE; 15586 } 15587 15588 @Override 15589 public boolean hasExternalStorage(int uid, String packageName) { 15590 return true; 15591 } 15592 }); 15593 } 15594 15595 @Override 15596 public boolean isSafeMode() { 15597 return mSafeMode; 15598 } 15599 15600 @Override 15601 public boolean hasSystemUidErrors() { 15602 return mHasSystemUidErrors; 15603 } 15604 15605 static String arrayToString(int[] array) { 15606 StringBuffer buf = new StringBuffer(128); 15607 buf.append('['); 15608 if (array != null) { 15609 for (int i=0; i<array.length; i++) { 15610 if (i > 0) buf.append(", "); 15611 buf.append(array[i]); 15612 } 15613 } 15614 buf.append(']'); 15615 return buf.toString(); 15616 } 15617 15618 static class DumpState { 15619 public static final int DUMP_LIBS = 1 << 0; 15620 public static final int DUMP_FEATURES = 1 << 1; 15621 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 15622 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 15623 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 15624 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 15625 public static final int DUMP_PERMISSIONS = 1 << 6; 15626 public static final int DUMP_PACKAGES = 1 << 7; 15627 public static final int DUMP_SHARED_USERS = 1 << 8; 15628 public static final int DUMP_MESSAGES = 1 << 9; 15629 public static final int DUMP_PROVIDERS = 1 << 10; 15630 public static final int DUMP_VERIFIERS = 1 << 11; 15631 public static final int DUMP_PREFERRED = 1 << 12; 15632 public static final int DUMP_PREFERRED_XML = 1 << 13; 15633 public static final int DUMP_KEYSETS = 1 << 14; 15634 public static final int DUMP_VERSION = 1 << 15; 15635 public static final int DUMP_INSTALLS = 1 << 16; 15636 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 15637 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 15638 15639 public static final int OPTION_SHOW_FILTERS = 1 << 0; 15640 15641 private int mTypes; 15642 15643 private int mOptions; 15644 15645 private boolean mTitlePrinted; 15646 15647 private SharedUserSetting mSharedUser; 15648 15649 public boolean isDumping(int type) { 15650 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 15651 return true; 15652 } 15653 15654 return (mTypes & type) != 0; 15655 } 15656 15657 public void setDump(int type) { 15658 mTypes |= type; 15659 } 15660 15661 public boolean isOptionEnabled(int option) { 15662 return (mOptions & option) != 0; 15663 } 15664 15665 public void setOptionEnabled(int option) { 15666 mOptions |= option; 15667 } 15668 15669 public boolean onTitlePrinted() { 15670 final boolean printed = mTitlePrinted; 15671 mTitlePrinted = true; 15672 return printed; 15673 } 15674 15675 public boolean getTitlePrinted() { 15676 return mTitlePrinted; 15677 } 15678 15679 public void setTitlePrinted(boolean enabled) { 15680 mTitlePrinted = enabled; 15681 } 15682 15683 public SharedUserSetting getSharedUser() { 15684 return mSharedUser; 15685 } 15686 15687 public void setSharedUser(SharedUserSetting user) { 15688 mSharedUser = user; 15689 } 15690 } 15691 15692 @Override 15693 public void onShellCommand(FileDescriptor in, FileDescriptor out, 15694 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 15695 (new PackageManagerShellCommand(this)).exec( 15696 this, in, out, err, args, resultReceiver); 15697 } 15698 15699 @Override 15700 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 15701 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 15702 != PackageManager.PERMISSION_GRANTED) { 15703 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 15704 + Binder.getCallingPid() 15705 + ", uid=" + Binder.getCallingUid() 15706 + " without permission " 15707 + android.Manifest.permission.DUMP); 15708 return; 15709 } 15710 15711 DumpState dumpState = new DumpState(); 15712 boolean fullPreferred = false; 15713 boolean checkin = false; 15714 15715 String packageName = null; 15716 ArraySet<String> permissionNames = null; 15717 15718 int opti = 0; 15719 while (opti < args.length) { 15720 String opt = args[opti]; 15721 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 15722 break; 15723 } 15724 opti++; 15725 15726 if ("-a".equals(opt)) { 15727 // Right now we only know how to print all. 15728 } else if ("-h".equals(opt)) { 15729 pw.println("Package manager dump options:"); 15730 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 15731 pw.println(" --checkin: dump for a checkin"); 15732 pw.println(" -f: print details of intent filters"); 15733 pw.println(" -h: print this help"); 15734 pw.println(" cmd may be one of:"); 15735 pw.println(" l[ibraries]: list known shared libraries"); 15736 pw.println(" f[eatures]: list device features"); 15737 pw.println(" k[eysets]: print known keysets"); 15738 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 15739 pw.println(" perm[issions]: dump permissions"); 15740 pw.println(" permission [name ...]: dump declaration and use of given permission"); 15741 pw.println(" pref[erred]: print preferred package settings"); 15742 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 15743 pw.println(" prov[iders]: dump content providers"); 15744 pw.println(" p[ackages]: dump installed packages"); 15745 pw.println(" s[hared-users]: dump shared user IDs"); 15746 pw.println(" m[essages]: print collected runtime messages"); 15747 pw.println(" v[erifiers]: print package verifier info"); 15748 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 15749 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 15750 pw.println(" version: print database version info"); 15751 pw.println(" write: write current settings now"); 15752 pw.println(" installs: details about install sessions"); 15753 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 15754 pw.println(" <package.name>: info about given package"); 15755 return; 15756 } else if ("--checkin".equals(opt)) { 15757 checkin = true; 15758 } else if ("-f".equals(opt)) { 15759 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 15760 } else { 15761 pw.println("Unknown argument: " + opt + "; use -h for help"); 15762 } 15763 } 15764 15765 // Is the caller requesting to dump a particular piece of data? 15766 if (opti < args.length) { 15767 String cmd = args[opti]; 15768 opti++; 15769 // Is this a package name? 15770 if ("android".equals(cmd) || cmd.contains(".")) { 15771 packageName = cmd; 15772 // When dumping a single package, we always dump all of its 15773 // filter information since the amount of data will be reasonable. 15774 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 15775 } else if ("check-permission".equals(cmd)) { 15776 if (opti >= args.length) { 15777 pw.println("Error: check-permission missing permission argument"); 15778 return; 15779 } 15780 String perm = args[opti]; 15781 opti++; 15782 if (opti >= args.length) { 15783 pw.println("Error: check-permission missing package argument"); 15784 return; 15785 } 15786 String pkg = args[opti]; 15787 opti++; 15788 int user = UserHandle.getUserId(Binder.getCallingUid()); 15789 if (opti < args.length) { 15790 try { 15791 user = Integer.parseInt(args[opti]); 15792 } catch (NumberFormatException e) { 15793 pw.println("Error: check-permission user argument is not a number: " 15794 + args[opti]); 15795 return; 15796 } 15797 } 15798 pw.println(checkPermission(perm, pkg, user)); 15799 return; 15800 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 15801 dumpState.setDump(DumpState.DUMP_LIBS); 15802 } else if ("f".equals(cmd) || "features".equals(cmd)) { 15803 dumpState.setDump(DumpState.DUMP_FEATURES); 15804 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 15805 if (opti >= args.length) { 15806 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 15807 | DumpState.DUMP_SERVICE_RESOLVERS 15808 | DumpState.DUMP_RECEIVER_RESOLVERS 15809 | DumpState.DUMP_CONTENT_RESOLVERS); 15810 } else { 15811 while (opti < args.length) { 15812 String name = args[opti]; 15813 if ("a".equals(name) || "activity".equals(name)) { 15814 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 15815 } else if ("s".equals(name) || "service".equals(name)) { 15816 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 15817 } else if ("r".equals(name) || "receiver".equals(name)) { 15818 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 15819 } else if ("c".equals(name) || "content".equals(name)) { 15820 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 15821 } else { 15822 pw.println("Error: unknown resolver table type: " + name); 15823 return; 15824 } 15825 opti++; 15826 } 15827 } 15828 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 15829 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 15830 } else if ("permission".equals(cmd)) { 15831 if (opti >= args.length) { 15832 pw.println("Error: permission requires permission name"); 15833 return; 15834 } 15835 permissionNames = new ArraySet<>(); 15836 while (opti < args.length) { 15837 permissionNames.add(args[opti]); 15838 opti++; 15839 } 15840 dumpState.setDump(DumpState.DUMP_PERMISSIONS 15841 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 15842 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 15843 dumpState.setDump(DumpState.DUMP_PREFERRED); 15844 } else if ("preferred-xml".equals(cmd)) { 15845 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 15846 if (opti < args.length && "--full".equals(args[opti])) { 15847 fullPreferred = true; 15848 opti++; 15849 } 15850 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 15851 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 15852 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 15853 dumpState.setDump(DumpState.DUMP_PACKAGES); 15854 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 15855 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 15856 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 15857 dumpState.setDump(DumpState.DUMP_PROVIDERS); 15858 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 15859 dumpState.setDump(DumpState.DUMP_MESSAGES); 15860 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 15861 dumpState.setDump(DumpState.DUMP_VERIFIERS); 15862 } else if ("i".equals(cmd) || "ifv".equals(cmd) 15863 || "intent-filter-verifiers".equals(cmd)) { 15864 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 15865 } else if ("version".equals(cmd)) { 15866 dumpState.setDump(DumpState.DUMP_VERSION); 15867 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 15868 dumpState.setDump(DumpState.DUMP_KEYSETS); 15869 } else if ("installs".equals(cmd)) { 15870 dumpState.setDump(DumpState.DUMP_INSTALLS); 15871 } else if ("write".equals(cmd)) { 15872 synchronized (mPackages) { 15873 mSettings.writeLPr(); 15874 pw.println("Settings written."); 15875 return; 15876 } 15877 } 15878 } 15879 15880 if (checkin) { 15881 pw.println("vers,1"); 15882 } 15883 15884 // reader 15885 synchronized (mPackages) { 15886 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 15887 if (!checkin) { 15888 if (dumpState.onTitlePrinted()) 15889 pw.println(); 15890 pw.println("Database versions:"); 15891 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 15892 } 15893 } 15894 15895 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 15896 if (!checkin) { 15897 if (dumpState.onTitlePrinted()) 15898 pw.println(); 15899 pw.println("Verifiers:"); 15900 pw.print(" Required: "); 15901 pw.print(mRequiredVerifierPackage); 15902 pw.print(" (uid="); 15903 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 15904 UserHandle.USER_SYSTEM)); 15905 pw.println(")"); 15906 } else if (mRequiredVerifierPackage != null) { 15907 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 15908 pw.print(","); 15909 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 15910 UserHandle.USER_SYSTEM)); 15911 } 15912 } 15913 15914 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 15915 packageName == null) { 15916 if (mIntentFilterVerifierComponent != null) { 15917 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 15918 if (!checkin) { 15919 if (dumpState.onTitlePrinted()) 15920 pw.println(); 15921 pw.println("Intent Filter Verifier:"); 15922 pw.print(" Using: "); 15923 pw.print(verifierPackageName); 15924 pw.print(" (uid="); 15925 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 15926 UserHandle.USER_SYSTEM)); 15927 pw.println(")"); 15928 } else if (verifierPackageName != null) { 15929 pw.print("ifv,"); pw.print(verifierPackageName); 15930 pw.print(","); 15931 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 15932 UserHandle.USER_SYSTEM)); 15933 } 15934 } else { 15935 pw.println(); 15936 pw.println("No Intent Filter Verifier available!"); 15937 } 15938 } 15939 15940 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 15941 boolean printedHeader = false; 15942 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 15943 while (it.hasNext()) { 15944 String name = it.next(); 15945 SharedLibraryEntry ent = mSharedLibraries.get(name); 15946 if (!checkin) { 15947 if (!printedHeader) { 15948 if (dumpState.onTitlePrinted()) 15949 pw.println(); 15950 pw.println("Libraries:"); 15951 printedHeader = true; 15952 } 15953 pw.print(" "); 15954 } else { 15955 pw.print("lib,"); 15956 } 15957 pw.print(name); 15958 if (!checkin) { 15959 pw.print(" -> "); 15960 } 15961 if (ent.path != null) { 15962 if (!checkin) { 15963 pw.print("(jar) "); 15964 pw.print(ent.path); 15965 } else { 15966 pw.print(",jar,"); 15967 pw.print(ent.path); 15968 } 15969 } else { 15970 if (!checkin) { 15971 pw.print("(apk) "); 15972 pw.print(ent.apk); 15973 } else { 15974 pw.print(",apk,"); 15975 pw.print(ent.apk); 15976 } 15977 } 15978 pw.println(); 15979 } 15980 } 15981 15982 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 15983 if (dumpState.onTitlePrinted()) 15984 pw.println(); 15985 if (!checkin) { 15986 pw.println("Features:"); 15987 } 15988 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 15989 while (it.hasNext()) { 15990 String name = it.next(); 15991 if (!checkin) { 15992 pw.print(" "); 15993 } else { 15994 pw.print("feat,"); 15995 } 15996 pw.println(name); 15997 } 15998 } 15999 16000 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 16001 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 16002 : "Activity Resolver Table:", " ", packageName, 16003 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 16004 dumpState.setTitlePrinted(true); 16005 } 16006 } 16007 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 16008 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 16009 : "Receiver Resolver Table:", " ", packageName, 16010 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 16011 dumpState.setTitlePrinted(true); 16012 } 16013 } 16014 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 16015 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 16016 : "Service Resolver Table:", " ", packageName, 16017 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 16018 dumpState.setTitlePrinted(true); 16019 } 16020 } 16021 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 16022 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 16023 : "Provider Resolver Table:", " ", packageName, 16024 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 16025 dumpState.setTitlePrinted(true); 16026 } 16027 } 16028 16029 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 16030 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16031 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16032 int user = mSettings.mPreferredActivities.keyAt(i); 16033 if (pir.dump(pw, 16034 dumpState.getTitlePrinted() 16035 ? "\nPreferred Activities User " + user + ":" 16036 : "Preferred Activities User " + user + ":", " ", 16037 packageName, true, false)) { 16038 dumpState.setTitlePrinted(true); 16039 } 16040 } 16041 } 16042 16043 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 16044 pw.flush(); 16045 FileOutputStream fout = new FileOutputStream(fd); 16046 BufferedOutputStream str = new BufferedOutputStream(fout); 16047 XmlSerializer serializer = new FastXmlSerializer(); 16048 try { 16049 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 16050 serializer.startDocument(null, true); 16051 serializer.setFeature( 16052 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 16053 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 16054 serializer.endDocument(); 16055 serializer.flush(); 16056 } catch (IllegalArgumentException e) { 16057 pw.println("Failed writing: " + e); 16058 } catch (IllegalStateException e) { 16059 pw.println("Failed writing: " + e); 16060 } catch (IOException e) { 16061 pw.println("Failed writing: " + e); 16062 } 16063 } 16064 16065 if (!checkin 16066 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 16067 && packageName == null) { 16068 pw.println(); 16069 int count = mSettings.mPackages.size(); 16070 if (count == 0) { 16071 pw.println("No applications!"); 16072 pw.println(); 16073 } else { 16074 final String prefix = " "; 16075 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 16076 if (allPackageSettings.size() == 0) { 16077 pw.println("No domain preferred apps!"); 16078 pw.println(); 16079 } else { 16080 pw.println("App verification status:"); 16081 pw.println(); 16082 count = 0; 16083 for (PackageSetting ps : allPackageSettings) { 16084 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 16085 if (ivi == null || ivi.getPackageName() == null) continue; 16086 pw.println(prefix + "Package: " + ivi.getPackageName()); 16087 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 16088 pw.println(prefix + "Status: " + ivi.getStatusString()); 16089 pw.println(); 16090 count++; 16091 } 16092 if (count == 0) { 16093 pw.println(prefix + "No app verification established."); 16094 pw.println(); 16095 } 16096 for (int userId : sUserManager.getUserIds()) { 16097 pw.println("App linkages for user " + userId + ":"); 16098 pw.println(); 16099 count = 0; 16100 for (PackageSetting ps : allPackageSettings) { 16101 final long status = ps.getDomainVerificationStatusForUser(userId); 16102 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 16103 continue; 16104 } 16105 pw.println(prefix + "Package: " + ps.name); 16106 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 16107 String statusStr = IntentFilterVerificationInfo. 16108 getStatusStringFromValue(status); 16109 pw.println(prefix + "Status: " + statusStr); 16110 pw.println(); 16111 count++; 16112 } 16113 if (count == 0) { 16114 pw.println(prefix + "No configured app linkages."); 16115 pw.println(); 16116 } 16117 } 16118 } 16119 } 16120 } 16121 16122 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 16123 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 16124 if (packageName == null && permissionNames == null) { 16125 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 16126 if (iperm == 0) { 16127 if (dumpState.onTitlePrinted()) 16128 pw.println(); 16129 pw.println("AppOp Permissions:"); 16130 } 16131 pw.print(" AppOp Permission "); 16132 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 16133 pw.println(":"); 16134 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 16135 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 16136 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 16137 } 16138 } 16139 } 16140 } 16141 16142 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 16143 boolean printedSomething = false; 16144 for (PackageParser.Provider p : mProviders.mProviders.values()) { 16145 if (packageName != null && !packageName.equals(p.info.packageName)) { 16146 continue; 16147 } 16148 if (!printedSomething) { 16149 if (dumpState.onTitlePrinted()) 16150 pw.println(); 16151 pw.println("Registered ContentProviders:"); 16152 printedSomething = true; 16153 } 16154 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 16155 pw.print(" "); pw.println(p.toString()); 16156 } 16157 printedSomething = false; 16158 for (Map.Entry<String, PackageParser.Provider> entry : 16159 mProvidersByAuthority.entrySet()) { 16160 PackageParser.Provider p = entry.getValue(); 16161 if (packageName != null && !packageName.equals(p.info.packageName)) { 16162 continue; 16163 } 16164 if (!printedSomething) { 16165 if (dumpState.onTitlePrinted()) 16166 pw.println(); 16167 pw.println("ContentProvider Authorities:"); 16168 printedSomething = true; 16169 } 16170 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 16171 pw.print(" "); pw.println(p.toString()); 16172 if (p.info != null && p.info.applicationInfo != null) { 16173 final String appInfo = p.info.applicationInfo.toString(); 16174 pw.print(" applicationInfo="); pw.println(appInfo); 16175 } 16176 } 16177 } 16178 16179 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 16180 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 16181 } 16182 16183 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 16184 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 16185 } 16186 16187 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 16188 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 16189 } 16190 16191 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 16192 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 16193 } 16194 16195 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 16196 // XXX should handle packageName != null by dumping only install data that 16197 // the given package is involved with. 16198 if (dumpState.onTitlePrinted()) pw.println(); 16199 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 16200 } 16201 16202 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 16203 if (dumpState.onTitlePrinted()) pw.println(); 16204 mSettings.dumpReadMessagesLPr(pw, dumpState); 16205 16206 pw.println(); 16207 pw.println("Package warning messages:"); 16208 BufferedReader in = null; 16209 String line = null; 16210 try { 16211 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 16212 while ((line = in.readLine()) != null) { 16213 if (line.contains("ignored: updated version")) continue; 16214 pw.println(line); 16215 } 16216 } catch (IOException ignored) { 16217 } finally { 16218 IoUtils.closeQuietly(in); 16219 } 16220 } 16221 16222 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 16223 BufferedReader in = null; 16224 String line = null; 16225 try { 16226 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 16227 while ((line = in.readLine()) != null) { 16228 if (line.contains("ignored: updated version")) continue; 16229 pw.print("msg,"); 16230 pw.println(line); 16231 } 16232 } catch (IOException ignored) { 16233 } finally { 16234 IoUtils.closeQuietly(in); 16235 } 16236 } 16237 } 16238 } 16239 16240 private String dumpDomainString(String packageName) { 16241 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName); 16242 List<IntentFilter> filters = getAllIntentFilters(packageName); 16243 16244 ArraySet<String> result = new ArraySet<>(); 16245 if (iviList.size() > 0) { 16246 for (IntentFilterVerificationInfo ivi : iviList) { 16247 for (String host : ivi.getDomains()) { 16248 result.add(host); 16249 } 16250 } 16251 } 16252 if (filters != null && filters.size() > 0) { 16253 for (IntentFilter filter : filters) { 16254 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 16255 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 16256 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 16257 result.addAll(filter.getHostsList()); 16258 } 16259 } 16260 } 16261 16262 StringBuilder sb = new StringBuilder(result.size() * 16); 16263 for (String domain : result) { 16264 if (sb.length() > 0) sb.append(" "); 16265 sb.append(domain); 16266 } 16267 return sb.toString(); 16268 } 16269 16270 // ------- apps on sdcard specific code ------- 16271 static final boolean DEBUG_SD_INSTALL = false; 16272 16273 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 16274 16275 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 16276 16277 private boolean mMediaMounted = false; 16278 16279 static String getEncryptKey() { 16280 try { 16281 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 16282 SD_ENCRYPTION_KEYSTORE_NAME); 16283 if (sdEncKey == null) { 16284 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 16285 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 16286 if (sdEncKey == null) { 16287 Slog.e(TAG, "Failed to create encryption keys"); 16288 return null; 16289 } 16290 } 16291 return sdEncKey; 16292 } catch (NoSuchAlgorithmException nsae) { 16293 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 16294 return null; 16295 } catch (IOException ioe) { 16296 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 16297 return null; 16298 } 16299 } 16300 16301 /* 16302 * Update media status on PackageManager. 16303 */ 16304 @Override 16305 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 16306 int callingUid = Binder.getCallingUid(); 16307 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 16308 throw new SecurityException("Media status can only be updated by the system"); 16309 } 16310 // reader; this apparently protects mMediaMounted, but should probably 16311 // be a different lock in that case. 16312 synchronized (mPackages) { 16313 Log.i(TAG, "Updating external media status from " 16314 + (mMediaMounted ? "mounted" : "unmounted") + " to " 16315 + (mediaStatus ? "mounted" : "unmounted")); 16316 if (DEBUG_SD_INSTALL) 16317 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 16318 + ", mMediaMounted=" + mMediaMounted); 16319 if (mediaStatus == mMediaMounted) { 16320 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 16321 : 0, -1); 16322 mHandler.sendMessage(msg); 16323 return; 16324 } 16325 mMediaMounted = mediaStatus; 16326 } 16327 // Queue up an async operation since the package installation may take a 16328 // little while. 16329 mHandler.post(new Runnable() { 16330 public void run() { 16331 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 16332 } 16333 }); 16334 } 16335 16336 /** 16337 * Called by MountService when the initial ASECs to scan are available. 16338 * Should block until all the ASEC containers are finished being scanned. 16339 */ 16340 public void scanAvailableAsecs() { 16341 updateExternalMediaStatusInner(true, false, false); 16342 } 16343 16344 /* 16345 * Collect information of applications on external media, map them against 16346 * existing containers and update information based on current mount status. 16347 * Please note that we always have to report status if reportStatus has been 16348 * set to true especially when unloading packages. 16349 */ 16350 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 16351 boolean externalStorage) { 16352 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 16353 int[] uidArr = EmptyArray.INT; 16354 16355 final String[] list = PackageHelper.getSecureContainerList(); 16356 if (ArrayUtils.isEmpty(list)) { 16357 Log.i(TAG, "No secure containers found"); 16358 } else { 16359 // Process list of secure containers and categorize them 16360 // as active or stale based on their package internal state. 16361 16362 // reader 16363 synchronized (mPackages) { 16364 for (String cid : list) { 16365 // Leave stages untouched for now; installer service owns them 16366 if (PackageInstallerService.isStageName(cid)) continue; 16367 16368 if (DEBUG_SD_INSTALL) 16369 Log.i(TAG, "Processing container " + cid); 16370 String pkgName = getAsecPackageName(cid); 16371 if (pkgName == null) { 16372 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 16373 continue; 16374 } 16375 if (DEBUG_SD_INSTALL) 16376 Log.i(TAG, "Looking for pkg : " + pkgName); 16377 16378 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16379 if (ps == null) { 16380 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 16381 continue; 16382 } 16383 16384 /* 16385 * Skip packages that are not external if we're unmounting 16386 * external storage. 16387 */ 16388 if (externalStorage && !isMounted && !isExternal(ps)) { 16389 continue; 16390 } 16391 16392 final AsecInstallArgs args = new AsecInstallArgs(cid, 16393 getAppDexInstructionSets(ps), ps.isForwardLocked()); 16394 // The package status is changed only if the code path 16395 // matches between settings and the container id. 16396 if (ps.codePathString != null 16397 && ps.codePathString.startsWith(args.getCodePath())) { 16398 if (DEBUG_SD_INSTALL) { 16399 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 16400 + " at code path: " + ps.codePathString); 16401 } 16402 16403 // We do have a valid package installed on sdcard 16404 processCids.put(args, ps.codePathString); 16405 final int uid = ps.appId; 16406 if (uid != -1) { 16407 uidArr = ArrayUtils.appendInt(uidArr, uid); 16408 } 16409 } else { 16410 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 16411 + ps.codePathString); 16412 } 16413 } 16414 } 16415 16416 Arrays.sort(uidArr); 16417 } 16418 16419 // Process packages with valid entries. 16420 if (isMounted) { 16421 if (DEBUG_SD_INSTALL) 16422 Log.i(TAG, "Loading packages"); 16423 loadMediaPackages(processCids, uidArr, externalStorage); 16424 startCleaningPackages(); 16425 mInstallerService.onSecureContainersAvailable(); 16426 } else { 16427 if (DEBUG_SD_INSTALL) 16428 Log.i(TAG, "Unloading packages"); 16429 unloadMediaPackages(processCids, uidArr, reportStatus); 16430 } 16431 } 16432 16433 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 16434 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 16435 final int size = infos.size(); 16436 final String[] packageNames = new String[size]; 16437 final int[] packageUids = new int[size]; 16438 for (int i = 0; i < size; i++) { 16439 final ApplicationInfo info = infos.get(i); 16440 packageNames[i] = info.packageName; 16441 packageUids[i] = info.uid; 16442 } 16443 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 16444 finishedReceiver); 16445 } 16446 16447 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 16448 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 16449 sendResourcesChangedBroadcast(mediaStatus, replacing, 16450 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 16451 } 16452 16453 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 16454 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 16455 int size = pkgList.length; 16456 if (size > 0) { 16457 // Send broadcasts here 16458 Bundle extras = new Bundle(); 16459 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 16460 if (uidArr != null) { 16461 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 16462 } 16463 if (replacing) { 16464 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 16465 } 16466 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 16467 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 16468 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 16469 } 16470 } 16471 16472 /* 16473 * Look at potentially valid container ids from processCids If package 16474 * information doesn't match the one on record or package scanning fails, 16475 * the cid is added to list of removeCids. We currently don't delete stale 16476 * containers. 16477 */ 16478 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 16479 boolean externalStorage) { 16480 ArrayList<String> pkgList = new ArrayList<String>(); 16481 Set<AsecInstallArgs> keys = processCids.keySet(); 16482 16483 for (AsecInstallArgs args : keys) { 16484 String codePath = processCids.get(args); 16485 if (DEBUG_SD_INSTALL) 16486 Log.i(TAG, "Loading container : " + args.cid); 16487 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 16488 try { 16489 // Make sure there are no container errors first. 16490 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 16491 Slog.e(TAG, "Failed to mount cid : " + args.cid 16492 + " when installing from sdcard"); 16493 continue; 16494 } 16495 // Check code path here. 16496 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 16497 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 16498 + " does not match one in settings " + codePath); 16499 continue; 16500 } 16501 // Parse package 16502 int parseFlags = mDefParseFlags; 16503 if (args.isExternalAsec()) { 16504 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 16505 } 16506 if (args.isFwdLocked()) { 16507 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 16508 } 16509 16510 synchronized (mInstallLock) { 16511 PackageParser.Package pkg = null; 16512 try { 16513 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null); 16514 } catch (PackageManagerException e) { 16515 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 16516 } 16517 // Scan the package 16518 if (pkg != null) { 16519 /* 16520 * TODO why is the lock being held? doPostInstall is 16521 * called in other places without the lock. This needs 16522 * to be straightened out. 16523 */ 16524 // writer 16525 synchronized (mPackages) { 16526 retCode = PackageManager.INSTALL_SUCCEEDED; 16527 pkgList.add(pkg.packageName); 16528 // Post process args 16529 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 16530 pkg.applicationInfo.uid); 16531 } 16532 } else { 16533 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 16534 } 16535 } 16536 16537 } finally { 16538 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 16539 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 16540 } 16541 } 16542 } 16543 // writer 16544 synchronized (mPackages) { 16545 // If the platform SDK has changed since the last time we booted, 16546 // we need to re-grant app permission to catch any new ones that 16547 // appear. This is really a hack, and means that apps can in some 16548 // cases get permissions that the user didn't initially explicitly 16549 // allow... it would be nice to have some better way to handle 16550 // this situation. 16551 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 16552 : mSettings.getInternalVersion(); 16553 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 16554 : StorageManager.UUID_PRIVATE_INTERNAL; 16555 16556 int updateFlags = UPDATE_PERMISSIONS_ALL; 16557 if (ver.sdkVersion != mSdkVersion) { 16558 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 16559 + mSdkVersion + "; regranting permissions for external"); 16560 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 16561 } 16562 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 16563 16564 // Yay, everything is now upgraded 16565 ver.forceCurrent(); 16566 16567 // can downgrade to reader 16568 // Persist settings 16569 mSettings.writeLPr(); 16570 } 16571 // Send a broadcast to let everyone know we are done processing 16572 if (pkgList.size() > 0) { 16573 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 16574 } 16575 } 16576 16577 /* 16578 * Utility method to unload a list of specified containers 16579 */ 16580 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 16581 // Just unmount all valid containers. 16582 for (AsecInstallArgs arg : cidArgs) { 16583 synchronized (mInstallLock) { 16584 arg.doPostDeleteLI(false); 16585 } 16586 } 16587 } 16588 16589 /* 16590 * Unload packages mounted on external media. This involves deleting package 16591 * data from internal structures, sending broadcasts about diabled packages, 16592 * gc'ing to free up references, unmounting all secure containers 16593 * corresponding to packages on external media, and posting a 16594 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 16595 * that we always have to post this message if status has been requested no 16596 * matter what. 16597 */ 16598 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 16599 final boolean reportStatus) { 16600 if (DEBUG_SD_INSTALL) 16601 Log.i(TAG, "unloading media packages"); 16602 ArrayList<String> pkgList = new ArrayList<String>(); 16603 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 16604 final Set<AsecInstallArgs> keys = processCids.keySet(); 16605 for (AsecInstallArgs args : keys) { 16606 String pkgName = args.getPackageName(); 16607 if (DEBUG_SD_INSTALL) 16608 Log.i(TAG, "Trying to unload pkg : " + pkgName); 16609 // Delete package internally 16610 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 16611 synchronized (mInstallLock) { 16612 boolean res = deletePackageLI(pkgName, null, false, null, null, 16613 PackageManager.DELETE_KEEP_DATA, outInfo, false); 16614 if (res) { 16615 pkgList.add(pkgName); 16616 } else { 16617 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 16618 failedList.add(args); 16619 } 16620 } 16621 } 16622 16623 // reader 16624 synchronized (mPackages) { 16625 // We didn't update the settings after removing each package; 16626 // write them now for all packages. 16627 mSettings.writeLPr(); 16628 } 16629 16630 // We have to absolutely send UPDATED_MEDIA_STATUS only 16631 // after confirming that all the receivers processed the ordered 16632 // broadcast when packages get disabled, force a gc to clean things up. 16633 // and unload all the containers. 16634 if (pkgList.size() > 0) { 16635 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 16636 new IIntentReceiver.Stub() { 16637 public void performReceive(Intent intent, int resultCode, String data, 16638 Bundle extras, boolean ordered, boolean sticky, 16639 int sendingUser) throws RemoteException { 16640 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 16641 reportStatus ? 1 : 0, 1, keys); 16642 mHandler.sendMessage(msg); 16643 } 16644 }); 16645 } else { 16646 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 16647 keys); 16648 mHandler.sendMessage(msg); 16649 } 16650 } 16651 16652 private void loadPrivatePackages(final VolumeInfo vol) { 16653 mHandler.post(new Runnable() { 16654 @Override 16655 public void run() { 16656 loadPrivatePackagesInner(vol); 16657 } 16658 }); 16659 } 16660 16661 private void loadPrivatePackagesInner(VolumeInfo vol) { 16662 final String volumeUuid = vol.fsUuid; 16663 if (TextUtils.isEmpty(volumeUuid)) { 16664 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 16665 return; 16666 } 16667 16668 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 16669 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 16670 16671 final VersionInfo ver; 16672 final List<PackageSetting> packages; 16673 synchronized (mPackages) { 16674 ver = mSettings.findOrCreateVersion(volumeUuid); 16675 packages = mSettings.getVolumePackagesLPr(volumeUuid); 16676 } 16677 16678 // TODO: introduce a new concept similar to "frozen" to prevent these 16679 // apps from being launched until after data has been fully reconciled 16680 for (PackageSetting ps : packages) { 16681 synchronized (mInstallLock) { 16682 final PackageParser.Package pkg; 16683 try { 16684 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 16685 loaded.add(pkg.applicationInfo); 16686 16687 } catch (PackageManagerException e) { 16688 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 16689 } 16690 16691 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 16692 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 16693 } 16694 } 16695 } 16696 16697 // Reconcile app data for all started/unlocked users 16698 final UserManager um = mContext.getSystemService(UserManager.class); 16699 for (UserInfo user : um.getUsers()) { 16700 if (um.isUserUnlocked(user.id)) { 16701 reconcileAppsData(volumeUuid, user.id, 16702 Installer.FLAG_DE_STORAGE | Installer.FLAG_CE_STORAGE); 16703 } else if (um.isUserRunning(user.id)) { 16704 reconcileAppsData(volumeUuid, user.id, Installer.FLAG_DE_STORAGE); 16705 } else { 16706 continue; 16707 } 16708 } 16709 16710 synchronized (mPackages) { 16711 int updateFlags = UPDATE_PERMISSIONS_ALL; 16712 if (ver.sdkVersion != mSdkVersion) { 16713 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 16714 + mSdkVersion + "; regranting permissions for " + volumeUuid); 16715 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 16716 } 16717 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 16718 16719 // Yay, everything is now upgraded 16720 ver.forceCurrent(); 16721 16722 mSettings.writeLPr(); 16723 } 16724 16725 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 16726 sendResourcesChangedBroadcast(true, false, loaded, null); 16727 } 16728 16729 private void unloadPrivatePackages(final VolumeInfo vol) { 16730 mHandler.post(new Runnable() { 16731 @Override 16732 public void run() { 16733 unloadPrivatePackagesInner(vol); 16734 } 16735 }); 16736 } 16737 16738 private void unloadPrivatePackagesInner(VolumeInfo vol) { 16739 final String volumeUuid = vol.fsUuid; 16740 if (TextUtils.isEmpty(volumeUuid)) { 16741 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 16742 return; 16743 } 16744 16745 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 16746 synchronized (mInstallLock) { 16747 synchronized (mPackages) { 16748 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 16749 for (PackageSetting ps : packages) { 16750 if (ps.pkg == null) continue; 16751 16752 final ApplicationInfo info = ps.pkg.applicationInfo; 16753 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 16754 if (deletePackageLI(ps.name, null, false, null, null, 16755 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 16756 unloaded.add(info); 16757 } else { 16758 Slog.w(TAG, "Failed to unload " + ps.codePath); 16759 } 16760 } 16761 16762 mSettings.writeLPr(); 16763 } 16764 } 16765 16766 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 16767 sendResourcesChangedBroadcast(false, false, unloaded, null); 16768 } 16769 16770 /** 16771 * Examine all users present on given mounted volume, and destroy data 16772 * belonging to users that are no longer valid, or whose user ID has been 16773 * recycled. 16774 */ 16775 private void reconcileUsers(String volumeUuid) { 16776 final File[] files = FileUtils 16777 .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid)); 16778 for (File file : files) { 16779 if (!file.isDirectory()) continue; 16780 16781 final int userId; 16782 final UserInfo info; 16783 try { 16784 userId = Integer.parseInt(file.getName()); 16785 info = sUserManager.getUserInfo(userId); 16786 } catch (NumberFormatException e) { 16787 Slog.w(TAG, "Invalid user directory " + file); 16788 continue; 16789 } 16790 16791 boolean destroyUser = false; 16792 if (info == null) { 16793 logCriticalInfo(Log.WARN, "Destroying user directory " + file 16794 + " because no matching user was found"); 16795 destroyUser = true; 16796 } else { 16797 try { 16798 UserManagerService.enforceSerialNumber(file, info.serialNumber); 16799 } catch (IOException e) { 16800 logCriticalInfo(Log.WARN, "Destroying user directory " + file 16801 + " because we failed to enforce serial number: " + e); 16802 destroyUser = true; 16803 } 16804 } 16805 16806 if (destroyUser) { 16807 synchronized (mInstallLock) { 16808 try { 16809 mInstaller.removeUserDataDirs(volumeUuid, userId); 16810 } catch (InstallerException e) { 16811 Slog.w(TAG, "Failed to clean up user dirs", e); 16812 } 16813 } 16814 } 16815 } 16816 16817 final StorageManager sm = mContext.getSystemService(StorageManager.class); 16818 final UserManager um = mContext.getSystemService(UserManager.class); 16819 for (UserInfo user : um.getUsers()) { 16820 final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id); 16821 if (userDir.exists()) continue; 16822 16823 try { 16824 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, user.isEphemeral()); 16825 UserManagerService.enforceSerialNumber(userDir, user.serialNumber); 16826 } catch (IOException e) { 16827 Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e); 16828 } 16829 } 16830 } 16831 16832 private void assertPackageKnown(String volumeUuid, String packageName) 16833 throws PackageManagerException { 16834 synchronized (mPackages) { 16835 final PackageSetting ps = mSettings.mPackages.get(packageName); 16836 if (ps == null) { 16837 throw new PackageManagerException("Package " + packageName + " is unknown"); 16838 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 16839 throw new PackageManagerException( 16840 "Package " + packageName + " found on unknown volume " + volumeUuid 16841 + "; expected volume " + ps.volumeUuid); 16842 } 16843 } 16844 } 16845 16846 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 16847 throws PackageManagerException { 16848 synchronized (mPackages) { 16849 final PackageSetting ps = mSettings.mPackages.get(packageName); 16850 if (ps == null) { 16851 throw new PackageManagerException("Package " + packageName + " is unknown"); 16852 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 16853 throw new PackageManagerException( 16854 "Package " + packageName + " found on unknown volume " + volumeUuid 16855 + "; expected volume " + ps.volumeUuid); 16856 } else if (!ps.getInstalled(userId)) { 16857 throw new PackageManagerException( 16858 "Package " + packageName + " not installed for user " + userId); 16859 } 16860 } 16861 } 16862 16863 /** 16864 * Examine all apps present on given mounted volume, and destroy apps that 16865 * aren't expected, either due to uninstallation or reinstallation on 16866 * another volume. 16867 */ 16868 private void reconcileApps(String volumeUuid) { 16869 final File[] files = FileUtils 16870 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 16871 for (File file : files) { 16872 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 16873 && !PackageInstallerService.isStageName(file.getName()); 16874 if (!isPackage) { 16875 // Ignore entries which are not packages 16876 continue; 16877 } 16878 16879 try { 16880 final PackageLite pkg = PackageParser.parsePackageLite(file, 16881 PackageParser.PARSE_MUST_BE_APK); 16882 assertPackageKnown(volumeUuid, pkg.packageName); 16883 16884 } catch (PackageParserException | PackageManagerException e) { 16885 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 16886 synchronized (mInstallLock) { 16887 removeCodePathLI(file); 16888 } 16889 } 16890 } 16891 } 16892 16893 /** 16894 * Reconcile all app data for the given user. 16895 * <p> 16896 * Verifies that directories exist and that ownership and labeling is 16897 * correct for all installed apps on all mounted volumes. 16898 */ 16899 void reconcileAppsData(int userId, @StorageFlags int flags) { 16900 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16901 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 16902 final String volumeUuid = vol.getFsUuid(); 16903 reconcileAppsData(volumeUuid, userId, flags); 16904 } 16905 } 16906 16907 /** 16908 * Reconcile all app data on given mounted volume. 16909 * <p> 16910 * Destroys app data that isn't expected, either due to uninstallation or 16911 * reinstallation on another volume. 16912 * <p> 16913 * Verifies that directories exist and that ownership and labeling is 16914 * correct for all installed apps. 16915 */ 16916 private void reconcileAppsData(String volumeUuid, int userId, @StorageFlags int flags) { 16917 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 16918 + Integer.toHexString(flags)); 16919 16920 final File ceDir = Environment.getDataUserCredentialEncryptedDirectory(volumeUuid, userId); 16921 final File deDir = Environment.getDataUserDeviceEncryptedDirectory(volumeUuid, userId); 16922 16923 boolean restoreconNeeded = false; 16924 16925 // First look for stale data that doesn't belong, and check if things 16926 // have changed since we did our last restorecon 16927 if ((flags & Installer.FLAG_CE_STORAGE) != 0) { 16928 if (!isUserKeyUnlocked(userId)) { 16929 throw new RuntimeException( 16930 "Yikes, someone asked us to reconcile CE storage while " + userId 16931 + " was still locked; this would have caused massive data loss!"); 16932 } 16933 16934 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 16935 16936 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 16937 for (File file : files) { 16938 final String packageName = file.getName(); 16939 try { 16940 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 16941 } catch (PackageManagerException e) { 16942 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 16943 synchronized (mInstallLock) { 16944 destroyAppDataLI(volumeUuid, packageName, userId, 16945 Installer.FLAG_CE_STORAGE); 16946 } 16947 } 16948 } 16949 } 16950 if ((flags & Installer.FLAG_DE_STORAGE) != 0) { 16951 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 16952 16953 final File[] files = FileUtils.listFilesOrEmpty(deDir); 16954 for (File file : files) { 16955 final String packageName = file.getName(); 16956 try { 16957 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 16958 } catch (PackageManagerException e) { 16959 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 16960 synchronized (mInstallLock) { 16961 destroyAppDataLI(volumeUuid, packageName, userId, 16962 Installer.FLAG_DE_STORAGE); 16963 } 16964 } 16965 } 16966 } 16967 16968 // Ensure that data directories are ready to roll for all packages 16969 // installed for this volume and user 16970 final List<PackageSetting> packages; 16971 synchronized (mPackages) { 16972 packages = mSettings.getVolumePackagesLPr(volumeUuid); 16973 } 16974 int preparedCount = 0; 16975 for (PackageSetting ps : packages) { 16976 final String packageName = ps.name; 16977 if (ps.pkg == null) { 16978 Slog.w(TAG, "Odd, missing scanned package " + packageName); 16979 // TODO: might be due to legacy ASEC apps; we should circle back 16980 // and reconcile again once they're scanned 16981 continue; 16982 } 16983 16984 if (ps.getInstalled(userId)) { 16985 prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded); 16986 preparedCount++; 16987 } 16988 } 16989 16990 if (restoreconNeeded) { 16991 if ((flags & Installer.FLAG_CE_STORAGE) != 0) { 16992 SELinuxMMAC.setRestoreconDone(ceDir); 16993 } 16994 if ((flags & Installer.FLAG_DE_STORAGE) != 0) { 16995 SELinuxMMAC.setRestoreconDone(deDir); 16996 } 16997 } 16998 16999 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 17000 + " packages; restoreconNeeded was " + restoreconNeeded); 17001 } 17002 17003 /** 17004 * Prepare app data for the given app just after it was installed or 17005 * upgraded. This method carefully only touches users that it's installed 17006 * for, and it forces a restorecon to handle any seinfo changes. 17007 * <p> 17008 * Verifies that directories exist and that ownership and labeling is 17009 * correct for all installed apps. If there is an ownership mismatch, it 17010 * will try recovering system apps by wiping data; third-party app data is 17011 * left intact. 17012 */ 17013 private void prepareAppDataAfterInstall(PackageParser.Package pkg) { 17014 final PackageSetting ps; 17015 synchronized (mPackages) { 17016 ps = mSettings.mPackages.get(pkg.packageName); 17017 } 17018 17019 final UserManager um = mContext.getSystemService(UserManager.class); 17020 for (UserInfo user : um.getUsers()) { 17021 final int flags; 17022 if (um.isUserUnlocked(user.id)) { 17023 flags = Installer.FLAG_DE_STORAGE | Installer.FLAG_CE_STORAGE; 17024 } else if (um.isUserRunning(user.id)) { 17025 flags = Installer.FLAG_DE_STORAGE; 17026 } else { 17027 continue; 17028 } 17029 17030 if (ps.getInstalled(user.id)) { 17031 // Whenever an app changes, force a restorecon of its data 17032 // TODO: when user data is locked, mark that we're still dirty 17033 prepareAppData(pkg.volumeUuid, user.id, flags, pkg, true); 17034 } 17035 } 17036 } 17037 17038 /** 17039 * Prepare app data for the given app. 17040 * <p> 17041 * Verifies that directories exist and that ownership and labeling is 17042 * correct for all installed apps. If there is an ownership mismatch, this 17043 * will try recovering system apps by wiping data; third-party app data is 17044 * left intact. 17045 */ 17046 private void prepareAppData(String volumeUuid, int userId, @StorageFlags int flags, 17047 PackageParser.Package pkg, boolean restoreconNeeded) { 17048 if (DEBUG_APP_DATA) { 17049 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 17050 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 17051 } 17052 17053 final String packageName = pkg.packageName; 17054 final ApplicationInfo app = pkg.applicationInfo; 17055 final int appId = UserHandle.getAppId(app.uid); 17056 17057 Preconditions.checkNotNull(app.seinfo); 17058 17059 synchronized (mInstallLock) { 17060 try { 17061 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 17062 appId, app.seinfo, app.targetSdkVersion); 17063 } catch (InstallerException e) { 17064 if (app.isSystemApp()) { 17065 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 17066 + ", but trying to recover: " + e); 17067 destroyAppDataLI(volumeUuid, packageName, userId, flags); 17068 try { 17069 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 17070 appId, app.seinfo, app.targetSdkVersion); 17071 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 17072 } catch (InstallerException e2) { 17073 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 17074 } 17075 } else { 17076 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 17077 } 17078 } 17079 17080 if (restoreconNeeded) { 17081 restoreconAppDataLI(volumeUuid, packageName, userId, flags, appId, app.seinfo); 17082 } 17083 17084 if ((flags & Installer.FLAG_CE_STORAGE) != 0) { 17085 // Create a native library symlink only if we have native libraries 17086 // and if the native libraries are 32 bit libraries. We do not provide 17087 // this symlink for 64 bit libraries. 17088 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 17089 final String nativeLibPath = app.nativeLibraryDir; 17090 try { 17091 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 17092 nativeLibPath, userId); 17093 } catch (InstallerException e) { 17094 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 17095 } 17096 } 17097 } 17098 } 17099 } 17100 17101 private void unfreezePackage(String packageName) { 17102 synchronized (mPackages) { 17103 final PackageSetting ps = mSettings.mPackages.get(packageName); 17104 if (ps != null) { 17105 ps.frozen = false; 17106 } 17107 } 17108 } 17109 17110 @Override 17111 public int movePackage(final String packageName, final String volumeUuid) { 17112 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 17113 17114 final int moveId = mNextMoveId.getAndIncrement(); 17115 mHandler.post(new Runnable() { 17116 @Override 17117 public void run() { 17118 try { 17119 movePackageInternal(packageName, volumeUuid, moveId); 17120 } catch (PackageManagerException e) { 17121 Slog.w(TAG, "Failed to move " + packageName, e); 17122 mMoveCallbacks.notifyStatusChanged(moveId, 17123 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 17124 } 17125 } 17126 }); 17127 return moveId; 17128 } 17129 17130 private void movePackageInternal(final String packageName, final String volumeUuid, 17131 final int moveId) throws PackageManagerException { 17132 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 17133 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17134 final PackageManager pm = mContext.getPackageManager(); 17135 17136 final boolean currentAsec; 17137 final String currentVolumeUuid; 17138 final File codeFile; 17139 final String installerPackageName; 17140 final String packageAbiOverride; 17141 final int appId; 17142 final String seinfo; 17143 final String label; 17144 final int targetSdkVersion; 17145 17146 // reader 17147 synchronized (mPackages) { 17148 final PackageParser.Package pkg = mPackages.get(packageName); 17149 final PackageSetting ps = mSettings.mPackages.get(packageName); 17150 if (pkg == null || ps == null) { 17151 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 17152 } 17153 17154 if (pkg.applicationInfo.isSystemApp()) { 17155 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 17156 "Cannot move system application"); 17157 } 17158 17159 if (pkg.applicationInfo.isExternalAsec()) { 17160 currentAsec = true; 17161 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 17162 } else if (pkg.applicationInfo.isForwardLocked()) { 17163 currentAsec = true; 17164 currentVolumeUuid = "forward_locked"; 17165 } else { 17166 currentAsec = false; 17167 currentVolumeUuid = ps.volumeUuid; 17168 17169 final File probe = new File(pkg.codePath); 17170 final File probeOat = new File(probe, "oat"); 17171 if (!probe.isDirectory() || !probeOat.isDirectory()) { 17172 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 17173 "Move only supported for modern cluster style installs"); 17174 } 17175 } 17176 17177 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 17178 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 17179 "Package already moved to " + volumeUuid); 17180 } 17181 17182 if (ps.frozen) { 17183 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 17184 "Failed to move already frozen package"); 17185 } 17186 ps.frozen = true; 17187 17188 codeFile = new File(pkg.codePath); 17189 installerPackageName = ps.installerPackageName; 17190 packageAbiOverride = ps.cpuAbiOverrideString; 17191 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 17192 seinfo = pkg.applicationInfo.seinfo; 17193 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 17194 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 17195 } 17196 17197 // Now that we're guarded by frozen state, kill app during move 17198 final long token = Binder.clearCallingIdentity(); 17199 try { 17200 killApplication(packageName, appId, "move pkg"); 17201 } finally { 17202 Binder.restoreCallingIdentity(token); 17203 } 17204 17205 final Bundle extras = new Bundle(); 17206 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 17207 extras.putString(Intent.EXTRA_TITLE, label); 17208 mMoveCallbacks.notifyCreated(moveId, extras); 17209 17210 int installFlags; 17211 final boolean moveCompleteApp; 17212 final File measurePath; 17213 17214 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 17215 installFlags = INSTALL_INTERNAL; 17216 moveCompleteApp = !currentAsec; 17217 measurePath = Environment.getDataAppDirectory(volumeUuid); 17218 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 17219 installFlags = INSTALL_EXTERNAL; 17220 moveCompleteApp = false; 17221 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 17222 } else { 17223 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 17224 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 17225 || !volume.isMountedWritable()) { 17226 unfreezePackage(packageName); 17227 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 17228 "Move location not mounted private volume"); 17229 } 17230 17231 Preconditions.checkState(!currentAsec); 17232 17233 installFlags = INSTALL_INTERNAL; 17234 moveCompleteApp = true; 17235 measurePath = Environment.getDataAppDirectory(volumeUuid); 17236 } 17237 17238 final PackageStats stats = new PackageStats(null, -1); 17239 synchronized (mInstaller) { 17240 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 17241 unfreezePackage(packageName); 17242 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 17243 "Failed to measure package size"); 17244 } 17245 } 17246 17247 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 17248 + stats.dataSize); 17249 17250 final long startFreeBytes = measurePath.getFreeSpace(); 17251 final long sizeBytes; 17252 if (moveCompleteApp) { 17253 sizeBytes = stats.codeSize + stats.dataSize; 17254 } else { 17255 sizeBytes = stats.codeSize; 17256 } 17257 17258 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 17259 unfreezePackage(packageName); 17260 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 17261 "Not enough free space to move"); 17262 } 17263 17264 mMoveCallbacks.notifyStatusChanged(moveId, 10); 17265 17266 final CountDownLatch installedLatch = new CountDownLatch(1); 17267 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 17268 @Override 17269 public void onUserActionRequired(Intent intent) throws RemoteException { 17270 throw new IllegalStateException(); 17271 } 17272 17273 @Override 17274 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 17275 Bundle extras) throws RemoteException { 17276 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 17277 + PackageManager.installStatusToString(returnCode, msg)); 17278 17279 installedLatch.countDown(); 17280 17281 // Regardless of success or failure of the move operation, 17282 // always unfreeze the package 17283 unfreezePackage(packageName); 17284 17285 final int status = PackageManager.installStatusToPublicStatus(returnCode); 17286 switch (status) { 17287 case PackageInstaller.STATUS_SUCCESS: 17288 mMoveCallbacks.notifyStatusChanged(moveId, 17289 PackageManager.MOVE_SUCCEEDED); 17290 break; 17291 case PackageInstaller.STATUS_FAILURE_STORAGE: 17292 mMoveCallbacks.notifyStatusChanged(moveId, 17293 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 17294 break; 17295 default: 17296 mMoveCallbacks.notifyStatusChanged(moveId, 17297 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 17298 break; 17299 } 17300 } 17301 }; 17302 17303 final MoveInfo move; 17304 if (moveCompleteApp) { 17305 // Kick off a thread to report progress estimates 17306 new Thread() { 17307 @Override 17308 public void run() { 17309 while (true) { 17310 try { 17311 if (installedLatch.await(1, TimeUnit.SECONDS)) { 17312 break; 17313 } 17314 } catch (InterruptedException ignored) { 17315 } 17316 17317 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 17318 final int progress = 10 + (int) MathUtils.constrain( 17319 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 17320 mMoveCallbacks.notifyStatusChanged(moveId, progress); 17321 } 17322 } 17323 }.start(); 17324 17325 final String dataAppName = codeFile.getName(); 17326 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 17327 dataAppName, appId, seinfo, targetSdkVersion); 17328 } else { 17329 move = null; 17330 } 17331 17332 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 17333 17334 final Message msg = mHandler.obtainMessage(INIT_COPY); 17335 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 17336 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 17337 installerPackageName, volumeUuid, null, user, packageAbiOverride, null); 17338 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 17339 msg.obj = params; 17340 17341 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 17342 System.identityHashCode(msg.obj)); 17343 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 17344 System.identityHashCode(msg.obj)); 17345 17346 mHandler.sendMessage(msg); 17347 } 17348 17349 @Override 17350 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 17351 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 17352 17353 final int realMoveId = mNextMoveId.getAndIncrement(); 17354 final Bundle extras = new Bundle(); 17355 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 17356 mMoveCallbacks.notifyCreated(realMoveId, extras); 17357 17358 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 17359 @Override 17360 public void onCreated(int moveId, Bundle extras) { 17361 // Ignored 17362 } 17363 17364 @Override 17365 public void onStatusChanged(int moveId, int status, long estMillis) { 17366 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 17367 } 17368 }; 17369 17370 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17371 storage.setPrimaryStorageUuid(volumeUuid, callback); 17372 return realMoveId; 17373 } 17374 17375 @Override 17376 public int getMoveStatus(int moveId) { 17377 mContext.enforceCallingOrSelfPermission( 17378 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 17379 return mMoveCallbacks.mLastStatus.get(moveId); 17380 } 17381 17382 @Override 17383 public void registerMoveCallback(IPackageMoveObserver callback) { 17384 mContext.enforceCallingOrSelfPermission( 17385 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 17386 mMoveCallbacks.register(callback); 17387 } 17388 17389 @Override 17390 public void unregisterMoveCallback(IPackageMoveObserver callback) { 17391 mContext.enforceCallingOrSelfPermission( 17392 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 17393 mMoveCallbacks.unregister(callback); 17394 } 17395 17396 @Override 17397 public boolean setInstallLocation(int loc) { 17398 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 17399 null); 17400 if (getInstallLocation() == loc) { 17401 return true; 17402 } 17403 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 17404 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 17405 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 17406 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 17407 return true; 17408 } 17409 return false; 17410 } 17411 17412 @Override 17413 public int getInstallLocation() { 17414 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 17415 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 17416 PackageHelper.APP_INSTALL_AUTO); 17417 } 17418 17419 /** Called by UserManagerService */ 17420 void cleanUpUser(UserManagerService userManager, int userHandle) { 17421 synchronized (mPackages) { 17422 mDirtyUsers.remove(userHandle); 17423 mUserNeedsBadging.delete(userHandle); 17424 mSettings.removeUserLPw(userHandle); 17425 mPendingBroadcasts.remove(userHandle); 17426 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 17427 } 17428 synchronized (mInstallLock) { 17429 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17430 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 17431 final String volumeUuid = vol.getFsUuid(); 17432 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 17433 try { 17434 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 17435 } catch (InstallerException e) { 17436 Slog.w(TAG, "Failed to remove user data", e); 17437 } 17438 } 17439 synchronized (mPackages) { 17440 removeUnusedPackagesLILPw(userManager, userHandle); 17441 } 17442 } 17443 } 17444 17445 /** 17446 * We're removing userHandle and would like to remove any downloaded packages 17447 * that are no longer in use by any other user. 17448 * @param userHandle the user being removed 17449 */ 17450 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 17451 final boolean DEBUG_CLEAN_APKS = false; 17452 int [] users = userManager.getUserIds(); 17453 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 17454 while (psit.hasNext()) { 17455 PackageSetting ps = psit.next(); 17456 if (ps.pkg == null) { 17457 continue; 17458 } 17459 final String packageName = ps.pkg.packageName; 17460 // Skip over if system app 17461 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 17462 continue; 17463 } 17464 if (DEBUG_CLEAN_APKS) { 17465 Slog.i(TAG, "Checking package " + packageName); 17466 } 17467 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 17468 if (keep) { 17469 if (DEBUG_CLEAN_APKS) { 17470 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 17471 } 17472 } else { 17473 for (int i = 0; i < users.length; i++) { 17474 if (users[i] != userHandle && ps.getInstalled(users[i])) { 17475 keep = true; 17476 if (DEBUG_CLEAN_APKS) { 17477 Slog.i(TAG, " Keeping package " + packageName + " for user " 17478 + users[i]); 17479 } 17480 break; 17481 } 17482 } 17483 } 17484 if (!keep) { 17485 if (DEBUG_CLEAN_APKS) { 17486 Slog.i(TAG, " Removing package " + packageName); 17487 } 17488 mHandler.post(new Runnable() { 17489 public void run() { 17490 deletePackageX(packageName, userHandle, 0); 17491 } //end run 17492 }); 17493 } 17494 } 17495 } 17496 17497 /** Called by UserManagerService */ 17498 void createNewUser(int userHandle) { 17499 synchronized (mInstallLock) { 17500 try { 17501 mInstaller.createUserConfig(userHandle); 17502 } catch (InstallerException e) { 17503 Slog.w(TAG, "Failed to create user config", e); 17504 } 17505 mSettings.createNewUserLI(this, mInstaller, userHandle); 17506 } 17507 synchronized (mPackages) { 17508 applyFactoryDefaultBrowserLPw(userHandle); 17509 primeDomainVerificationsLPw(userHandle); 17510 } 17511 } 17512 17513 void newUserCreated(final int userHandle) { 17514 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 17515 // If permission review for legacy apps is required, we represent 17516 // dagerous permissions for such apps as always granted runtime 17517 // permissions to keep per user flag state whether review is needed. 17518 // Hence, if a new user is added we have to propagate dangerous 17519 // permission grants for these legacy apps. 17520 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 17521 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 17522 | UPDATE_PERMISSIONS_REPLACE_ALL); 17523 } 17524 } 17525 17526 @Override 17527 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 17528 mContext.enforceCallingOrSelfPermission( 17529 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 17530 "Only package verification agents can read the verifier device identity"); 17531 17532 synchronized (mPackages) { 17533 return mSettings.getVerifierDeviceIdentityLPw(); 17534 } 17535 } 17536 17537 @Override 17538 public void setPermissionEnforced(String permission, boolean enforced) { 17539 // TODO: Now that we no longer change GID for storage, this should to away. 17540 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 17541 "setPermissionEnforced"); 17542 if (READ_EXTERNAL_STORAGE.equals(permission)) { 17543 synchronized (mPackages) { 17544 if (mSettings.mReadExternalStorageEnforced == null 17545 || mSettings.mReadExternalStorageEnforced != enforced) { 17546 mSettings.mReadExternalStorageEnforced = enforced; 17547 mSettings.writeLPr(); 17548 } 17549 } 17550 // kill any non-foreground processes so we restart them and 17551 // grant/revoke the GID. 17552 final IActivityManager am = ActivityManagerNative.getDefault(); 17553 if (am != null) { 17554 final long token = Binder.clearCallingIdentity(); 17555 try { 17556 am.killProcessesBelowForeground("setPermissionEnforcement"); 17557 } catch (RemoteException e) { 17558 } finally { 17559 Binder.restoreCallingIdentity(token); 17560 } 17561 } 17562 } else { 17563 throw new IllegalArgumentException("No selective enforcement for " + permission); 17564 } 17565 } 17566 17567 @Override 17568 @Deprecated 17569 public boolean isPermissionEnforced(String permission) { 17570 return true; 17571 } 17572 17573 @Override 17574 public boolean isStorageLow() { 17575 final long token = Binder.clearCallingIdentity(); 17576 try { 17577 final DeviceStorageMonitorInternal 17578 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 17579 if (dsm != null) { 17580 return dsm.isMemoryLow(); 17581 } else { 17582 return false; 17583 } 17584 } finally { 17585 Binder.restoreCallingIdentity(token); 17586 } 17587 } 17588 17589 @Override 17590 public IPackageInstaller getPackageInstaller() { 17591 return mInstallerService; 17592 } 17593 17594 private boolean userNeedsBadging(int userId) { 17595 int index = mUserNeedsBadging.indexOfKey(userId); 17596 if (index < 0) { 17597 final UserInfo userInfo; 17598 final long token = Binder.clearCallingIdentity(); 17599 try { 17600 userInfo = sUserManager.getUserInfo(userId); 17601 } finally { 17602 Binder.restoreCallingIdentity(token); 17603 } 17604 final boolean b; 17605 if (userInfo != null && userInfo.isManagedProfile()) { 17606 b = true; 17607 } else { 17608 b = false; 17609 } 17610 mUserNeedsBadging.put(userId, b); 17611 return b; 17612 } 17613 return mUserNeedsBadging.valueAt(index); 17614 } 17615 17616 @Override 17617 public KeySet getKeySetByAlias(String packageName, String alias) { 17618 if (packageName == null || alias == null) { 17619 return null; 17620 } 17621 synchronized(mPackages) { 17622 final PackageParser.Package pkg = mPackages.get(packageName); 17623 if (pkg == null) { 17624 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 17625 throw new IllegalArgumentException("Unknown package: " + packageName); 17626 } 17627 KeySetManagerService ksms = mSettings.mKeySetManagerService; 17628 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 17629 } 17630 } 17631 17632 @Override 17633 public KeySet getSigningKeySet(String packageName) { 17634 if (packageName == null) { 17635 return null; 17636 } 17637 synchronized(mPackages) { 17638 final PackageParser.Package pkg = mPackages.get(packageName); 17639 if (pkg == null) { 17640 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 17641 throw new IllegalArgumentException("Unknown package: " + packageName); 17642 } 17643 if (pkg.applicationInfo.uid != Binder.getCallingUid() 17644 && Process.SYSTEM_UID != Binder.getCallingUid()) { 17645 throw new SecurityException("May not access signing KeySet of other apps."); 17646 } 17647 KeySetManagerService ksms = mSettings.mKeySetManagerService; 17648 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 17649 } 17650 } 17651 17652 @Override 17653 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 17654 if (packageName == null || ks == null) { 17655 return false; 17656 } 17657 synchronized(mPackages) { 17658 final PackageParser.Package pkg = mPackages.get(packageName); 17659 if (pkg == null) { 17660 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 17661 throw new IllegalArgumentException("Unknown package: " + packageName); 17662 } 17663 IBinder ksh = ks.getToken(); 17664 if (ksh instanceof KeySetHandle) { 17665 KeySetManagerService ksms = mSettings.mKeySetManagerService; 17666 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 17667 } 17668 return false; 17669 } 17670 } 17671 17672 @Override 17673 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 17674 if (packageName == null || ks == null) { 17675 return false; 17676 } 17677 synchronized(mPackages) { 17678 final PackageParser.Package pkg = mPackages.get(packageName); 17679 if (pkg == null) { 17680 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 17681 throw new IllegalArgumentException("Unknown package: " + packageName); 17682 } 17683 IBinder ksh = ks.getToken(); 17684 if (ksh instanceof KeySetHandle) { 17685 KeySetManagerService ksms = mSettings.mKeySetManagerService; 17686 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 17687 } 17688 return false; 17689 } 17690 } 17691 17692 private void deletePackageIfUnusedLPr(final String packageName) { 17693 PackageSetting ps = mSettings.mPackages.get(packageName); 17694 if (ps == null) { 17695 return; 17696 } 17697 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 17698 // TODO Implement atomic delete if package is unused 17699 // It is currently possible that the package will be deleted even if it is installed 17700 // after this method returns. 17701 mHandler.post(new Runnable() { 17702 public void run() { 17703 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 17704 } 17705 }); 17706 } 17707 } 17708 17709 /** 17710 * Check and throw if the given before/after packages would be considered a 17711 * downgrade. 17712 */ 17713 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 17714 throws PackageManagerException { 17715 if (after.versionCode < before.mVersionCode) { 17716 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 17717 "Update version code " + after.versionCode + " is older than current " 17718 + before.mVersionCode); 17719 } else if (after.versionCode == before.mVersionCode) { 17720 if (after.baseRevisionCode < before.baseRevisionCode) { 17721 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 17722 "Update base revision code " + after.baseRevisionCode 17723 + " is older than current " + before.baseRevisionCode); 17724 } 17725 17726 if (!ArrayUtils.isEmpty(after.splitNames)) { 17727 for (int i = 0; i < after.splitNames.length; i++) { 17728 final String splitName = after.splitNames[i]; 17729 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 17730 if (j != -1) { 17731 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 17732 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 17733 "Update split " + splitName + " revision code " 17734 + after.splitRevisionCodes[i] + " is older than current " 17735 + before.splitRevisionCodes[j]); 17736 } 17737 } 17738 } 17739 } 17740 } 17741 } 17742 17743 private static class MoveCallbacks extends Handler { 17744 private static final int MSG_CREATED = 1; 17745 private static final int MSG_STATUS_CHANGED = 2; 17746 17747 private final RemoteCallbackList<IPackageMoveObserver> 17748 mCallbacks = new RemoteCallbackList<>(); 17749 17750 private final SparseIntArray mLastStatus = new SparseIntArray(); 17751 17752 public MoveCallbacks(Looper looper) { 17753 super(looper); 17754 } 17755 17756 public void register(IPackageMoveObserver callback) { 17757 mCallbacks.register(callback); 17758 } 17759 17760 public void unregister(IPackageMoveObserver callback) { 17761 mCallbacks.unregister(callback); 17762 } 17763 17764 @Override 17765 public void handleMessage(Message msg) { 17766 final SomeArgs args = (SomeArgs) msg.obj; 17767 final int n = mCallbacks.beginBroadcast(); 17768 for (int i = 0; i < n; i++) { 17769 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 17770 try { 17771 invokeCallback(callback, msg.what, args); 17772 } catch (RemoteException ignored) { 17773 } 17774 } 17775 mCallbacks.finishBroadcast(); 17776 args.recycle(); 17777 } 17778 17779 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 17780 throws RemoteException { 17781 switch (what) { 17782 case MSG_CREATED: { 17783 callback.onCreated(args.argi1, (Bundle) args.arg2); 17784 break; 17785 } 17786 case MSG_STATUS_CHANGED: { 17787 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 17788 break; 17789 } 17790 } 17791 } 17792 17793 private void notifyCreated(int moveId, Bundle extras) { 17794 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 17795 17796 final SomeArgs args = SomeArgs.obtain(); 17797 args.argi1 = moveId; 17798 args.arg2 = extras; 17799 obtainMessage(MSG_CREATED, args).sendToTarget(); 17800 } 17801 17802 private void notifyStatusChanged(int moveId, int status) { 17803 notifyStatusChanged(moveId, status, -1); 17804 } 17805 17806 private void notifyStatusChanged(int moveId, int status, long estMillis) { 17807 Slog.v(TAG, "Move " + moveId + " status " + status); 17808 17809 final SomeArgs args = SomeArgs.obtain(); 17810 args.argi1 = moveId; 17811 args.argi2 = status; 17812 args.arg3 = estMillis; 17813 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 17814 17815 synchronized (mLastStatus) { 17816 mLastStatus.put(moveId, status); 17817 } 17818 } 17819 } 17820 17821 private final static class OnPermissionChangeListeners extends Handler { 17822 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 17823 17824 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 17825 new RemoteCallbackList<>(); 17826 17827 public OnPermissionChangeListeners(Looper looper) { 17828 super(looper); 17829 } 17830 17831 @Override 17832 public void handleMessage(Message msg) { 17833 switch (msg.what) { 17834 case MSG_ON_PERMISSIONS_CHANGED: { 17835 final int uid = msg.arg1; 17836 handleOnPermissionsChanged(uid); 17837 } break; 17838 } 17839 } 17840 17841 public void addListenerLocked(IOnPermissionsChangeListener listener) { 17842 mPermissionListeners.register(listener); 17843 17844 } 17845 17846 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 17847 mPermissionListeners.unregister(listener); 17848 } 17849 17850 public void onPermissionsChanged(int uid) { 17851 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 17852 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 17853 } 17854 } 17855 17856 private void handleOnPermissionsChanged(int uid) { 17857 final int count = mPermissionListeners.beginBroadcast(); 17858 try { 17859 for (int i = 0; i < count; i++) { 17860 IOnPermissionsChangeListener callback = mPermissionListeners 17861 .getBroadcastItem(i); 17862 try { 17863 callback.onPermissionsChanged(uid); 17864 } catch (RemoteException e) { 17865 Log.e(TAG, "Permission listener is dead", e); 17866 } 17867 } 17868 } finally { 17869 mPermissionListeners.finishBroadcast(); 17870 } 17871 } 17872 } 17873 17874 private class PackageManagerInternalImpl extends PackageManagerInternal { 17875 @Override 17876 public void setLocationPackagesProvider(PackagesProvider provider) { 17877 synchronized (mPackages) { 17878 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 17879 } 17880 } 17881 17882 @Override 17883 public void setImePackagesProvider(PackagesProvider provider) { 17884 synchronized (mPackages) { 17885 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 17886 } 17887 } 17888 17889 @Override 17890 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 17891 synchronized (mPackages) { 17892 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 17893 } 17894 } 17895 17896 @Override 17897 public void setSmsAppPackagesProvider(PackagesProvider provider) { 17898 synchronized (mPackages) { 17899 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 17900 } 17901 } 17902 17903 @Override 17904 public void setDialerAppPackagesProvider(PackagesProvider provider) { 17905 synchronized (mPackages) { 17906 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 17907 } 17908 } 17909 17910 @Override 17911 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 17912 synchronized (mPackages) { 17913 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 17914 } 17915 } 17916 17917 @Override 17918 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 17919 synchronized (mPackages) { 17920 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 17921 } 17922 } 17923 17924 @Override 17925 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 17926 synchronized (mPackages) { 17927 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 17928 packageName, userId); 17929 } 17930 } 17931 17932 @Override 17933 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 17934 synchronized (mPackages) { 17935 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 17936 packageName, userId); 17937 } 17938 } 17939 17940 @Override 17941 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 17942 synchronized (mPackages) { 17943 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 17944 packageName, userId); 17945 } 17946 } 17947 17948 @Override 17949 public void setKeepUninstalledPackages(final List<String> packageList) { 17950 Preconditions.checkNotNull(packageList); 17951 List<String> removedFromList = null; 17952 synchronized (mPackages) { 17953 if (mKeepUninstalledPackages != null) { 17954 final int packagesCount = mKeepUninstalledPackages.size(); 17955 for (int i = 0; i < packagesCount; i++) { 17956 String oldPackage = mKeepUninstalledPackages.get(i); 17957 if (packageList != null && packageList.contains(oldPackage)) { 17958 continue; 17959 } 17960 if (removedFromList == null) { 17961 removedFromList = new ArrayList<>(); 17962 } 17963 removedFromList.add(oldPackage); 17964 } 17965 } 17966 mKeepUninstalledPackages = new ArrayList<>(packageList); 17967 if (removedFromList != null) { 17968 final int removedCount = removedFromList.size(); 17969 for (int i = 0; i < removedCount; i++) { 17970 deletePackageIfUnusedLPr(removedFromList.get(i)); 17971 } 17972 } 17973 } 17974 } 17975 17976 @Override 17977 public boolean isPermissionsReviewRequired(String packageName, int userId) { 17978 synchronized (mPackages) { 17979 // If we do not support permission review, done. 17980 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 17981 return false; 17982 } 17983 17984 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 17985 if (packageSetting == null) { 17986 return false; 17987 } 17988 17989 // Permission review applies only to apps not supporting the new permission model. 17990 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 17991 return false; 17992 } 17993 17994 // Legacy apps have the permission and get user consent on launch. 17995 PermissionsState permissionsState = packageSetting.getPermissionsState(); 17996 return permissionsState.isPermissionReviewRequired(userId); 17997 } 17998 } 17999 } 18000 18001 @Override 18002 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 18003 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 18004 synchronized (mPackages) { 18005 final long identity = Binder.clearCallingIdentity(); 18006 try { 18007 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 18008 packageNames, userId); 18009 } finally { 18010 Binder.restoreCallingIdentity(identity); 18011 } 18012 } 18013 } 18014 18015 private static void enforceSystemOrPhoneCaller(String tag) { 18016 int callingUid = Binder.getCallingUid(); 18017 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 18018 throw new SecurityException( 18019 "Cannot call " + tag + " from UID " + callingUid); 18020 } 18021 } 18022} 18023