PackageManagerService.java revision f340974e06980e1fcc3a6ef8b5603307b6650187
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_DUPLICATE_PACKAGE; 38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 39import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 40import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 41import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 42import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 43import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 44import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 45import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 46import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 47import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 48import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 49import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 50import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 51import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 52import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 53import static android.content.pm.PackageManager.INSTALL_INTERNAL; 54import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 55import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 60import static android.content.pm.PackageManager.MATCH_ALL; 61import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 62import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS; 63import static android.content.pm.PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE; 64import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 65import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 66import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 67import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 68import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 69import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 70import static android.content.pm.PackageManager.PERMISSION_DENIED; 71import static android.content.pm.PackageManager.PERMISSION_GRANTED; 72import static android.content.pm.PackageParser.isApkFile; 73import static android.os.Process.PACKAGE_INFO_GID; 74import static android.os.Process.SYSTEM_UID; 75import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 76import static android.system.OsConstants.O_CREAT; 77import static android.system.OsConstants.O_RDWR; 78import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 79import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 80import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 81import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 82import static com.android.internal.util.ArrayUtils.appendInt; 83import static com.android.server.pm.Installer.DEXOPT_PUBLIC; 84import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 85import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 86import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 87import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 88import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 89import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 90import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 91import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 92 93import android.Manifest; 94import android.annotation.NonNull; 95import android.annotation.Nullable; 96import android.app.ActivityManager; 97import android.app.ActivityManagerNative; 98import android.app.AppGlobals; 99import android.app.IActivityManager; 100import android.app.admin.IDevicePolicyManager; 101import android.app.backup.IBackupManager; 102import android.content.BroadcastReceiver; 103import android.content.ComponentName; 104import android.content.Context; 105import android.content.IIntentReceiver; 106import android.content.Intent; 107import android.content.IntentFilter; 108import android.content.IntentSender; 109import android.content.IntentSender.SendIntentException; 110import android.content.ServiceConnection; 111import android.content.pm.ActivityInfo; 112import android.content.pm.ApplicationInfo; 113import android.content.pm.AppsQueryHelper; 114import android.content.pm.ComponentInfo; 115import android.content.pm.EphemeralApplicationInfo; 116import android.content.pm.EphemeralResolveInfo; 117import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo; 118import android.content.pm.FeatureInfo; 119import android.content.pm.IOnPermissionsChangeListener; 120import android.content.pm.IPackageDataObserver; 121import android.content.pm.IPackageDeleteObserver; 122import android.content.pm.IPackageDeleteObserver2; 123import android.content.pm.IPackageInstallObserver2; 124import android.content.pm.IPackageInstaller; 125import android.content.pm.IPackageManager; 126import android.content.pm.IPackageMoveObserver; 127import android.content.pm.IPackageStatsObserver; 128import android.content.pm.InstrumentationInfo; 129import android.content.pm.IntentFilterVerificationInfo; 130import android.content.pm.KeySet; 131import android.content.pm.PackageCleanItem; 132import android.content.pm.PackageInfo; 133import android.content.pm.PackageInfoLite; 134import android.content.pm.PackageInstaller; 135import android.content.pm.PackageManager; 136import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 137import android.content.pm.PackageManagerInternal; 138import android.content.pm.PackageParser; 139import android.content.pm.PackageParser.ActivityIntentInfo; 140import android.content.pm.PackageParser.PackageLite; 141import android.content.pm.PackageParser.PackageParserException; 142import android.content.pm.PackageStats; 143import android.content.pm.PackageUserState; 144import android.content.pm.ParceledListSlice; 145import android.content.pm.PermissionGroupInfo; 146import android.content.pm.PermissionInfo; 147import android.content.pm.ProviderInfo; 148import android.content.pm.ResolveInfo; 149import android.content.pm.ServiceInfo; 150import android.content.pm.Signature; 151import android.content.pm.UserInfo; 152import android.content.pm.VerificationParams; 153import android.content.pm.VerifierDeviceIdentity; 154import android.content.pm.VerifierInfo; 155import android.content.res.Resources; 156import android.graphics.Bitmap; 157import android.hardware.display.DisplayManager; 158import android.net.Uri; 159import android.os.Binder; 160import android.os.Build; 161import android.os.Bundle; 162import android.os.Debug; 163import android.os.Environment; 164import android.os.Environment.UserEnvironment; 165import android.os.FileUtils; 166import android.os.Handler; 167import android.os.IBinder; 168import android.os.Looper; 169import android.os.Message; 170import android.os.Parcel; 171import android.os.ParcelFileDescriptor; 172import android.os.Process; 173import android.os.RemoteCallbackList; 174import android.os.RemoteException; 175import android.os.ResultReceiver; 176import android.os.SELinux; 177import android.os.ServiceManager; 178import android.os.SystemClock; 179import android.os.SystemProperties; 180import android.os.Trace; 181import android.os.UserHandle; 182import android.os.UserManager; 183import android.os.storage.IMountService; 184import android.os.storage.MountServiceInternal; 185import android.os.storage.StorageEventListener; 186import android.os.storage.StorageManager; 187import android.os.storage.VolumeInfo; 188import android.os.storage.VolumeRecord; 189import android.security.KeyStore; 190import android.security.SystemKeyStore; 191import android.system.ErrnoException; 192import android.system.Os; 193import android.text.TextUtils; 194import android.text.format.DateUtils; 195import android.util.ArrayMap; 196import android.util.ArraySet; 197import android.util.AtomicFile; 198import android.util.DisplayMetrics; 199import android.util.EventLog; 200import android.util.ExceptionUtils; 201import android.util.Log; 202import android.util.LogPrinter; 203import android.util.MathUtils; 204import android.util.PrintStreamPrinter; 205import android.util.Slog; 206import android.util.SparseArray; 207import android.util.SparseBooleanArray; 208import android.util.SparseIntArray; 209import android.util.Xml; 210import android.view.Display; 211 212import com.android.internal.R; 213import com.android.internal.annotations.GuardedBy; 214import com.android.internal.app.IMediaContainerService; 215import com.android.internal.app.ResolverActivity; 216import com.android.internal.content.NativeLibraryHelper; 217import com.android.internal.content.PackageHelper; 218import com.android.internal.os.IParcelFileDescriptorFactory; 219import com.android.internal.os.InstallerConnection.InstallerException; 220import com.android.internal.os.SomeArgs; 221import com.android.internal.os.Zygote; 222import com.android.internal.util.ArrayUtils; 223import com.android.internal.util.FastPrintWriter; 224import com.android.internal.util.FastXmlSerializer; 225import com.android.internal.util.IndentingPrintWriter; 226import com.android.internal.util.Preconditions; 227import com.android.internal.util.XmlUtils; 228import com.android.server.EventLogTags; 229import com.android.server.FgThread; 230import com.android.server.IntentResolver; 231import com.android.server.LocalServices; 232import com.android.server.ServiceThread; 233import com.android.server.SystemConfig; 234import com.android.server.Watchdog; 235import com.android.server.pm.Installer.StorageFlags; 236import com.android.server.pm.PermissionsState.PermissionState; 237import com.android.server.pm.Settings.DatabaseVersion; 238import com.android.server.pm.Settings.VersionInfo; 239import com.android.server.storage.DeviceStorageMonitorInternal; 240 241import dalvik.system.DexFile; 242import dalvik.system.VMRuntime; 243 244import libcore.io.IoUtils; 245import libcore.util.EmptyArray; 246 247import org.xmlpull.v1.XmlPullParser; 248import org.xmlpull.v1.XmlPullParserException; 249import org.xmlpull.v1.XmlSerializer; 250 251import java.io.BufferedInputStream; 252import java.io.BufferedOutputStream; 253import java.io.BufferedReader; 254import java.io.ByteArrayInputStream; 255import java.io.ByteArrayOutputStream; 256import java.io.File; 257import java.io.FileDescriptor; 258import java.io.FileNotFoundException; 259import java.io.FileOutputStream; 260import java.io.FileReader; 261import java.io.FilenameFilter; 262import java.io.IOException; 263import java.io.InputStream; 264import java.io.PrintWriter; 265import java.nio.charset.StandardCharsets; 266import java.security.MessageDigest; 267import java.security.NoSuchAlgorithmException; 268import java.security.PublicKey; 269import java.security.cert.CertificateEncodingException; 270import java.security.cert.CertificateException; 271import java.text.SimpleDateFormat; 272import java.util.ArrayList; 273import java.util.Arrays; 274import java.util.Collection; 275import java.util.Collections; 276import java.util.Comparator; 277import java.util.Date; 278import java.util.Iterator; 279import java.util.List; 280import java.util.Map; 281import java.util.Objects; 282import java.util.Set; 283import java.util.concurrent.CountDownLatch; 284import java.util.concurrent.TimeUnit; 285import java.util.concurrent.atomic.AtomicBoolean; 286import java.util.concurrent.atomic.AtomicInteger; 287import java.util.concurrent.atomic.AtomicLong; 288 289/** 290 * Keep track of all those .apks everywhere. 291 * 292 * This is very central to the platform's security; please run the unit 293 * tests whenever making modifications here: 294 * 295runtest -c android.content.pm.PackageManagerTests frameworks-core 296 * 297 * {@hide} 298 */ 299public class PackageManagerService extends IPackageManager.Stub { 300 static final String TAG = "PackageManager"; 301 static final boolean DEBUG_SETTINGS = false; 302 static final boolean DEBUG_PREFERRED = false; 303 static final boolean DEBUG_UPGRADE = false; 304 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 305 private static final boolean DEBUG_BACKUP = false; 306 private static final boolean DEBUG_INSTALL = false; 307 private static final boolean DEBUG_REMOVE = false; 308 private static final boolean DEBUG_BROADCASTS = false; 309 private static final boolean DEBUG_SHOW_INFO = false; 310 private static final boolean DEBUG_PACKAGE_INFO = false; 311 private static final boolean DEBUG_INTENT_MATCHING = false; 312 private static final boolean DEBUG_PACKAGE_SCANNING = false; 313 private static final boolean DEBUG_VERIFY = false; 314 private static final boolean DEBUG_DEXOPT = false; 315 private static final boolean DEBUG_ABI_SELECTION = false; 316 private static final boolean DEBUG_EPHEMERAL = false; 317 private static final boolean DEBUG_TRIAGED_MISSING = false; 318 private static final boolean DEBUG_APP_DATA = false; 319 320 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 321 322 private static final boolean DISABLE_EPHEMERAL_APPS = true; 323 324 private static final int RADIO_UID = Process.PHONE_UID; 325 private static final int LOG_UID = Process.LOG_UID; 326 private static final int NFC_UID = Process.NFC_UID; 327 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 328 private static final int SHELL_UID = Process.SHELL_UID; 329 330 // Cap the size of permission trees that 3rd party apps can define 331 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 332 333 // Suffix used during package installation when copying/moving 334 // package apks to install directory. 335 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 336 337 static final int SCAN_NO_DEX = 1<<1; 338 static final int SCAN_FORCE_DEX = 1<<2; 339 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 340 static final int SCAN_NEW_INSTALL = 1<<4; 341 static final int SCAN_NO_PATHS = 1<<5; 342 static final int SCAN_UPDATE_TIME = 1<<6; 343 static final int SCAN_DEFER_DEX = 1<<7; 344 static final int SCAN_BOOTING = 1<<8; 345 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 346 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 347 static final int SCAN_REPLACING = 1<<11; 348 static final int SCAN_REQUIRE_KNOWN = 1<<12; 349 static final int SCAN_MOVE = 1<<13; 350 static final int SCAN_INITIAL = 1<<14; 351 352 static final int REMOVE_CHATTY = 1<<16; 353 354 private static final int[] EMPTY_INT_ARRAY = new int[0]; 355 356 /** 357 * Timeout (in milliseconds) after which the watchdog should declare that 358 * our handler thread is wedged. The usual default for such things is one 359 * minute but we sometimes do very lengthy I/O operations on this thread, 360 * such as installing multi-gigabyte applications, so ours needs to be longer. 361 */ 362 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 363 364 /** 365 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 366 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 367 * settings entry if available, otherwise we use the hardcoded default. If it's been 368 * more than this long since the last fstrim, we force one during the boot sequence. 369 * 370 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 371 * one gets run at the next available charging+idle time. This final mandatory 372 * no-fstrim check kicks in only of the other scheduling criteria is never met. 373 */ 374 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 375 376 /** 377 * Whether verification is enabled by default. 378 */ 379 private static final boolean DEFAULT_VERIFY_ENABLE = true; 380 381 /** 382 * The default maximum time to wait for the verification agent to return in 383 * milliseconds. 384 */ 385 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 386 387 /** 388 * The default response for package verification timeout. 389 * 390 * This can be either PackageManager.VERIFICATION_ALLOW or 391 * PackageManager.VERIFICATION_REJECT. 392 */ 393 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 394 395 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 396 397 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 398 DEFAULT_CONTAINER_PACKAGE, 399 "com.android.defcontainer.DefaultContainerService"); 400 401 private static final String KILL_APP_REASON_GIDS_CHANGED = 402 "permission grant or revoke changed gids"; 403 404 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 405 "permissions revoked"; 406 407 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 408 409 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 410 411 /** Permission grant: not grant the permission. */ 412 private static final int GRANT_DENIED = 1; 413 414 /** Permission grant: grant the permission as an install permission. */ 415 private static final int GRANT_INSTALL = 2; 416 417 /** Permission grant: grant the permission as a runtime one. */ 418 private static final int GRANT_RUNTIME = 3; 419 420 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 421 private static final int GRANT_UPGRADE = 4; 422 423 /** Canonical intent used to identify what counts as a "web browser" app */ 424 private static final Intent sBrowserIntent; 425 static { 426 sBrowserIntent = new Intent(); 427 sBrowserIntent.setAction(Intent.ACTION_VIEW); 428 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 429 sBrowserIntent.setData(Uri.parse("http:")); 430 } 431 432 final ServiceThread mHandlerThread; 433 434 final PackageHandler mHandler; 435 436 /** 437 * Messages for {@link #mHandler} that need to wait for system ready before 438 * being dispatched. 439 */ 440 private ArrayList<Message> mPostSystemReadyMessages; 441 442 final int mSdkVersion = Build.VERSION.SDK_INT; 443 444 final Context mContext; 445 final boolean mFactoryTest; 446 final boolean mOnlyCore; 447 final DisplayMetrics mMetrics; 448 final int mDefParseFlags; 449 final String[] mSeparateProcesses; 450 final boolean mIsUpgrade; 451 452 /** The location for ASEC container files on internal storage. */ 453 final String mAsecInternalPath; 454 455 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 456 // LOCK HELD. Can be called with mInstallLock held. 457 @GuardedBy("mInstallLock") 458 final Installer mInstaller; 459 460 /** Directory where installed third-party apps stored */ 461 final File mAppInstallDir; 462 final File mEphemeralInstallDir; 463 464 /** 465 * Directory to which applications installed internally have their 466 * 32 bit native libraries copied. 467 */ 468 private File mAppLib32InstallDir; 469 470 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 471 // apps. 472 final File mDrmAppPrivateInstallDir; 473 474 // ---------------------------------------------------------------- 475 476 // Lock for state used when installing and doing other long running 477 // operations. Methods that must be called with this lock held have 478 // the suffix "LI". 479 final Object mInstallLock = new Object(); 480 481 // ---------------------------------------------------------------- 482 483 // Keys are String (package name), values are Package. This also serves 484 // as the lock for the global state. Methods that must be called with 485 // this lock held have the prefix "LP". 486 @GuardedBy("mPackages") 487 final ArrayMap<String, PackageParser.Package> mPackages = 488 new ArrayMap<String, PackageParser.Package>(); 489 490 // Tracks available target package names -> overlay package paths. 491 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 492 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 493 494 /** 495 * Tracks new system packages [received in an OTA] that we expect to 496 * find updated user-installed versions. Keys are package name, values 497 * are package location. 498 */ 499 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 500 501 /** 502 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 503 */ 504 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 505 /** 506 * Whether or not system app permissions should be promoted from install to runtime. 507 */ 508 boolean mPromoteSystemApps; 509 510 final Settings mSettings; 511 boolean mRestoredSettings; 512 513 // System configuration read by SystemConfig. 514 final int[] mGlobalGids; 515 final SparseArray<ArraySet<String>> mSystemPermissions; 516 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 517 518 // If mac_permissions.xml was found for seinfo labeling. 519 boolean mFoundPolicyFile; 520 521 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 522 523 public static final class SharedLibraryEntry { 524 public final String path; 525 public final String apk; 526 527 SharedLibraryEntry(String _path, String _apk) { 528 path = _path; 529 apk = _apk; 530 } 531 } 532 533 // Currently known shared libraries. 534 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 535 new ArrayMap<String, SharedLibraryEntry>(); 536 537 // All available activities, for your resolving pleasure. 538 final ActivityIntentResolver mActivities = 539 new ActivityIntentResolver(); 540 541 // All available receivers, for your resolving pleasure. 542 final ActivityIntentResolver mReceivers = 543 new ActivityIntentResolver(); 544 545 // All available services, for your resolving pleasure. 546 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 547 548 // All available providers, for your resolving pleasure. 549 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 550 551 // Mapping from provider base names (first directory in content URI codePath) 552 // to the provider information. 553 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 554 new ArrayMap<String, PackageParser.Provider>(); 555 556 // Mapping from instrumentation class names to info about them. 557 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 558 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 559 560 // Mapping from permission names to info about them. 561 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 562 new ArrayMap<String, PackageParser.PermissionGroup>(); 563 564 // Packages whose data we have transfered into another package, thus 565 // should no longer exist. 566 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 567 568 // Broadcast actions that are only available to the system. 569 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 570 571 /** List of packages waiting for verification. */ 572 final SparseArray<PackageVerificationState> mPendingVerification 573 = new SparseArray<PackageVerificationState>(); 574 575 /** Set of packages associated with each app op permission. */ 576 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 577 578 final PackageInstallerService mInstallerService; 579 580 private final PackageDexOptimizer mPackageDexOptimizer; 581 582 private AtomicInteger mNextMoveId = new AtomicInteger(); 583 private final MoveCallbacks mMoveCallbacks; 584 585 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 586 587 // Cache of users who need badging. 588 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 589 590 /** Token for keys in mPendingVerification. */ 591 private int mPendingVerificationToken = 0; 592 593 volatile boolean mSystemReady; 594 volatile boolean mSafeMode; 595 volatile boolean mHasSystemUidErrors; 596 597 ApplicationInfo mAndroidApplication; 598 final ActivityInfo mResolveActivity = new ActivityInfo(); 599 final ResolveInfo mResolveInfo = new ResolveInfo(); 600 ComponentName mResolveComponentName; 601 PackageParser.Package mPlatformPackage; 602 ComponentName mCustomResolverComponentName; 603 604 boolean mResolverReplaced = false; 605 606 private final @Nullable ComponentName mIntentFilterVerifierComponent; 607 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 608 609 private int mIntentFilterVerificationToken = 0; 610 611 /** Component that knows whether or not an ephemeral application exists */ 612 final ComponentName mEphemeralResolverComponent; 613 /** The service connection to the ephemeral resolver */ 614 final EphemeralResolverConnection mEphemeralResolverConnection; 615 616 /** Component used to install ephemeral applications */ 617 final ComponentName mEphemeralInstallerComponent; 618 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 619 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 620 621 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 622 = new SparseArray<IntentFilterVerificationState>(); 623 624 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 625 new DefaultPermissionGrantPolicy(this); 626 627 // List of packages names to keep cached, even if they are uninstalled for all users 628 private List<String> mKeepUninstalledPackages; 629 630 private static class IFVerificationParams { 631 PackageParser.Package pkg; 632 boolean replacing; 633 int userId; 634 int verifierUid; 635 636 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 637 int _userId, int _verifierUid) { 638 pkg = _pkg; 639 replacing = _replacing; 640 userId = _userId; 641 replacing = _replacing; 642 verifierUid = _verifierUid; 643 } 644 } 645 646 private interface IntentFilterVerifier<T extends IntentFilter> { 647 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 648 T filter, String packageName); 649 void startVerifications(int userId); 650 void receiveVerificationResponse(int verificationId); 651 } 652 653 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 654 private Context mContext; 655 private ComponentName mIntentFilterVerifierComponent; 656 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 657 658 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 659 mContext = context; 660 mIntentFilterVerifierComponent = verifierComponent; 661 } 662 663 private String getDefaultScheme() { 664 return IntentFilter.SCHEME_HTTPS; 665 } 666 667 @Override 668 public void startVerifications(int userId) { 669 // Launch verifications requests 670 int count = mCurrentIntentFilterVerifications.size(); 671 for (int n=0; n<count; n++) { 672 int verificationId = mCurrentIntentFilterVerifications.get(n); 673 final IntentFilterVerificationState ivs = 674 mIntentFilterVerificationStates.get(verificationId); 675 676 String packageName = ivs.getPackageName(); 677 678 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 679 final int filterCount = filters.size(); 680 ArraySet<String> domainsSet = new ArraySet<>(); 681 for (int m=0; m<filterCount; m++) { 682 PackageParser.ActivityIntentInfo filter = filters.get(m); 683 domainsSet.addAll(filter.getHostsList()); 684 } 685 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 686 synchronized (mPackages) { 687 if (mSettings.createIntentFilterVerificationIfNeededLPw( 688 packageName, domainsList) != null) { 689 scheduleWriteSettingsLocked(); 690 } 691 } 692 sendVerificationRequest(userId, verificationId, ivs); 693 } 694 mCurrentIntentFilterVerifications.clear(); 695 } 696 697 private void sendVerificationRequest(int userId, int verificationId, 698 IntentFilterVerificationState ivs) { 699 700 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 701 verificationIntent.putExtra( 702 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 703 verificationId); 704 verificationIntent.putExtra( 705 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 706 getDefaultScheme()); 707 verificationIntent.putExtra( 708 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 709 ivs.getHostsString()); 710 verificationIntent.putExtra( 711 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 712 ivs.getPackageName()); 713 verificationIntent.setComponent(mIntentFilterVerifierComponent); 714 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 715 716 UserHandle user = new UserHandle(userId); 717 mContext.sendBroadcastAsUser(verificationIntent, user); 718 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 719 "Sending IntentFilter verification broadcast"); 720 } 721 722 public void receiveVerificationResponse(int verificationId) { 723 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 724 725 final boolean verified = ivs.isVerified(); 726 727 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 728 final int count = filters.size(); 729 if (DEBUG_DOMAIN_VERIFICATION) { 730 Slog.i(TAG, "Received verification response " + verificationId 731 + " for " + count + " filters, verified=" + verified); 732 } 733 for (int n=0; n<count; n++) { 734 PackageParser.ActivityIntentInfo filter = filters.get(n); 735 filter.setVerified(verified); 736 737 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 738 + " verified with result:" + verified + " and hosts:" 739 + ivs.getHostsString()); 740 } 741 742 mIntentFilterVerificationStates.remove(verificationId); 743 744 final String packageName = ivs.getPackageName(); 745 IntentFilterVerificationInfo ivi = null; 746 747 synchronized (mPackages) { 748 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 749 } 750 if (ivi == null) { 751 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 752 + verificationId + " packageName:" + packageName); 753 return; 754 } 755 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 756 "Updating IntentFilterVerificationInfo for package " + packageName 757 +" verificationId:" + verificationId); 758 759 synchronized (mPackages) { 760 if (verified) { 761 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 762 } else { 763 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 764 } 765 scheduleWriteSettingsLocked(); 766 767 final int userId = ivs.getUserId(); 768 if (userId != UserHandle.USER_ALL) { 769 final int userStatus = 770 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 771 772 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 773 boolean needUpdate = false; 774 775 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 776 // already been set by the User thru the Disambiguation dialog 777 switch (userStatus) { 778 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 779 if (verified) { 780 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 781 } else { 782 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 783 } 784 needUpdate = true; 785 break; 786 787 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 788 if (verified) { 789 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 790 needUpdate = true; 791 } 792 break; 793 794 default: 795 // Nothing to do 796 } 797 798 if (needUpdate) { 799 mSettings.updateIntentFilterVerificationStatusLPw( 800 packageName, updatedStatus, userId); 801 scheduleWritePackageRestrictionsLocked(userId); 802 } 803 } 804 } 805 } 806 807 @Override 808 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 809 ActivityIntentInfo filter, String packageName) { 810 if (!hasValidDomains(filter)) { 811 return false; 812 } 813 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 814 if (ivs == null) { 815 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 816 packageName); 817 } 818 if (DEBUG_DOMAIN_VERIFICATION) { 819 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 820 } 821 ivs.addFilter(filter); 822 return true; 823 } 824 825 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 826 int userId, int verificationId, String packageName) { 827 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 828 verifierUid, userId, packageName); 829 ivs.setPendingState(); 830 synchronized (mPackages) { 831 mIntentFilterVerificationStates.append(verificationId, ivs); 832 mCurrentIntentFilterVerifications.add(verificationId); 833 } 834 return ivs; 835 } 836 } 837 838 private static boolean hasValidDomains(ActivityIntentInfo filter) { 839 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 840 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 841 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 842 } 843 844 // Set of pending broadcasts for aggregating enable/disable of components. 845 static class PendingPackageBroadcasts { 846 // for each user id, a map of <package name -> components within that package> 847 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 848 849 public PendingPackageBroadcasts() { 850 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 851 } 852 853 public ArrayList<String> get(int userId, String packageName) { 854 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 855 return packages.get(packageName); 856 } 857 858 public void put(int userId, String packageName, ArrayList<String> components) { 859 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 860 packages.put(packageName, components); 861 } 862 863 public void remove(int userId, String packageName) { 864 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 865 if (packages != null) { 866 packages.remove(packageName); 867 } 868 } 869 870 public void remove(int userId) { 871 mUidMap.remove(userId); 872 } 873 874 public int userIdCount() { 875 return mUidMap.size(); 876 } 877 878 public int userIdAt(int n) { 879 return mUidMap.keyAt(n); 880 } 881 882 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 883 return mUidMap.get(userId); 884 } 885 886 public int size() { 887 // total number of pending broadcast entries across all userIds 888 int num = 0; 889 for (int i = 0; i< mUidMap.size(); i++) { 890 num += mUidMap.valueAt(i).size(); 891 } 892 return num; 893 } 894 895 public void clear() { 896 mUidMap.clear(); 897 } 898 899 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 900 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 901 if (map == null) { 902 map = new ArrayMap<String, ArrayList<String>>(); 903 mUidMap.put(userId, map); 904 } 905 return map; 906 } 907 } 908 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 909 910 // Service Connection to remote media container service to copy 911 // package uri's from external media onto secure containers 912 // or internal storage. 913 private IMediaContainerService mContainerService = null; 914 915 static final int SEND_PENDING_BROADCAST = 1; 916 static final int MCS_BOUND = 3; 917 static final int END_COPY = 4; 918 static final int INIT_COPY = 5; 919 static final int MCS_UNBIND = 6; 920 static final int START_CLEANING_PACKAGE = 7; 921 static final int FIND_INSTALL_LOC = 8; 922 static final int POST_INSTALL = 9; 923 static final int MCS_RECONNECT = 10; 924 static final int MCS_GIVE_UP = 11; 925 static final int UPDATED_MEDIA_STATUS = 12; 926 static final int WRITE_SETTINGS = 13; 927 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 928 static final int PACKAGE_VERIFIED = 15; 929 static final int CHECK_PENDING_VERIFICATION = 16; 930 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 931 static final int INTENT_FILTER_VERIFIED = 18; 932 933 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 934 935 // Delay time in millisecs 936 static final int BROADCAST_DELAY = 10 * 1000; 937 938 static UserManagerService sUserManager; 939 940 // Stores a list of users whose package restrictions file needs to be updated 941 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 942 943 final private DefaultContainerConnection mDefContainerConn = 944 new DefaultContainerConnection(); 945 class DefaultContainerConnection implements ServiceConnection { 946 public void onServiceConnected(ComponentName name, IBinder service) { 947 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 948 IMediaContainerService imcs = 949 IMediaContainerService.Stub.asInterface(service); 950 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 951 } 952 953 public void onServiceDisconnected(ComponentName name) { 954 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 955 } 956 } 957 958 // Recordkeeping of restore-after-install operations that are currently in flight 959 // between the Package Manager and the Backup Manager 960 static class PostInstallData { 961 public InstallArgs args; 962 public PackageInstalledInfo res; 963 964 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 965 args = _a; 966 res = _r; 967 } 968 } 969 970 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 971 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 972 973 // XML tags for backup/restore of various bits of state 974 private static final String TAG_PREFERRED_BACKUP = "pa"; 975 private static final String TAG_DEFAULT_APPS = "da"; 976 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 977 978 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 979 private static final String TAG_ALL_GRANTS = "rt-grants"; 980 private static final String TAG_GRANT = "grant"; 981 private static final String ATTR_PACKAGE_NAME = "pkg"; 982 983 private static final String TAG_PERMISSION = "perm"; 984 private static final String ATTR_PERMISSION_NAME = "name"; 985 private static final String ATTR_IS_GRANTED = "g"; 986 private static final String ATTR_USER_SET = "set"; 987 private static final String ATTR_USER_FIXED = "fixed"; 988 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 989 990 // System/policy permission grants are not backed up 991 private static final int SYSTEM_RUNTIME_GRANT_MASK = 992 FLAG_PERMISSION_POLICY_FIXED 993 | FLAG_PERMISSION_SYSTEM_FIXED 994 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 995 996 // And we back up these user-adjusted states 997 private static final int USER_RUNTIME_GRANT_MASK = 998 FLAG_PERMISSION_USER_SET 999 | FLAG_PERMISSION_USER_FIXED 1000 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1001 1002 final @Nullable String mRequiredVerifierPackage; 1003 final @Nullable String mRequiredInstallerPackage; 1004 1005 private final PackageUsage mPackageUsage = new PackageUsage(); 1006 1007 private class PackageUsage { 1008 private static final int WRITE_INTERVAL 1009 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 1010 1011 private final Object mFileLock = new Object(); 1012 private final AtomicLong mLastWritten = new AtomicLong(0); 1013 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 1014 1015 private boolean mIsHistoricalPackageUsageAvailable = true; 1016 1017 boolean isHistoricalPackageUsageAvailable() { 1018 return mIsHistoricalPackageUsageAvailable; 1019 } 1020 1021 void write(boolean force) { 1022 if (force) { 1023 writeInternal(); 1024 return; 1025 } 1026 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 1027 && !DEBUG_DEXOPT) { 1028 return; 1029 } 1030 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 1031 new Thread("PackageUsage_DiskWriter") { 1032 @Override 1033 public void run() { 1034 try { 1035 writeInternal(); 1036 } finally { 1037 mBackgroundWriteRunning.set(false); 1038 } 1039 } 1040 }.start(); 1041 } 1042 } 1043 1044 private void writeInternal() { 1045 synchronized (mPackages) { 1046 synchronized (mFileLock) { 1047 AtomicFile file = getFile(); 1048 FileOutputStream f = null; 1049 try { 1050 f = file.startWrite(); 1051 BufferedOutputStream out = new BufferedOutputStream(f); 1052 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1053 StringBuilder sb = new StringBuilder(); 1054 for (PackageParser.Package pkg : mPackages.values()) { 1055 if (pkg.mLastPackageUsageTimeInMills == 0) { 1056 continue; 1057 } 1058 sb.setLength(0); 1059 sb.append(pkg.packageName); 1060 sb.append(' '); 1061 sb.append((long)pkg.mLastPackageUsageTimeInMills); 1062 sb.append('\n'); 1063 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1064 } 1065 out.flush(); 1066 file.finishWrite(f); 1067 } catch (IOException e) { 1068 if (f != null) { 1069 file.failWrite(f); 1070 } 1071 Log.e(TAG, "Failed to write package usage times", e); 1072 } 1073 } 1074 } 1075 mLastWritten.set(SystemClock.elapsedRealtime()); 1076 } 1077 1078 void readLP() { 1079 synchronized (mFileLock) { 1080 AtomicFile file = getFile(); 1081 BufferedInputStream in = null; 1082 try { 1083 in = new BufferedInputStream(file.openRead()); 1084 StringBuffer sb = new StringBuffer(); 1085 while (true) { 1086 String packageName = readToken(in, sb, ' '); 1087 if (packageName == null) { 1088 break; 1089 } 1090 String timeInMillisString = readToken(in, sb, '\n'); 1091 if (timeInMillisString == null) { 1092 throw new IOException("Failed to find last usage time for package " 1093 + packageName); 1094 } 1095 PackageParser.Package pkg = mPackages.get(packageName); 1096 if (pkg == null) { 1097 continue; 1098 } 1099 long timeInMillis; 1100 try { 1101 timeInMillis = Long.parseLong(timeInMillisString); 1102 } catch (NumberFormatException e) { 1103 throw new IOException("Failed to parse " + timeInMillisString 1104 + " as a long.", e); 1105 } 1106 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1107 } 1108 } catch (FileNotFoundException expected) { 1109 mIsHistoricalPackageUsageAvailable = false; 1110 } catch (IOException e) { 1111 Log.w(TAG, "Failed to read package usage times", e); 1112 } finally { 1113 IoUtils.closeQuietly(in); 1114 } 1115 } 1116 mLastWritten.set(SystemClock.elapsedRealtime()); 1117 } 1118 1119 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1120 throws IOException { 1121 sb.setLength(0); 1122 while (true) { 1123 int ch = in.read(); 1124 if (ch == -1) { 1125 if (sb.length() == 0) { 1126 return null; 1127 } 1128 throw new IOException("Unexpected EOF"); 1129 } 1130 if (ch == endOfToken) { 1131 return sb.toString(); 1132 } 1133 sb.append((char)ch); 1134 } 1135 } 1136 1137 private AtomicFile getFile() { 1138 File dataDir = Environment.getDataDirectory(); 1139 File systemDir = new File(dataDir, "system"); 1140 File fname = new File(systemDir, "package-usage.list"); 1141 return new AtomicFile(fname); 1142 } 1143 } 1144 1145 class PackageHandler extends Handler { 1146 private boolean mBound = false; 1147 final ArrayList<HandlerParams> mPendingInstalls = 1148 new ArrayList<HandlerParams>(); 1149 1150 private boolean connectToService() { 1151 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1152 " DefaultContainerService"); 1153 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1154 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1155 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1156 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1157 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1158 mBound = true; 1159 return true; 1160 } 1161 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1162 return false; 1163 } 1164 1165 private void disconnectService() { 1166 mContainerService = null; 1167 mBound = false; 1168 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1169 mContext.unbindService(mDefContainerConn); 1170 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1171 } 1172 1173 PackageHandler(Looper looper) { 1174 super(looper); 1175 } 1176 1177 public void handleMessage(Message msg) { 1178 try { 1179 doHandleMessage(msg); 1180 } finally { 1181 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1182 } 1183 } 1184 1185 void doHandleMessage(Message msg) { 1186 switch (msg.what) { 1187 case INIT_COPY: { 1188 HandlerParams params = (HandlerParams) msg.obj; 1189 int idx = mPendingInstalls.size(); 1190 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1191 // If a bind was already initiated we dont really 1192 // need to do anything. The pending install 1193 // will be processed later on. 1194 if (!mBound) { 1195 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1196 System.identityHashCode(mHandler)); 1197 // If this is the only one pending we might 1198 // have to bind to the service again. 1199 if (!connectToService()) { 1200 Slog.e(TAG, "Failed to bind to media container service"); 1201 params.serviceError(); 1202 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1203 System.identityHashCode(mHandler)); 1204 if (params.traceMethod != null) { 1205 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1206 params.traceCookie); 1207 } 1208 return; 1209 } else { 1210 // Once we bind to the service, the first 1211 // pending request will be processed. 1212 mPendingInstalls.add(idx, params); 1213 } 1214 } else { 1215 mPendingInstalls.add(idx, params); 1216 // Already bound to the service. Just make 1217 // sure we trigger off processing the first request. 1218 if (idx == 0) { 1219 mHandler.sendEmptyMessage(MCS_BOUND); 1220 } 1221 } 1222 break; 1223 } 1224 case MCS_BOUND: { 1225 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1226 if (msg.obj != null) { 1227 mContainerService = (IMediaContainerService) msg.obj; 1228 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1229 System.identityHashCode(mHandler)); 1230 } 1231 if (mContainerService == null) { 1232 if (!mBound) { 1233 // Something seriously wrong since we are not bound and we are not 1234 // waiting for connection. Bail out. 1235 Slog.e(TAG, "Cannot bind to media container service"); 1236 for (HandlerParams params : mPendingInstalls) { 1237 // Indicate service bind error 1238 params.serviceError(); 1239 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1240 System.identityHashCode(params)); 1241 if (params.traceMethod != null) { 1242 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1243 params.traceMethod, params.traceCookie); 1244 } 1245 return; 1246 } 1247 mPendingInstalls.clear(); 1248 } else { 1249 Slog.w(TAG, "Waiting to connect to media container service"); 1250 } 1251 } else if (mPendingInstalls.size() > 0) { 1252 HandlerParams params = mPendingInstalls.get(0); 1253 if (params != null) { 1254 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1255 System.identityHashCode(params)); 1256 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1257 if (params.startCopy()) { 1258 // We are done... look for more work or to 1259 // go idle. 1260 if (DEBUG_SD_INSTALL) Log.i(TAG, 1261 "Checking for more work or unbind..."); 1262 // Delete pending install 1263 if (mPendingInstalls.size() > 0) { 1264 mPendingInstalls.remove(0); 1265 } 1266 if (mPendingInstalls.size() == 0) { 1267 if (mBound) { 1268 if (DEBUG_SD_INSTALL) Log.i(TAG, 1269 "Posting delayed MCS_UNBIND"); 1270 removeMessages(MCS_UNBIND); 1271 Message ubmsg = obtainMessage(MCS_UNBIND); 1272 // Unbind after a little delay, to avoid 1273 // continual thrashing. 1274 sendMessageDelayed(ubmsg, 10000); 1275 } 1276 } else { 1277 // There are more pending requests in queue. 1278 // Just post MCS_BOUND message to trigger processing 1279 // of next pending install. 1280 if (DEBUG_SD_INSTALL) Log.i(TAG, 1281 "Posting MCS_BOUND for next work"); 1282 mHandler.sendEmptyMessage(MCS_BOUND); 1283 } 1284 } 1285 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1286 } 1287 } else { 1288 // Should never happen ideally. 1289 Slog.w(TAG, "Empty queue"); 1290 } 1291 break; 1292 } 1293 case MCS_RECONNECT: { 1294 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1295 if (mPendingInstalls.size() > 0) { 1296 if (mBound) { 1297 disconnectService(); 1298 } 1299 if (!connectToService()) { 1300 Slog.e(TAG, "Failed to bind to media container service"); 1301 for (HandlerParams params : mPendingInstalls) { 1302 // Indicate service bind error 1303 params.serviceError(); 1304 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1305 System.identityHashCode(params)); 1306 } 1307 mPendingInstalls.clear(); 1308 } 1309 } 1310 break; 1311 } 1312 case MCS_UNBIND: { 1313 // If there is no actual work left, then time to unbind. 1314 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1315 1316 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1317 if (mBound) { 1318 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1319 1320 disconnectService(); 1321 } 1322 } else if (mPendingInstalls.size() > 0) { 1323 // There are more pending requests in queue. 1324 // Just post MCS_BOUND message to trigger processing 1325 // of next pending install. 1326 mHandler.sendEmptyMessage(MCS_BOUND); 1327 } 1328 1329 break; 1330 } 1331 case MCS_GIVE_UP: { 1332 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1333 HandlerParams params = mPendingInstalls.remove(0); 1334 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1335 System.identityHashCode(params)); 1336 break; 1337 } 1338 case SEND_PENDING_BROADCAST: { 1339 String packages[]; 1340 ArrayList<String> components[]; 1341 int size = 0; 1342 int uids[]; 1343 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1344 synchronized (mPackages) { 1345 if (mPendingBroadcasts == null) { 1346 return; 1347 } 1348 size = mPendingBroadcasts.size(); 1349 if (size <= 0) { 1350 // Nothing to be done. Just return 1351 return; 1352 } 1353 packages = new String[size]; 1354 components = new ArrayList[size]; 1355 uids = new int[size]; 1356 int i = 0; // filling out the above arrays 1357 1358 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1359 int packageUserId = mPendingBroadcasts.userIdAt(n); 1360 Iterator<Map.Entry<String, ArrayList<String>>> it 1361 = mPendingBroadcasts.packagesForUserId(packageUserId) 1362 .entrySet().iterator(); 1363 while (it.hasNext() && i < size) { 1364 Map.Entry<String, ArrayList<String>> ent = it.next(); 1365 packages[i] = ent.getKey(); 1366 components[i] = ent.getValue(); 1367 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1368 uids[i] = (ps != null) 1369 ? UserHandle.getUid(packageUserId, ps.appId) 1370 : -1; 1371 i++; 1372 } 1373 } 1374 size = i; 1375 mPendingBroadcasts.clear(); 1376 } 1377 // Send broadcasts 1378 for (int i = 0; i < size; i++) { 1379 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1380 } 1381 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1382 break; 1383 } 1384 case START_CLEANING_PACKAGE: { 1385 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1386 final String packageName = (String)msg.obj; 1387 final int userId = msg.arg1; 1388 final boolean andCode = msg.arg2 != 0; 1389 synchronized (mPackages) { 1390 if (userId == UserHandle.USER_ALL) { 1391 int[] users = sUserManager.getUserIds(); 1392 for (int user : users) { 1393 mSettings.addPackageToCleanLPw( 1394 new PackageCleanItem(user, packageName, andCode)); 1395 } 1396 } else { 1397 mSettings.addPackageToCleanLPw( 1398 new PackageCleanItem(userId, packageName, andCode)); 1399 } 1400 } 1401 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1402 startCleaningPackages(); 1403 } break; 1404 case POST_INSTALL: { 1405 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1406 1407 PostInstallData data = mRunningInstalls.get(msg.arg1); 1408 mRunningInstalls.delete(msg.arg1); 1409 boolean deleteOld = false; 1410 1411 if (data != null) { 1412 InstallArgs args = data.args; 1413 PackageInstalledInfo res = data.res; 1414 1415 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1416 final String packageName = res.pkg.applicationInfo.packageName; 1417 res.removedInfo.sendBroadcast(false, true, false); 1418 Bundle extras = new Bundle(1); 1419 extras.putInt(Intent.EXTRA_UID, res.uid); 1420 1421 // Now that we successfully installed the package, grant runtime 1422 // permissions if requested before broadcasting the install. 1423 if ((args.installFlags 1424 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 1425 && res.pkg.applicationInfo.targetSdkVersion 1426 >= Build.VERSION_CODES.M) { 1427 grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(), 1428 args.installGrantPermissions); 1429 } 1430 1431 synchronized (mPackages) { 1432 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1433 } 1434 1435 // Determine the set of users who are adding this 1436 // package for the first time vs. those who are seeing 1437 // an update. 1438 int[] firstUsers; 1439 int[] updateUsers = new int[0]; 1440 if (res.origUsers == null || res.origUsers.length == 0) { 1441 firstUsers = res.newUsers; 1442 } else { 1443 firstUsers = new int[0]; 1444 for (int i=0; i<res.newUsers.length; i++) { 1445 int user = res.newUsers[i]; 1446 boolean isNew = true; 1447 for (int j=0; j<res.origUsers.length; j++) { 1448 if (res.origUsers[j] == user) { 1449 isNew = false; 1450 break; 1451 } 1452 } 1453 if (isNew) { 1454 int[] newFirst = new int[firstUsers.length+1]; 1455 System.arraycopy(firstUsers, 0, newFirst, 0, 1456 firstUsers.length); 1457 newFirst[firstUsers.length] = user; 1458 firstUsers = newFirst; 1459 } else { 1460 int[] newUpdate = new int[updateUsers.length+1]; 1461 System.arraycopy(updateUsers, 0, newUpdate, 0, 1462 updateUsers.length); 1463 newUpdate[updateUsers.length] = user; 1464 updateUsers = newUpdate; 1465 } 1466 } 1467 } 1468 // don't broadcast for ephemeral installs/updates 1469 final boolean isEphemeral = isEphemeral(res.pkg); 1470 if (!isEphemeral) { 1471 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1472 extras, 0 /*flags*/, null /*targetPackage*/, 1473 null /*finishedReceiver*/, firstUsers); 1474 } 1475 final boolean update = res.removedInfo.removedPackage != null; 1476 if (update) { 1477 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1478 } 1479 if (!isEphemeral) { 1480 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1481 extras, 0 /*flags*/, null /*targetPackage*/, 1482 null /*finishedReceiver*/, updateUsers); 1483 } 1484 if (update) { 1485 if (!isEphemeral) { 1486 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1487 packageName, extras, 0 /*flags*/, 1488 null /*targetPackage*/, null /*finishedReceiver*/, 1489 updateUsers); 1490 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1491 null /*package*/, null /*extras*/, 0 /*flags*/, 1492 packageName /*targetPackage*/, 1493 null /*finishedReceiver*/, updateUsers); 1494 } 1495 1496 // treat asec-hosted packages like removable media on upgrade 1497 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1498 if (DEBUG_INSTALL) { 1499 Slog.i(TAG, "upgrading pkg " + res.pkg 1500 + " is ASEC-hosted -> AVAILABLE"); 1501 } 1502 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1503 ArrayList<String> pkgList = new ArrayList<String>(1); 1504 pkgList.add(packageName); 1505 sendResourcesChangedBroadcast(true, true, 1506 pkgList,uidArray, null); 1507 } 1508 } 1509 if (res.removedInfo.args != null) { 1510 // Remove the replaced package's older resources safely now 1511 deleteOld = true; 1512 } 1513 1514 1515 // Work that needs to happen on first install within each user 1516 if (firstUsers.length > 0) { 1517 for (int userId : firstUsers) { 1518 synchronized (mPackages) { 1519 // If this app is a browser and it's newly-installed for 1520 // some users, clear any default-browser state in those 1521 // users. The app's nature doesn't depend on the user, 1522 // so we can just check its browser nature in any user 1523 // and generalize. 1524 if (packageIsBrowser(packageName, firstUsers[0])) { 1525 mSettings.setDefaultBrowserPackageNameLPw( 1526 null, userId); 1527 } 1528 1529 // We may also need to apply pending (restored) runtime 1530 // permission grants within these users. 1531 mSettings.applyPendingPermissionGrantsLPw( 1532 packageName, userId); 1533 } 1534 } 1535 } 1536 // Log current value of "unknown sources" setting 1537 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1538 getUnknownSourcesSettings()); 1539 } 1540 // Force a gc to clear up things 1541 Runtime.getRuntime().gc(); 1542 // We delete after a gc for applications on sdcard. 1543 if (deleteOld) { 1544 synchronized (mInstallLock) { 1545 res.removedInfo.args.doPostDeleteLI(true); 1546 } 1547 } 1548 if (args.observer != null) { 1549 try { 1550 Bundle extras = extrasForInstallResult(res); 1551 args.observer.onPackageInstalled(res.name, res.returnCode, 1552 res.returnMsg, extras); 1553 } catch (RemoteException e) { 1554 Slog.i(TAG, "Observer no longer exists."); 1555 } 1556 } 1557 if (args.traceMethod != null) { 1558 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1559 args.traceCookie); 1560 } 1561 return; 1562 } else { 1563 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1564 } 1565 1566 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1567 } break; 1568 case UPDATED_MEDIA_STATUS: { 1569 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1570 boolean reportStatus = msg.arg1 == 1; 1571 boolean doGc = msg.arg2 == 1; 1572 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1573 if (doGc) { 1574 // Force a gc to clear up stale containers. 1575 Runtime.getRuntime().gc(); 1576 } 1577 if (msg.obj != null) { 1578 @SuppressWarnings("unchecked") 1579 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1580 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1581 // Unload containers 1582 unloadAllContainers(args); 1583 } 1584 if (reportStatus) { 1585 try { 1586 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1587 PackageHelper.getMountService().finishMediaUpdate(); 1588 } catch (RemoteException e) { 1589 Log.e(TAG, "MountService not running?"); 1590 } 1591 } 1592 } break; 1593 case WRITE_SETTINGS: { 1594 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1595 synchronized (mPackages) { 1596 removeMessages(WRITE_SETTINGS); 1597 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1598 mSettings.writeLPr(); 1599 mDirtyUsers.clear(); 1600 } 1601 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1602 } break; 1603 case WRITE_PACKAGE_RESTRICTIONS: { 1604 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1605 synchronized (mPackages) { 1606 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1607 for (int userId : mDirtyUsers) { 1608 mSettings.writePackageRestrictionsLPr(userId); 1609 } 1610 mDirtyUsers.clear(); 1611 } 1612 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1613 } break; 1614 case CHECK_PENDING_VERIFICATION: { 1615 final int verificationId = msg.arg1; 1616 final PackageVerificationState state = mPendingVerification.get(verificationId); 1617 1618 if ((state != null) && !state.timeoutExtended()) { 1619 final InstallArgs args = state.getInstallArgs(); 1620 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1621 1622 Slog.i(TAG, "Verification timed out for " + originUri); 1623 mPendingVerification.remove(verificationId); 1624 1625 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1626 1627 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1628 Slog.i(TAG, "Continuing with installation of " + originUri); 1629 state.setVerifierResponse(Binder.getCallingUid(), 1630 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1631 broadcastPackageVerified(verificationId, originUri, 1632 PackageManager.VERIFICATION_ALLOW, 1633 state.getInstallArgs().getUser()); 1634 try { 1635 ret = args.copyApk(mContainerService, true); 1636 } catch (RemoteException e) { 1637 Slog.e(TAG, "Could not contact the ContainerService"); 1638 } 1639 } else { 1640 broadcastPackageVerified(verificationId, originUri, 1641 PackageManager.VERIFICATION_REJECT, 1642 state.getInstallArgs().getUser()); 1643 } 1644 1645 Trace.asyncTraceEnd( 1646 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1647 1648 processPendingInstall(args, ret); 1649 mHandler.sendEmptyMessage(MCS_UNBIND); 1650 } 1651 break; 1652 } 1653 case PACKAGE_VERIFIED: { 1654 final int verificationId = msg.arg1; 1655 1656 final PackageVerificationState state = mPendingVerification.get(verificationId); 1657 if (state == null) { 1658 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1659 break; 1660 } 1661 1662 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1663 1664 state.setVerifierResponse(response.callerUid, response.code); 1665 1666 if (state.isVerificationComplete()) { 1667 mPendingVerification.remove(verificationId); 1668 1669 final InstallArgs args = state.getInstallArgs(); 1670 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1671 1672 int ret; 1673 if (state.isInstallAllowed()) { 1674 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1675 broadcastPackageVerified(verificationId, originUri, 1676 response.code, state.getInstallArgs().getUser()); 1677 try { 1678 ret = args.copyApk(mContainerService, true); 1679 } catch (RemoteException e) { 1680 Slog.e(TAG, "Could not contact the ContainerService"); 1681 } 1682 } else { 1683 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1684 } 1685 1686 Trace.asyncTraceEnd( 1687 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1688 1689 processPendingInstall(args, ret); 1690 mHandler.sendEmptyMessage(MCS_UNBIND); 1691 } 1692 1693 break; 1694 } 1695 case START_INTENT_FILTER_VERIFICATIONS: { 1696 IFVerificationParams params = (IFVerificationParams) msg.obj; 1697 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1698 params.replacing, params.pkg); 1699 break; 1700 } 1701 case INTENT_FILTER_VERIFIED: { 1702 final int verificationId = msg.arg1; 1703 1704 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1705 verificationId); 1706 if (state == null) { 1707 Slog.w(TAG, "Invalid IntentFilter verification token " 1708 + verificationId + " received"); 1709 break; 1710 } 1711 1712 final int userId = state.getUserId(); 1713 1714 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1715 "Processing IntentFilter verification with token:" 1716 + verificationId + " and userId:" + userId); 1717 1718 final IntentFilterVerificationResponse response = 1719 (IntentFilterVerificationResponse) msg.obj; 1720 1721 state.setVerifierResponse(response.callerUid, response.code); 1722 1723 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1724 "IntentFilter verification with token:" + verificationId 1725 + " and userId:" + userId 1726 + " is settings verifier response with response code:" 1727 + response.code); 1728 1729 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1730 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1731 + response.getFailedDomainsString()); 1732 } 1733 1734 if (state.isVerificationComplete()) { 1735 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1736 } else { 1737 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1738 "IntentFilter verification with token:" + verificationId 1739 + " was not said to be complete"); 1740 } 1741 1742 break; 1743 } 1744 } 1745 } 1746 } 1747 1748 private StorageEventListener mStorageListener = new StorageEventListener() { 1749 @Override 1750 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1751 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1752 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1753 final String volumeUuid = vol.getFsUuid(); 1754 1755 // Clean up any users or apps that were removed or recreated 1756 // while this volume was missing 1757 reconcileUsers(volumeUuid); 1758 reconcileApps(volumeUuid); 1759 1760 // Clean up any install sessions that expired or were 1761 // cancelled while this volume was missing 1762 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1763 1764 loadPrivatePackages(vol); 1765 1766 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1767 unloadPrivatePackages(vol); 1768 } 1769 } 1770 1771 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1772 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1773 updateExternalMediaStatus(true, false); 1774 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1775 updateExternalMediaStatus(false, false); 1776 } 1777 } 1778 } 1779 1780 @Override 1781 public void onVolumeForgotten(String fsUuid) { 1782 if (TextUtils.isEmpty(fsUuid)) { 1783 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1784 return; 1785 } 1786 1787 // Remove any apps installed on the forgotten volume 1788 synchronized (mPackages) { 1789 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1790 for (PackageSetting ps : packages) { 1791 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1792 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1793 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1794 } 1795 1796 mSettings.onVolumeForgotten(fsUuid); 1797 mSettings.writeLPr(); 1798 } 1799 } 1800 }; 1801 1802 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId, 1803 String[] grantedPermissions) { 1804 if (userId >= UserHandle.USER_SYSTEM) { 1805 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1806 } else if (userId == UserHandle.USER_ALL) { 1807 final int[] userIds; 1808 synchronized (mPackages) { 1809 userIds = UserManagerService.getInstance().getUserIds(); 1810 } 1811 for (int someUserId : userIds) { 1812 grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions); 1813 } 1814 } 1815 1816 // We could have touched GID membership, so flush out packages.list 1817 synchronized (mPackages) { 1818 mSettings.writePackageListLPr(); 1819 } 1820 } 1821 1822 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1823 String[] grantedPermissions) { 1824 SettingBase sb = (SettingBase) pkg.mExtras; 1825 if (sb == null) { 1826 return; 1827 } 1828 1829 PermissionsState permissionsState = sb.getPermissionsState(); 1830 1831 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 1832 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 1833 1834 synchronized (mPackages) { 1835 for (String permission : pkg.requestedPermissions) { 1836 BasePermission bp = mSettings.mPermissions.get(permission); 1837 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 1838 && (grantedPermissions == null 1839 || ArrayUtils.contains(grantedPermissions, permission))) { 1840 final int flags = permissionsState.getPermissionFlags(permission, userId); 1841 // Installer cannot change immutable permissions. 1842 if ((flags & immutableFlags) == 0) { 1843 grantRuntimePermission(pkg.packageName, permission, userId); 1844 } 1845 } 1846 } 1847 } 1848 } 1849 1850 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1851 Bundle extras = null; 1852 switch (res.returnCode) { 1853 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1854 extras = new Bundle(); 1855 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1856 res.origPermission); 1857 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1858 res.origPackage); 1859 break; 1860 } 1861 case PackageManager.INSTALL_SUCCEEDED: { 1862 extras = new Bundle(); 1863 extras.putBoolean(Intent.EXTRA_REPLACING, 1864 res.removedInfo != null && res.removedInfo.removedPackage != null); 1865 break; 1866 } 1867 } 1868 return extras; 1869 } 1870 1871 void scheduleWriteSettingsLocked() { 1872 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1873 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1874 } 1875 } 1876 1877 void scheduleWritePackageRestrictionsLocked(int userId) { 1878 if (!sUserManager.exists(userId)) return; 1879 mDirtyUsers.add(userId); 1880 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1881 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1882 } 1883 } 1884 1885 public static PackageManagerService main(Context context, Installer installer, 1886 boolean factoryTest, boolean onlyCore) { 1887 PackageManagerService m = new PackageManagerService(context, installer, 1888 factoryTest, onlyCore); 1889 m.enableSystemUserPackages(); 1890 ServiceManager.addService("package", m); 1891 return m; 1892 } 1893 1894 private void enableSystemUserPackages() { 1895 if (!UserManager.isSplitSystemUser()) { 1896 return; 1897 } 1898 // For system user, enable apps based on the following conditions: 1899 // - app is whitelisted or belong to one of these groups: 1900 // -- system app which has no launcher icons 1901 // -- system app which has INTERACT_ACROSS_USERS permission 1902 // -- system IME app 1903 // - app is not in the blacklist 1904 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 1905 Set<String> enableApps = new ArraySet<>(); 1906 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 1907 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 1908 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 1909 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 1910 enableApps.addAll(wlApps); 1911 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 1912 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 1913 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 1914 enableApps.removeAll(blApps); 1915 Log.i(TAG, "Applications installed for system user: " + enableApps); 1916 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 1917 UserHandle.SYSTEM); 1918 final int allAppsSize = allAps.size(); 1919 synchronized (mPackages) { 1920 for (int i = 0; i < allAppsSize; i++) { 1921 String pName = allAps.get(i); 1922 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 1923 // Should not happen, but we shouldn't be failing if it does 1924 if (pkgSetting == null) { 1925 continue; 1926 } 1927 boolean install = enableApps.contains(pName); 1928 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 1929 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 1930 + " for system user"); 1931 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 1932 } 1933 } 1934 } 1935 } 1936 1937 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1938 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1939 Context.DISPLAY_SERVICE); 1940 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1941 } 1942 1943 public PackageManagerService(Context context, Installer installer, 1944 boolean factoryTest, boolean onlyCore) { 1945 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1946 SystemClock.uptimeMillis()); 1947 1948 if (mSdkVersion <= 0) { 1949 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1950 } 1951 1952 mContext = context; 1953 mFactoryTest = factoryTest; 1954 mOnlyCore = onlyCore; 1955 mMetrics = new DisplayMetrics(); 1956 mSettings = new Settings(mPackages); 1957 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1958 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1959 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1960 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1961 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1962 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1963 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1964 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1965 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1966 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1967 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1968 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1969 1970 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1971 if (separateProcesses != null && separateProcesses.length() > 0) { 1972 if ("*".equals(separateProcesses)) { 1973 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1974 mSeparateProcesses = null; 1975 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1976 } else { 1977 mDefParseFlags = 0; 1978 mSeparateProcesses = separateProcesses.split(","); 1979 Slog.w(TAG, "Running with debug.separate_processes: " 1980 + separateProcesses); 1981 } 1982 } else { 1983 mDefParseFlags = 0; 1984 mSeparateProcesses = null; 1985 } 1986 1987 mInstaller = installer; 1988 mPackageDexOptimizer = new PackageDexOptimizer(this); 1989 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1990 1991 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 1992 FgThread.get().getLooper()); 1993 1994 getDefaultDisplayMetrics(context, mMetrics); 1995 1996 SystemConfig systemConfig = SystemConfig.getInstance(); 1997 mGlobalGids = systemConfig.getGlobalGids(); 1998 mSystemPermissions = systemConfig.getSystemPermissions(); 1999 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2000 2001 synchronized (mInstallLock) { 2002 // writer 2003 synchronized (mPackages) { 2004 mHandlerThread = new ServiceThread(TAG, 2005 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2006 mHandlerThread.start(); 2007 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2008 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2009 2010 File dataDir = Environment.getDataDirectory(); 2011 mAppInstallDir = new File(dataDir, "app"); 2012 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2013 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2014 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2015 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2016 2017 sUserManager = new UserManagerService(context, this, mPackages); 2018 2019 // Propagate permission configuration in to package manager. 2020 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2021 = systemConfig.getPermissions(); 2022 for (int i=0; i<permConfig.size(); i++) { 2023 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2024 BasePermission bp = mSettings.mPermissions.get(perm.name); 2025 if (bp == null) { 2026 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2027 mSettings.mPermissions.put(perm.name, bp); 2028 } 2029 if (perm.gids != null) { 2030 bp.setGids(perm.gids, perm.perUser); 2031 } 2032 } 2033 2034 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2035 for (int i=0; i<libConfig.size(); i++) { 2036 mSharedLibraries.put(libConfig.keyAt(i), 2037 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2038 } 2039 2040 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2041 2042 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 2043 2044 String customResolverActivity = Resources.getSystem().getString( 2045 R.string.config_customResolverActivity); 2046 if (TextUtils.isEmpty(customResolverActivity)) { 2047 customResolverActivity = null; 2048 } else { 2049 mCustomResolverComponentName = ComponentName.unflattenFromString( 2050 customResolverActivity); 2051 } 2052 2053 long startTime = SystemClock.uptimeMillis(); 2054 2055 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2056 startTime); 2057 2058 // Set flag to monitor and not change apk file paths when 2059 // scanning install directories. 2060 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2061 2062 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2063 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2064 2065 if (bootClassPath == null) { 2066 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2067 } 2068 2069 if (systemServerClassPath == null) { 2070 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2071 } 2072 2073 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2074 final String[] dexCodeInstructionSets = 2075 getDexCodeInstructionSets( 2076 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2077 2078 /** 2079 * Ensure all external libraries have had dexopt run on them. 2080 */ 2081 if (mSharedLibraries.size() > 0) { 2082 // NOTE: For now, we're compiling these system "shared libraries" 2083 // (and framework jars) into all available architectures. It's possible 2084 // to compile them only when we come across an app that uses them (there's 2085 // already logic for that in scanPackageLI) but that adds some complexity. 2086 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2087 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2088 final String lib = libEntry.path; 2089 if (lib == null) { 2090 continue; 2091 } 2092 2093 try { 2094 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 2095 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2096 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2097 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/); 2098 } 2099 } catch (FileNotFoundException e) { 2100 Slog.w(TAG, "Library not found: " + lib); 2101 } catch (IOException | InstallerException e) { 2102 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2103 + e.getMessage()); 2104 } 2105 } 2106 } 2107 } 2108 2109 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2110 2111 final VersionInfo ver = mSettings.getInternalVersion(); 2112 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2113 // when upgrading from pre-M, promote system app permissions from install to runtime 2114 mPromoteSystemApps = 2115 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2116 2117 // save off the names of pre-existing system packages prior to scanning; we don't 2118 // want to automatically grant runtime permissions for new system apps 2119 if (mPromoteSystemApps) { 2120 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2121 while (pkgSettingIter.hasNext()) { 2122 PackageSetting ps = pkgSettingIter.next(); 2123 if (isSystemApp(ps)) { 2124 mExistingSystemPackages.add(ps.name); 2125 } 2126 } 2127 } 2128 2129 // Collect vendor overlay packages. 2130 // (Do this before scanning any apps.) 2131 // For security and version matching reason, only consider 2132 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2133 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2134 scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2135 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2136 2137 // Find base frameworks (resource packages without code). 2138 scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2139 | PackageParser.PARSE_IS_SYSTEM_DIR 2140 | PackageParser.PARSE_IS_PRIVILEGED, 2141 scanFlags | SCAN_NO_DEX, 0); 2142 2143 // Collected privileged system packages. 2144 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2145 scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2146 | PackageParser.PARSE_IS_SYSTEM_DIR 2147 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2148 2149 // Collect ordinary system packages. 2150 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2151 scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2152 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2153 2154 // Collect all vendor packages. 2155 File vendorAppDir = new File("/vendor/app"); 2156 try { 2157 vendorAppDir = vendorAppDir.getCanonicalFile(); 2158 } catch (IOException e) { 2159 // failed to look up canonical path, continue with original one 2160 } 2161 scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2162 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2163 2164 // Collect all OEM packages. 2165 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2166 scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2167 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2168 2169 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 2170 try { 2171 mInstaller.moveFiles(); 2172 } catch (InstallerException e) { 2173 logCriticalInfo(Log.WARN, "Update commands failed: " + e); 2174 } 2175 2176 // Prune any system packages that no longer exist. 2177 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2178 if (!mOnlyCore) { 2179 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2180 while (psit.hasNext()) { 2181 PackageSetting ps = psit.next(); 2182 2183 /* 2184 * If this is not a system app, it can't be a 2185 * disable system app. 2186 */ 2187 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2188 continue; 2189 } 2190 2191 /* 2192 * If the package is scanned, it's not erased. 2193 */ 2194 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2195 if (scannedPkg != null) { 2196 /* 2197 * If the system app is both scanned and in the 2198 * disabled packages list, then it must have been 2199 * added via OTA. Remove it from the currently 2200 * scanned package so the previously user-installed 2201 * application can be scanned. 2202 */ 2203 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2204 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2205 + ps.name + "; removing system app. Last known codePath=" 2206 + ps.codePathString + ", installStatus=" + ps.installStatus 2207 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2208 + scannedPkg.mVersionCode); 2209 removePackageLI(ps, true); 2210 mExpectingBetter.put(ps.name, ps.codePath); 2211 } 2212 2213 continue; 2214 } 2215 2216 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2217 psit.remove(); 2218 logCriticalInfo(Log.WARN, "System package " + ps.name 2219 + " no longer exists; wiping its data"); 2220 removeDataDirsLI(null, ps.name); 2221 } else { 2222 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2223 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2224 possiblyDeletedUpdatedSystemApps.add(ps.name); 2225 } 2226 } 2227 } 2228 } 2229 2230 //look for any incomplete package installations 2231 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2232 //clean up list 2233 for(int i = 0; i < deletePkgsList.size(); i++) { 2234 //clean up here 2235 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2236 } 2237 //delete tmp files 2238 deleteTempPackageFiles(); 2239 2240 // Remove any shared userIDs that have no associated packages 2241 mSettings.pruneSharedUsersLPw(); 2242 2243 if (!mOnlyCore) { 2244 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2245 SystemClock.uptimeMillis()); 2246 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2247 2248 scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2249 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2250 2251 scanDirLI(mEphemeralInstallDir, PackageParser.PARSE_IS_EPHEMERAL, 2252 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2253 2254 /** 2255 * Remove disable package settings for any updated system 2256 * apps that were removed via an OTA. If they're not a 2257 * previously-updated app, remove them completely. 2258 * Otherwise, just revoke their system-level permissions. 2259 */ 2260 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2261 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2262 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2263 2264 String msg; 2265 if (deletedPkg == null) { 2266 msg = "Updated system package " + deletedAppName 2267 + " no longer exists; wiping its data"; 2268 removeDataDirsLI(null, deletedAppName); 2269 } else { 2270 msg = "Updated system app + " + deletedAppName 2271 + " no longer present; removing system privileges for " 2272 + deletedAppName; 2273 2274 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2275 2276 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2277 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2278 } 2279 logCriticalInfo(Log.WARN, msg); 2280 } 2281 2282 /** 2283 * Make sure all system apps that we expected to appear on 2284 * the userdata partition actually showed up. If they never 2285 * appeared, crawl back and revive the system version. 2286 */ 2287 for (int i = 0; i < mExpectingBetter.size(); i++) { 2288 final String packageName = mExpectingBetter.keyAt(i); 2289 if (!mPackages.containsKey(packageName)) { 2290 final File scanFile = mExpectingBetter.valueAt(i); 2291 2292 logCriticalInfo(Log.WARN, "Expected better " + packageName 2293 + " but never showed up; reverting to system"); 2294 2295 final int reparseFlags; 2296 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2297 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2298 | PackageParser.PARSE_IS_SYSTEM_DIR 2299 | PackageParser.PARSE_IS_PRIVILEGED; 2300 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2301 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2302 | PackageParser.PARSE_IS_SYSTEM_DIR; 2303 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2304 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2305 | PackageParser.PARSE_IS_SYSTEM_DIR; 2306 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2307 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2308 | PackageParser.PARSE_IS_SYSTEM_DIR; 2309 } else { 2310 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2311 continue; 2312 } 2313 2314 mSettings.enableSystemPackageLPw(packageName); 2315 2316 try { 2317 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2318 } catch (PackageManagerException e) { 2319 Slog.e(TAG, "Failed to parse original system package: " 2320 + e.getMessage()); 2321 } 2322 } 2323 } 2324 } 2325 mExpectingBetter.clear(); 2326 2327 // Now that we know all of the shared libraries, update all clients to have 2328 // the correct library paths. 2329 updateAllSharedLibrariesLPw(); 2330 2331 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2332 // NOTE: We ignore potential failures here during a system scan (like 2333 // the rest of the commands above) because there's precious little we 2334 // can do about it. A settings error is reported, though. 2335 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2336 false /* boot complete */); 2337 } 2338 2339 // Now that we know all the packages we are keeping, 2340 // read and update their last usage times. 2341 mPackageUsage.readLP(); 2342 2343 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2344 SystemClock.uptimeMillis()); 2345 Slog.i(TAG, "Time to scan packages: " 2346 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2347 + " seconds"); 2348 2349 // If the platform SDK has changed since the last time we booted, 2350 // we need to re-grant app permission to catch any new ones that 2351 // appear. This is really a hack, and means that apps can in some 2352 // cases get permissions that the user didn't initially explicitly 2353 // allow... it would be nice to have some better way to handle 2354 // this situation. 2355 int updateFlags = UPDATE_PERMISSIONS_ALL; 2356 if (ver.sdkVersion != mSdkVersion) { 2357 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2358 + mSdkVersion + "; regranting permissions for internal storage"); 2359 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2360 } 2361 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2362 ver.sdkVersion = mSdkVersion; 2363 2364 // If this is the first boot or an update from pre-M, and it is a normal 2365 // boot, then we need to initialize the default preferred apps across 2366 // all defined users. 2367 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2368 for (UserInfo user : sUserManager.getUsers(true)) { 2369 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2370 applyFactoryDefaultBrowserLPw(user.id); 2371 primeDomainVerificationsLPw(user.id); 2372 } 2373 } 2374 2375 // Prepare storage for system user really early during boot, 2376 // since core system apps like SettingsProvider and SystemUI 2377 // can't wait for user to start 2378 final int flags; 2379 if (StorageManager.isFileBasedEncryptionEnabled()) { 2380 flags = Installer.FLAG_DE_STORAGE; 2381 } else { 2382 flags = Installer.FLAG_DE_STORAGE | Installer.FLAG_CE_STORAGE; 2383 } 2384 reconcileAppsData(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, flags); 2385 2386 // If this is first boot after an OTA, and a normal boot, then 2387 // we need to clear code cache directories. 2388 if (mIsUpgrade && !onlyCore) { 2389 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2390 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2391 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2392 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2393 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2394 } 2395 } 2396 ver.fingerprint = Build.FINGERPRINT; 2397 } 2398 2399 checkDefaultBrowser(); 2400 2401 // clear only after permissions and other defaults have been updated 2402 mExistingSystemPackages.clear(); 2403 mPromoteSystemApps = false; 2404 2405 // All the changes are done during package scanning. 2406 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2407 2408 // can downgrade to reader 2409 mSettings.writeLPr(); 2410 2411 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2412 SystemClock.uptimeMillis()); 2413 2414 if (!mOnlyCore) { 2415 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2416 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2417 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2418 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2419 mIntentFilterVerifierComponent); 2420 } else { 2421 mRequiredVerifierPackage = null; 2422 mRequiredInstallerPackage = null; 2423 mIntentFilterVerifierComponent = null; 2424 mIntentFilterVerifier = null; 2425 } 2426 2427 mInstallerService = new PackageInstallerService(context, this); 2428 2429 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2430 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2431 // both the installer and resolver must be present to enable ephemeral 2432 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2433 if (DEBUG_EPHEMERAL) { 2434 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2435 + " installer:" + ephemeralInstallerComponent); 2436 } 2437 mEphemeralResolverComponent = ephemeralResolverComponent; 2438 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2439 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2440 mEphemeralResolverConnection = 2441 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2442 } else { 2443 if (DEBUG_EPHEMERAL) { 2444 final String missingComponent = 2445 (ephemeralResolverComponent == null) 2446 ? (ephemeralInstallerComponent == null) 2447 ? "resolver and installer" 2448 : "resolver" 2449 : "installer"; 2450 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2451 } 2452 mEphemeralResolverComponent = null; 2453 mEphemeralInstallerComponent = null; 2454 mEphemeralResolverConnection = null; 2455 } 2456 2457 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2458 } // synchronized (mPackages) 2459 } // synchronized (mInstallLock) 2460 2461 // Now after opening every single application zip, make sure they 2462 // are all flushed. Not really needed, but keeps things nice and 2463 // tidy. 2464 Runtime.getRuntime().gc(); 2465 2466 // The initial scanning above does many calls into installd while 2467 // holding the mPackages lock, but we're mostly interested in yelling 2468 // once we have a booted system. 2469 mInstaller.setWarnIfHeld(mPackages); 2470 2471 // Expose private service for system components to use. 2472 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2473 } 2474 2475 @Override 2476 public boolean isFirstBoot() { 2477 return !mRestoredSettings; 2478 } 2479 2480 @Override 2481 public boolean isOnlyCoreApps() { 2482 return mOnlyCore; 2483 } 2484 2485 @Override 2486 public boolean isUpgrade() { 2487 return mIsUpgrade; 2488 } 2489 2490 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2491 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2492 2493 final List<ResolveInfo> matches = queryIntentReceivers(intent, PACKAGE_MIME_TYPE, 2494 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2495 if (matches.size() == 1) { 2496 return matches.get(0).getComponentInfo().packageName; 2497 } else { 2498 Log.e(TAG, "There should probably be exactly one verifier; found " + matches); 2499 return null; 2500 } 2501 } 2502 2503 private @NonNull String getRequiredInstallerLPr() { 2504 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2505 intent.addCategory(Intent.CATEGORY_DEFAULT); 2506 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2507 2508 final List<ResolveInfo> matches = queryIntentActivities(intent, PACKAGE_MIME_TYPE, 2509 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2510 if (matches.size() == 1) { 2511 return matches.get(0).getComponentInfo().packageName; 2512 } else { 2513 throw new RuntimeException("There must be exactly one installer; found " + matches); 2514 } 2515 } 2516 2517 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2518 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2519 2520 final List<ResolveInfo> matches = queryIntentReceivers(intent, PACKAGE_MIME_TYPE, 2521 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2522 ResolveInfo best = null; 2523 final int N = matches.size(); 2524 for (int i = 0; i < N; i++) { 2525 final ResolveInfo cur = matches.get(i); 2526 final String packageName = cur.getComponentInfo().packageName; 2527 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2528 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2529 continue; 2530 } 2531 2532 if (best == null || cur.priority > best.priority) { 2533 best = cur; 2534 } 2535 } 2536 2537 if (best != null) { 2538 return best.getComponentInfo().getComponentName(); 2539 } else { 2540 throw new RuntimeException("There must be at least one intent filter verifier"); 2541 } 2542 } 2543 2544 private @Nullable ComponentName getEphemeralResolverLPr() { 2545 final String[] packageArray = 2546 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2547 if (packageArray.length == 0) { 2548 if (DEBUG_EPHEMERAL) { 2549 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2550 } 2551 return null; 2552 } 2553 2554 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2555 final List<ResolveInfo> resolvers = queryIntentServices(resolverIntent, null, 2556 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2557 2558 final int N = resolvers.size(); 2559 if (N == 0) { 2560 if (DEBUG_EPHEMERAL) { 2561 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2562 } 2563 return null; 2564 } 2565 2566 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2567 for (int i = 0; i < N; i++) { 2568 final ResolveInfo info = resolvers.get(i); 2569 2570 if (info.serviceInfo == null) { 2571 continue; 2572 } 2573 2574 final String packageName = info.serviceInfo.packageName; 2575 if (!possiblePackages.contains(packageName)) { 2576 if (DEBUG_EPHEMERAL) { 2577 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2578 + " pkg: " + packageName + ", info:" + info); 2579 } 2580 continue; 2581 } 2582 2583 if (DEBUG_EPHEMERAL) { 2584 Slog.v(TAG, "Ephemeral resolver found;" 2585 + " pkg: " + packageName + ", info:" + info); 2586 } 2587 return new ComponentName(packageName, info.serviceInfo.name); 2588 } 2589 if (DEBUG_EPHEMERAL) { 2590 Slog.v(TAG, "Ephemeral resolver NOT found"); 2591 } 2592 return null; 2593 } 2594 2595 private @Nullable ComponentName getEphemeralInstallerLPr() { 2596 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2597 intent.addCategory(Intent.CATEGORY_DEFAULT); 2598 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2599 2600 final List<ResolveInfo> matches = queryIntentActivities(intent, PACKAGE_MIME_TYPE, 2601 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2602 if (matches.size() == 0) { 2603 return null; 2604 } else if (matches.size() == 1) { 2605 return matches.get(0).getComponentInfo().getComponentName(); 2606 } else { 2607 throw new RuntimeException( 2608 "There must be at most one ephemeral installer; found " + matches); 2609 } 2610 } 2611 2612 private void primeDomainVerificationsLPw(int userId) { 2613 if (DEBUG_DOMAIN_VERIFICATION) { 2614 Slog.d(TAG, "Priming domain verifications in user " + userId); 2615 } 2616 2617 SystemConfig systemConfig = SystemConfig.getInstance(); 2618 ArraySet<String> packages = systemConfig.getLinkedApps(); 2619 ArraySet<String> domains = new ArraySet<String>(); 2620 2621 for (String packageName : packages) { 2622 PackageParser.Package pkg = mPackages.get(packageName); 2623 if (pkg != null) { 2624 if (!pkg.isSystemApp()) { 2625 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2626 continue; 2627 } 2628 2629 domains.clear(); 2630 for (PackageParser.Activity a : pkg.activities) { 2631 for (ActivityIntentInfo filter : a.intents) { 2632 if (hasValidDomains(filter)) { 2633 domains.addAll(filter.getHostsList()); 2634 } 2635 } 2636 } 2637 2638 if (domains.size() > 0) { 2639 if (DEBUG_DOMAIN_VERIFICATION) { 2640 Slog.v(TAG, " + " + packageName); 2641 } 2642 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2643 // state w.r.t. the formal app-linkage "no verification attempted" state; 2644 // and then 'always' in the per-user state actually used for intent resolution. 2645 final IntentFilterVerificationInfo ivi; 2646 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2647 new ArrayList<String>(domains)); 2648 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2649 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2650 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2651 } else { 2652 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2653 + "' does not handle web links"); 2654 } 2655 } else { 2656 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 2657 } 2658 } 2659 2660 scheduleWritePackageRestrictionsLocked(userId); 2661 scheduleWriteSettingsLocked(); 2662 } 2663 2664 private void applyFactoryDefaultBrowserLPw(int userId) { 2665 // The default browser app's package name is stored in a string resource, 2666 // with a product-specific overlay used for vendor customization. 2667 String browserPkg = mContext.getResources().getString( 2668 com.android.internal.R.string.default_browser); 2669 if (!TextUtils.isEmpty(browserPkg)) { 2670 // non-empty string => required to be a known package 2671 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2672 if (ps == null) { 2673 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2674 browserPkg = null; 2675 } else { 2676 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2677 } 2678 } 2679 2680 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2681 // default. If there's more than one, just leave everything alone. 2682 if (browserPkg == null) { 2683 calculateDefaultBrowserLPw(userId); 2684 } 2685 } 2686 2687 private void calculateDefaultBrowserLPw(int userId) { 2688 List<String> allBrowsers = resolveAllBrowserApps(userId); 2689 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2690 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2691 } 2692 2693 private List<String> resolveAllBrowserApps(int userId) { 2694 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2695 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2696 PackageManager.MATCH_ALL, userId); 2697 2698 final int count = list.size(); 2699 List<String> result = new ArrayList<String>(count); 2700 for (int i=0; i<count; i++) { 2701 ResolveInfo info = list.get(i); 2702 if (info.activityInfo == null 2703 || !info.handleAllWebDataURI 2704 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2705 || result.contains(info.activityInfo.packageName)) { 2706 continue; 2707 } 2708 result.add(info.activityInfo.packageName); 2709 } 2710 2711 return result; 2712 } 2713 2714 private boolean packageIsBrowser(String packageName, int userId) { 2715 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2716 PackageManager.MATCH_ALL, userId); 2717 final int N = list.size(); 2718 for (int i = 0; i < N; i++) { 2719 ResolveInfo info = list.get(i); 2720 if (packageName.equals(info.activityInfo.packageName)) { 2721 return true; 2722 } 2723 } 2724 return false; 2725 } 2726 2727 private void checkDefaultBrowser() { 2728 final int myUserId = UserHandle.myUserId(); 2729 final String packageName = getDefaultBrowserPackageName(myUserId); 2730 if (packageName != null) { 2731 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2732 if (info == null) { 2733 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2734 synchronized (mPackages) { 2735 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2736 } 2737 } 2738 } 2739 } 2740 2741 @Override 2742 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2743 throws RemoteException { 2744 try { 2745 return super.onTransact(code, data, reply, flags); 2746 } catch (RuntimeException e) { 2747 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2748 Slog.wtf(TAG, "Package Manager Crash", e); 2749 } 2750 throw e; 2751 } 2752 } 2753 2754 void cleanupInstallFailedPackage(PackageSetting ps) { 2755 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2756 2757 removeDataDirsLI(ps.volumeUuid, ps.name); 2758 if (ps.codePath != null) { 2759 removeCodePathLI(ps.codePath); 2760 } 2761 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2762 if (ps.resourcePath.isDirectory()) { 2763 FileUtils.deleteContents(ps.resourcePath); 2764 } 2765 ps.resourcePath.delete(); 2766 } 2767 mSettings.removePackageLPw(ps.name); 2768 } 2769 2770 static int[] appendInts(int[] cur, int[] add) { 2771 if (add == null) return cur; 2772 if (cur == null) return add; 2773 final int N = add.length; 2774 for (int i=0; i<N; i++) { 2775 cur = appendInt(cur, add[i]); 2776 } 2777 return cur; 2778 } 2779 2780 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2781 if (!sUserManager.exists(userId)) return null; 2782 final PackageSetting ps = (PackageSetting) p.mExtras; 2783 if (ps == null) { 2784 return null; 2785 } 2786 2787 final PermissionsState permissionsState = ps.getPermissionsState(); 2788 2789 final int[] gids = permissionsState.computeGids(userId); 2790 final Set<String> permissions = permissionsState.getPermissions(userId); 2791 final PackageUserState state = ps.readUserState(userId); 2792 2793 return PackageParser.generatePackageInfo(p, gids, flags, 2794 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2795 } 2796 2797 @Override 2798 public void checkPackageStartable(String packageName, int userId) { 2799 final boolean userKeyUnlocked = isUserKeyUnlocked(userId); 2800 2801 synchronized (mPackages) { 2802 final PackageSetting ps = mSettings.mPackages.get(packageName); 2803 if (ps == null) { 2804 throw new SecurityException("Package " + packageName + " was not found!"); 2805 } 2806 2807 if (ps.frozen) { 2808 throw new SecurityException("Package " + packageName + " is currently frozen!"); 2809 } 2810 2811 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isEncryptionAware() 2812 || ps.pkg.applicationInfo.isPartiallyEncryptionAware())) { 2813 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 2814 } 2815 } 2816 } 2817 2818 @Override 2819 public boolean isPackageAvailable(String packageName, int userId) { 2820 if (!sUserManager.exists(userId)) return false; 2821 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2822 synchronized (mPackages) { 2823 PackageParser.Package p = mPackages.get(packageName); 2824 if (p != null) { 2825 final PackageSetting ps = (PackageSetting) p.mExtras; 2826 if (ps != null) { 2827 final PackageUserState state = ps.readUserState(userId); 2828 if (state != null) { 2829 return PackageParser.isAvailable(state); 2830 } 2831 } 2832 } 2833 } 2834 return false; 2835 } 2836 2837 @Override 2838 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2839 if (!sUserManager.exists(userId)) return null; 2840 flags = updateFlagsForPackage(flags, userId, packageName); 2841 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2842 // reader 2843 synchronized (mPackages) { 2844 PackageParser.Package p = mPackages.get(packageName); 2845 if (DEBUG_PACKAGE_INFO) 2846 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2847 if (p != null) { 2848 return generatePackageInfo(p, flags, userId); 2849 } 2850 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 2851 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2852 } 2853 } 2854 return null; 2855 } 2856 2857 @Override 2858 public String[] currentToCanonicalPackageNames(String[] names) { 2859 String[] out = new String[names.length]; 2860 // reader 2861 synchronized (mPackages) { 2862 for (int i=names.length-1; i>=0; i--) { 2863 PackageSetting ps = mSettings.mPackages.get(names[i]); 2864 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2865 } 2866 } 2867 return out; 2868 } 2869 2870 @Override 2871 public String[] canonicalToCurrentPackageNames(String[] names) { 2872 String[] out = new String[names.length]; 2873 // reader 2874 synchronized (mPackages) { 2875 for (int i=names.length-1; i>=0; i--) { 2876 String cur = mSettings.mRenamedPackages.get(names[i]); 2877 out[i] = cur != null ? cur : names[i]; 2878 } 2879 } 2880 return out; 2881 } 2882 2883 @Override 2884 public int getPackageUid(String packageName, int flags, int userId) { 2885 if (!sUserManager.exists(userId)) return -1; 2886 flags = updateFlagsForPackage(flags, userId, packageName); 2887 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2888 2889 // reader 2890 synchronized (mPackages) { 2891 final PackageParser.Package p = mPackages.get(packageName); 2892 if (p != null && p.isMatch(flags)) { 2893 return UserHandle.getUid(userId, p.applicationInfo.uid); 2894 } 2895 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 2896 final PackageSetting ps = mSettings.mPackages.get(packageName); 2897 if (ps != null && ps.isMatch(flags)) { 2898 return UserHandle.getUid(userId, ps.appId); 2899 } 2900 } 2901 } 2902 2903 return -1; 2904 } 2905 2906 @Override 2907 public int[] getPackageGids(String packageName, int flags, int userId) { 2908 if (!sUserManager.exists(userId)) return null; 2909 flags = updateFlagsForPackage(flags, userId, packageName); 2910 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2911 "getPackageGids"); 2912 2913 // reader 2914 synchronized (mPackages) { 2915 final PackageParser.Package p = mPackages.get(packageName); 2916 if (p != null && p.isMatch(flags)) { 2917 PackageSetting ps = (PackageSetting) p.mExtras; 2918 return ps.getPermissionsState().computeGids(userId); 2919 } 2920 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 2921 final PackageSetting ps = mSettings.mPackages.get(packageName); 2922 if (ps != null && ps.isMatch(flags)) { 2923 return ps.getPermissionsState().computeGids(userId); 2924 } 2925 } 2926 } 2927 2928 return null; 2929 } 2930 2931 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 2932 if (bp.perm != null) { 2933 return PackageParser.generatePermissionInfo(bp.perm, flags); 2934 } 2935 PermissionInfo pi = new PermissionInfo(); 2936 pi.name = bp.name; 2937 pi.packageName = bp.sourcePackage; 2938 pi.nonLocalizedLabel = bp.name; 2939 pi.protectionLevel = bp.protectionLevel; 2940 return pi; 2941 } 2942 2943 @Override 2944 public PermissionInfo getPermissionInfo(String name, int flags) { 2945 // reader 2946 synchronized (mPackages) { 2947 final BasePermission p = mSettings.mPermissions.get(name); 2948 if (p != null) { 2949 return generatePermissionInfo(p, flags); 2950 } 2951 return null; 2952 } 2953 } 2954 2955 @Override 2956 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2957 // reader 2958 synchronized (mPackages) { 2959 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2960 for (BasePermission p : mSettings.mPermissions.values()) { 2961 if (group == null) { 2962 if (p.perm == null || p.perm.info.group == null) { 2963 out.add(generatePermissionInfo(p, flags)); 2964 } 2965 } else { 2966 if (p.perm != null && group.equals(p.perm.info.group)) { 2967 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2968 } 2969 } 2970 } 2971 2972 if (out.size() > 0) { 2973 return out; 2974 } 2975 return mPermissionGroups.containsKey(group) ? out : null; 2976 } 2977 } 2978 2979 @Override 2980 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2981 // reader 2982 synchronized (mPackages) { 2983 return PackageParser.generatePermissionGroupInfo( 2984 mPermissionGroups.get(name), flags); 2985 } 2986 } 2987 2988 @Override 2989 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2990 // reader 2991 synchronized (mPackages) { 2992 final int N = mPermissionGroups.size(); 2993 ArrayList<PermissionGroupInfo> out 2994 = new ArrayList<PermissionGroupInfo>(N); 2995 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2996 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2997 } 2998 return out; 2999 } 3000 } 3001 3002 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3003 int userId) { 3004 if (!sUserManager.exists(userId)) return null; 3005 PackageSetting ps = mSettings.mPackages.get(packageName); 3006 if (ps != null) { 3007 if (ps.pkg == null) { 3008 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 3009 flags, userId); 3010 if (pInfo != null) { 3011 return pInfo.applicationInfo; 3012 } 3013 return null; 3014 } 3015 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3016 ps.readUserState(userId), userId); 3017 } 3018 return null; 3019 } 3020 3021 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 3022 int userId) { 3023 if (!sUserManager.exists(userId)) return null; 3024 PackageSetting ps = mSettings.mPackages.get(packageName); 3025 if (ps != null) { 3026 PackageParser.Package pkg = ps.pkg; 3027 if (pkg == null) { 3028 if ((flags & MATCH_UNINSTALLED_PACKAGES) == 0) { 3029 return null; 3030 } 3031 // Only data remains, so we aren't worried about code paths 3032 pkg = new PackageParser.Package(packageName); 3033 pkg.applicationInfo.packageName = packageName; 3034 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 3035 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 3036 pkg.applicationInfo.uid = ps.appId; 3037 pkg.applicationInfo.initForUser(userId); 3038 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 3039 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 3040 } 3041 return generatePackageInfo(pkg, flags, userId); 3042 } 3043 return null; 3044 } 3045 3046 @Override 3047 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3048 if (!sUserManager.exists(userId)) return null; 3049 flags = updateFlagsForApplication(flags, userId, packageName); 3050 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 3051 // writer 3052 synchronized (mPackages) { 3053 PackageParser.Package p = mPackages.get(packageName); 3054 if (DEBUG_PACKAGE_INFO) Log.v( 3055 TAG, "getApplicationInfo " + packageName 3056 + ": " + p); 3057 if (p != null) { 3058 PackageSetting ps = mSettings.mPackages.get(packageName); 3059 if (ps == null) return null; 3060 // Note: isEnabledLP() does not apply here - always return info 3061 return PackageParser.generateApplicationInfo( 3062 p, flags, ps.readUserState(userId), userId); 3063 } 3064 if ("android".equals(packageName)||"system".equals(packageName)) { 3065 return mAndroidApplication; 3066 } 3067 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3068 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3069 } 3070 } 3071 return null; 3072 } 3073 3074 @Override 3075 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3076 final IPackageDataObserver observer) { 3077 mContext.enforceCallingOrSelfPermission( 3078 android.Manifest.permission.CLEAR_APP_CACHE, null); 3079 // Queue up an async operation since clearing cache may take a little while. 3080 mHandler.post(new Runnable() { 3081 public void run() { 3082 mHandler.removeCallbacks(this); 3083 boolean success = true; 3084 synchronized (mInstallLock) { 3085 try { 3086 mInstaller.freeCache(volumeUuid, freeStorageSize); 3087 } catch (InstallerException e) { 3088 Slog.w(TAG, "Couldn't clear application caches: " + e); 3089 success = false; 3090 } 3091 } 3092 if (observer != null) { 3093 try { 3094 observer.onRemoveCompleted(null, success); 3095 } catch (RemoteException e) { 3096 Slog.w(TAG, "RemoveException when invoking call back"); 3097 } 3098 } 3099 } 3100 }); 3101 } 3102 3103 @Override 3104 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3105 final IntentSender pi) { 3106 mContext.enforceCallingOrSelfPermission( 3107 android.Manifest.permission.CLEAR_APP_CACHE, null); 3108 // Queue up an async operation since clearing cache may take a little while. 3109 mHandler.post(new Runnable() { 3110 public void run() { 3111 mHandler.removeCallbacks(this); 3112 boolean success = true; 3113 synchronized (mInstallLock) { 3114 try { 3115 mInstaller.freeCache(volumeUuid, freeStorageSize); 3116 } catch (InstallerException e) { 3117 Slog.w(TAG, "Couldn't clear application caches: " + e); 3118 success = false; 3119 } 3120 } 3121 if(pi != null) { 3122 try { 3123 // Callback via pending intent 3124 int code = success ? 1 : 0; 3125 pi.sendIntent(null, code, null, 3126 null, null); 3127 } catch (SendIntentException e1) { 3128 Slog.i(TAG, "Failed to send pending intent"); 3129 } 3130 } 3131 } 3132 }); 3133 } 3134 3135 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3136 synchronized (mInstallLock) { 3137 try { 3138 mInstaller.freeCache(volumeUuid, freeStorageSize); 3139 } catch (InstallerException e) { 3140 throw new IOException("Failed to free enough space", e); 3141 } 3142 } 3143 } 3144 3145 /** 3146 * Return if the user key is currently unlocked. 3147 */ 3148 private boolean isUserKeyUnlocked(int userId) { 3149 if (StorageManager.isFileBasedEncryptionEnabled()) { 3150 final IMountService mount = IMountService.Stub 3151 .asInterface(ServiceManager.getService("mount")); 3152 if (mount == null) { 3153 Slog.w(TAG, "Early during boot, assuming locked"); 3154 return false; 3155 } 3156 final long token = Binder.clearCallingIdentity(); 3157 try { 3158 return mount.isUserKeyUnlocked(userId); 3159 } catch (RemoteException e) { 3160 throw e.rethrowAsRuntimeException(); 3161 } finally { 3162 Binder.restoreCallingIdentity(token); 3163 } 3164 } else { 3165 return true; 3166 } 3167 } 3168 3169 /** 3170 * Update given flags based on encryption status of current user. 3171 */ 3172 private int updateFlags(int flags, int userId) { 3173 if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE 3174 | PackageManager.MATCH_ENCRYPTION_AWARE)) != 0) { 3175 // Caller expressed an explicit opinion about what encryption 3176 // aware/unaware components they want to see, so fall through and 3177 // give them what they want 3178 } else { 3179 // Caller expressed no opinion, so match based on user state 3180 if (isUserKeyUnlocked(userId)) { 3181 flags |= PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE; 3182 } else { 3183 flags |= PackageManager.MATCH_ENCRYPTION_AWARE; 3184 } 3185 } 3186 3187 // Safe mode means we should ignore any third-party apps 3188 if (mSafeMode) { 3189 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3190 } 3191 3192 return flags; 3193 } 3194 3195 /** 3196 * Update given flags when being used to request {@link PackageInfo}. 3197 */ 3198 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3199 boolean triaged = true; 3200 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3201 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3202 // Caller is asking for component details, so they'd better be 3203 // asking for specific encryption matching behavior, or be triaged 3204 if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE 3205 | PackageManager.MATCH_ENCRYPTION_AWARE 3206 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3207 triaged = false; 3208 } 3209 } 3210 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3211 | PackageManager.MATCH_SYSTEM_ONLY 3212 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3213 triaged = false; 3214 } 3215 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3216 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3217 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3218 } 3219 return updateFlags(flags, userId); 3220 } 3221 3222 /** 3223 * Update given flags when being used to request {@link ApplicationInfo}. 3224 */ 3225 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3226 return updateFlagsForPackage(flags, userId, cookie); 3227 } 3228 3229 /** 3230 * Update given flags when being used to request {@link ComponentInfo}. 3231 */ 3232 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3233 if (cookie instanceof Intent) { 3234 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3235 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3236 } 3237 } 3238 3239 boolean triaged = true; 3240 // Caller is asking for component details, so they'd better be 3241 // asking for specific encryption matching behavior, or be triaged 3242 if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE 3243 | PackageManager.MATCH_ENCRYPTION_AWARE 3244 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3245 triaged = false; 3246 } 3247 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3248 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3249 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3250 } 3251 return updateFlags(flags, userId); 3252 } 3253 3254 /** 3255 * Update given flags when being used to request {@link ResolveInfo}. 3256 */ 3257 private int updateFlagsForResolve(int flags, int userId, Object cookie) { 3258 return updateFlagsForComponent(flags, userId, cookie); 3259 } 3260 3261 @Override 3262 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3263 if (!sUserManager.exists(userId)) return null; 3264 flags = updateFlagsForComponent(flags, userId, component); 3265 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 3266 synchronized (mPackages) { 3267 PackageParser.Activity a = mActivities.mActivities.get(component); 3268 3269 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3270 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3271 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3272 if (ps == null) return null; 3273 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3274 userId); 3275 } 3276 if (mResolveComponentName.equals(component)) { 3277 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3278 new PackageUserState(), userId); 3279 } 3280 } 3281 return null; 3282 } 3283 3284 @Override 3285 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3286 String resolvedType) { 3287 synchronized (mPackages) { 3288 if (component.equals(mResolveComponentName)) { 3289 // The resolver supports EVERYTHING! 3290 return true; 3291 } 3292 PackageParser.Activity a = mActivities.mActivities.get(component); 3293 if (a == null) { 3294 return false; 3295 } 3296 for (int i=0; i<a.intents.size(); i++) { 3297 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3298 intent.getData(), intent.getCategories(), TAG) >= 0) { 3299 return true; 3300 } 3301 } 3302 return false; 3303 } 3304 } 3305 3306 @Override 3307 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3308 if (!sUserManager.exists(userId)) return null; 3309 flags = updateFlagsForComponent(flags, userId, component); 3310 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 3311 synchronized (mPackages) { 3312 PackageParser.Activity a = mReceivers.mActivities.get(component); 3313 if (DEBUG_PACKAGE_INFO) Log.v( 3314 TAG, "getReceiverInfo " + component + ": " + a); 3315 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3316 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3317 if (ps == null) return null; 3318 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3319 userId); 3320 } 3321 } 3322 return null; 3323 } 3324 3325 @Override 3326 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3327 if (!sUserManager.exists(userId)) return null; 3328 flags = updateFlagsForComponent(flags, userId, component); 3329 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 3330 synchronized (mPackages) { 3331 PackageParser.Service s = mServices.mServices.get(component); 3332 if (DEBUG_PACKAGE_INFO) Log.v( 3333 TAG, "getServiceInfo " + component + ": " + s); 3334 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3335 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3336 if (ps == null) return null; 3337 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3338 userId); 3339 } 3340 } 3341 return null; 3342 } 3343 3344 @Override 3345 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3346 if (!sUserManager.exists(userId)) return null; 3347 flags = updateFlagsForComponent(flags, userId, component); 3348 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 3349 synchronized (mPackages) { 3350 PackageParser.Provider p = mProviders.mProviders.get(component); 3351 if (DEBUG_PACKAGE_INFO) Log.v( 3352 TAG, "getProviderInfo " + component + ": " + p); 3353 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3354 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3355 if (ps == null) return null; 3356 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3357 userId); 3358 } 3359 } 3360 return null; 3361 } 3362 3363 @Override 3364 public String[] getSystemSharedLibraryNames() { 3365 Set<String> libSet; 3366 synchronized (mPackages) { 3367 libSet = mSharedLibraries.keySet(); 3368 int size = libSet.size(); 3369 if (size > 0) { 3370 String[] libs = new String[size]; 3371 libSet.toArray(libs); 3372 return libs; 3373 } 3374 } 3375 return null; 3376 } 3377 3378 /** 3379 * @hide 3380 */ 3381 PackageParser.Package findSharedNonSystemLibrary(String libName) { 3382 synchronized (mPackages) { 3383 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 3384 if (lib != null && lib.apk != null) { 3385 return mPackages.get(lib.apk); 3386 } 3387 } 3388 return null; 3389 } 3390 3391 @Override 3392 public FeatureInfo[] getSystemAvailableFeatures() { 3393 Collection<FeatureInfo> featSet; 3394 synchronized (mPackages) { 3395 featSet = mAvailableFeatures.values(); 3396 int size = featSet.size(); 3397 if (size > 0) { 3398 FeatureInfo[] features = new FeatureInfo[size+1]; 3399 featSet.toArray(features); 3400 FeatureInfo fi = new FeatureInfo(); 3401 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3402 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3403 features[size] = fi; 3404 return features; 3405 } 3406 } 3407 return null; 3408 } 3409 3410 @Override 3411 public boolean hasSystemFeature(String name) { 3412 synchronized (mPackages) { 3413 return mAvailableFeatures.containsKey(name); 3414 } 3415 } 3416 3417 @Override 3418 public int checkPermission(String permName, String pkgName, int userId) { 3419 if (!sUserManager.exists(userId)) { 3420 return PackageManager.PERMISSION_DENIED; 3421 } 3422 3423 synchronized (mPackages) { 3424 final PackageParser.Package p = mPackages.get(pkgName); 3425 if (p != null && p.mExtras != null) { 3426 final PackageSetting ps = (PackageSetting) p.mExtras; 3427 final PermissionsState permissionsState = ps.getPermissionsState(); 3428 if (permissionsState.hasPermission(permName, userId)) { 3429 return PackageManager.PERMISSION_GRANTED; 3430 } 3431 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3432 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3433 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3434 return PackageManager.PERMISSION_GRANTED; 3435 } 3436 } 3437 } 3438 3439 return PackageManager.PERMISSION_DENIED; 3440 } 3441 3442 @Override 3443 public int checkUidPermission(String permName, int uid) { 3444 final int userId = UserHandle.getUserId(uid); 3445 3446 if (!sUserManager.exists(userId)) { 3447 return PackageManager.PERMISSION_DENIED; 3448 } 3449 3450 synchronized (mPackages) { 3451 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3452 if (obj != null) { 3453 final SettingBase ps = (SettingBase) obj; 3454 final PermissionsState permissionsState = ps.getPermissionsState(); 3455 if (permissionsState.hasPermission(permName, userId)) { 3456 return PackageManager.PERMISSION_GRANTED; 3457 } 3458 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3459 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3460 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3461 return PackageManager.PERMISSION_GRANTED; 3462 } 3463 } else { 3464 ArraySet<String> perms = mSystemPermissions.get(uid); 3465 if (perms != null) { 3466 if (perms.contains(permName)) { 3467 return PackageManager.PERMISSION_GRANTED; 3468 } 3469 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3470 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3471 return PackageManager.PERMISSION_GRANTED; 3472 } 3473 } 3474 } 3475 } 3476 3477 return PackageManager.PERMISSION_DENIED; 3478 } 3479 3480 @Override 3481 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3482 if (UserHandle.getCallingUserId() != userId) { 3483 mContext.enforceCallingPermission( 3484 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3485 "isPermissionRevokedByPolicy for user " + userId); 3486 } 3487 3488 if (checkPermission(permission, packageName, userId) 3489 == PackageManager.PERMISSION_GRANTED) { 3490 return false; 3491 } 3492 3493 final long identity = Binder.clearCallingIdentity(); 3494 try { 3495 final int flags = getPermissionFlags(permission, packageName, userId); 3496 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3497 } finally { 3498 Binder.restoreCallingIdentity(identity); 3499 } 3500 } 3501 3502 @Override 3503 public String getPermissionControllerPackageName() { 3504 synchronized (mPackages) { 3505 return mRequiredInstallerPackage; 3506 } 3507 } 3508 3509 /** 3510 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3511 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3512 * @param checkShell TODO(yamasani): 3513 * @param message the message to log on security exception 3514 */ 3515 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3516 boolean checkShell, String message) { 3517 if (userId < 0) { 3518 throw new IllegalArgumentException("Invalid userId " + userId); 3519 } 3520 if (checkShell) { 3521 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3522 } 3523 if (userId == UserHandle.getUserId(callingUid)) return; 3524 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3525 if (requireFullPermission) { 3526 mContext.enforceCallingOrSelfPermission( 3527 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3528 } else { 3529 try { 3530 mContext.enforceCallingOrSelfPermission( 3531 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3532 } catch (SecurityException se) { 3533 mContext.enforceCallingOrSelfPermission( 3534 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3535 } 3536 } 3537 } 3538 } 3539 3540 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3541 if (callingUid == Process.SHELL_UID) { 3542 if (userHandle >= 0 3543 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3544 throw new SecurityException("Shell does not have permission to access user " 3545 + userHandle); 3546 } else if (userHandle < 0) { 3547 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3548 + Debug.getCallers(3)); 3549 } 3550 } 3551 } 3552 3553 private BasePermission findPermissionTreeLP(String permName) { 3554 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3555 if (permName.startsWith(bp.name) && 3556 permName.length() > bp.name.length() && 3557 permName.charAt(bp.name.length()) == '.') { 3558 return bp; 3559 } 3560 } 3561 return null; 3562 } 3563 3564 private BasePermission checkPermissionTreeLP(String permName) { 3565 if (permName != null) { 3566 BasePermission bp = findPermissionTreeLP(permName); 3567 if (bp != null) { 3568 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3569 return bp; 3570 } 3571 throw new SecurityException("Calling uid " 3572 + Binder.getCallingUid() 3573 + " is not allowed to add to permission tree " 3574 + bp.name + " owned by uid " + bp.uid); 3575 } 3576 } 3577 throw new SecurityException("No permission tree found for " + permName); 3578 } 3579 3580 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3581 if (s1 == null) { 3582 return s2 == null; 3583 } 3584 if (s2 == null) { 3585 return false; 3586 } 3587 if (s1.getClass() != s2.getClass()) { 3588 return false; 3589 } 3590 return s1.equals(s2); 3591 } 3592 3593 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3594 if (pi1.icon != pi2.icon) return false; 3595 if (pi1.logo != pi2.logo) return false; 3596 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3597 if (!compareStrings(pi1.name, pi2.name)) return false; 3598 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3599 // We'll take care of setting this one. 3600 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3601 // These are not currently stored in settings. 3602 //if (!compareStrings(pi1.group, pi2.group)) return false; 3603 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3604 //if (pi1.labelRes != pi2.labelRes) return false; 3605 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3606 return true; 3607 } 3608 3609 int permissionInfoFootprint(PermissionInfo info) { 3610 int size = info.name.length(); 3611 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3612 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3613 return size; 3614 } 3615 3616 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3617 int size = 0; 3618 for (BasePermission perm : mSettings.mPermissions.values()) { 3619 if (perm.uid == tree.uid) { 3620 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3621 } 3622 } 3623 return size; 3624 } 3625 3626 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3627 // We calculate the max size of permissions defined by this uid and throw 3628 // if that plus the size of 'info' would exceed our stated maximum. 3629 if (tree.uid != Process.SYSTEM_UID) { 3630 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3631 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3632 throw new SecurityException("Permission tree size cap exceeded"); 3633 } 3634 } 3635 } 3636 3637 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3638 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3639 throw new SecurityException("Label must be specified in permission"); 3640 } 3641 BasePermission tree = checkPermissionTreeLP(info.name); 3642 BasePermission bp = mSettings.mPermissions.get(info.name); 3643 boolean added = bp == null; 3644 boolean changed = true; 3645 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3646 if (added) { 3647 enforcePermissionCapLocked(info, tree); 3648 bp = new BasePermission(info.name, tree.sourcePackage, 3649 BasePermission.TYPE_DYNAMIC); 3650 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3651 throw new SecurityException( 3652 "Not allowed to modify non-dynamic permission " 3653 + info.name); 3654 } else { 3655 if (bp.protectionLevel == fixedLevel 3656 && bp.perm.owner.equals(tree.perm.owner) 3657 && bp.uid == tree.uid 3658 && comparePermissionInfos(bp.perm.info, info)) { 3659 changed = false; 3660 } 3661 } 3662 bp.protectionLevel = fixedLevel; 3663 info = new PermissionInfo(info); 3664 info.protectionLevel = fixedLevel; 3665 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3666 bp.perm.info.packageName = tree.perm.info.packageName; 3667 bp.uid = tree.uid; 3668 if (added) { 3669 mSettings.mPermissions.put(info.name, bp); 3670 } 3671 if (changed) { 3672 if (!async) { 3673 mSettings.writeLPr(); 3674 } else { 3675 scheduleWriteSettingsLocked(); 3676 } 3677 } 3678 return added; 3679 } 3680 3681 @Override 3682 public boolean addPermission(PermissionInfo info) { 3683 synchronized (mPackages) { 3684 return addPermissionLocked(info, false); 3685 } 3686 } 3687 3688 @Override 3689 public boolean addPermissionAsync(PermissionInfo info) { 3690 synchronized (mPackages) { 3691 return addPermissionLocked(info, true); 3692 } 3693 } 3694 3695 @Override 3696 public void removePermission(String name) { 3697 synchronized (mPackages) { 3698 checkPermissionTreeLP(name); 3699 BasePermission bp = mSettings.mPermissions.get(name); 3700 if (bp != null) { 3701 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3702 throw new SecurityException( 3703 "Not allowed to modify non-dynamic permission " 3704 + name); 3705 } 3706 mSettings.mPermissions.remove(name); 3707 mSettings.writeLPr(); 3708 } 3709 } 3710 } 3711 3712 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 3713 BasePermission bp) { 3714 int index = pkg.requestedPermissions.indexOf(bp.name); 3715 if (index == -1) { 3716 throw new SecurityException("Package " + pkg.packageName 3717 + " has not requested permission " + bp.name); 3718 } 3719 if (!bp.isRuntime() && !bp.isDevelopment()) { 3720 throw new SecurityException("Permission " + bp.name 3721 + " is not a changeable permission type"); 3722 } 3723 } 3724 3725 @Override 3726 public void grantRuntimePermission(String packageName, String name, final int userId) { 3727 if (!sUserManager.exists(userId)) { 3728 Log.e(TAG, "No such user:" + userId); 3729 return; 3730 } 3731 3732 mContext.enforceCallingOrSelfPermission( 3733 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3734 "grantRuntimePermission"); 3735 3736 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3737 "grantRuntimePermission"); 3738 3739 final int uid; 3740 final SettingBase sb; 3741 3742 synchronized (mPackages) { 3743 final PackageParser.Package pkg = mPackages.get(packageName); 3744 if (pkg == null) { 3745 throw new IllegalArgumentException("Unknown package: " + packageName); 3746 } 3747 3748 final BasePermission bp = mSettings.mPermissions.get(name); 3749 if (bp == null) { 3750 throw new IllegalArgumentException("Unknown permission: " + name); 3751 } 3752 3753 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3754 3755 // If a permission review is required for legacy apps we represent 3756 // their permissions as always granted runtime ones since we need 3757 // to keep the review required permission flag per user while an 3758 // install permission's state is shared across all users. 3759 if (Build.PERMISSIONS_REVIEW_REQUIRED 3760 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 3761 && bp.isRuntime()) { 3762 return; 3763 } 3764 3765 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3766 sb = (SettingBase) pkg.mExtras; 3767 if (sb == null) { 3768 throw new IllegalArgumentException("Unknown package: " + packageName); 3769 } 3770 3771 final PermissionsState permissionsState = sb.getPermissionsState(); 3772 3773 final int flags = permissionsState.getPermissionFlags(name, userId); 3774 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3775 throw new SecurityException("Cannot grant system fixed permission " 3776 + name + " for package " + packageName); 3777 } 3778 3779 if (bp.isDevelopment()) { 3780 // Development permissions must be handled specially, since they are not 3781 // normal runtime permissions. For now they apply to all users. 3782 if (permissionsState.grantInstallPermission(bp) != 3783 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3784 scheduleWriteSettingsLocked(); 3785 } 3786 return; 3787 } 3788 3789 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 3790 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 3791 return; 3792 } 3793 3794 final int result = permissionsState.grantRuntimePermission(bp, userId); 3795 switch (result) { 3796 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3797 return; 3798 } 3799 3800 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3801 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3802 mHandler.post(new Runnable() { 3803 @Override 3804 public void run() { 3805 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 3806 } 3807 }); 3808 } 3809 break; 3810 } 3811 3812 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3813 3814 // Not critical if that is lost - app has to request again. 3815 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3816 } 3817 3818 // Only need to do this if user is initialized. Otherwise it's a new user 3819 // and there are no processes running as the user yet and there's no need 3820 // to make an expensive call to remount processes for the changed permissions. 3821 if (READ_EXTERNAL_STORAGE.equals(name) 3822 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3823 final long token = Binder.clearCallingIdentity(); 3824 try { 3825 if (sUserManager.isInitialized(userId)) { 3826 MountServiceInternal mountServiceInternal = LocalServices.getService( 3827 MountServiceInternal.class); 3828 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 3829 } 3830 } finally { 3831 Binder.restoreCallingIdentity(token); 3832 } 3833 } 3834 } 3835 3836 @Override 3837 public void revokeRuntimePermission(String packageName, String name, int userId) { 3838 if (!sUserManager.exists(userId)) { 3839 Log.e(TAG, "No such user:" + userId); 3840 return; 3841 } 3842 3843 mContext.enforceCallingOrSelfPermission( 3844 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3845 "revokeRuntimePermission"); 3846 3847 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3848 "revokeRuntimePermission"); 3849 3850 final int appId; 3851 3852 synchronized (mPackages) { 3853 final PackageParser.Package pkg = mPackages.get(packageName); 3854 if (pkg == null) { 3855 throw new IllegalArgumentException("Unknown package: " + packageName); 3856 } 3857 3858 final BasePermission bp = mSettings.mPermissions.get(name); 3859 if (bp == null) { 3860 throw new IllegalArgumentException("Unknown permission: " + name); 3861 } 3862 3863 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3864 3865 // If a permission review is required for legacy apps we represent 3866 // their permissions as always granted runtime ones since we need 3867 // to keep the review required permission flag per user while an 3868 // install permission's state is shared across all users. 3869 if (Build.PERMISSIONS_REVIEW_REQUIRED 3870 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 3871 && bp.isRuntime()) { 3872 return; 3873 } 3874 3875 SettingBase sb = (SettingBase) pkg.mExtras; 3876 if (sb == null) { 3877 throw new IllegalArgumentException("Unknown package: " + packageName); 3878 } 3879 3880 final PermissionsState permissionsState = sb.getPermissionsState(); 3881 3882 final int flags = permissionsState.getPermissionFlags(name, userId); 3883 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3884 throw new SecurityException("Cannot revoke system fixed permission " 3885 + name + " for package " + packageName); 3886 } 3887 3888 if (bp.isDevelopment()) { 3889 // Development permissions must be handled specially, since they are not 3890 // normal runtime permissions. For now they apply to all users. 3891 if (permissionsState.revokeInstallPermission(bp) != 3892 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3893 scheduleWriteSettingsLocked(); 3894 } 3895 return; 3896 } 3897 3898 if (permissionsState.revokeRuntimePermission(bp, userId) == 3899 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3900 return; 3901 } 3902 3903 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3904 3905 // Critical, after this call app should never have the permission. 3906 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3907 3908 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3909 } 3910 3911 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3912 } 3913 3914 @Override 3915 public void resetRuntimePermissions() { 3916 mContext.enforceCallingOrSelfPermission( 3917 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3918 "revokeRuntimePermission"); 3919 3920 int callingUid = Binder.getCallingUid(); 3921 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3922 mContext.enforceCallingOrSelfPermission( 3923 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3924 "resetRuntimePermissions"); 3925 } 3926 3927 synchronized (mPackages) { 3928 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 3929 for (int userId : UserManagerService.getInstance().getUserIds()) { 3930 final int packageCount = mPackages.size(); 3931 for (int i = 0; i < packageCount; i++) { 3932 PackageParser.Package pkg = mPackages.valueAt(i); 3933 if (!(pkg.mExtras instanceof PackageSetting)) { 3934 continue; 3935 } 3936 PackageSetting ps = (PackageSetting) pkg.mExtras; 3937 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 3938 } 3939 } 3940 } 3941 } 3942 3943 @Override 3944 public int getPermissionFlags(String name, String packageName, int userId) { 3945 if (!sUserManager.exists(userId)) { 3946 return 0; 3947 } 3948 3949 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 3950 3951 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3952 "getPermissionFlags"); 3953 3954 synchronized (mPackages) { 3955 final PackageParser.Package pkg = mPackages.get(packageName); 3956 if (pkg == null) { 3957 throw new IllegalArgumentException("Unknown package: " + packageName); 3958 } 3959 3960 final BasePermission bp = mSettings.mPermissions.get(name); 3961 if (bp == null) { 3962 throw new IllegalArgumentException("Unknown permission: " + name); 3963 } 3964 3965 SettingBase sb = (SettingBase) pkg.mExtras; 3966 if (sb == null) { 3967 throw new IllegalArgumentException("Unknown package: " + packageName); 3968 } 3969 3970 PermissionsState permissionsState = sb.getPermissionsState(); 3971 return permissionsState.getPermissionFlags(name, userId); 3972 } 3973 } 3974 3975 @Override 3976 public void updatePermissionFlags(String name, String packageName, int flagMask, 3977 int flagValues, int userId) { 3978 if (!sUserManager.exists(userId)) { 3979 return; 3980 } 3981 3982 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 3983 3984 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3985 "updatePermissionFlags"); 3986 3987 // Only the system can change these flags and nothing else. 3988 if (getCallingUid() != Process.SYSTEM_UID) { 3989 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3990 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3991 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3992 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3993 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 3994 } 3995 3996 synchronized (mPackages) { 3997 final PackageParser.Package pkg = mPackages.get(packageName); 3998 if (pkg == null) { 3999 throw new IllegalArgumentException("Unknown package: " + packageName); 4000 } 4001 4002 final BasePermission bp = mSettings.mPermissions.get(name); 4003 if (bp == null) { 4004 throw new IllegalArgumentException("Unknown permission: " + name); 4005 } 4006 4007 SettingBase sb = (SettingBase) pkg.mExtras; 4008 if (sb == null) { 4009 throw new IllegalArgumentException("Unknown package: " + packageName); 4010 } 4011 4012 PermissionsState permissionsState = sb.getPermissionsState(); 4013 4014 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4015 4016 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4017 // Install and runtime permissions are stored in different places, 4018 // so figure out what permission changed and persist the change. 4019 if (permissionsState.getInstallPermissionState(name) != null) { 4020 scheduleWriteSettingsLocked(); 4021 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4022 || hadState) { 4023 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4024 } 4025 } 4026 } 4027 } 4028 4029 /** 4030 * Update the permission flags for all packages and runtime permissions of a user in order 4031 * to allow device or profile owner to remove POLICY_FIXED. 4032 */ 4033 @Override 4034 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4035 if (!sUserManager.exists(userId)) { 4036 return; 4037 } 4038 4039 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4040 4041 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 4042 "updatePermissionFlagsForAllApps"); 4043 4044 // Only the system can change system fixed flags. 4045 if (getCallingUid() != Process.SYSTEM_UID) { 4046 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4047 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4048 } 4049 4050 synchronized (mPackages) { 4051 boolean changed = false; 4052 final int packageCount = mPackages.size(); 4053 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4054 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4055 SettingBase sb = (SettingBase) pkg.mExtras; 4056 if (sb == null) { 4057 continue; 4058 } 4059 PermissionsState permissionsState = sb.getPermissionsState(); 4060 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4061 userId, flagMask, flagValues); 4062 } 4063 if (changed) { 4064 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4065 } 4066 } 4067 } 4068 4069 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4070 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4071 != PackageManager.PERMISSION_GRANTED 4072 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4073 != PackageManager.PERMISSION_GRANTED) { 4074 throw new SecurityException(message + " requires " 4075 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4076 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4077 } 4078 } 4079 4080 @Override 4081 public boolean shouldShowRequestPermissionRationale(String permissionName, 4082 String packageName, int userId) { 4083 if (UserHandle.getCallingUserId() != userId) { 4084 mContext.enforceCallingPermission( 4085 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4086 "canShowRequestPermissionRationale for user " + userId); 4087 } 4088 4089 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4090 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4091 return false; 4092 } 4093 4094 if (checkPermission(permissionName, packageName, userId) 4095 == PackageManager.PERMISSION_GRANTED) { 4096 return false; 4097 } 4098 4099 final int flags; 4100 4101 final long identity = Binder.clearCallingIdentity(); 4102 try { 4103 flags = getPermissionFlags(permissionName, 4104 packageName, userId); 4105 } finally { 4106 Binder.restoreCallingIdentity(identity); 4107 } 4108 4109 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4110 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4111 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4112 4113 if ((flags & fixedFlags) != 0) { 4114 return false; 4115 } 4116 4117 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4118 } 4119 4120 @Override 4121 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4122 mContext.enforceCallingOrSelfPermission( 4123 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4124 "addOnPermissionsChangeListener"); 4125 4126 synchronized (mPackages) { 4127 mOnPermissionChangeListeners.addListenerLocked(listener); 4128 } 4129 } 4130 4131 @Override 4132 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4133 synchronized (mPackages) { 4134 mOnPermissionChangeListeners.removeListenerLocked(listener); 4135 } 4136 } 4137 4138 @Override 4139 public boolean isProtectedBroadcast(String actionName) { 4140 synchronized (mPackages) { 4141 if (mProtectedBroadcasts.contains(actionName)) { 4142 return true; 4143 } else if (actionName != null) { 4144 // TODO: remove these terrible hacks 4145 if (actionName.startsWith("android.net.netmon.lingerExpired") 4146 || actionName.startsWith("com.android.server.sip.SipWakeupTimer")) { 4147 return true; 4148 } 4149 } 4150 } 4151 return false; 4152 } 4153 4154 @Override 4155 public int checkSignatures(String pkg1, String pkg2) { 4156 synchronized (mPackages) { 4157 final PackageParser.Package p1 = mPackages.get(pkg1); 4158 final PackageParser.Package p2 = mPackages.get(pkg2); 4159 if (p1 == null || p1.mExtras == null 4160 || p2 == null || p2.mExtras == null) { 4161 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4162 } 4163 return compareSignatures(p1.mSignatures, p2.mSignatures); 4164 } 4165 } 4166 4167 @Override 4168 public int checkUidSignatures(int uid1, int uid2) { 4169 // Map to base uids. 4170 uid1 = UserHandle.getAppId(uid1); 4171 uid2 = UserHandle.getAppId(uid2); 4172 // reader 4173 synchronized (mPackages) { 4174 Signature[] s1; 4175 Signature[] s2; 4176 Object obj = mSettings.getUserIdLPr(uid1); 4177 if (obj != null) { 4178 if (obj instanceof SharedUserSetting) { 4179 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4180 } else if (obj instanceof PackageSetting) { 4181 s1 = ((PackageSetting)obj).signatures.mSignatures; 4182 } else { 4183 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4184 } 4185 } else { 4186 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4187 } 4188 obj = mSettings.getUserIdLPr(uid2); 4189 if (obj != null) { 4190 if (obj instanceof SharedUserSetting) { 4191 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4192 } else if (obj instanceof PackageSetting) { 4193 s2 = ((PackageSetting)obj).signatures.mSignatures; 4194 } else { 4195 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4196 } 4197 } else { 4198 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4199 } 4200 return compareSignatures(s1, s2); 4201 } 4202 } 4203 4204 private void killUid(int appId, int userId, String reason) { 4205 final long identity = Binder.clearCallingIdentity(); 4206 try { 4207 IActivityManager am = ActivityManagerNative.getDefault(); 4208 if (am != null) { 4209 try { 4210 am.killUid(appId, userId, reason); 4211 } catch (RemoteException e) { 4212 /* ignore - same process */ 4213 } 4214 } 4215 } finally { 4216 Binder.restoreCallingIdentity(identity); 4217 } 4218 } 4219 4220 /** 4221 * Compares two sets of signatures. Returns: 4222 * <br /> 4223 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4224 * <br /> 4225 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4226 * <br /> 4227 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4228 * <br /> 4229 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4230 * <br /> 4231 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4232 */ 4233 static int compareSignatures(Signature[] s1, Signature[] s2) { 4234 if (s1 == null) { 4235 return s2 == null 4236 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4237 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4238 } 4239 4240 if (s2 == null) { 4241 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4242 } 4243 4244 if (s1.length != s2.length) { 4245 return PackageManager.SIGNATURE_NO_MATCH; 4246 } 4247 4248 // Since both signature sets are of size 1, we can compare without HashSets. 4249 if (s1.length == 1) { 4250 return s1[0].equals(s2[0]) ? 4251 PackageManager.SIGNATURE_MATCH : 4252 PackageManager.SIGNATURE_NO_MATCH; 4253 } 4254 4255 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4256 for (Signature sig : s1) { 4257 set1.add(sig); 4258 } 4259 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4260 for (Signature sig : s2) { 4261 set2.add(sig); 4262 } 4263 // Make sure s2 contains all signatures in s1. 4264 if (set1.equals(set2)) { 4265 return PackageManager.SIGNATURE_MATCH; 4266 } 4267 return PackageManager.SIGNATURE_NO_MATCH; 4268 } 4269 4270 /** 4271 * If the database version for this type of package (internal storage or 4272 * external storage) is less than the version where package signatures 4273 * were updated, return true. 4274 */ 4275 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4276 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4277 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4278 } 4279 4280 /** 4281 * Used for backward compatibility to make sure any packages with 4282 * certificate chains get upgraded to the new style. {@code existingSigs} 4283 * will be in the old format (since they were stored on disk from before the 4284 * system upgrade) and {@code scannedSigs} will be in the newer format. 4285 */ 4286 private int compareSignaturesCompat(PackageSignatures existingSigs, 4287 PackageParser.Package scannedPkg) { 4288 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4289 return PackageManager.SIGNATURE_NO_MATCH; 4290 } 4291 4292 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4293 for (Signature sig : existingSigs.mSignatures) { 4294 existingSet.add(sig); 4295 } 4296 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4297 for (Signature sig : scannedPkg.mSignatures) { 4298 try { 4299 Signature[] chainSignatures = sig.getChainSignatures(); 4300 for (Signature chainSig : chainSignatures) { 4301 scannedCompatSet.add(chainSig); 4302 } 4303 } catch (CertificateEncodingException e) { 4304 scannedCompatSet.add(sig); 4305 } 4306 } 4307 /* 4308 * Make sure the expanded scanned set contains all signatures in the 4309 * existing one. 4310 */ 4311 if (scannedCompatSet.equals(existingSet)) { 4312 // Migrate the old signatures to the new scheme. 4313 existingSigs.assignSignatures(scannedPkg.mSignatures); 4314 // The new KeySets will be re-added later in the scanning process. 4315 synchronized (mPackages) { 4316 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4317 } 4318 return PackageManager.SIGNATURE_MATCH; 4319 } 4320 return PackageManager.SIGNATURE_NO_MATCH; 4321 } 4322 4323 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4324 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4325 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4326 } 4327 4328 private int compareSignaturesRecover(PackageSignatures existingSigs, 4329 PackageParser.Package scannedPkg) { 4330 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4331 return PackageManager.SIGNATURE_NO_MATCH; 4332 } 4333 4334 String msg = null; 4335 try { 4336 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4337 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4338 + scannedPkg.packageName); 4339 return PackageManager.SIGNATURE_MATCH; 4340 } 4341 } catch (CertificateException e) { 4342 msg = e.getMessage(); 4343 } 4344 4345 logCriticalInfo(Log.INFO, 4346 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4347 return PackageManager.SIGNATURE_NO_MATCH; 4348 } 4349 4350 @Override 4351 public String[] getPackagesForUid(int uid) { 4352 uid = UserHandle.getAppId(uid); 4353 // reader 4354 synchronized (mPackages) { 4355 Object obj = mSettings.getUserIdLPr(uid); 4356 if (obj instanceof SharedUserSetting) { 4357 final SharedUserSetting sus = (SharedUserSetting) obj; 4358 final int N = sus.packages.size(); 4359 final String[] res = new String[N]; 4360 final Iterator<PackageSetting> it = sus.packages.iterator(); 4361 int i = 0; 4362 while (it.hasNext()) { 4363 res[i++] = it.next().name; 4364 } 4365 return res; 4366 } else if (obj instanceof PackageSetting) { 4367 final PackageSetting ps = (PackageSetting) obj; 4368 return new String[] { ps.name }; 4369 } 4370 } 4371 return null; 4372 } 4373 4374 @Override 4375 public String getNameForUid(int uid) { 4376 // reader 4377 synchronized (mPackages) { 4378 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4379 if (obj instanceof SharedUserSetting) { 4380 final SharedUserSetting sus = (SharedUserSetting) obj; 4381 return sus.name + ":" + sus.userId; 4382 } else if (obj instanceof PackageSetting) { 4383 final PackageSetting ps = (PackageSetting) obj; 4384 return ps.name; 4385 } 4386 } 4387 return null; 4388 } 4389 4390 @Override 4391 public int getUidForSharedUser(String sharedUserName) { 4392 if(sharedUserName == null) { 4393 return -1; 4394 } 4395 // reader 4396 synchronized (mPackages) { 4397 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4398 if (suid == null) { 4399 return -1; 4400 } 4401 return suid.userId; 4402 } 4403 } 4404 4405 @Override 4406 public int getFlagsForUid(int uid) { 4407 synchronized (mPackages) { 4408 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4409 if (obj instanceof SharedUserSetting) { 4410 final SharedUserSetting sus = (SharedUserSetting) obj; 4411 return sus.pkgFlags; 4412 } else if (obj instanceof PackageSetting) { 4413 final PackageSetting ps = (PackageSetting) obj; 4414 return ps.pkgFlags; 4415 } 4416 } 4417 return 0; 4418 } 4419 4420 @Override 4421 public int getPrivateFlagsForUid(int uid) { 4422 synchronized (mPackages) { 4423 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4424 if (obj instanceof SharedUserSetting) { 4425 final SharedUserSetting sus = (SharedUserSetting) obj; 4426 return sus.pkgPrivateFlags; 4427 } else if (obj instanceof PackageSetting) { 4428 final PackageSetting ps = (PackageSetting) obj; 4429 return ps.pkgPrivateFlags; 4430 } 4431 } 4432 return 0; 4433 } 4434 4435 @Override 4436 public boolean isUidPrivileged(int uid) { 4437 uid = UserHandle.getAppId(uid); 4438 // reader 4439 synchronized (mPackages) { 4440 Object obj = mSettings.getUserIdLPr(uid); 4441 if (obj instanceof SharedUserSetting) { 4442 final SharedUserSetting sus = (SharedUserSetting) obj; 4443 final Iterator<PackageSetting> it = sus.packages.iterator(); 4444 while (it.hasNext()) { 4445 if (it.next().isPrivileged()) { 4446 return true; 4447 } 4448 } 4449 } else if (obj instanceof PackageSetting) { 4450 final PackageSetting ps = (PackageSetting) obj; 4451 return ps.isPrivileged(); 4452 } 4453 } 4454 return false; 4455 } 4456 4457 @Override 4458 public String[] getAppOpPermissionPackages(String permissionName) { 4459 synchronized (mPackages) { 4460 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4461 if (pkgs == null) { 4462 return null; 4463 } 4464 return pkgs.toArray(new String[pkgs.size()]); 4465 } 4466 } 4467 4468 @Override 4469 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4470 int flags, int userId) { 4471 if (!sUserManager.exists(userId)) return null; 4472 flags = updateFlagsForResolve(flags, userId, intent); 4473 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 4474 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4475 final ResolveInfo bestChoice = 4476 chooseBestActivity(intent, resolvedType, flags, query, userId); 4477 4478 if (isEphemeralAllowed(intent, query, userId)) { 4479 final EphemeralResolveInfo ai = 4480 getEphemeralResolveInfo(intent, resolvedType, userId); 4481 if (ai != null) { 4482 if (DEBUG_EPHEMERAL) { 4483 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4484 } 4485 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4486 bestChoice.ephemeralResolveInfo = ai; 4487 } 4488 } 4489 return bestChoice; 4490 } 4491 4492 @Override 4493 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4494 IntentFilter filter, int match, ComponentName activity) { 4495 final int userId = UserHandle.getCallingUserId(); 4496 if (DEBUG_PREFERRED) { 4497 Log.v(TAG, "setLastChosenActivity intent=" + intent 4498 + " resolvedType=" + resolvedType 4499 + " flags=" + flags 4500 + " filter=" + filter 4501 + " match=" + match 4502 + " activity=" + activity); 4503 filter.dump(new PrintStreamPrinter(System.out), " "); 4504 } 4505 intent.setComponent(null); 4506 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4507 // Find any earlier preferred or last chosen entries and nuke them 4508 findPreferredActivity(intent, resolvedType, 4509 flags, query, 0, false, true, false, userId); 4510 // Add the new activity as the last chosen for this filter 4511 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4512 "Setting last chosen"); 4513 } 4514 4515 @Override 4516 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4517 final int userId = UserHandle.getCallingUserId(); 4518 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4519 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4520 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4521 false, false, false, userId); 4522 } 4523 4524 4525 private boolean isEphemeralAllowed( 4526 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4527 // Short circuit and return early if possible. 4528 if (DISABLE_EPHEMERAL_APPS) { 4529 return false; 4530 } 4531 final int callingUser = UserHandle.getCallingUserId(); 4532 if (callingUser != UserHandle.USER_SYSTEM) { 4533 return false; 4534 } 4535 if (mEphemeralResolverConnection == null) { 4536 return false; 4537 } 4538 if (intent.getComponent() != null) { 4539 return false; 4540 } 4541 if (intent.getPackage() != null) { 4542 return false; 4543 } 4544 final boolean isWebUri = hasWebURI(intent); 4545 if (!isWebUri) { 4546 return false; 4547 } 4548 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4549 synchronized (mPackages) { 4550 final int count = resolvedActivites.size(); 4551 for (int n = 0; n < count; n++) { 4552 ResolveInfo info = resolvedActivites.get(n); 4553 String packageName = info.activityInfo.packageName; 4554 PackageSetting ps = mSettings.mPackages.get(packageName); 4555 if (ps != null) { 4556 // Try to get the status from User settings first 4557 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4558 int status = (int) (packedStatus >> 32); 4559 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4560 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4561 if (DEBUG_EPHEMERAL) { 4562 Slog.v(TAG, "DENY ephemeral apps;" 4563 + " pkg: " + packageName + ", status: " + status); 4564 } 4565 return false; 4566 } 4567 } 4568 } 4569 } 4570 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4571 return true; 4572 } 4573 4574 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 4575 int userId) { 4576 MessageDigest digest = null; 4577 try { 4578 digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM); 4579 } catch (NoSuchAlgorithmException e) { 4580 // If we can't create a digest, ignore ephemeral apps. 4581 return null; 4582 } 4583 4584 final byte[] hostBytes = intent.getData().getHost().getBytes(); 4585 final byte[] digestBytes = digest.digest(hostBytes); 4586 int shaPrefix = 4587 digestBytes[0] << 24 4588 | digestBytes[1] << 16 4589 | digestBytes[2] << 8 4590 | digestBytes[3] << 0; 4591 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4592 mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix); 4593 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4594 // No hash prefix match; there are no ephemeral apps for this domain. 4595 return null; 4596 } 4597 for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) { 4598 EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i); 4599 if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) { 4600 continue; 4601 } 4602 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4603 // No filters; this should never happen. 4604 if (filters.isEmpty()) { 4605 continue; 4606 } 4607 // We have a domain match; resolve the filters to see if anything matches. 4608 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4609 for (int j = filters.size() - 1; j >= 0; --j) { 4610 final EphemeralResolveIntentInfo intentInfo = 4611 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 4612 ephemeralResolver.addFilter(intentInfo); 4613 } 4614 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 4615 intent, resolvedType, false /*defaultOnly*/, userId); 4616 if (!matchedResolveInfoList.isEmpty()) { 4617 return matchedResolveInfoList.get(0); 4618 } 4619 } 4620 // Hash or filter mis-match; no ephemeral apps for this domain. 4621 return null; 4622 } 4623 4624 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4625 int flags, List<ResolveInfo> query, int userId) { 4626 if (query != null) { 4627 final int N = query.size(); 4628 if (N == 1) { 4629 return query.get(0); 4630 } else if (N > 1) { 4631 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4632 // If there is more than one activity with the same priority, 4633 // then let the user decide between them. 4634 ResolveInfo r0 = query.get(0); 4635 ResolveInfo r1 = query.get(1); 4636 if (DEBUG_INTENT_MATCHING || debug) { 4637 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4638 + r1.activityInfo.name + "=" + r1.priority); 4639 } 4640 // If the first activity has a higher priority, or a different 4641 // default, then it is always desirable to pick it. 4642 if (r0.priority != r1.priority 4643 || r0.preferredOrder != r1.preferredOrder 4644 || r0.isDefault != r1.isDefault) { 4645 return query.get(0); 4646 } 4647 // If we have saved a preference for a preferred activity for 4648 // this Intent, use that. 4649 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4650 flags, query, r0.priority, true, false, debug, userId); 4651 if (ri != null) { 4652 return ri; 4653 } 4654 ri = new ResolveInfo(mResolveInfo); 4655 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4656 ri.activityInfo.applicationInfo = new ApplicationInfo( 4657 ri.activityInfo.applicationInfo); 4658 if (userId != 0) { 4659 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4660 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4661 } 4662 // Make sure that the resolver is displayable in car mode 4663 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 4664 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 4665 return ri; 4666 } 4667 } 4668 return null; 4669 } 4670 4671 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4672 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4673 final int N = query.size(); 4674 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4675 .get(userId); 4676 // Get the list of persistent preferred activities that handle the intent 4677 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4678 List<PersistentPreferredActivity> pprefs = ppir != null 4679 ? ppir.queryIntent(intent, resolvedType, 4680 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4681 : null; 4682 if (pprefs != null && pprefs.size() > 0) { 4683 final int M = pprefs.size(); 4684 for (int i=0; i<M; i++) { 4685 final PersistentPreferredActivity ppa = pprefs.get(i); 4686 if (DEBUG_PREFERRED || debug) { 4687 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4688 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4689 + "\n component=" + ppa.mComponent); 4690 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4691 } 4692 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4693 flags | MATCH_DISABLED_COMPONENTS, userId); 4694 if (DEBUG_PREFERRED || debug) { 4695 Slog.v(TAG, "Found persistent preferred activity:"); 4696 if (ai != null) { 4697 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4698 } else { 4699 Slog.v(TAG, " null"); 4700 } 4701 } 4702 if (ai == null) { 4703 // This previously registered persistent preferred activity 4704 // component is no longer known. Ignore it and do NOT remove it. 4705 continue; 4706 } 4707 for (int j=0; j<N; j++) { 4708 final ResolveInfo ri = query.get(j); 4709 if (!ri.activityInfo.applicationInfo.packageName 4710 .equals(ai.applicationInfo.packageName)) { 4711 continue; 4712 } 4713 if (!ri.activityInfo.name.equals(ai.name)) { 4714 continue; 4715 } 4716 // Found a persistent preference that can handle the intent. 4717 if (DEBUG_PREFERRED || debug) { 4718 Slog.v(TAG, "Returning persistent preferred activity: " + 4719 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4720 } 4721 return ri; 4722 } 4723 } 4724 } 4725 return null; 4726 } 4727 4728 // TODO: handle preferred activities missing while user has amnesia 4729 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4730 List<ResolveInfo> query, int priority, boolean always, 4731 boolean removeMatches, boolean debug, int userId) { 4732 if (!sUserManager.exists(userId)) return null; 4733 flags = updateFlagsForResolve(flags, userId, intent); 4734 // writer 4735 synchronized (mPackages) { 4736 if (intent.getSelector() != null) { 4737 intent = intent.getSelector(); 4738 } 4739 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4740 4741 // Try to find a matching persistent preferred activity. 4742 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4743 debug, userId); 4744 4745 // If a persistent preferred activity matched, use it. 4746 if (pri != null) { 4747 return pri; 4748 } 4749 4750 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4751 // Get the list of preferred activities that handle the intent 4752 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4753 List<PreferredActivity> prefs = pir != null 4754 ? pir.queryIntent(intent, resolvedType, 4755 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4756 : null; 4757 if (prefs != null && prefs.size() > 0) { 4758 boolean changed = false; 4759 try { 4760 // First figure out how good the original match set is. 4761 // We will only allow preferred activities that came 4762 // from the same match quality. 4763 int match = 0; 4764 4765 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4766 4767 final int N = query.size(); 4768 for (int j=0; j<N; j++) { 4769 final ResolveInfo ri = query.get(j); 4770 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4771 + ": 0x" + Integer.toHexString(match)); 4772 if (ri.match > match) { 4773 match = ri.match; 4774 } 4775 } 4776 4777 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4778 + Integer.toHexString(match)); 4779 4780 match &= IntentFilter.MATCH_CATEGORY_MASK; 4781 final int M = prefs.size(); 4782 for (int i=0; i<M; i++) { 4783 final PreferredActivity pa = prefs.get(i); 4784 if (DEBUG_PREFERRED || debug) { 4785 Slog.v(TAG, "Checking PreferredActivity ds=" 4786 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4787 + "\n component=" + pa.mPref.mComponent); 4788 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4789 } 4790 if (pa.mPref.mMatch != match) { 4791 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4792 + Integer.toHexString(pa.mPref.mMatch)); 4793 continue; 4794 } 4795 // If it's not an "always" type preferred activity and that's what we're 4796 // looking for, skip it. 4797 if (always && !pa.mPref.mAlways) { 4798 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4799 continue; 4800 } 4801 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4802 flags | MATCH_DISABLED_COMPONENTS, userId); 4803 if (DEBUG_PREFERRED || debug) { 4804 Slog.v(TAG, "Found preferred activity:"); 4805 if (ai != null) { 4806 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4807 } else { 4808 Slog.v(TAG, " null"); 4809 } 4810 } 4811 if (ai == null) { 4812 // This previously registered preferred activity 4813 // component is no longer known. Most likely an update 4814 // to the app was installed and in the new version this 4815 // component no longer exists. Clean it up by removing 4816 // it from the preferred activities list, and skip it. 4817 Slog.w(TAG, "Removing dangling preferred activity: " 4818 + pa.mPref.mComponent); 4819 pir.removeFilter(pa); 4820 changed = true; 4821 continue; 4822 } 4823 for (int j=0; j<N; j++) { 4824 final ResolveInfo ri = query.get(j); 4825 if (!ri.activityInfo.applicationInfo.packageName 4826 .equals(ai.applicationInfo.packageName)) { 4827 continue; 4828 } 4829 if (!ri.activityInfo.name.equals(ai.name)) { 4830 continue; 4831 } 4832 4833 if (removeMatches) { 4834 pir.removeFilter(pa); 4835 changed = true; 4836 if (DEBUG_PREFERRED) { 4837 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4838 } 4839 break; 4840 } 4841 4842 // Okay we found a previously set preferred or last chosen app. 4843 // If the result set is different from when this 4844 // was created, we need to clear it and re-ask the 4845 // user their preference, if we're looking for an "always" type entry. 4846 if (always && !pa.mPref.sameSet(query)) { 4847 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4848 + intent + " type " + resolvedType); 4849 if (DEBUG_PREFERRED) { 4850 Slog.v(TAG, "Removing preferred activity since set changed " 4851 + pa.mPref.mComponent); 4852 } 4853 pir.removeFilter(pa); 4854 // Re-add the filter as a "last chosen" entry (!always) 4855 PreferredActivity lastChosen = new PreferredActivity( 4856 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4857 pir.addFilter(lastChosen); 4858 changed = true; 4859 return null; 4860 } 4861 4862 // Yay! Either the set matched or we're looking for the last chosen 4863 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4864 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4865 return ri; 4866 } 4867 } 4868 } finally { 4869 if (changed) { 4870 if (DEBUG_PREFERRED) { 4871 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4872 } 4873 scheduleWritePackageRestrictionsLocked(userId); 4874 } 4875 } 4876 } 4877 } 4878 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4879 return null; 4880 } 4881 4882 /* 4883 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4884 */ 4885 @Override 4886 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4887 int targetUserId) { 4888 mContext.enforceCallingOrSelfPermission( 4889 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4890 List<CrossProfileIntentFilter> matches = 4891 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4892 if (matches != null) { 4893 int size = matches.size(); 4894 for (int i = 0; i < size; i++) { 4895 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4896 } 4897 } 4898 if (hasWebURI(intent)) { 4899 // cross-profile app linking works only towards the parent. 4900 final UserInfo parent = getProfileParent(sourceUserId); 4901 synchronized(mPackages) { 4902 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 4903 intent, resolvedType, 0, sourceUserId, parent.id); 4904 return xpDomainInfo != null; 4905 } 4906 } 4907 return false; 4908 } 4909 4910 private UserInfo getProfileParent(int userId) { 4911 final long identity = Binder.clearCallingIdentity(); 4912 try { 4913 return sUserManager.getProfileParent(userId); 4914 } finally { 4915 Binder.restoreCallingIdentity(identity); 4916 } 4917 } 4918 4919 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4920 String resolvedType, int userId) { 4921 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4922 if (resolver != null) { 4923 return resolver.queryIntent(intent, resolvedType, false, userId); 4924 } 4925 return null; 4926 } 4927 4928 @Override 4929 public List<ResolveInfo> queryIntentActivities(Intent intent, 4930 String resolvedType, int flags, int userId) { 4931 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4932 flags = updateFlagsForResolve(flags, userId, intent); 4933 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4934 ComponentName comp = intent.getComponent(); 4935 if (comp == null) { 4936 if (intent.getSelector() != null) { 4937 intent = intent.getSelector(); 4938 comp = intent.getComponent(); 4939 } 4940 } 4941 4942 if (comp != null) { 4943 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4944 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4945 if (ai != null) { 4946 final ResolveInfo ri = new ResolveInfo(); 4947 ri.activityInfo = ai; 4948 list.add(ri); 4949 } 4950 return list; 4951 } 4952 4953 // reader 4954 synchronized (mPackages) { 4955 final String pkgName = intent.getPackage(); 4956 if (pkgName == null) { 4957 List<CrossProfileIntentFilter> matchingFilters = 4958 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4959 // Check for results that need to skip the current profile. 4960 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4961 resolvedType, flags, userId); 4962 if (xpResolveInfo != null) { 4963 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4964 result.add(xpResolveInfo); 4965 return filterIfNotSystemUser(result, userId); 4966 } 4967 4968 // Check for results in the current profile. 4969 List<ResolveInfo> result = mActivities.queryIntent( 4970 intent, resolvedType, flags, userId); 4971 result = filterIfNotSystemUser(result, userId); 4972 4973 // Check for cross profile results. 4974 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 4975 xpResolveInfo = queryCrossProfileIntents( 4976 matchingFilters, intent, resolvedType, flags, userId, 4977 hasNonNegativePriorityResult); 4978 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4979 boolean isVisibleToUser = filterIfNotSystemUser( 4980 Collections.singletonList(xpResolveInfo), userId).size() > 0; 4981 if (isVisibleToUser) { 4982 result.add(xpResolveInfo); 4983 Collections.sort(result, mResolvePrioritySorter); 4984 } 4985 } 4986 if (hasWebURI(intent)) { 4987 CrossProfileDomainInfo xpDomainInfo = null; 4988 final UserInfo parent = getProfileParent(userId); 4989 if (parent != null) { 4990 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 4991 flags, userId, parent.id); 4992 } 4993 if (xpDomainInfo != null) { 4994 if (xpResolveInfo != null) { 4995 // If we didn't remove it, the cross-profile ResolveInfo would be twice 4996 // in the result. 4997 result.remove(xpResolveInfo); 4998 } 4999 if (result.size() == 0) { 5000 result.add(xpDomainInfo.resolveInfo); 5001 return result; 5002 } 5003 } else if (result.size() <= 1) { 5004 return result; 5005 } 5006 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 5007 xpDomainInfo, userId); 5008 Collections.sort(result, mResolvePrioritySorter); 5009 } 5010 return result; 5011 } 5012 final PackageParser.Package pkg = mPackages.get(pkgName); 5013 if (pkg != null) { 5014 return filterIfNotSystemUser( 5015 mActivities.queryIntentForPackage( 5016 intent, resolvedType, flags, pkg.activities, userId), 5017 userId); 5018 } 5019 return new ArrayList<ResolveInfo>(); 5020 } 5021 } 5022 5023 private static class CrossProfileDomainInfo { 5024 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5025 ResolveInfo resolveInfo; 5026 /* Best domain verification status of the activities found in the other profile */ 5027 int bestDomainVerificationStatus; 5028 } 5029 5030 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5031 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5032 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5033 sourceUserId)) { 5034 return null; 5035 } 5036 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5037 resolvedType, flags, parentUserId); 5038 5039 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5040 return null; 5041 } 5042 CrossProfileDomainInfo result = null; 5043 int size = resultTargetUser.size(); 5044 for (int i = 0; i < size; i++) { 5045 ResolveInfo riTargetUser = resultTargetUser.get(i); 5046 // Intent filter verification is only for filters that specify a host. So don't return 5047 // those that handle all web uris. 5048 if (riTargetUser.handleAllWebDataURI) { 5049 continue; 5050 } 5051 String packageName = riTargetUser.activityInfo.packageName; 5052 PackageSetting ps = mSettings.mPackages.get(packageName); 5053 if (ps == null) { 5054 continue; 5055 } 5056 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5057 int status = (int)(verificationState >> 32); 5058 if (result == null) { 5059 result = new CrossProfileDomainInfo(); 5060 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5061 sourceUserId, parentUserId); 5062 result.bestDomainVerificationStatus = status; 5063 } else { 5064 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5065 result.bestDomainVerificationStatus); 5066 } 5067 } 5068 // Don't consider matches with status NEVER across profiles. 5069 if (result != null && result.bestDomainVerificationStatus 5070 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5071 return null; 5072 } 5073 return result; 5074 } 5075 5076 /** 5077 * Verification statuses are ordered from the worse to the best, except for 5078 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5079 */ 5080 private int bestDomainVerificationStatus(int status1, int status2) { 5081 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5082 return status2; 5083 } 5084 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5085 return status1; 5086 } 5087 return (int) MathUtils.max(status1, status2); 5088 } 5089 5090 private boolean isUserEnabled(int userId) { 5091 long callingId = Binder.clearCallingIdentity(); 5092 try { 5093 UserInfo userInfo = sUserManager.getUserInfo(userId); 5094 return userInfo != null && userInfo.isEnabled(); 5095 } finally { 5096 Binder.restoreCallingIdentity(callingId); 5097 } 5098 } 5099 5100 /** 5101 * Filter out activities with systemUserOnly flag set, when current user is not System. 5102 * 5103 * @return filtered list 5104 */ 5105 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5106 if (userId == UserHandle.USER_SYSTEM) { 5107 return resolveInfos; 5108 } 5109 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5110 ResolveInfo info = resolveInfos.get(i); 5111 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5112 resolveInfos.remove(i); 5113 } 5114 } 5115 return resolveInfos; 5116 } 5117 5118 /** 5119 * @param resolveInfos list of resolve infos in descending priority order 5120 * @return if the list contains a resolve info with non-negative priority 5121 */ 5122 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5123 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5124 } 5125 5126 private static boolean hasWebURI(Intent intent) { 5127 if (intent.getData() == null) { 5128 return false; 5129 } 5130 final String scheme = intent.getScheme(); 5131 if (TextUtils.isEmpty(scheme)) { 5132 return false; 5133 } 5134 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5135 } 5136 5137 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5138 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5139 int userId) { 5140 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5141 5142 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5143 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5144 candidates.size()); 5145 } 5146 5147 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5148 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5149 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5150 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5151 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5152 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5153 5154 synchronized (mPackages) { 5155 final int count = candidates.size(); 5156 // First, try to use linked apps. Partition the candidates into four lists: 5157 // one for the final results, one for the "do not use ever", one for "undefined status" 5158 // and finally one for "browser app type". 5159 for (int n=0; n<count; n++) { 5160 ResolveInfo info = candidates.get(n); 5161 String packageName = info.activityInfo.packageName; 5162 PackageSetting ps = mSettings.mPackages.get(packageName); 5163 if (ps != null) { 5164 // Add to the special match all list (Browser use case) 5165 if (info.handleAllWebDataURI) { 5166 matchAllList.add(info); 5167 continue; 5168 } 5169 // Try to get the status from User settings first 5170 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5171 int status = (int)(packedStatus >> 32); 5172 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5173 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5174 if (DEBUG_DOMAIN_VERIFICATION) { 5175 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5176 + " : linkgen=" + linkGeneration); 5177 } 5178 // Use link-enabled generation as preferredOrder, i.e. 5179 // prefer newly-enabled over earlier-enabled. 5180 info.preferredOrder = linkGeneration; 5181 alwaysList.add(info); 5182 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5183 if (DEBUG_DOMAIN_VERIFICATION) { 5184 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5185 } 5186 neverList.add(info); 5187 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5188 if (DEBUG_DOMAIN_VERIFICATION) { 5189 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5190 } 5191 alwaysAskList.add(info); 5192 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5193 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5194 if (DEBUG_DOMAIN_VERIFICATION) { 5195 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5196 } 5197 undefinedList.add(info); 5198 } 5199 } 5200 } 5201 5202 // We'll want to include browser possibilities in a few cases 5203 boolean includeBrowser = false; 5204 5205 // First try to add the "always" resolution(s) for the current user, if any 5206 if (alwaysList.size() > 0) { 5207 result.addAll(alwaysList); 5208 } else { 5209 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5210 result.addAll(undefinedList); 5211 // Maybe add one for the other profile. 5212 if (xpDomainInfo != null && ( 5213 xpDomainInfo.bestDomainVerificationStatus 5214 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5215 result.add(xpDomainInfo.resolveInfo); 5216 } 5217 includeBrowser = true; 5218 } 5219 5220 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5221 // If there were 'always' entries their preferred order has been set, so we also 5222 // back that off to make the alternatives equivalent 5223 if (alwaysAskList.size() > 0) { 5224 for (ResolveInfo i : result) { 5225 i.preferredOrder = 0; 5226 } 5227 result.addAll(alwaysAskList); 5228 includeBrowser = true; 5229 } 5230 5231 if (includeBrowser) { 5232 // Also add browsers (all of them or only the default one) 5233 if (DEBUG_DOMAIN_VERIFICATION) { 5234 Slog.v(TAG, " ...including browsers in candidate set"); 5235 } 5236 if ((matchFlags & MATCH_ALL) != 0) { 5237 result.addAll(matchAllList); 5238 } else { 5239 // Browser/generic handling case. If there's a default browser, go straight 5240 // to that (but only if there is no other higher-priority match). 5241 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5242 int maxMatchPrio = 0; 5243 ResolveInfo defaultBrowserMatch = null; 5244 final int numCandidates = matchAllList.size(); 5245 for (int n = 0; n < numCandidates; n++) { 5246 ResolveInfo info = matchAllList.get(n); 5247 // track the highest overall match priority... 5248 if (info.priority > maxMatchPrio) { 5249 maxMatchPrio = info.priority; 5250 } 5251 // ...and the highest-priority default browser match 5252 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5253 if (defaultBrowserMatch == null 5254 || (defaultBrowserMatch.priority < info.priority)) { 5255 if (debug) { 5256 Slog.v(TAG, "Considering default browser match " + info); 5257 } 5258 defaultBrowserMatch = info; 5259 } 5260 } 5261 } 5262 if (defaultBrowserMatch != null 5263 && defaultBrowserMatch.priority >= maxMatchPrio 5264 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5265 { 5266 if (debug) { 5267 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5268 } 5269 result.add(defaultBrowserMatch); 5270 } else { 5271 result.addAll(matchAllList); 5272 } 5273 } 5274 5275 // If there is nothing selected, add all candidates and remove the ones that the user 5276 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5277 if (result.size() == 0) { 5278 result.addAll(candidates); 5279 result.removeAll(neverList); 5280 } 5281 } 5282 } 5283 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5284 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5285 result.size()); 5286 for (ResolveInfo info : result) { 5287 Slog.v(TAG, " + " + info.activityInfo); 5288 } 5289 } 5290 return result; 5291 } 5292 5293 // Returns a packed value as a long: 5294 // 5295 // high 'int'-sized word: link status: undefined/ask/never/always. 5296 // low 'int'-sized word: relative priority among 'always' results. 5297 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5298 long result = ps.getDomainVerificationStatusForUser(userId); 5299 // if none available, get the master status 5300 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5301 if (ps.getIntentFilterVerificationInfo() != null) { 5302 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5303 } 5304 } 5305 return result; 5306 } 5307 5308 private ResolveInfo querySkipCurrentProfileIntents( 5309 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5310 int flags, int sourceUserId) { 5311 if (matchingFilters != null) { 5312 int size = matchingFilters.size(); 5313 for (int i = 0; i < size; i ++) { 5314 CrossProfileIntentFilter filter = matchingFilters.get(i); 5315 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5316 // Checking if there are activities in the target user that can handle the 5317 // intent. 5318 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5319 resolvedType, flags, sourceUserId); 5320 if (resolveInfo != null) { 5321 return resolveInfo; 5322 } 5323 } 5324 } 5325 } 5326 return null; 5327 } 5328 5329 // Return matching ResolveInfo in target user if any. 5330 private ResolveInfo queryCrossProfileIntents( 5331 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5332 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5333 if (matchingFilters != null) { 5334 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5335 // match the same intent. For performance reasons, it is better not to 5336 // run queryIntent twice for the same userId 5337 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5338 int size = matchingFilters.size(); 5339 for (int i = 0; i < size; i++) { 5340 CrossProfileIntentFilter filter = matchingFilters.get(i); 5341 int targetUserId = filter.getTargetUserId(); 5342 boolean skipCurrentProfile = 5343 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5344 boolean skipCurrentProfileIfNoMatchFound = 5345 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5346 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5347 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5348 // Checking if there are activities in the target user that can handle the 5349 // intent. 5350 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5351 resolvedType, flags, sourceUserId); 5352 if (resolveInfo != null) return resolveInfo; 5353 alreadyTriedUserIds.put(targetUserId, true); 5354 } 5355 } 5356 } 5357 return null; 5358 } 5359 5360 /** 5361 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5362 * will forward the intent to the filter's target user. 5363 * Otherwise, returns null. 5364 */ 5365 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5366 String resolvedType, int flags, int sourceUserId) { 5367 int targetUserId = filter.getTargetUserId(); 5368 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5369 resolvedType, flags, targetUserId); 5370 if (resultTargetUser != null && !resultTargetUser.isEmpty() 5371 && isUserEnabled(targetUserId)) { 5372 return createForwardingResolveInfoUnchecked(filter, sourceUserId, targetUserId); 5373 } 5374 return null; 5375 } 5376 5377 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5378 int sourceUserId, int targetUserId) { 5379 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5380 long ident = Binder.clearCallingIdentity(); 5381 boolean targetIsProfile; 5382 try { 5383 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5384 } finally { 5385 Binder.restoreCallingIdentity(ident); 5386 } 5387 String className; 5388 if (targetIsProfile) { 5389 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5390 } else { 5391 className = FORWARD_INTENT_TO_PARENT; 5392 } 5393 ComponentName forwardingActivityComponentName = new ComponentName( 5394 mAndroidApplication.packageName, className); 5395 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5396 sourceUserId); 5397 if (!targetIsProfile) { 5398 forwardingActivityInfo.showUserIcon = targetUserId; 5399 forwardingResolveInfo.noResourceId = true; 5400 } 5401 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5402 forwardingResolveInfo.priority = 0; 5403 forwardingResolveInfo.preferredOrder = 0; 5404 forwardingResolveInfo.match = 0; 5405 forwardingResolveInfo.isDefault = true; 5406 forwardingResolveInfo.filter = filter; 5407 forwardingResolveInfo.targetUserId = targetUserId; 5408 return forwardingResolveInfo; 5409 } 5410 5411 @Override 5412 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5413 Intent[] specifics, String[] specificTypes, Intent intent, 5414 String resolvedType, int flags, int userId) { 5415 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5416 flags = updateFlagsForResolve(flags, userId, intent); 5417 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 5418 false, "query intent activity options"); 5419 final String resultsAction = intent.getAction(); 5420 5421 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 5422 | PackageManager.GET_RESOLVED_FILTER, userId); 5423 5424 if (DEBUG_INTENT_MATCHING) { 5425 Log.v(TAG, "Query " + intent + ": " + results); 5426 } 5427 5428 int specificsPos = 0; 5429 int N; 5430 5431 // todo: note that the algorithm used here is O(N^2). This 5432 // isn't a problem in our current environment, but if we start running 5433 // into situations where we have more than 5 or 10 matches then this 5434 // should probably be changed to something smarter... 5435 5436 // First we go through and resolve each of the specific items 5437 // that were supplied, taking care of removing any corresponding 5438 // duplicate items in the generic resolve list. 5439 if (specifics != null) { 5440 for (int i=0; i<specifics.length; i++) { 5441 final Intent sintent = specifics[i]; 5442 if (sintent == null) { 5443 continue; 5444 } 5445 5446 if (DEBUG_INTENT_MATCHING) { 5447 Log.v(TAG, "Specific #" + i + ": " + sintent); 5448 } 5449 5450 String action = sintent.getAction(); 5451 if (resultsAction != null && resultsAction.equals(action)) { 5452 // If this action was explicitly requested, then don't 5453 // remove things that have it. 5454 action = null; 5455 } 5456 5457 ResolveInfo ri = null; 5458 ActivityInfo ai = null; 5459 5460 ComponentName comp = sintent.getComponent(); 5461 if (comp == null) { 5462 ri = resolveIntent( 5463 sintent, 5464 specificTypes != null ? specificTypes[i] : null, 5465 flags, userId); 5466 if (ri == null) { 5467 continue; 5468 } 5469 if (ri == mResolveInfo) { 5470 // ACK! Must do something better with this. 5471 } 5472 ai = ri.activityInfo; 5473 comp = new ComponentName(ai.applicationInfo.packageName, 5474 ai.name); 5475 } else { 5476 ai = getActivityInfo(comp, flags, userId); 5477 if (ai == null) { 5478 continue; 5479 } 5480 } 5481 5482 // Look for any generic query activities that are duplicates 5483 // of this specific one, and remove them from the results. 5484 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5485 N = results.size(); 5486 int j; 5487 for (j=specificsPos; j<N; j++) { 5488 ResolveInfo sri = results.get(j); 5489 if ((sri.activityInfo.name.equals(comp.getClassName()) 5490 && sri.activityInfo.applicationInfo.packageName.equals( 5491 comp.getPackageName())) 5492 || (action != null && sri.filter.matchAction(action))) { 5493 results.remove(j); 5494 if (DEBUG_INTENT_MATCHING) Log.v( 5495 TAG, "Removing duplicate item from " + j 5496 + " due to specific " + specificsPos); 5497 if (ri == null) { 5498 ri = sri; 5499 } 5500 j--; 5501 N--; 5502 } 5503 } 5504 5505 // Add this specific item to its proper place. 5506 if (ri == null) { 5507 ri = new ResolveInfo(); 5508 ri.activityInfo = ai; 5509 } 5510 results.add(specificsPos, ri); 5511 ri.specificIndex = i; 5512 specificsPos++; 5513 } 5514 } 5515 5516 // Now we go through the remaining generic results and remove any 5517 // duplicate actions that are found here. 5518 N = results.size(); 5519 for (int i=specificsPos; i<N-1; i++) { 5520 final ResolveInfo rii = results.get(i); 5521 if (rii.filter == null) { 5522 continue; 5523 } 5524 5525 // Iterate over all of the actions of this result's intent 5526 // filter... typically this should be just one. 5527 final Iterator<String> it = rii.filter.actionsIterator(); 5528 if (it == null) { 5529 continue; 5530 } 5531 while (it.hasNext()) { 5532 final String action = it.next(); 5533 if (resultsAction != null && resultsAction.equals(action)) { 5534 // If this action was explicitly requested, then don't 5535 // remove things that have it. 5536 continue; 5537 } 5538 for (int j=i+1; j<N; j++) { 5539 final ResolveInfo rij = results.get(j); 5540 if (rij.filter != null && rij.filter.hasAction(action)) { 5541 results.remove(j); 5542 if (DEBUG_INTENT_MATCHING) Log.v( 5543 TAG, "Removing duplicate item from " + j 5544 + " due to action " + action + " at " + i); 5545 j--; 5546 N--; 5547 } 5548 } 5549 } 5550 5551 // If the caller didn't request filter information, drop it now 5552 // so we don't have to marshall/unmarshall it. 5553 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5554 rii.filter = null; 5555 } 5556 } 5557 5558 // Filter out the caller activity if so requested. 5559 if (caller != null) { 5560 N = results.size(); 5561 for (int i=0; i<N; i++) { 5562 ActivityInfo ainfo = results.get(i).activityInfo; 5563 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5564 && caller.getClassName().equals(ainfo.name)) { 5565 results.remove(i); 5566 break; 5567 } 5568 } 5569 } 5570 5571 // If the caller didn't request filter information, 5572 // drop them now so we don't have to 5573 // marshall/unmarshall it. 5574 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5575 N = results.size(); 5576 for (int i=0; i<N; i++) { 5577 results.get(i).filter = null; 5578 } 5579 } 5580 5581 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5582 return results; 5583 } 5584 5585 @Override 5586 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 5587 int userId) { 5588 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5589 flags = updateFlagsForResolve(flags, userId, intent); 5590 ComponentName comp = intent.getComponent(); 5591 if (comp == null) { 5592 if (intent.getSelector() != null) { 5593 intent = intent.getSelector(); 5594 comp = intent.getComponent(); 5595 } 5596 } 5597 if (comp != null) { 5598 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5599 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5600 if (ai != null) { 5601 ResolveInfo ri = new ResolveInfo(); 5602 ri.activityInfo = ai; 5603 list.add(ri); 5604 } 5605 return list; 5606 } 5607 5608 // reader 5609 synchronized (mPackages) { 5610 String pkgName = intent.getPackage(); 5611 if (pkgName == null) { 5612 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5613 } 5614 final PackageParser.Package pkg = mPackages.get(pkgName); 5615 if (pkg != null) { 5616 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5617 userId); 5618 } 5619 return null; 5620 } 5621 } 5622 5623 @Override 5624 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5625 if (!sUserManager.exists(userId)) return null; 5626 flags = updateFlagsForResolve(flags, userId, intent); 5627 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 5628 if (query != null) { 5629 if (query.size() >= 1) { 5630 // If there is more than one service with the same priority, 5631 // just arbitrarily pick the first one. 5632 return query.get(0); 5633 } 5634 } 5635 return null; 5636 } 5637 5638 @Override 5639 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 5640 int userId) { 5641 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5642 flags = updateFlagsForResolve(flags, userId, intent); 5643 ComponentName comp = intent.getComponent(); 5644 if (comp == null) { 5645 if (intent.getSelector() != null) { 5646 intent = intent.getSelector(); 5647 comp = intent.getComponent(); 5648 } 5649 } 5650 if (comp != null) { 5651 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5652 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5653 if (si != null) { 5654 final ResolveInfo ri = new ResolveInfo(); 5655 ri.serviceInfo = si; 5656 list.add(ri); 5657 } 5658 return list; 5659 } 5660 5661 // reader 5662 synchronized (mPackages) { 5663 String pkgName = intent.getPackage(); 5664 if (pkgName == null) { 5665 return mServices.queryIntent(intent, resolvedType, flags, userId); 5666 } 5667 final PackageParser.Package pkg = mPackages.get(pkgName); 5668 if (pkg != null) { 5669 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5670 userId); 5671 } 5672 return null; 5673 } 5674 } 5675 5676 @Override 5677 public List<ResolveInfo> queryIntentContentProviders( 5678 Intent intent, String resolvedType, int flags, int userId) { 5679 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5680 flags = updateFlagsForResolve(flags, userId, intent); 5681 ComponentName comp = intent.getComponent(); 5682 if (comp == null) { 5683 if (intent.getSelector() != null) { 5684 intent = intent.getSelector(); 5685 comp = intent.getComponent(); 5686 } 5687 } 5688 if (comp != null) { 5689 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5690 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5691 if (pi != null) { 5692 final ResolveInfo ri = new ResolveInfo(); 5693 ri.providerInfo = pi; 5694 list.add(ri); 5695 } 5696 return list; 5697 } 5698 5699 // reader 5700 synchronized (mPackages) { 5701 String pkgName = intent.getPackage(); 5702 if (pkgName == null) { 5703 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5704 } 5705 final PackageParser.Package pkg = mPackages.get(pkgName); 5706 if (pkg != null) { 5707 return mProviders.queryIntentForPackage( 5708 intent, resolvedType, flags, pkg.providers, userId); 5709 } 5710 return null; 5711 } 5712 } 5713 5714 @Override 5715 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5716 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5717 flags = updateFlagsForPackage(flags, userId, null); 5718 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5719 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 5720 5721 // writer 5722 synchronized (mPackages) { 5723 ArrayList<PackageInfo> list; 5724 if (listUninstalled) { 5725 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5726 for (PackageSetting ps : mSettings.mPackages.values()) { 5727 PackageInfo pi; 5728 if (ps.pkg != null) { 5729 pi = generatePackageInfo(ps.pkg, flags, userId); 5730 } else { 5731 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5732 } 5733 if (pi != null) { 5734 list.add(pi); 5735 } 5736 } 5737 } else { 5738 list = new ArrayList<PackageInfo>(mPackages.size()); 5739 for (PackageParser.Package p : mPackages.values()) { 5740 PackageInfo pi = generatePackageInfo(p, flags, userId); 5741 if (pi != null) { 5742 list.add(pi); 5743 } 5744 } 5745 } 5746 5747 return new ParceledListSlice<PackageInfo>(list); 5748 } 5749 } 5750 5751 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5752 String[] permissions, boolean[] tmp, int flags, int userId) { 5753 int numMatch = 0; 5754 final PermissionsState permissionsState = ps.getPermissionsState(); 5755 for (int i=0; i<permissions.length; i++) { 5756 final String permission = permissions[i]; 5757 if (permissionsState.hasPermission(permission, userId)) { 5758 tmp[i] = true; 5759 numMatch++; 5760 } else { 5761 tmp[i] = false; 5762 } 5763 } 5764 if (numMatch == 0) { 5765 return; 5766 } 5767 PackageInfo pi; 5768 if (ps.pkg != null) { 5769 pi = generatePackageInfo(ps.pkg, flags, userId); 5770 } else { 5771 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5772 } 5773 // The above might return null in cases of uninstalled apps or install-state 5774 // skew across users/profiles. 5775 if (pi != null) { 5776 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5777 if (numMatch == permissions.length) { 5778 pi.requestedPermissions = permissions; 5779 } else { 5780 pi.requestedPermissions = new String[numMatch]; 5781 numMatch = 0; 5782 for (int i=0; i<permissions.length; i++) { 5783 if (tmp[i]) { 5784 pi.requestedPermissions[numMatch] = permissions[i]; 5785 numMatch++; 5786 } 5787 } 5788 } 5789 } 5790 list.add(pi); 5791 } 5792 } 5793 5794 @Override 5795 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5796 String[] permissions, int flags, int userId) { 5797 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5798 flags = updateFlagsForPackage(flags, userId, permissions); 5799 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5800 5801 // writer 5802 synchronized (mPackages) { 5803 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5804 boolean[] tmpBools = new boolean[permissions.length]; 5805 if (listUninstalled) { 5806 for (PackageSetting ps : mSettings.mPackages.values()) { 5807 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5808 } 5809 } else { 5810 for (PackageParser.Package pkg : mPackages.values()) { 5811 PackageSetting ps = (PackageSetting)pkg.mExtras; 5812 if (ps != null) { 5813 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5814 userId); 5815 } 5816 } 5817 } 5818 5819 return new ParceledListSlice<PackageInfo>(list); 5820 } 5821 } 5822 5823 @Override 5824 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5825 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5826 flags = updateFlagsForApplication(flags, userId, null); 5827 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5828 5829 // writer 5830 synchronized (mPackages) { 5831 ArrayList<ApplicationInfo> list; 5832 if (listUninstalled) { 5833 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5834 for (PackageSetting ps : mSettings.mPackages.values()) { 5835 ApplicationInfo ai; 5836 if (ps.pkg != null) { 5837 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5838 ps.readUserState(userId), userId); 5839 } else { 5840 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5841 } 5842 if (ai != null) { 5843 list.add(ai); 5844 } 5845 } 5846 } else { 5847 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5848 for (PackageParser.Package p : mPackages.values()) { 5849 if (p.mExtras != null) { 5850 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5851 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5852 if (ai != null) { 5853 list.add(ai); 5854 } 5855 } 5856 } 5857 } 5858 5859 return new ParceledListSlice<ApplicationInfo>(list); 5860 } 5861 } 5862 5863 @Override 5864 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 5865 if (DISABLE_EPHEMERAL_APPS) { 5866 return null; 5867 } 5868 5869 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 5870 "getEphemeralApplications"); 5871 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5872 "getEphemeralApplications"); 5873 synchronized (mPackages) { 5874 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 5875 .getEphemeralApplicationsLPw(userId); 5876 if (ephemeralApps != null) { 5877 return new ParceledListSlice<>(ephemeralApps); 5878 } 5879 } 5880 return null; 5881 } 5882 5883 @Override 5884 public boolean isEphemeralApplication(String packageName, int userId) { 5885 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5886 "isEphemeral"); 5887 if (DISABLE_EPHEMERAL_APPS) { 5888 return false; 5889 } 5890 5891 if (!isCallerSameApp(packageName)) { 5892 return false; 5893 } 5894 synchronized (mPackages) { 5895 PackageParser.Package pkg = mPackages.get(packageName); 5896 if (pkg != null) { 5897 return pkg.applicationInfo.isEphemeralApp(); 5898 } 5899 } 5900 return false; 5901 } 5902 5903 @Override 5904 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 5905 if (DISABLE_EPHEMERAL_APPS) { 5906 return null; 5907 } 5908 5909 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5910 "getCookie"); 5911 if (!isCallerSameApp(packageName)) { 5912 return null; 5913 } 5914 synchronized (mPackages) { 5915 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 5916 packageName, userId); 5917 } 5918 } 5919 5920 @Override 5921 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 5922 if (DISABLE_EPHEMERAL_APPS) { 5923 return true; 5924 } 5925 5926 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5927 "setCookie"); 5928 if (!isCallerSameApp(packageName)) { 5929 return false; 5930 } 5931 synchronized (mPackages) { 5932 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 5933 packageName, cookie, userId); 5934 } 5935 } 5936 5937 @Override 5938 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 5939 if (DISABLE_EPHEMERAL_APPS) { 5940 return null; 5941 } 5942 5943 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 5944 "getEphemeralApplicationIcon"); 5945 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5946 "getEphemeralApplicationIcon"); 5947 synchronized (mPackages) { 5948 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 5949 packageName, userId); 5950 } 5951 } 5952 5953 private boolean isCallerSameApp(String packageName) { 5954 PackageParser.Package pkg = mPackages.get(packageName); 5955 return pkg != null 5956 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 5957 } 5958 5959 public List<ApplicationInfo> getPersistentApplications(int flags) { 5960 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 5961 5962 // reader 5963 synchronized (mPackages) { 5964 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 5965 final int userId = UserHandle.getCallingUserId(); 5966 while (i.hasNext()) { 5967 final PackageParser.Package p = i.next(); 5968 if (p.applicationInfo != null 5969 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 5970 && (!mSafeMode || isSystemApp(p))) { 5971 PackageSetting ps = mSettings.mPackages.get(p.packageName); 5972 if (ps != null) { 5973 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5974 ps.readUserState(userId), userId); 5975 if (ai != null) { 5976 finalList.add(ai); 5977 } 5978 } 5979 } 5980 } 5981 } 5982 5983 return finalList; 5984 } 5985 5986 @Override 5987 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 5988 if (!sUserManager.exists(userId)) return null; 5989 flags = updateFlagsForComponent(flags, userId, name); 5990 // reader 5991 synchronized (mPackages) { 5992 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 5993 PackageSetting ps = provider != null 5994 ? mSettings.mPackages.get(provider.owner.packageName) 5995 : null; 5996 return ps != null 5997 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 5998 ? PackageParser.generateProviderInfo(provider, flags, 5999 ps.readUserState(userId), userId) 6000 : null; 6001 } 6002 } 6003 6004 /** 6005 * @deprecated 6006 */ 6007 @Deprecated 6008 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6009 // reader 6010 synchronized (mPackages) { 6011 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6012 .entrySet().iterator(); 6013 final int userId = UserHandle.getCallingUserId(); 6014 while (i.hasNext()) { 6015 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6016 PackageParser.Provider p = entry.getValue(); 6017 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6018 6019 if (ps != null && p.syncable 6020 && (!mSafeMode || (p.info.applicationInfo.flags 6021 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6022 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6023 ps.readUserState(userId), userId); 6024 if (info != null) { 6025 outNames.add(entry.getKey()); 6026 outInfo.add(info); 6027 } 6028 } 6029 } 6030 } 6031 } 6032 6033 @Override 6034 public ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6035 int uid, int flags) { 6036 final int userId = processName != null ? UserHandle.getUserId(uid) 6037 : UserHandle.getCallingUserId(); 6038 if (!sUserManager.exists(userId)) return null; 6039 flags = updateFlagsForComponent(flags, userId, processName); 6040 6041 ArrayList<ProviderInfo> finalList = null; 6042 // reader 6043 synchronized (mPackages) { 6044 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6045 while (i.hasNext()) { 6046 final PackageParser.Provider p = i.next(); 6047 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6048 if (ps != null && p.info.authority != null 6049 && (processName == null 6050 || (p.info.processName.equals(processName) 6051 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6052 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6053 if (finalList == null) { 6054 finalList = new ArrayList<ProviderInfo>(3); 6055 } 6056 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6057 ps.readUserState(userId), userId); 6058 if (info != null) { 6059 finalList.add(info); 6060 } 6061 } 6062 } 6063 } 6064 6065 if (finalList != null) { 6066 Collections.sort(finalList, mProviderInitOrderSorter); 6067 return new ParceledListSlice<ProviderInfo>(finalList); 6068 } 6069 6070 return null; 6071 } 6072 6073 @Override 6074 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6075 // reader 6076 synchronized (mPackages) { 6077 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6078 return PackageParser.generateInstrumentationInfo(i, flags); 6079 } 6080 } 6081 6082 @Override 6083 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 6084 int flags) { 6085 ArrayList<InstrumentationInfo> finalList = 6086 new ArrayList<InstrumentationInfo>(); 6087 6088 // reader 6089 synchronized (mPackages) { 6090 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6091 while (i.hasNext()) { 6092 final PackageParser.Instrumentation p = i.next(); 6093 if (targetPackage == null 6094 || targetPackage.equals(p.info.targetPackage)) { 6095 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6096 flags); 6097 if (ii != null) { 6098 finalList.add(ii); 6099 } 6100 } 6101 } 6102 } 6103 6104 return finalList; 6105 } 6106 6107 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6108 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6109 if (overlays == null) { 6110 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6111 return; 6112 } 6113 for (PackageParser.Package opkg : overlays.values()) { 6114 // Not much to do if idmap fails: we already logged the error 6115 // and we certainly don't want to abort installation of pkg simply 6116 // because an overlay didn't fit properly. For these reasons, 6117 // ignore the return value of createIdmapForPackagePairLI. 6118 createIdmapForPackagePairLI(pkg, opkg); 6119 } 6120 } 6121 6122 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6123 PackageParser.Package opkg) { 6124 if (!opkg.mTrustedOverlay) { 6125 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6126 opkg.baseCodePath + ": overlay not trusted"); 6127 return false; 6128 } 6129 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6130 if (overlaySet == null) { 6131 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6132 opkg.baseCodePath + " but target package has no known overlays"); 6133 return false; 6134 } 6135 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6136 // TODO: generate idmap for split APKs 6137 try { 6138 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6139 } catch (InstallerException e) { 6140 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6141 + opkg.baseCodePath); 6142 return false; 6143 } 6144 PackageParser.Package[] overlayArray = 6145 overlaySet.values().toArray(new PackageParser.Package[0]); 6146 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6147 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6148 return p1.mOverlayPriority - p2.mOverlayPriority; 6149 } 6150 }; 6151 Arrays.sort(overlayArray, cmp); 6152 6153 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6154 int i = 0; 6155 for (PackageParser.Package p : overlayArray) { 6156 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6157 } 6158 return true; 6159 } 6160 6161 private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6162 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6163 try { 6164 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6165 } finally { 6166 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6167 } 6168 } 6169 6170 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6171 final File[] files = dir.listFiles(); 6172 if (ArrayUtils.isEmpty(files)) { 6173 Log.d(TAG, "No files in app dir " + dir); 6174 return; 6175 } 6176 6177 if (DEBUG_PACKAGE_SCANNING) { 6178 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6179 + " flags=0x" + Integer.toHexString(parseFlags)); 6180 } 6181 6182 for (File file : files) { 6183 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6184 && !PackageInstallerService.isStageName(file.getName()); 6185 if (!isPackage) { 6186 // Ignore entries which are not packages 6187 continue; 6188 } 6189 try { 6190 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6191 scanFlags, currentTime, null); 6192 } catch (PackageManagerException e) { 6193 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6194 6195 // Delete invalid userdata apps 6196 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6197 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6198 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6199 removeCodePathLI(file); 6200 } 6201 } 6202 } 6203 } 6204 6205 private static File getSettingsProblemFile() { 6206 File dataDir = Environment.getDataDirectory(); 6207 File systemDir = new File(dataDir, "system"); 6208 File fname = new File(systemDir, "uiderrors.txt"); 6209 return fname; 6210 } 6211 6212 static void reportSettingsProblem(int priority, String msg) { 6213 logCriticalInfo(priority, msg); 6214 } 6215 6216 static void logCriticalInfo(int priority, String msg) { 6217 Slog.println(priority, TAG, msg); 6218 EventLogTags.writePmCriticalInfo(msg); 6219 try { 6220 File fname = getSettingsProblemFile(); 6221 FileOutputStream out = new FileOutputStream(fname, true); 6222 PrintWriter pw = new FastPrintWriter(out); 6223 SimpleDateFormat formatter = new SimpleDateFormat(); 6224 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6225 pw.println(dateString + ": " + msg); 6226 pw.close(); 6227 FileUtils.setPermissions( 6228 fname.toString(), 6229 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6230 -1, -1); 6231 } catch (java.io.IOException e) { 6232 } 6233 } 6234 6235 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 6236 PackageParser.Package pkg, File srcFile, int parseFlags) 6237 throws PackageManagerException { 6238 if (ps != null 6239 && ps.codePath.equals(srcFile) 6240 && ps.timeStamp == srcFile.lastModified() 6241 && !isCompatSignatureUpdateNeeded(pkg) 6242 && !isRecoverSignatureUpdateNeeded(pkg)) { 6243 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6244 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6245 ArraySet<PublicKey> signingKs; 6246 synchronized (mPackages) { 6247 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6248 } 6249 if (ps.signatures.mSignatures != null 6250 && ps.signatures.mSignatures.length != 0 6251 && signingKs != null) { 6252 // Optimization: reuse the existing cached certificates 6253 // if the package appears to be unchanged. 6254 pkg.mSignatures = ps.signatures.mSignatures; 6255 pkg.mSigningKeys = signingKs; 6256 return; 6257 } 6258 6259 Slog.w(TAG, "PackageSetting for " + ps.name 6260 + " is missing signatures. Collecting certs again to recover them."); 6261 } else { 6262 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6263 } 6264 6265 try { 6266 pp.collectCertificates(pkg, parseFlags); 6267 } catch (PackageParserException e) { 6268 throw PackageManagerException.from(e); 6269 } 6270 } 6271 6272 /** 6273 * Traces a package scan. 6274 * @see #scanPackageLI(File, int, int, long, UserHandle) 6275 */ 6276 private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags, 6277 long currentTime, UserHandle user) throws PackageManagerException { 6278 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6279 try { 6280 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6281 } finally { 6282 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6283 } 6284 } 6285 6286 /** 6287 * Scans a package and returns the newly parsed package. 6288 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6289 */ 6290 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6291 long currentTime, UserHandle user) throws PackageManagerException { 6292 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6293 parseFlags |= mDefParseFlags; 6294 PackageParser pp = new PackageParser(); 6295 pp.setSeparateProcesses(mSeparateProcesses); 6296 pp.setOnlyCoreApps(mOnlyCore); 6297 pp.setDisplayMetrics(mMetrics); 6298 6299 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6300 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6301 } 6302 6303 final PackageParser.Package pkg; 6304 try { 6305 pkg = pp.parsePackage(scanFile, parseFlags); 6306 } catch (PackageParserException e) { 6307 throw PackageManagerException.from(e); 6308 } 6309 6310 PackageSetting ps = null; 6311 PackageSetting updatedPkg; 6312 // reader 6313 synchronized (mPackages) { 6314 // Look to see if we already know about this package. 6315 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6316 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6317 // This package has been renamed to its original name. Let's 6318 // use that. 6319 ps = mSettings.peekPackageLPr(oldName); 6320 } 6321 // If there was no original package, see one for the real package name. 6322 if (ps == null) { 6323 ps = mSettings.peekPackageLPr(pkg.packageName); 6324 } 6325 // Check to see if this package could be hiding/updating a system 6326 // package. Must look for it either under the original or real 6327 // package name depending on our state. 6328 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6329 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6330 } 6331 boolean updatedPkgBetter = false; 6332 // First check if this is a system package that may involve an update 6333 if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6334 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6335 // it needs to drop FLAG_PRIVILEGED. 6336 if (locationIsPrivileged(scanFile)) { 6337 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6338 } else { 6339 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6340 } 6341 6342 if (ps != null && !ps.codePath.equals(scanFile)) { 6343 // The path has changed from what was last scanned... check the 6344 // version of the new path against what we have stored to determine 6345 // what to do. 6346 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6347 if (pkg.mVersionCode <= ps.versionCode) { 6348 // The system package has been updated and the code path does not match 6349 // Ignore entry. Skip it. 6350 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6351 + " ignored: updated version " + ps.versionCode 6352 + " better than this " + pkg.mVersionCode); 6353 if (!updatedPkg.codePath.equals(scanFile)) { 6354 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6355 + ps.name + " changing from " + updatedPkg.codePathString 6356 + " to " + scanFile); 6357 updatedPkg.codePath = scanFile; 6358 updatedPkg.codePathString = scanFile.toString(); 6359 updatedPkg.resourcePath = scanFile; 6360 updatedPkg.resourcePathString = scanFile.toString(); 6361 } 6362 updatedPkg.pkg = pkg; 6363 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6364 "Package " + ps.name + " at " + scanFile 6365 + " ignored: updated version " + ps.versionCode 6366 + " better than this " + pkg.mVersionCode); 6367 } else { 6368 // The current app on the system partition is better than 6369 // what we have updated to on the data partition; switch 6370 // back to the system partition version. 6371 // At this point, its safely assumed that package installation for 6372 // apps in system partition will go through. If not there won't be a working 6373 // version of the app 6374 // writer 6375 synchronized (mPackages) { 6376 // Just remove the loaded entries from package lists. 6377 mPackages.remove(ps.name); 6378 } 6379 6380 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6381 + " reverting from " + ps.codePathString 6382 + ": new version " + pkg.mVersionCode 6383 + " better than installed " + ps.versionCode); 6384 6385 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6386 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6387 synchronized (mInstallLock) { 6388 args.cleanUpResourcesLI(); 6389 } 6390 synchronized (mPackages) { 6391 mSettings.enableSystemPackageLPw(ps.name); 6392 } 6393 updatedPkgBetter = true; 6394 } 6395 } 6396 } 6397 6398 if (updatedPkg != null) { 6399 // An updated system app will not have the PARSE_IS_SYSTEM flag set 6400 // initially 6401 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 6402 6403 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 6404 // flag set initially 6405 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 6406 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 6407 } 6408 } 6409 6410 // Verify certificates against what was last scanned 6411 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 6412 6413 /* 6414 * A new system app appeared, but we already had a non-system one of the 6415 * same name installed earlier. 6416 */ 6417 boolean shouldHideSystemApp = false; 6418 if (updatedPkg == null && ps != null 6419 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 6420 /* 6421 * Check to make sure the signatures match first. If they don't, 6422 * wipe the installed application and its data. 6423 */ 6424 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 6425 != PackageManager.SIGNATURE_MATCH) { 6426 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 6427 + " signatures don't match existing userdata copy; removing"); 6428 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 6429 ps = null; 6430 } else { 6431 /* 6432 * If the newly-added system app is an older version than the 6433 * already installed version, hide it. It will be scanned later 6434 * and re-added like an update. 6435 */ 6436 if (pkg.mVersionCode <= ps.versionCode) { 6437 shouldHideSystemApp = true; 6438 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 6439 + " but new version " + pkg.mVersionCode + " better than installed " 6440 + ps.versionCode + "; hiding system"); 6441 } else { 6442 /* 6443 * The newly found system app is a newer version that the 6444 * one previously installed. Simply remove the 6445 * already-installed application and replace it with our own 6446 * while keeping the application data. 6447 */ 6448 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6449 + " reverting from " + ps.codePathString + ": new version " 6450 + pkg.mVersionCode + " better than installed " + ps.versionCode); 6451 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6452 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6453 synchronized (mInstallLock) { 6454 args.cleanUpResourcesLI(); 6455 } 6456 } 6457 } 6458 } 6459 6460 // The apk is forward locked (not public) if its code and resources 6461 // are kept in different files. (except for app in either system or 6462 // vendor path). 6463 // TODO grab this value from PackageSettings 6464 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6465 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 6466 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 6467 } 6468 } 6469 6470 // TODO: extend to support forward-locked splits 6471 String resourcePath = null; 6472 String baseResourcePath = null; 6473 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 6474 if (ps != null && ps.resourcePathString != null) { 6475 resourcePath = ps.resourcePathString; 6476 baseResourcePath = ps.resourcePathString; 6477 } else { 6478 // Should not happen at all. Just log an error. 6479 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 6480 } 6481 } else { 6482 resourcePath = pkg.codePath; 6483 baseResourcePath = pkg.baseCodePath; 6484 } 6485 6486 // Set application objects path explicitly. 6487 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 6488 pkg.applicationInfo.setCodePath(pkg.codePath); 6489 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 6490 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 6491 pkg.applicationInfo.setResourcePath(resourcePath); 6492 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 6493 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 6494 6495 // Note that we invoke the following method only if we are about to unpack an application 6496 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 6497 | SCAN_UPDATE_SIGNATURE, currentTime, user); 6498 6499 /* 6500 * If the system app should be overridden by a previously installed 6501 * data, hide the system app now and let the /data/app scan pick it up 6502 * again. 6503 */ 6504 if (shouldHideSystemApp) { 6505 synchronized (mPackages) { 6506 mSettings.disableSystemPackageLPw(pkg.packageName); 6507 } 6508 } 6509 6510 return scannedPkg; 6511 } 6512 6513 private static String fixProcessName(String defProcessName, 6514 String processName, int uid) { 6515 if (processName == null) { 6516 return defProcessName; 6517 } 6518 return processName; 6519 } 6520 6521 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 6522 throws PackageManagerException { 6523 if (pkgSetting.signatures.mSignatures != null) { 6524 // Already existing package. Make sure signatures match 6525 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 6526 == PackageManager.SIGNATURE_MATCH; 6527 if (!match) { 6528 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 6529 == PackageManager.SIGNATURE_MATCH; 6530 } 6531 if (!match) { 6532 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 6533 == PackageManager.SIGNATURE_MATCH; 6534 } 6535 if (!match) { 6536 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 6537 + pkg.packageName + " signatures do not match the " 6538 + "previously installed version; ignoring!"); 6539 } 6540 } 6541 6542 // Check for shared user signatures 6543 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 6544 // Already existing package. Make sure signatures match 6545 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6546 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 6547 if (!match) { 6548 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 6549 == PackageManager.SIGNATURE_MATCH; 6550 } 6551 if (!match) { 6552 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 6553 == PackageManager.SIGNATURE_MATCH; 6554 } 6555 if (!match) { 6556 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 6557 "Package " + pkg.packageName 6558 + " has no signatures that match those in shared user " 6559 + pkgSetting.sharedUser.name + "; ignoring!"); 6560 } 6561 } 6562 } 6563 6564 /** 6565 * Enforces that only the system UID or root's UID can call a method exposed 6566 * via Binder. 6567 * 6568 * @param message used as message if SecurityException is thrown 6569 * @throws SecurityException if the caller is not system or root 6570 */ 6571 private static final void enforceSystemOrRoot(String message) { 6572 final int uid = Binder.getCallingUid(); 6573 if (uid != Process.SYSTEM_UID && uid != 0) { 6574 throw new SecurityException(message); 6575 } 6576 } 6577 6578 @Override 6579 public void performFstrimIfNeeded() { 6580 enforceSystemOrRoot("Only the system can request fstrim"); 6581 6582 // Before everything else, see whether we need to fstrim. 6583 try { 6584 IMountService ms = PackageHelper.getMountService(); 6585 if (ms != null) { 6586 final boolean isUpgrade = isUpgrade(); 6587 boolean doTrim = isUpgrade; 6588 if (doTrim) { 6589 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 6590 } else { 6591 final long interval = android.provider.Settings.Global.getLong( 6592 mContext.getContentResolver(), 6593 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 6594 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 6595 if (interval > 0) { 6596 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 6597 if (timeSinceLast > interval) { 6598 doTrim = true; 6599 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 6600 + "; running immediately"); 6601 } 6602 } 6603 } 6604 if (doTrim) { 6605 if (!isFirstBoot()) { 6606 try { 6607 ActivityManagerNative.getDefault().showBootMessage( 6608 mContext.getResources().getString( 6609 R.string.android_upgrading_fstrim), true); 6610 } catch (RemoteException e) { 6611 } 6612 } 6613 ms.runMaintenance(); 6614 } 6615 } else { 6616 Slog.e(TAG, "Mount service unavailable!"); 6617 } 6618 } catch (RemoteException e) { 6619 // Can't happen; MountService is local 6620 } 6621 } 6622 6623 private ArraySet<String> getPackageNamesForIntent(Intent intent, int userId) { 6624 List<ResolveInfo> ris = null; 6625 try { 6626 ris = AppGlobals.getPackageManager().queryIntentReceivers( 6627 intent, null, 0, userId); 6628 } catch (RemoteException e) { 6629 } 6630 ArraySet<String> pkgNames = new ArraySet<String>(); 6631 if (ris != null) { 6632 for (ResolveInfo ri : ris) { 6633 pkgNames.add(ri.activityInfo.packageName); 6634 } 6635 } 6636 return pkgNames; 6637 } 6638 6639 @Override 6640 public void notifyPackageUse(String packageName) { 6641 synchronized (mPackages) { 6642 PackageParser.Package p = mPackages.get(packageName); 6643 if (p == null) { 6644 return; 6645 } 6646 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6647 } 6648 } 6649 6650 @Override 6651 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6652 return performDexOptTraced(packageName, instructionSet); 6653 } 6654 6655 public boolean performDexOpt(String packageName, String instructionSet) { 6656 return performDexOptTraced(packageName, instructionSet); 6657 } 6658 6659 private boolean performDexOptTraced(String packageName, String instructionSet) { 6660 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 6661 try { 6662 return performDexOptInternal(packageName, instructionSet); 6663 } finally { 6664 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6665 } 6666 } 6667 6668 private boolean performDexOptInternal(String packageName, String instructionSet) { 6669 PackageParser.Package p; 6670 final String targetInstructionSet; 6671 synchronized (mPackages) { 6672 p = mPackages.get(packageName); 6673 if (p == null) { 6674 return false; 6675 } 6676 mPackageUsage.write(false); 6677 6678 targetInstructionSet = instructionSet != null ? instructionSet : 6679 getPrimaryInstructionSet(p.applicationInfo); 6680 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 6681 return false; 6682 } 6683 } 6684 long callingId = Binder.clearCallingIdentity(); 6685 try { 6686 synchronized (mInstallLock) { 6687 final String[] instructionSets = new String[] { targetInstructionSet }; 6688 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 6689 true /* inclDependencies */); 6690 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6691 } 6692 } finally { 6693 Binder.restoreCallingIdentity(callingId); 6694 } 6695 } 6696 6697 public ArraySet<String> getPackagesThatNeedDexOpt() { 6698 ArraySet<String> pkgs = null; 6699 synchronized (mPackages) { 6700 for (PackageParser.Package p : mPackages.values()) { 6701 if (DEBUG_DEXOPT) { 6702 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 6703 } 6704 if (!p.mDexOptPerformed.isEmpty()) { 6705 continue; 6706 } 6707 if (pkgs == null) { 6708 pkgs = new ArraySet<String>(); 6709 } 6710 pkgs.add(p.packageName); 6711 } 6712 } 6713 return pkgs; 6714 } 6715 6716 public void shutdown() { 6717 mPackageUsage.write(true); 6718 } 6719 6720 @Override 6721 public void forceDexOpt(String packageName) { 6722 enforceSystemOrRoot("forceDexOpt"); 6723 6724 PackageParser.Package pkg; 6725 synchronized (mPackages) { 6726 pkg = mPackages.get(packageName); 6727 if (pkg == null) { 6728 throw new IllegalArgumentException("Unknown package: " + packageName); 6729 } 6730 } 6731 6732 synchronized (mInstallLock) { 6733 final String[] instructionSets = new String[] { 6734 getPrimaryInstructionSet(pkg.applicationInfo) }; 6735 6736 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 6737 6738 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 6739 true /* inclDependencies */); 6740 6741 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6742 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 6743 throw new IllegalStateException("Failed to dexopt: " + res); 6744 } 6745 } 6746 } 6747 6748 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 6749 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 6750 Slog.w(TAG, "Unable to update from " + oldPkg.name 6751 + " to " + newPkg.packageName 6752 + ": old package not in system partition"); 6753 return false; 6754 } else if (mPackages.get(oldPkg.name) != null) { 6755 Slog.w(TAG, "Unable to update from " + oldPkg.name 6756 + " to " + newPkg.packageName 6757 + ": old package still exists"); 6758 return false; 6759 } 6760 return true; 6761 } 6762 6763 private boolean removeDataDirsLI(String volumeUuid, String packageName) { 6764 // TODO: triage flags as part of 26466827 6765 final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE; 6766 6767 boolean res = true; 6768 final int[] users = sUserManager.getUserIds(); 6769 for (int user : users) { 6770 try { 6771 mInstaller.destroyAppData(volumeUuid, packageName, user, flags); 6772 } catch (InstallerException e) { 6773 Slog.w(TAG, "Failed to delete data directory", e); 6774 res = false; 6775 } 6776 } 6777 return res; 6778 } 6779 6780 void removeCodePathLI(File codePath) { 6781 if (codePath.isDirectory()) { 6782 try { 6783 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 6784 } catch (InstallerException e) { 6785 Slog.w(TAG, "Failed to remove code path", e); 6786 } 6787 } else { 6788 codePath.delete(); 6789 } 6790 } 6791 6792 void destroyAppDataLI(String volumeUuid, String packageName, int userId, int flags) { 6793 try { 6794 mInstaller.destroyAppData(volumeUuid, packageName, userId, flags); 6795 } catch (InstallerException e) { 6796 Slog.w(TAG, "Failed to destroy app data", e); 6797 } 6798 } 6799 6800 void restoreconAppDataLI(String volumeUuid, String packageName, int userId, int flags, 6801 int appId, String seinfo) { 6802 try { 6803 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, seinfo); 6804 } catch (InstallerException e) { 6805 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 6806 } 6807 } 6808 6809 private void deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 6810 // TODO: triage flags as part of 26466827 6811 final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE; 6812 6813 final int[] users = sUserManager.getUserIds(); 6814 for (int user : users) { 6815 try { 6816 mInstaller.clearAppData(volumeUuid, packageName, user, 6817 flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 6818 } catch (InstallerException e) { 6819 Slog.w(TAG, "Failed to delete code cache directory", e); 6820 } 6821 } 6822 } 6823 6824 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 6825 PackageParser.Package changingLib) { 6826 if (file.path != null) { 6827 usesLibraryFiles.add(file.path); 6828 return; 6829 } 6830 PackageParser.Package p = mPackages.get(file.apk); 6831 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 6832 // If we are doing this while in the middle of updating a library apk, 6833 // then we need to make sure to use that new apk for determining the 6834 // dependencies here. (We haven't yet finished committing the new apk 6835 // to the package manager state.) 6836 if (p == null || p.packageName.equals(changingLib.packageName)) { 6837 p = changingLib; 6838 } 6839 } 6840 if (p != null) { 6841 usesLibraryFiles.addAll(p.getAllCodePaths()); 6842 } 6843 } 6844 6845 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 6846 PackageParser.Package changingLib) throws PackageManagerException { 6847 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 6848 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 6849 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 6850 for (int i=0; i<N; i++) { 6851 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 6852 if (file == null) { 6853 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 6854 "Package " + pkg.packageName + " requires unavailable shared library " 6855 + pkg.usesLibraries.get(i) + "; failing!"); 6856 } 6857 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6858 } 6859 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 6860 for (int i=0; i<N; i++) { 6861 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 6862 if (file == null) { 6863 Slog.w(TAG, "Package " + pkg.packageName 6864 + " desires unavailable shared library " 6865 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 6866 } else { 6867 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6868 } 6869 } 6870 N = usesLibraryFiles.size(); 6871 if (N > 0) { 6872 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 6873 } else { 6874 pkg.usesLibraryFiles = null; 6875 } 6876 } 6877 } 6878 6879 private static boolean hasString(List<String> list, List<String> which) { 6880 if (list == null) { 6881 return false; 6882 } 6883 for (int i=list.size()-1; i>=0; i--) { 6884 for (int j=which.size()-1; j>=0; j--) { 6885 if (which.get(j).equals(list.get(i))) { 6886 return true; 6887 } 6888 } 6889 } 6890 return false; 6891 } 6892 6893 private void updateAllSharedLibrariesLPw() { 6894 for (PackageParser.Package pkg : mPackages.values()) { 6895 try { 6896 updateSharedLibrariesLPw(pkg, null); 6897 } catch (PackageManagerException e) { 6898 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6899 } 6900 } 6901 } 6902 6903 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 6904 PackageParser.Package changingPkg) { 6905 ArrayList<PackageParser.Package> res = null; 6906 for (PackageParser.Package pkg : mPackages.values()) { 6907 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 6908 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 6909 if (res == null) { 6910 res = new ArrayList<PackageParser.Package>(); 6911 } 6912 res.add(pkg); 6913 try { 6914 updateSharedLibrariesLPw(pkg, changingPkg); 6915 } catch (PackageManagerException e) { 6916 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6917 } 6918 } 6919 } 6920 return res; 6921 } 6922 6923 /** 6924 * Derive the value of the {@code cpuAbiOverride} based on the provided 6925 * value and an optional stored value from the package settings. 6926 */ 6927 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 6928 String cpuAbiOverride = null; 6929 6930 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 6931 cpuAbiOverride = null; 6932 } else if (abiOverride != null) { 6933 cpuAbiOverride = abiOverride; 6934 } else if (settings != null) { 6935 cpuAbiOverride = settings.cpuAbiOverrideString; 6936 } 6937 6938 return cpuAbiOverride; 6939 } 6940 6941 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags, 6942 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6943 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6944 try { 6945 return scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user); 6946 } finally { 6947 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6948 } 6949 } 6950 6951 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 6952 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6953 boolean success = false; 6954 try { 6955 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 6956 currentTime, user); 6957 success = true; 6958 return res; 6959 } finally { 6960 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 6961 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 6962 } 6963 } 6964 } 6965 6966 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 6967 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6968 final File scanFile = new File(pkg.codePath); 6969 if (pkg.applicationInfo.getCodePath() == null || 6970 pkg.applicationInfo.getResourcePath() == null) { 6971 // Bail out. The resource and code paths haven't been set. 6972 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 6973 "Code and resource paths haven't been set correctly"); 6974 } 6975 6976 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 6977 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 6978 } else { 6979 // Only allow system apps to be flagged as core apps. 6980 pkg.coreApp = false; 6981 } 6982 6983 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 6984 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6985 } 6986 6987 if (mCustomResolverComponentName != null && 6988 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 6989 setUpCustomResolverActivity(pkg); 6990 } 6991 6992 if (pkg.packageName.equals("android")) { 6993 synchronized (mPackages) { 6994 if (mAndroidApplication != null) { 6995 Slog.w(TAG, "*************************************************"); 6996 Slog.w(TAG, "Core android package being redefined. Skipping."); 6997 Slog.w(TAG, " file=" + scanFile); 6998 Slog.w(TAG, "*************************************************"); 6999 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7000 "Core android package being redefined. Skipping."); 7001 } 7002 7003 // Set up information for our fall-back user intent resolution activity. 7004 mPlatformPackage = pkg; 7005 pkg.mVersionCode = mSdkVersion; 7006 mAndroidApplication = pkg.applicationInfo; 7007 7008 if (!mResolverReplaced) { 7009 mResolveActivity.applicationInfo = mAndroidApplication; 7010 mResolveActivity.name = ResolverActivity.class.getName(); 7011 mResolveActivity.packageName = mAndroidApplication.packageName; 7012 mResolveActivity.processName = "system:ui"; 7013 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7014 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 7015 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 7016 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 7017 mResolveActivity.exported = true; 7018 mResolveActivity.enabled = true; 7019 mResolveInfo.activityInfo = mResolveActivity; 7020 mResolveInfo.priority = 0; 7021 mResolveInfo.preferredOrder = 0; 7022 mResolveInfo.match = 0; 7023 mResolveComponentName = new ComponentName( 7024 mAndroidApplication.packageName, mResolveActivity.name); 7025 } 7026 } 7027 } 7028 7029 if (DEBUG_PACKAGE_SCANNING) { 7030 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7031 Log.d(TAG, "Scanning package " + pkg.packageName); 7032 } 7033 7034 if (mPackages.containsKey(pkg.packageName) 7035 || mSharedLibraries.containsKey(pkg.packageName)) { 7036 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7037 "Application package " + pkg.packageName 7038 + " already installed. Skipping duplicate."); 7039 } 7040 7041 // If we're only installing presumed-existing packages, require that the 7042 // scanned APK is both already known and at the path previously established 7043 // for it. Previously unknown packages we pick up normally, but if we have an 7044 // a priori expectation about this package's install presence, enforce it. 7045 // With a singular exception for new system packages. When an OTA contains 7046 // a new system package, we allow the codepath to change from a system location 7047 // to the user-installed location. If we don't allow this change, any newer, 7048 // user-installed version of the application will be ignored. 7049 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 7050 if (mExpectingBetter.containsKey(pkg.packageName)) { 7051 logCriticalInfo(Log.WARN, 7052 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 7053 } else { 7054 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 7055 if (known != null) { 7056 if (DEBUG_PACKAGE_SCANNING) { 7057 Log.d(TAG, "Examining " + pkg.codePath 7058 + " and requiring known paths " + known.codePathString 7059 + " & " + known.resourcePathString); 7060 } 7061 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 7062 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 7063 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 7064 "Application package " + pkg.packageName 7065 + " found at " + pkg.applicationInfo.getCodePath() 7066 + " but expected at " + known.codePathString + "; ignoring."); 7067 } 7068 } 7069 } 7070 } 7071 7072 // Initialize package source and resource directories 7073 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 7074 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 7075 7076 SharedUserSetting suid = null; 7077 PackageSetting pkgSetting = null; 7078 7079 if (!isSystemApp(pkg)) { 7080 // Only system apps can use these features. 7081 pkg.mOriginalPackages = null; 7082 pkg.mRealPackage = null; 7083 pkg.mAdoptPermissions = null; 7084 } 7085 7086 // writer 7087 synchronized (mPackages) { 7088 if (pkg.mSharedUserId != null) { 7089 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 7090 if (suid == null) { 7091 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7092 "Creating application package " + pkg.packageName 7093 + " for shared user failed"); 7094 } 7095 if (DEBUG_PACKAGE_SCANNING) { 7096 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7097 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 7098 + "): packages=" + suid.packages); 7099 } 7100 } 7101 7102 // Check if we are renaming from an original package name. 7103 PackageSetting origPackage = null; 7104 String realName = null; 7105 if (pkg.mOriginalPackages != null) { 7106 // This package may need to be renamed to a previously 7107 // installed name. Let's check on that... 7108 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 7109 if (pkg.mOriginalPackages.contains(renamed)) { 7110 // This package had originally been installed as the 7111 // original name, and we have already taken care of 7112 // transitioning to the new one. Just update the new 7113 // one to continue using the old name. 7114 realName = pkg.mRealPackage; 7115 if (!pkg.packageName.equals(renamed)) { 7116 // Callers into this function may have already taken 7117 // care of renaming the package; only do it here if 7118 // it is not already done. 7119 pkg.setPackageName(renamed); 7120 } 7121 7122 } else { 7123 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 7124 if ((origPackage = mSettings.peekPackageLPr( 7125 pkg.mOriginalPackages.get(i))) != null) { 7126 // We do have the package already installed under its 7127 // original name... should we use it? 7128 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 7129 // New package is not compatible with original. 7130 origPackage = null; 7131 continue; 7132 } else if (origPackage.sharedUser != null) { 7133 // Make sure uid is compatible between packages. 7134 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 7135 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 7136 + " to " + pkg.packageName + ": old uid " 7137 + origPackage.sharedUser.name 7138 + " differs from " + pkg.mSharedUserId); 7139 origPackage = null; 7140 continue; 7141 } 7142 } else { 7143 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 7144 + pkg.packageName + " to old name " + origPackage.name); 7145 } 7146 break; 7147 } 7148 } 7149 } 7150 } 7151 7152 if (mTransferedPackages.contains(pkg.packageName)) { 7153 Slog.w(TAG, "Package " + pkg.packageName 7154 + " was transferred to another, but its .apk remains"); 7155 } 7156 7157 // Just create the setting, don't add it yet. For already existing packages 7158 // the PkgSetting exists already and doesn't have to be created. 7159 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 7160 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 7161 pkg.applicationInfo.primaryCpuAbi, 7162 pkg.applicationInfo.secondaryCpuAbi, 7163 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 7164 user, false); 7165 if (pkgSetting == null) { 7166 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7167 "Creating application package " + pkg.packageName + " failed"); 7168 } 7169 7170 if (pkgSetting.origPackage != null) { 7171 // If we are first transitioning from an original package, 7172 // fix up the new package's name now. We need to do this after 7173 // looking up the package under its new name, so getPackageLP 7174 // can take care of fiddling things correctly. 7175 pkg.setPackageName(origPackage.name); 7176 7177 // File a report about this. 7178 String msg = "New package " + pkgSetting.realName 7179 + " renamed to replace old package " + pkgSetting.name; 7180 reportSettingsProblem(Log.WARN, msg); 7181 7182 // Make a note of it. 7183 mTransferedPackages.add(origPackage.name); 7184 7185 // No longer need to retain this. 7186 pkgSetting.origPackage = null; 7187 } 7188 7189 if (realName != null) { 7190 // Make a note of it. 7191 mTransferedPackages.add(pkg.packageName); 7192 } 7193 7194 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 7195 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 7196 } 7197 7198 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7199 // Check all shared libraries and map to their actual file path. 7200 // We only do this here for apps not on a system dir, because those 7201 // are the only ones that can fail an install due to this. We 7202 // will take care of the system apps by updating all of their 7203 // library paths after the scan is done. 7204 updateSharedLibrariesLPw(pkg, null); 7205 } 7206 7207 if (mFoundPolicyFile) { 7208 SELinuxMMAC.assignSeinfoValue(pkg); 7209 } 7210 7211 pkg.applicationInfo.uid = pkgSetting.appId; 7212 pkg.mExtras = pkgSetting; 7213 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 7214 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 7215 // We just determined the app is signed correctly, so bring 7216 // over the latest parsed certs. 7217 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7218 } else { 7219 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7220 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7221 "Package " + pkg.packageName + " upgrade keys do not match the " 7222 + "previously installed version"); 7223 } else { 7224 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7225 String msg = "System package " + pkg.packageName 7226 + " signature changed; retaining data."; 7227 reportSettingsProblem(Log.WARN, msg); 7228 } 7229 } 7230 } else { 7231 try { 7232 verifySignaturesLP(pkgSetting, pkg); 7233 // We just determined the app is signed correctly, so bring 7234 // over the latest parsed certs. 7235 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7236 } catch (PackageManagerException e) { 7237 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7238 throw e; 7239 } 7240 // The signature has changed, but this package is in the system 7241 // image... let's recover! 7242 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7243 // However... if this package is part of a shared user, but it 7244 // doesn't match the signature of the shared user, let's fail. 7245 // What this means is that you can't change the signatures 7246 // associated with an overall shared user, which doesn't seem all 7247 // that unreasonable. 7248 if (pkgSetting.sharedUser != null) { 7249 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7250 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 7251 throw new PackageManagerException( 7252 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 7253 "Signature mismatch for shared user: " 7254 + pkgSetting.sharedUser); 7255 } 7256 } 7257 // File a report about this. 7258 String msg = "System package " + pkg.packageName 7259 + " signature changed; retaining data."; 7260 reportSettingsProblem(Log.WARN, msg); 7261 } 7262 } 7263 // Verify that this new package doesn't have any content providers 7264 // that conflict with existing packages. Only do this if the 7265 // package isn't already installed, since we don't want to break 7266 // things that are installed. 7267 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 7268 final int N = pkg.providers.size(); 7269 int i; 7270 for (i=0; i<N; i++) { 7271 PackageParser.Provider p = pkg.providers.get(i); 7272 if (p.info.authority != null) { 7273 String names[] = p.info.authority.split(";"); 7274 for (int j = 0; j < names.length; j++) { 7275 if (mProvidersByAuthority.containsKey(names[j])) { 7276 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7277 final String otherPackageName = 7278 ((other != null && other.getComponentName() != null) ? 7279 other.getComponentName().getPackageName() : "?"); 7280 throw new PackageManagerException( 7281 INSTALL_FAILED_CONFLICTING_PROVIDER, 7282 "Can't install because provider name " + names[j] 7283 + " (in package " + pkg.applicationInfo.packageName 7284 + ") is already used by " + otherPackageName); 7285 } 7286 } 7287 } 7288 } 7289 } 7290 7291 if (pkg.mAdoptPermissions != null) { 7292 // This package wants to adopt ownership of permissions from 7293 // another package. 7294 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 7295 final String origName = pkg.mAdoptPermissions.get(i); 7296 final PackageSetting orig = mSettings.peekPackageLPr(origName); 7297 if (orig != null) { 7298 if (verifyPackageUpdateLPr(orig, pkg)) { 7299 Slog.i(TAG, "Adopting permissions from " + origName + " to " 7300 + pkg.packageName); 7301 mSettings.transferPermissionsLPw(origName, pkg.packageName); 7302 } 7303 } 7304 } 7305 } 7306 } 7307 7308 final String pkgName = pkg.packageName; 7309 7310 final long scanFileTime = scanFile.lastModified(); 7311 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 7312 pkg.applicationInfo.processName = fixProcessName( 7313 pkg.applicationInfo.packageName, 7314 pkg.applicationInfo.processName, 7315 pkg.applicationInfo.uid); 7316 7317 if (pkg != mPlatformPackage) { 7318 // Get all of our default paths setup 7319 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 7320 } 7321 7322 final String path = scanFile.getPath(); 7323 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 7324 7325 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 7326 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 7327 7328 // Some system apps still use directory structure for native libraries 7329 // in which case we might end up not detecting abi solely based on apk 7330 // structure. Try to detect abi based on directory structure. 7331 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 7332 pkg.applicationInfo.primaryCpuAbi == null) { 7333 setBundledAppAbisAndRoots(pkg, pkgSetting); 7334 setNativeLibraryPaths(pkg); 7335 } 7336 7337 } else { 7338 if ((scanFlags & SCAN_MOVE) != 0) { 7339 // We haven't run dex-opt for this move (since we've moved the compiled output too) 7340 // but we already have this packages package info in the PackageSetting. We just 7341 // use that and derive the native library path based on the new codepath. 7342 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 7343 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 7344 } 7345 7346 // Set native library paths again. For moves, the path will be updated based on the 7347 // ABIs we've determined above. For non-moves, the path will be updated based on the 7348 // ABIs we determined during compilation, but the path will depend on the final 7349 // package path (after the rename away from the stage path). 7350 setNativeLibraryPaths(pkg); 7351 } 7352 7353 // This is a special case for the "system" package, where the ABI is 7354 // dictated by the zygote configuration (and init.rc). We should keep track 7355 // of this ABI so that we can deal with "normal" applications that run under 7356 // the same UID correctly. 7357 if (mPlatformPackage == pkg) { 7358 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 7359 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 7360 } 7361 7362 // If there's a mismatch between the abi-override in the package setting 7363 // and the abiOverride specified for the install. Warn about this because we 7364 // would've already compiled the app without taking the package setting into 7365 // account. 7366 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 7367 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 7368 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 7369 " for package " + pkg.packageName); 7370 } 7371 } 7372 7373 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7374 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7375 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 7376 7377 // Copy the derived override back to the parsed package, so that we can 7378 // update the package settings accordingly. 7379 pkg.cpuAbiOverride = cpuAbiOverride; 7380 7381 if (DEBUG_ABI_SELECTION) { 7382 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 7383 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 7384 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 7385 } 7386 7387 // Push the derived path down into PackageSettings so we know what to 7388 // clean up at uninstall time. 7389 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 7390 7391 if (DEBUG_ABI_SELECTION) { 7392 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 7393 " primary=" + pkg.applicationInfo.primaryCpuAbi + 7394 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 7395 } 7396 7397 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 7398 // We don't do this here during boot because we can do it all 7399 // at once after scanning all existing packages. 7400 // 7401 // We also do this *before* we perform dexopt on this package, so that 7402 // we can avoid redundant dexopts, and also to make sure we've got the 7403 // code and package path correct. 7404 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 7405 pkg, true /* boot complete */); 7406 } 7407 7408 if (mFactoryTest && pkg.requestedPermissions.contains( 7409 android.Manifest.permission.FACTORY_TEST)) { 7410 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 7411 } 7412 7413 ArrayList<PackageParser.Package> clientLibPkgs = null; 7414 7415 // writer 7416 synchronized (mPackages) { 7417 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7418 // Only system apps can add new shared libraries. 7419 if (pkg.libraryNames != null) { 7420 for (int i=0; i<pkg.libraryNames.size(); i++) { 7421 String name = pkg.libraryNames.get(i); 7422 boolean allowed = false; 7423 if (pkg.isUpdatedSystemApp()) { 7424 // New library entries can only be added through the 7425 // system image. This is important to get rid of a lot 7426 // of nasty edge cases: for example if we allowed a non- 7427 // system update of the app to add a library, then uninstalling 7428 // the update would make the library go away, and assumptions 7429 // we made such as through app install filtering would now 7430 // have allowed apps on the device which aren't compatible 7431 // with it. Better to just have the restriction here, be 7432 // conservative, and create many fewer cases that can negatively 7433 // impact the user experience. 7434 final PackageSetting sysPs = mSettings 7435 .getDisabledSystemPkgLPr(pkg.packageName); 7436 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 7437 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 7438 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 7439 allowed = true; 7440 break; 7441 } 7442 } 7443 } 7444 } else { 7445 allowed = true; 7446 } 7447 if (allowed) { 7448 if (!mSharedLibraries.containsKey(name)) { 7449 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 7450 } else if (!name.equals(pkg.packageName)) { 7451 Slog.w(TAG, "Package " + pkg.packageName + " library " 7452 + name + " already exists; skipping"); 7453 } 7454 } else { 7455 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 7456 + name + " that is not declared on system image; skipping"); 7457 } 7458 } 7459 if ((scanFlags & SCAN_BOOTING) == 0) { 7460 // If we are not booting, we need to update any applications 7461 // that are clients of our shared library. If we are booting, 7462 // this will all be done once the scan is complete. 7463 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 7464 } 7465 } 7466 } 7467 } 7468 7469 // Request the ActivityManager to kill the process(only for existing packages) 7470 // so that we do not end up in a confused state while the user is still using the older 7471 // version of the application while the new one gets installed. 7472 if ((scanFlags & SCAN_REPLACING) != 0) { 7473 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication"); 7474 7475 killApplication(pkg.applicationInfo.packageName, 7476 pkg.applicationInfo.uid, "replace pkg"); 7477 7478 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7479 } 7480 7481 // Also need to kill any apps that are dependent on the library. 7482 if (clientLibPkgs != null) { 7483 for (int i=0; i<clientLibPkgs.size(); i++) { 7484 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7485 killApplication(clientPkg.applicationInfo.packageName, 7486 clientPkg.applicationInfo.uid, "update lib"); 7487 } 7488 } 7489 7490 // Make sure we're not adding any bogus keyset info 7491 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7492 ksms.assertScannedPackageValid(pkg); 7493 7494 // writer 7495 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 7496 7497 boolean createIdmapFailed = false; 7498 synchronized (mPackages) { 7499 // We don't expect installation to fail beyond this point 7500 7501 // Add the new setting to mSettings 7502 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 7503 // Add the new setting to mPackages 7504 mPackages.put(pkg.applicationInfo.packageName, pkg); 7505 // Make sure we don't accidentally delete its data. 7506 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 7507 while (iter.hasNext()) { 7508 PackageCleanItem item = iter.next(); 7509 if (pkgName.equals(item.packageName)) { 7510 iter.remove(); 7511 } 7512 } 7513 7514 // Take care of first install / last update times. 7515 if (currentTime != 0) { 7516 if (pkgSetting.firstInstallTime == 0) { 7517 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7518 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7519 pkgSetting.lastUpdateTime = currentTime; 7520 } 7521 } else if (pkgSetting.firstInstallTime == 0) { 7522 // We need *something*. Take time time stamp of the file. 7523 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7524 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7525 if (scanFileTime != pkgSetting.timeStamp) { 7526 // A package on the system image has changed; consider this 7527 // to be an update. 7528 pkgSetting.lastUpdateTime = scanFileTime; 7529 } 7530 } 7531 7532 // Add the package's KeySets to the global KeySetManagerService 7533 ksms.addScannedPackageLPw(pkg); 7534 7535 int N = pkg.providers.size(); 7536 StringBuilder r = null; 7537 int i; 7538 for (i=0; i<N; i++) { 7539 PackageParser.Provider p = pkg.providers.get(i); 7540 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7541 p.info.processName, pkg.applicationInfo.uid); 7542 mProviders.addProvider(p); 7543 p.syncable = p.info.isSyncable; 7544 if (p.info.authority != null) { 7545 String names[] = p.info.authority.split(";"); 7546 p.info.authority = null; 7547 for (int j = 0; j < names.length; j++) { 7548 if (j == 1 && p.syncable) { 7549 // We only want the first authority for a provider to possibly be 7550 // syncable, so if we already added this provider using a different 7551 // authority clear the syncable flag. We copy the provider before 7552 // changing it because the mProviders object contains a reference 7553 // to a provider that we don't want to change. 7554 // Only do this for the second authority since the resulting provider 7555 // object can be the same for all future authorities for this provider. 7556 p = new PackageParser.Provider(p); 7557 p.syncable = false; 7558 } 7559 if (!mProvidersByAuthority.containsKey(names[j])) { 7560 mProvidersByAuthority.put(names[j], p); 7561 if (p.info.authority == null) { 7562 p.info.authority = names[j]; 7563 } else { 7564 p.info.authority = p.info.authority + ";" + names[j]; 7565 } 7566 if (DEBUG_PACKAGE_SCANNING) { 7567 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7568 Log.d(TAG, "Registered content provider: " + names[j] 7569 + ", className = " + p.info.name + ", isSyncable = " 7570 + p.info.isSyncable); 7571 } 7572 } else { 7573 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7574 Slog.w(TAG, "Skipping provider name " + names[j] + 7575 " (in package " + pkg.applicationInfo.packageName + 7576 "): name already used by " 7577 + ((other != null && other.getComponentName() != null) 7578 ? other.getComponentName().getPackageName() : "?")); 7579 } 7580 } 7581 } 7582 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7583 if (r == null) { 7584 r = new StringBuilder(256); 7585 } else { 7586 r.append(' '); 7587 } 7588 r.append(p.info.name); 7589 } 7590 } 7591 if (r != null) { 7592 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7593 } 7594 7595 N = pkg.services.size(); 7596 r = null; 7597 for (i=0; i<N; i++) { 7598 PackageParser.Service s = pkg.services.get(i); 7599 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 7600 s.info.processName, pkg.applicationInfo.uid); 7601 mServices.addService(s); 7602 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7603 if (r == null) { 7604 r = new StringBuilder(256); 7605 } else { 7606 r.append(' '); 7607 } 7608 r.append(s.info.name); 7609 } 7610 } 7611 if (r != null) { 7612 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 7613 } 7614 7615 N = pkg.receivers.size(); 7616 r = null; 7617 for (i=0; i<N; i++) { 7618 PackageParser.Activity a = pkg.receivers.get(i); 7619 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7620 a.info.processName, pkg.applicationInfo.uid); 7621 mReceivers.addActivity(a, "receiver"); 7622 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7623 if (r == null) { 7624 r = new StringBuilder(256); 7625 } else { 7626 r.append(' '); 7627 } 7628 r.append(a.info.name); 7629 } 7630 } 7631 if (r != null) { 7632 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 7633 } 7634 7635 N = pkg.activities.size(); 7636 r = null; 7637 for (i=0; i<N; i++) { 7638 PackageParser.Activity a = pkg.activities.get(i); 7639 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7640 a.info.processName, pkg.applicationInfo.uid); 7641 mActivities.addActivity(a, "activity"); 7642 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7643 if (r == null) { 7644 r = new StringBuilder(256); 7645 } else { 7646 r.append(' '); 7647 } 7648 r.append(a.info.name); 7649 } 7650 } 7651 if (r != null) { 7652 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 7653 } 7654 7655 N = pkg.permissionGroups.size(); 7656 r = null; 7657 for (i=0; i<N; i++) { 7658 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 7659 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 7660 if (cur == null) { 7661 mPermissionGroups.put(pg.info.name, pg); 7662 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7663 if (r == null) { 7664 r = new StringBuilder(256); 7665 } else { 7666 r.append(' '); 7667 } 7668 r.append(pg.info.name); 7669 } 7670 } else { 7671 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 7672 + pg.info.packageName + " ignored: original from " 7673 + cur.info.packageName); 7674 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7675 if (r == null) { 7676 r = new StringBuilder(256); 7677 } else { 7678 r.append(' '); 7679 } 7680 r.append("DUP:"); 7681 r.append(pg.info.name); 7682 } 7683 } 7684 } 7685 if (r != null) { 7686 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 7687 } 7688 7689 N = pkg.permissions.size(); 7690 r = null; 7691 for (i=0; i<N; i++) { 7692 PackageParser.Permission p = pkg.permissions.get(i); 7693 7694 // Assume by default that we did not install this permission into the system. 7695 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 7696 7697 // Now that permission groups have a special meaning, we ignore permission 7698 // groups for legacy apps to prevent unexpected behavior. In particular, 7699 // permissions for one app being granted to someone just becuase they happen 7700 // to be in a group defined by another app (before this had no implications). 7701 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 7702 p.group = mPermissionGroups.get(p.info.group); 7703 // Warn for a permission in an unknown group. 7704 if (p.info.group != null && p.group == null) { 7705 Slog.w(TAG, "Permission " + p.info.name + " from package " 7706 + p.info.packageName + " in an unknown group " + p.info.group); 7707 } 7708 } 7709 7710 ArrayMap<String, BasePermission> permissionMap = 7711 p.tree ? mSettings.mPermissionTrees 7712 : mSettings.mPermissions; 7713 BasePermission bp = permissionMap.get(p.info.name); 7714 7715 // Allow system apps to redefine non-system permissions 7716 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 7717 final boolean currentOwnerIsSystem = (bp.perm != null 7718 && isSystemApp(bp.perm.owner)); 7719 if (isSystemApp(p.owner)) { 7720 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 7721 // It's a built-in permission and no owner, take ownership now 7722 bp.packageSetting = pkgSetting; 7723 bp.perm = p; 7724 bp.uid = pkg.applicationInfo.uid; 7725 bp.sourcePackage = p.info.packageName; 7726 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7727 } else if (!currentOwnerIsSystem) { 7728 String msg = "New decl " + p.owner + " of permission " 7729 + p.info.name + " is system; overriding " + bp.sourcePackage; 7730 reportSettingsProblem(Log.WARN, msg); 7731 bp = null; 7732 } 7733 } 7734 } 7735 7736 if (bp == null) { 7737 bp = new BasePermission(p.info.name, p.info.packageName, 7738 BasePermission.TYPE_NORMAL); 7739 permissionMap.put(p.info.name, bp); 7740 } 7741 7742 if (bp.perm == null) { 7743 if (bp.sourcePackage == null 7744 || bp.sourcePackage.equals(p.info.packageName)) { 7745 BasePermission tree = findPermissionTreeLP(p.info.name); 7746 if (tree == null 7747 || tree.sourcePackage.equals(p.info.packageName)) { 7748 bp.packageSetting = pkgSetting; 7749 bp.perm = p; 7750 bp.uid = pkg.applicationInfo.uid; 7751 bp.sourcePackage = p.info.packageName; 7752 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7753 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7754 if (r == null) { 7755 r = new StringBuilder(256); 7756 } else { 7757 r.append(' '); 7758 } 7759 r.append(p.info.name); 7760 } 7761 } else { 7762 Slog.w(TAG, "Permission " + p.info.name + " from package " 7763 + p.info.packageName + " ignored: base tree " 7764 + tree.name + " is from package " 7765 + tree.sourcePackage); 7766 } 7767 } else { 7768 Slog.w(TAG, "Permission " + p.info.name + " from package " 7769 + p.info.packageName + " ignored: original from " 7770 + bp.sourcePackage); 7771 } 7772 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7773 if (r == null) { 7774 r = new StringBuilder(256); 7775 } else { 7776 r.append(' '); 7777 } 7778 r.append("DUP:"); 7779 r.append(p.info.name); 7780 } 7781 if (bp.perm == p) { 7782 bp.protectionLevel = p.info.protectionLevel; 7783 } 7784 } 7785 7786 if (r != null) { 7787 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 7788 } 7789 7790 N = pkg.instrumentation.size(); 7791 r = null; 7792 for (i=0; i<N; i++) { 7793 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7794 a.info.packageName = pkg.applicationInfo.packageName; 7795 a.info.sourceDir = pkg.applicationInfo.sourceDir; 7796 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 7797 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 7798 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 7799 a.info.dataDir = pkg.applicationInfo.dataDir; 7800 a.info.deviceEncryptedDataDir = pkg.applicationInfo.deviceEncryptedDataDir; 7801 a.info.credentialEncryptedDataDir = pkg.applicationInfo.credentialEncryptedDataDir; 7802 7803 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 7804 // need other information about the application, like the ABI and what not ? 7805 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 7806 mInstrumentation.put(a.getComponentName(), a); 7807 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7808 if (r == null) { 7809 r = new StringBuilder(256); 7810 } else { 7811 r.append(' '); 7812 } 7813 r.append(a.info.name); 7814 } 7815 } 7816 if (r != null) { 7817 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 7818 } 7819 7820 if (pkg.protectedBroadcasts != null) { 7821 N = pkg.protectedBroadcasts.size(); 7822 for (i=0; i<N; i++) { 7823 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 7824 } 7825 } 7826 7827 pkgSetting.setTimeStamp(scanFileTime); 7828 7829 // Create idmap files for pairs of (packages, overlay packages). 7830 // Note: "android", ie framework-res.apk, is handled by native layers. 7831 if (pkg.mOverlayTarget != null) { 7832 // This is an overlay package. 7833 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 7834 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 7835 mOverlays.put(pkg.mOverlayTarget, 7836 new ArrayMap<String, PackageParser.Package>()); 7837 } 7838 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 7839 map.put(pkg.packageName, pkg); 7840 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 7841 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 7842 createIdmapFailed = true; 7843 } 7844 } 7845 } else if (mOverlays.containsKey(pkg.packageName) && 7846 !pkg.packageName.equals("android")) { 7847 // This is a regular package, with one or more known overlay packages. 7848 createIdmapsForPackageLI(pkg); 7849 } 7850 } 7851 7852 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7853 7854 if (createIdmapFailed) { 7855 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7856 "scanPackageLI failed to createIdmap"); 7857 } 7858 return pkg; 7859 } 7860 7861 /** 7862 * Derive the ABI of a non-system package located at {@code scanFile}. This information 7863 * is derived purely on the basis of the contents of {@code scanFile} and 7864 * {@code cpuAbiOverride}. 7865 * 7866 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 7867 */ 7868 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 7869 String cpuAbiOverride, boolean extractLibs) 7870 throws PackageManagerException { 7871 // TODO: We can probably be smarter about this stuff. For installed apps, 7872 // we can calculate this information at install time once and for all. For 7873 // system apps, we can probably assume that this information doesn't change 7874 // after the first boot scan. As things stand, we do lots of unnecessary work. 7875 7876 // Give ourselves some initial paths; we'll come back for another 7877 // pass once we've determined ABI below. 7878 setNativeLibraryPaths(pkg); 7879 7880 // We would never need to extract libs for forward-locked and external packages, 7881 // since the container service will do it for us. We shouldn't attempt to 7882 // extract libs from system app when it was not updated. 7883 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 7884 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 7885 extractLibs = false; 7886 } 7887 7888 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7889 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7890 7891 NativeLibraryHelper.Handle handle = null; 7892 try { 7893 handle = NativeLibraryHelper.Handle.create(pkg); 7894 // TODO(multiArch): This can be null for apps that didn't go through the 7895 // usual installation process. We can calculate it again, like we 7896 // do during install time. 7897 // 7898 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7899 // unnecessary. 7900 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7901 7902 // Null out the abis so that they can be recalculated. 7903 pkg.applicationInfo.primaryCpuAbi = null; 7904 pkg.applicationInfo.secondaryCpuAbi = null; 7905 if (isMultiArch(pkg.applicationInfo)) { 7906 // Warn if we've set an abiOverride for multi-lib packages.. 7907 // By definition, we need to copy both 32 and 64 bit libraries for 7908 // such packages. 7909 if (pkg.cpuAbiOverride != null 7910 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7911 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7912 } 7913 7914 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7915 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7916 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7917 if (extractLibs) { 7918 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7919 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7920 useIsaSpecificSubdirs); 7921 } else { 7922 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7923 } 7924 } 7925 7926 maybeThrowExceptionForMultiArchCopy( 7927 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7928 7929 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7930 if (extractLibs) { 7931 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7932 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7933 useIsaSpecificSubdirs); 7934 } else { 7935 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7936 } 7937 } 7938 7939 maybeThrowExceptionForMultiArchCopy( 7940 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7941 7942 if (abi64 >= 0) { 7943 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7944 } 7945 7946 if (abi32 >= 0) { 7947 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7948 if (abi64 >= 0) { 7949 pkg.applicationInfo.secondaryCpuAbi = abi; 7950 } else { 7951 pkg.applicationInfo.primaryCpuAbi = abi; 7952 } 7953 } 7954 } else { 7955 String[] abiList = (cpuAbiOverride != null) ? 7956 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7957 7958 // Enable gross and lame hacks for apps that are built with old 7959 // SDK tools. We must scan their APKs for renderscript bitcode and 7960 // not launch them if it's present. Don't bother checking on devices 7961 // that don't have 64 bit support. 7962 boolean needsRenderScriptOverride = false; 7963 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7964 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7965 abiList = Build.SUPPORTED_32_BIT_ABIS; 7966 needsRenderScriptOverride = true; 7967 } 7968 7969 final int copyRet; 7970 if (extractLibs) { 7971 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7972 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7973 } else { 7974 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7975 } 7976 7977 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7978 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7979 "Error unpackaging native libs for app, errorCode=" + copyRet); 7980 } 7981 7982 if (copyRet >= 0) { 7983 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7984 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7985 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7986 } else if (needsRenderScriptOverride) { 7987 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7988 } 7989 } 7990 } catch (IOException ioe) { 7991 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7992 } finally { 7993 IoUtils.closeQuietly(handle); 7994 } 7995 7996 // Now that we've calculated the ABIs and determined if it's an internal app, 7997 // we will go ahead and populate the nativeLibraryPath. 7998 setNativeLibraryPaths(pkg); 7999 } 8000 8001 /** 8002 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 8003 * i.e, so that all packages can be run inside a single process if required. 8004 * 8005 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 8006 * this function will either try and make the ABI for all packages in {@code packagesForUser} 8007 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 8008 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 8009 * updating a package that belongs to a shared user. 8010 * 8011 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 8012 * adds unnecessary complexity. 8013 */ 8014 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 8015 PackageParser.Package scannedPackage, boolean bootComplete) { 8016 String requiredInstructionSet = null; 8017 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 8018 requiredInstructionSet = VMRuntime.getInstructionSet( 8019 scannedPackage.applicationInfo.primaryCpuAbi); 8020 } 8021 8022 PackageSetting requirer = null; 8023 for (PackageSetting ps : packagesForUser) { 8024 // If packagesForUser contains scannedPackage, we skip it. This will happen 8025 // when scannedPackage is an update of an existing package. Without this check, 8026 // we will never be able to change the ABI of any package belonging to a shared 8027 // user, even if it's compatible with other packages. 8028 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8029 if (ps.primaryCpuAbiString == null) { 8030 continue; 8031 } 8032 8033 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 8034 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 8035 // We have a mismatch between instruction sets (say arm vs arm64) warn about 8036 // this but there's not much we can do. 8037 String errorMessage = "Instruction set mismatch, " 8038 + ((requirer == null) ? "[caller]" : requirer) 8039 + " requires " + requiredInstructionSet + " whereas " + ps 8040 + " requires " + instructionSet; 8041 Slog.w(TAG, errorMessage); 8042 } 8043 8044 if (requiredInstructionSet == null) { 8045 requiredInstructionSet = instructionSet; 8046 requirer = ps; 8047 } 8048 } 8049 } 8050 8051 if (requiredInstructionSet != null) { 8052 String adjustedAbi; 8053 if (requirer != null) { 8054 // requirer != null implies that either scannedPackage was null or that scannedPackage 8055 // did not require an ABI, in which case we have to adjust scannedPackage to match 8056 // the ABI of the set (which is the same as requirer's ABI) 8057 adjustedAbi = requirer.primaryCpuAbiString; 8058 if (scannedPackage != null) { 8059 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 8060 } 8061 } else { 8062 // requirer == null implies that we're updating all ABIs in the set to 8063 // match scannedPackage. 8064 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 8065 } 8066 8067 for (PackageSetting ps : packagesForUser) { 8068 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8069 if (ps.primaryCpuAbiString != null) { 8070 continue; 8071 } 8072 8073 ps.primaryCpuAbiString = adjustedAbi; 8074 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 8075 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 8076 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi); 8077 try { 8078 mInstaller.rmdex(ps.codePathString, 8079 getDexCodeInstructionSet(getPreferredInstructionSet())); 8080 } catch (InstallerException ignored) { 8081 } 8082 } 8083 } 8084 } 8085 } 8086 } 8087 8088 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 8089 synchronized (mPackages) { 8090 mResolverReplaced = true; 8091 // Set up information for custom user intent resolution activity. 8092 mResolveActivity.applicationInfo = pkg.applicationInfo; 8093 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 8094 mResolveActivity.packageName = pkg.applicationInfo.packageName; 8095 mResolveActivity.processName = pkg.applicationInfo.packageName; 8096 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8097 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8098 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8099 mResolveActivity.theme = 0; 8100 mResolveActivity.exported = true; 8101 mResolveActivity.enabled = true; 8102 mResolveInfo.activityInfo = mResolveActivity; 8103 mResolveInfo.priority = 0; 8104 mResolveInfo.preferredOrder = 0; 8105 mResolveInfo.match = 0; 8106 mResolveComponentName = mCustomResolverComponentName; 8107 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 8108 mResolveComponentName); 8109 } 8110 } 8111 8112 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 8113 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 8114 8115 // Set up information for ephemeral installer activity 8116 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 8117 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 8118 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 8119 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 8120 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8121 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8122 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8123 mEphemeralInstallerActivity.theme = 0; 8124 mEphemeralInstallerActivity.exported = true; 8125 mEphemeralInstallerActivity.enabled = true; 8126 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 8127 mEphemeralInstallerInfo.priority = 0; 8128 mEphemeralInstallerInfo.preferredOrder = 0; 8129 mEphemeralInstallerInfo.match = 0; 8130 8131 if (DEBUG_EPHEMERAL) { 8132 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 8133 } 8134 } 8135 8136 private static String calculateBundledApkRoot(final String codePathString) { 8137 final File codePath = new File(codePathString); 8138 final File codeRoot; 8139 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 8140 codeRoot = Environment.getRootDirectory(); 8141 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 8142 codeRoot = Environment.getOemDirectory(); 8143 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 8144 codeRoot = Environment.getVendorDirectory(); 8145 } else { 8146 // Unrecognized code path; take its top real segment as the apk root: 8147 // e.g. /something/app/blah.apk => /something 8148 try { 8149 File f = codePath.getCanonicalFile(); 8150 File parent = f.getParentFile(); // non-null because codePath is a file 8151 File tmp; 8152 while ((tmp = parent.getParentFile()) != null) { 8153 f = parent; 8154 parent = tmp; 8155 } 8156 codeRoot = f; 8157 Slog.w(TAG, "Unrecognized code path " 8158 + codePath + " - using " + codeRoot); 8159 } catch (IOException e) { 8160 // Can't canonicalize the code path -- shenanigans? 8161 Slog.w(TAG, "Can't canonicalize code path " + codePath); 8162 return Environment.getRootDirectory().getPath(); 8163 } 8164 } 8165 return codeRoot.getPath(); 8166 } 8167 8168 /** 8169 * Derive and set the location of native libraries for the given package, 8170 * which varies depending on where and how the package was installed. 8171 */ 8172 private void setNativeLibraryPaths(PackageParser.Package pkg) { 8173 final ApplicationInfo info = pkg.applicationInfo; 8174 final String codePath = pkg.codePath; 8175 final File codeFile = new File(codePath); 8176 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 8177 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 8178 8179 info.nativeLibraryRootDir = null; 8180 info.nativeLibraryRootRequiresIsa = false; 8181 info.nativeLibraryDir = null; 8182 info.secondaryNativeLibraryDir = null; 8183 8184 if (isApkFile(codeFile)) { 8185 // Monolithic install 8186 if (bundledApp) { 8187 // If "/system/lib64/apkname" exists, assume that is the per-package 8188 // native library directory to use; otherwise use "/system/lib/apkname". 8189 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 8190 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 8191 getPrimaryInstructionSet(info)); 8192 8193 // This is a bundled system app so choose the path based on the ABI. 8194 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 8195 // is just the default path. 8196 final String apkName = deriveCodePathName(codePath); 8197 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 8198 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 8199 apkName).getAbsolutePath(); 8200 8201 if (info.secondaryCpuAbi != null) { 8202 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 8203 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 8204 secondaryLibDir, apkName).getAbsolutePath(); 8205 } 8206 } else if (asecApp) { 8207 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 8208 .getAbsolutePath(); 8209 } else { 8210 final String apkName = deriveCodePathName(codePath); 8211 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 8212 .getAbsolutePath(); 8213 } 8214 8215 info.nativeLibraryRootRequiresIsa = false; 8216 info.nativeLibraryDir = info.nativeLibraryRootDir; 8217 } else { 8218 // Cluster install 8219 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 8220 info.nativeLibraryRootRequiresIsa = true; 8221 8222 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 8223 getPrimaryInstructionSet(info)).getAbsolutePath(); 8224 8225 if (info.secondaryCpuAbi != null) { 8226 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 8227 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 8228 } 8229 } 8230 } 8231 8232 /** 8233 * Calculate the abis and roots for a bundled app. These can uniquely 8234 * be determined from the contents of the system partition, i.e whether 8235 * it contains 64 or 32 bit shared libraries etc. We do not validate any 8236 * of this information, and instead assume that the system was built 8237 * sensibly. 8238 */ 8239 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 8240 PackageSetting pkgSetting) { 8241 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 8242 8243 // If "/system/lib64/apkname" exists, assume that is the per-package 8244 // native library directory to use; otherwise use "/system/lib/apkname". 8245 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 8246 setBundledAppAbi(pkg, apkRoot, apkName); 8247 // pkgSetting might be null during rescan following uninstall of updates 8248 // to a bundled app, so accommodate that possibility. The settings in 8249 // that case will be established later from the parsed package. 8250 // 8251 // If the settings aren't null, sync them up with what we've just derived. 8252 // note that apkRoot isn't stored in the package settings. 8253 if (pkgSetting != null) { 8254 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8255 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8256 } 8257 } 8258 8259 /** 8260 * Deduces the ABI of a bundled app and sets the relevant fields on the 8261 * parsed pkg object. 8262 * 8263 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 8264 * under which system libraries are installed. 8265 * @param apkName the name of the installed package. 8266 */ 8267 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 8268 final File codeFile = new File(pkg.codePath); 8269 8270 final boolean has64BitLibs; 8271 final boolean has32BitLibs; 8272 if (isApkFile(codeFile)) { 8273 // Monolithic install 8274 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 8275 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 8276 } else { 8277 // Cluster install 8278 final File rootDir = new File(codeFile, LIB_DIR_NAME); 8279 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 8280 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 8281 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 8282 has64BitLibs = (new File(rootDir, isa)).exists(); 8283 } else { 8284 has64BitLibs = false; 8285 } 8286 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 8287 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 8288 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 8289 has32BitLibs = (new File(rootDir, isa)).exists(); 8290 } else { 8291 has32BitLibs = false; 8292 } 8293 } 8294 8295 if (has64BitLibs && !has32BitLibs) { 8296 // The package has 64 bit libs, but not 32 bit libs. Its primary 8297 // ABI should be 64 bit. We can safely assume here that the bundled 8298 // native libraries correspond to the most preferred ABI in the list. 8299 8300 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8301 pkg.applicationInfo.secondaryCpuAbi = null; 8302 } else if (has32BitLibs && !has64BitLibs) { 8303 // The package has 32 bit libs but not 64 bit libs. Its primary 8304 // ABI should be 32 bit. 8305 8306 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8307 pkg.applicationInfo.secondaryCpuAbi = null; 8308 } else if (has32BitLibs && has64BitLibs) { 8309 // The application has both 64 and 32 bit bundled libraries. We check 8310 // here that the app declares multiArch support, and warn if it doesn't. 8311 // 8312 // We will be lenient here and record both ABIs. The primary will be the 8313 // ABI that's higher on the list, i.e, a device that's configured to prefer 8314 // 64 bit apps will see a 64 bit primary ABI, 8315 8316 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 8317 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 8318 } 8319 8320 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 8321 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8322 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8323 } else { 8324 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8325 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8326 } 8327 } else { 8328 pkg.applicationInfo.primaryCpuAbi = null; 8329 pkg.applicationInfo.secondaryCpuAbi = null; 8330 } 8331 } 8332 8333 private void killApplication(String pkgName, int appId, String reason) { 8334 // Request the ActivityManager to kill the process(only for existing packages) 8335 // so that we do not end up in a confused state while the user is still using the older 8336 // version of the application while the new one gets installed. 8337 IActivityManager am = ActivityManagerNative.getDefault(); 8338 if (am != null) { 8339 try { 8340 am.killApplicationWithAppId(pkgName, appId, reason); 8341 } catch (RemoteException e) { 8342 } 8343 } 8344 } 8345 8346 void removePackageLI(PackageSetting ps, boolean chatty) { 8347 if (DEBUG_INSTALL) { 8348 if (chatty) 8349 Log.d(TAG, "Removing package " + ps.name); 8350 } 8351 8352 // writer 8353 synchronized (mPackages) { 8354 mPackages.remove(ps.name); 8355 final PackageParser.Package pkg = ps.pkg; 8356 if (pkg != null) { 8357 cleanPackageDataStructuresLILPw(pkg, chatty); 8358 } 8359 } 8360 } 8361 8362 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 8363 if (DEBUG_INSTALL) { 8364 if (chatty) 8365 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 8366 } 8367 8368 // writer 8369 synchronized (mPackages) { 8370 mPackages.remove(pkg.applicationInfo.packageName); 8371 cleanPackageDataStructuresLILPw(pkg, chatty); 8372 } 8373 } 8374 8375 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 8376 int N = pkg.providers.size(); 8377 StringBuilder r = null; 8378 int i; 8379 for (i=0; i<N; i++) { 8380 PackageParser.Provider p = pkg.providers.get(i); 8381 mProviders.removeProvider(p); 8382 if (p.info.authority == null) { 8383 8384 /* There was another ContentProvider with this authority when 8385 * this app was installed so this authority is null, 8386 * Ignore it as we don't have to unregister the provider. 8387 */ 8388 continue; 8389 } 8390 String names[] = p.info.authority.split(";"); 8391 for (int j = 0; j < names.length; j++) { 8392 if (mProvidersByAuthority.get(names[j]) == p) { 8393 mProvidersByAuthority.remove(names[j]); 8394 if (DEBUG_REMOVE) { 8395 if (chatty) 8396 Log.d(TAG, "Unregistered content provider: " + names[j] 8397 + ", className = " + p.info.name + ", isSyncable = " 8398 + p.info.isSyncable); 8399 } 8400 } 8401 } 8402 if (DEBUG_REMOVE && chatty) { 8403 if (r == null) { 8404 r = new StringBuilder(256); 8405 } else { 8406 r.append(' '); 8407 } 8408 r.append(p.info.name); 8409 } 8410 } 8411 if (r != null) { 8412 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 8413 } 8414 8415 N = pkg.services.size(); 8416 r = null; 8417 for (i=0; i<N; i++) { 8418 PackageParser.Service s = pkg.services.get(i); 8419 mServices.removeService(s); 8420 if (chatty) { 8421 if (r == null) { 8422 r = new StringBuilder(256); 8423 } else { 8424 r.append(' '); 8425 } 8426 r.append(s.info.name); 8427 } 8428 } 8429 if (r != null) { 8430 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 8431 } 8432 8433 N = pkg.receivers.size(); 8434 r = null; 8435 for (i=0; i<N; i++) { 8436 PackageParser.Activity a = pkg.receivers.get(i); 8437 mReceivers.removeActivity(a, "receiver"); 8438 if (DEBUG_REMOVE && chatty) { 8439 if (r == null) { 8440 r = new StringBuilder(256); 8441 } else { 8442 r.append(' '); 8443 } 8444 r.append(a.info.name); 8445 } 8446 } 8447 if (r != null) { 8448 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 8449 } 8450 8451 N = pkg.activities.size(); 8452 r = null; 8453 for (i=0; i<N; i++) { 8454 PackageParser.Activity a = pkg.activities.get(i); 8455 mActivities.removeActivity(a, "activity"); 8456 if (DEBUG_REMOVE && chatty) { 8457 if (r == null) { 8458 r = new StringBuilder(256); 8459 } else { 8460 r.append(' '); 8461 } 8462 r.append(a.info.name); 8463 } 8464 } 8465 if (r != null) { 8466 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 8467 } 8468 8469 N = pkg.permissions.size(); 8470 r = null; 8471 for (i=0; i<N; i++) { 8472 PackageParser.Permission p = pkg.permissions.get(i); 8473 BasePermission bp = mSettings.mPermissions.get(p.info.name); 8474 if (bp == null) { 8475 bp = mSettings.mPermissionTrees.get(p.info.name); 8476 } 8477 if (bp != null && bp.perm == p) { 8478 bp.perm = null; 8479 if (DEBUG_REMOVE && chatty) { 8480 if (r == null) { 8481 r = new StringBuilder(256); 8482 } else { 8483 r.append(' '); 8484 } 8485 r.append(p.info.name); 8486 } 8487 } 8488 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8489 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 8490 if (appOpPkgs != null) { 8491 appOpPkgs.remove(pkg.packageName); 8492 } 8493 } 8494 } 8495 if (r != null) { 8496 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8497 } 8498 8499 N = pkg.requestedPermissions.size(); 8500 r = null; 8501 for (i=0; i<N; i++) { 8502 String perm = pkg.requestedPermissions.get(i); 8503 BasePermission bp = mSettings.mPermissions.get(perm); 8504 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8505 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 8506 if (appOpPkgs != null) { 8507 appOpPkgs.remove(pkg.packageName); 8508 if (appOpPkgs.isEmpty()) { 8509 mAppOpPermissionPackages.remove(perm); 8510 } 8511 } 8512 } 8513 } 8514 if (r != null) { 8515 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8516 } 8517 8518 N = pkg.instrumentation.size(); 8519 r = null; 8520 for (i=0; i<N; i++) { 8521 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8522 mInstrumentation.remove(a.getComponentName()); 8523 if (DEBUG_REMOVE && chatty) { 8524 if (r == null) { 8525 r = new StringBuilder(256); 8526 } else { 8527 r.append(' '); 8528 } 8529 r.append(a.info.name); 8530 } 8531 } 8532 if (r != null) { 8533 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 8534 } 8535 8536 r = null; 8537 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8538 // Only system apps can hold shared libraries. 8539 if (pkg.libraryNames != null) { 8540 for (i=0; i<pkg.libraryNames.size(); i++) { 8541 String name = pkg.libraryNames.get(i); 8542 SharedLibraryEntry cur = mSharedLibraries.get(name); 8543 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 8544 mSharedLibraries.remove(name); 8545 if (DEBUG_REMOVE && chatty) { 8546 if (r == null) { 8547 r = new StringBuilder(256); 8548 } else { 8549 r.append(' '); 8550 } 8551 r.append(name); 8552 } 8553 } 8554 } 8555 } 8556 } 8557 if (r != null) { 8558 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 8559 } 8560 } 8561 8562 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 8563 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 8564 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 8565 return true; 8566 } 8567 } 8568 return false; 8569 } 8570 8571 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 8572 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 8573 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 8574 8575 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 8576 int flags) { 8577 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 8578 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 8579 } 8580 8581 private void updatePermissionsLPw(String changingPkg, 8582 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 8583 // Make sure there are no dangling permission trees. 8584 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 8585 while (it.hasNext()) { 8586 final BasePermission bp = it.next(); 8587 if (bp.packageSetting == null) { 8588 // We may not yet have parsed the package, so just see if 8589 // we still know about its settings. 8590 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8591 } 8592 if (bp.packageSetting == null) { 8593 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 8594 + " from package " + bp.sourcePackage); 8595 it.remove(); 8596 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8597 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8598 Slog.i(TAG, "Removing old permission tree: " + bp.name 8599 + " from package " + bp.sourcePackage); 8600 flags |= UPDATE_PERMISSIONS_ALL; 8601 it.remove(); 8602 } 8603 } 8604 } 8605 8606 // Make sure all dynamic permissions have been assigned to a package, 8607 // and make sure there are no dangling permissions. 8608 it = mSettings.mPermissions.values().iterator(); 8609 while (it.hasNext()) { 8610 final BasePermission bp = it.next(); 8611 if (bp.type == BasePermission.TYPE_DYNAMIC) { 8612 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 8613 + bp.name + " pkg=" + bp.sourcePackage 8614 + " info=" + bp.pendingInfo); 8615 if (bp.packageSetting == null && bp.pendingInfo != null) { 8616 final BasePermission tree = findPermissionTreeLP(bp.name); 8617 if (tree != null && tree.perm != null) { 8618 bp.packageSetting = tree.packageSetting; 8619 bp.perm = new PackageParser.Permission(tree.perm.owner, 8620 new PermissionInfo(bp.pendingInfo)); 8621 bp.perm.info.packageName = tree.perm.info.packageName; 8622 bp.perm.info.name = bp.name; 8623 bp.uid = tree.uid; 8624 } 8625 } 8626 } 8627 if (bp.packageSetting == null) { 8628 // We may not yet have parsed the package, so just see if 8629 // we still know about its settings. 8630 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8631 } 8632 if (bp.packageSetting == null) { 8633 Slog.w(TAG, "Removing dangling permission: " + bp.name 8634 + " from package " + bp.sourcePackage); 8635 it.remove(); 8636 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8637 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8638 Slog.i(TAG, "Removing old permission: " + bp.name 8639 + " from package " + bp.sourcePackage); 8640 flags |= UPDATE_PERMISSIONS_ALL; 8641 it.remove(); 8642 } 8643 } 8644 } 8645 8646 // Now update the permissions for all packages, in particular 8647 // replace the granted permissions of the system packages. 8648 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 8649 for (PackageParser.Package pkg : mPackages.values()) { 8650 if (pkg != pkgInfo) { 8651 // Only replace for packages on requested volume 8652 final String volumeUuid = getVolumeUuidForPackage(pkg); 8653 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 8654 && Objects.equals(replaceVolumeUuid, volumeUuid); 8655 grantPermissionsLPw(pkg, replace, changingPkg); 8656 } 8657 } 8658 } 8659 8660 if (pkgInfo != null) { 8661 // Only replace for packages on requested volume 8662 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 8663 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 8664 && Objects.equals(replaceVolumeUuid, volumeUuid); 8665 grantPermissionsLPw(pkgInfo, replace, changingPkg); 8666 } 8667 } 8668 8669 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 8670 String packageOfInterest) { 8671 // IMPORTANT: There are two types of permissions: install and runtime. 8672 // Install time permissions are granted when the app is installed to 8673 // all device users and users added in the future. Runtime permissions 8674 // are granted at runtime explicitly to specific users. Normal and signature 8675 // protected permissions are install time permissions. Dangerous permissions 8676 // are install permissions if the app's target SDK is Lollipop MR1 or older, 8677 // otherwise they are runtime permissions. This function does not manage 8678 // runtime permissions except for the case an app targeting Lollipop MR1 8679 // being upgraded to target a newer SDK, in which case dangerous permissions 8680 // are transformed from install time to runtime ones. 8681 8682 final PackageSetting ps = (PackageSetting) pkg.mExtras; 8683 if (ps == null) { 8684 return; 8685 } 8686 8687 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 8688 8689 PermissionsState permissionsState = ps.getPermissionsState(); 8690 PermissionsState origPermissions = permissionsState; 8691 8692 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 8693 8694 boolean runtimePermissionsRevoked = false; 8695 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 8696 8697 boolean changedInstallPermission = false; 8698 8699 if (replace) { 8700 ps.installPermissionsFixed = false; 8701 if (!ps.isSharedUser()) { 8702 origPermissions = new PermissionsState(permissionsState); 8703 permissionsState.reset(); 8704 } else { 8705 // We need to know only about runtime permission changes since the 8706 // calling code always writes the install permissions state but 8707 // the runtime ones are written only if changed. The only cases of 8708 // changed runtime permissions here are promotion of an install to 8709 // runtime and revocation of a runtime from a shared user. 8710 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 8711 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 8712 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 8713 runtimePermissionsRevoked = true; 8714 } 8715 } 8716 } 8717 8718 permissionsState.setGlobalGids(mGlobalGids); 8719 8720 final int N = pkg.requestedPermissions.size(); 8721 for (int i=0; i<N; i++) { 8722 final String name = pkg.requestedPermissions.get(i); 8723 final BasePermission bp = mSettings.mPermissions.get(name); 8724 8725 if (DEBUG_INSTALL) { 8726 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 8727 } 8728 8729 if (bp == null || bp.packageSetting == null) { 8730 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8731 Slog.w(TAG, "Unknown permission " + name 8732 + " in package " + pkg.packageName); 8733 } 8734 continue; 8735 } 8736 8737 final String perm = bp.name; 8738 boolean allowedSig = false; 8739 int grant = GRANT_DENIED; 8740 8741 // Keep track of app op permissions. 8742 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8743 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 8744 if (pkgs == null) { 8745 pkgs = new ArraySet<>(); 8746 mAppOpPermissionPackages.put(bp.name, pkgs); 8747 } 8748 pkgs.add(pkg.packageName); 8749 } 8750 8751 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 8752 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 8753 >= Build.VERSION_CODES.M; 8754 switch (level) { 8755 case PermissionInfo.PROTECTION_NORMAL: { 8756 // For all apps normal permissions are install time ones. 8757 grant = GRANT_INSTALL; 8758 } break; 8759 8760 case PermissionInfo.PROTECTION_DANGEROUS: { 8761 // If a permission review is required for legacy apps we represent 8762 // their permissions as always granted runtime ones since we need 8763 // to keep the review required permission flag per user while an 8764 // install permission's state is shared across all users. 8765 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 8766 // For legacy apps dangerous permissions are install time ones. 8767 grant = GRANT_INSTALL; 8768 } else if (origPermissions.hasInstallPermission(bp.name)) { 8769 // For legacy apps that became modern, install becomes runtime. 8770 grant = GRANT_UPGRADE; 8771 } else if (mPromoteSystemApps 8772 && isSystemApp(ps) 8773 && mExistingSystemPackages.contains(ps.name)) { 8774 // For legacy system apps, install becomes runtime. 8775 // We cannot check hasInstallPermission() for system apps since those 8776 // permissions were granted implicitly and not persisted pre-M. 8777 grant = GRANT_UPGRADE; 8778 } else { 8779 // For modern apps keep runtime permissions unchanged. 8780 grant = GRANT_RUNTIME; 8781 } 8782 } break; 8783 8784 case PermissionInfo.PROTECTION_SIGNATURE: { 8785 // For all apps signature permissions are install time ones. 8786 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 8787 if (allowedSig) { 8788 grant = GRANT_INSTALL; 8789 } 8790 } break; 8791 } 8792 8793 if (DEBUG_INSTALL) { 8794 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 8795 } 8796 8797 if (grant != GRANT_DENIED) { 8798 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 8799 // If this is an existing, non-system package, then 8800 // we can't add any new permissions to it. 8801 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 8802 // Except... if this is a permission that was added 8803 // to the platform (note: need to only do this when 8804 // updating the platform). 8805 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 8806 grant = GRANT_DENIED; 8807 } 8808 } 8809 } 8810 8811 switch (grant) { 8812 case GRANT_INSTALL: { 8813 // Revoke this as runtime permission to handle the case of 8814 // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps 8815 for (int userId : UserManagerService.getInstance().getUserIds()) { 8816 if (origPermissions.getRuntimePermissionState( 8817 bp.name, userId) != null) { 8818 // Revoke the runtime permission and clear the flags. 8819 origPermissions.revokeRuntimePermission(bp, userId); 8820 origPermissions.updatePermissionFlags(bp, userId, 8821 PackageManager.MASK_PERMISSION_FLAGS, 0); 8822 // If we revoked a permission permission, we have to write. 8823 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8824 changedRuntimePermissionUserIds, userId); 8825 } 8826 } 8827 // Grant an install permission. 8828 if (permissionsState.grantInstallPermission(bp) != 8829 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8830 changedInstallPermission = true; 8831 } 8832 } break; 8833 8834 case GRANT_RUNTIME: { 8835 // Grant previously granted runtime permissions. 8836 for (int userId : UserManagerService.getInstance().getUserIds()) { 8837 PermissionState permissionState = origPermissions 8838 .getRuntimePermissionState(bp.name, userId); 8839 int flags = permissionState != null 8840 ? permissionState.getFlags() : 0; 8841 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8842 if (permissionsState.grantRuntimePermission(bp, userId) == 8843 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8844 // If we cannot put the permission as it was, we have to write. 8845 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8846 changedRuntimePermissionUserIds, userId); 8847 } 8848 // If the app supports runtime permissions no need for a review. 8849 if (Build.PERMISSIONS_REVIEW_REQUIRED 8850 && appSupportsRuntimePermissions 8851 && (flags & PackageManager 8852 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 8853 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 8854 // Since we changed the flags, we have to write. 8855 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8856 changedRuntimePermissionUserIds, userId); 8857 } 8858 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 8859 && !appSupportsRuntimePermissions) { 8860 // For legacy apps that need a permission review, every new 8861 // runtime permission is granted but it is pending a review. 8862 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 8863 permissionsState.grantRuntimePermission(bp, userId); 8864 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 8865 // We changed the permission and flags, hence have to write. 8866 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8867 changedRuntimePermissionUserIds, userId); 8868 } 8869 } 8870 // Propagate the permission flags. 8871 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 8872 } 8873 } break; 8874 8875 case GRANT_UPGRADE: { 8876 // Grant runtime permissions for a previously held install permission. 8877 PermissionState permissionState = origPermissions 8878 .getInstallPermissionState(bp.name); 8879 final int flags = permissionState != null ? permissionState.getFlags() : 0; 8880 8881 if (origPermissions.revokeInstallPermission(bp) 8882 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 8883 // We will be transferring the permission flags, so clear them. 8884 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 8885 PackageManager.MASK_PERMISSION_FLAGS, 0); 8886 changedInstallPermission = true; 8887 } 8888 8889 // If the permission is not to be promoted to runtime we ignore it and 8890 // also its other flags as they are not applicable to install permissions. 8891 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 8892 for (int userId : currentUserIds) { 8893 if (permissionsState.grantRuntimePermission(bp, userId) != 8894 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8895 // Transfer the permission flags. 8896 permissionsState.updatePermissionFlags(bp, userId, 8897 flags, flags); 8898 // If we granted the permission, we have to write. 8899 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8900 changedRuntimePermissionUserIds, userId); 8901 } 8902 } 8903 } 8904 } break; 8905 8906 default: { 8907 if (packageOfInterest == null 8908 || packageOfInterest.equals(pkg.packageName)) { 8909 Slog.w(TAG, "Not granting permission " + perm 8910 + " to package " + pkg.packageName 8911 + " because it was previously installed without"); 8912 } 8913 } break; 8914 } 8915 } else { 8916 if (permissionsState.revokeInstallPermission(bp) != 8917 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8918 // Also drop the permission flags. 8919 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 8920 PackageManager.MASK_PERMISSION_FLAGS, 0); 8921 changedInstallPermission = true; 8922 Slog.i(TAG, "Un-granting permission " + perm 8923 + " from package " + pkg.packageName 8924 + " (protectionLevel=" + bp.protectionLevel 8925 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8926 + ")"); 8927 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 8928 // Don't print warning for app op permissions, since it is fine for them 8929 // not to be granted, there is a UI for the user to decide. 8930 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8931 Slog.w(TAG, "Not granting permission " + perm 8932 + " to package " + pkg.packageName 8933 + " (protectionLevel=" + bp.protectionLevel 8934 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8935 + ")"); 8936 } 8937 } 8938 } 8939 } 8940 8941 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 8942 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 8943 // This is the first that we have heard about this package, so the 8944 // permissions we have now selected are fixed until explicitly 8945 // changed. 8946 ps.installPermissionsFixed = true; 8947 } 8948 8949 // Persist the runtime permissions state for users with changes. If permissions 8950 // were revoked because no app in the shared user declares them we have to 8951 // write synchronously to avoid losing runtime permissions state. 8952 for (int userId : changedRuntimePermissionUserIds) { 8953 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 8954 } 8955 8956 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8957 } 8958 8959 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8960 boolean allowed = false; 8961 final int NP = PackageParser.NEW_PERMISSIONS.length; 8962 for (int ip=0; ip<NP; ip++) { 8963 final PackageParser.NewPermissionInfo npi 8964 = PackageParser.NEW_PERMISSIONS[ip]; 8965 if (npi.name.equals(perm) 8966 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8967 allowed = true; 8968 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8969 + pkg.packageName); 8970 break; 8971 } 8972 } 8973 return allowed; 8974 } 8975 8976 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 8977 BasePermission bp, PermissionsState origPermissions) { 8978 boolean allowed; 8979 allowed = (compareSignatures( 8980 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 8981 == PackageManager.SIGNATURE_MATCH) 8982 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 8983 == PackageManager.SIGNATURE_MATCH); 8984 if (!allowed && (bp.protectionLevel 8985 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 8986 if (isSystemApp(pkg)) { 8987 // For updated system applications, a system permission 8988 // is granted only if it had been defined by the original application. 8989 if (pkg.isUpdatedSystemApp()) { 8990 final PackageSetting sysPs = mSettings 8991 .getDisabledSystemPkgLPr(pkg.packageName); 8992 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 8993 // If the original was granted this permission, we take 8994 // that grant decision as read and propagate it to the 8995 // update. 8996 if (sysPs.isPrivileged()) { 8997 allowed = true; 8998 } 8999 } else { 9000 // The system apk may have been updated with an older 9001 // version of the one on the data partition, but which 9002 // granted a new system permission that it didn't have 9003 // before. In this case we do want to allow the app to 9004 // now get the new permission if the ancestral apk is 9005 // privileged to get it. 9006 if (sysPs.pkg != null && sysPs.isPrivileged()) { 9007 for (int j=0; 9008 j<sysPs.pkg.requestedPermissions.size(); j++) { 9009 if (perm.equals( 9010 sysPs.pkg.requestedPermissions.get(j))) { 9011 allowed = true; 9012 break; 9013 } 9014 } 9015 } 9016 } 9017 } else { 9018 allowed = isPrivilegedApp(pkg); 9019 } 9020 } 9021 } 9022 if (!allowed) { 9023 if (!allowed && (bp.protectionLevel 9024 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 9025 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 9026 // If this was a previously normal/dangerous permission that got moved 9027 // to a system permission as part of the runtime permission redesign, then 9028 // we still want to blindly grant it to old apps. 9029 allowed = true; 9030 } 9031 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 9032 && pkg.packageName.equals(mRequiredInstallerPackage)) { 9033 // If this permission is to be granted to the system installer and 9034 // this app is an installer, then it gets the permission. 9035 allowed = true; 9036 } 9037 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 9038 && pkg.packageName.equals(mRequiredVerifierPackage)) { 9039 // If this permission is to be granted to the system verifier and 9040 // this app is a verifier, then it gets the permission. 9041 allowed = true; 9042 } 9043 if (!allowed && (bp.protectionLevel 9044 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 9045 && isSystemApp(pkg)) { 9046 // Any pre-installed system app is allowed to get this permission. 9047 allowed = true; 9048 } 9049 if (!allowed && (bp.protectionLevel 9050 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 9051 // For development permissions, a development permission 9052 // is granted only if it was already granted. 9053 allowed = origPermissions.hasInstallPermission(perm); 9054 } 9055 } 9056 return allowed; 9057 } 9058 9059 final class ActivityIntentResolver 9060 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 9061 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9062 boolean defaultOnly, int userId) { 9063 if (!sUserManager.exists(userId)) return null; 9064 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9065 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9066 } 9067 9068 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9069 int userId) { 9070 if (!sUserManager.exists(userId)) return null; 9071 mFlags = flags; 9072 return super.queryIntent(intent, resolvedType, 9073 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9074 } 9075 9076 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9077 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 9078 if (!sUserManager.exists(userId)) return null; 9079 if (packageActivities == null) { 9080 return null; 9081 } 9082 mFlags = flags; 9083 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9084 final int N = packageActivities.size(); 9085 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 9086 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 9087 9088 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 9089 for (int i = 0; i < N; ++i) { 9090 intentFilters = packageActivities.get(i).intents; 9091 if (intentFilters != null && intentFilters.size() > 0) { 9092 PackageParser.ActivityIntentInfo[] array = 9093 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 9094 intentFilters.toArray(array); 9095 listCut.add(array); 9096 } 9097 } 9098 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9099 } 9100 9101 public final void addActivity(PackageParser.Activity a, String type) { 9102 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 9103 mActivities.put(a.getComponentName(), a); 9104 if (DEBUG_SHOW_INFO) 9105 Log.v( 9106 TAG, " " + type + " " + 9107 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 9108 if (DEBUG_SHOW_INFO) 9109 Log.v(TAG, " Class=" + a.info.name); 9110 final int NI = a.intents.size(); 9111 for (int j=0; j<NI; j++) { 9112 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 9113 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 9114 intent.setPriority(0); 9115 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 9116 + a.className + " with priority > 0, forcing to 0"); 9117 } 9118 if (DEBUG_SHOW_INFO) { 9119 Log.v(TAG, " IntentFilter:"); 9120 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9121 } 9122 if (!intent.debugCheck()) { 9123 Log.w(TAG, "==> For Activity " + a.info.name); 9124 } 9125 addFilter(intent); 9126 } 9127 } 9128 9129 public final void removeActivity(PackageParser.Activity a, String type) { 9130 mActivities.remove(a.getComponentName()); 9131 if (DEBUG_SHOW_INFO) { 9132 Log.v(TAG, " " + type + " " 9133 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 9134 : a.info.name) + ":"); 9135 Log.v(TAG, " Class=" + a.info.name); 9136 } 9137 final int NI = a.intents.size(); 9138 for (int j=0; j<NI; j++) { 9139 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 9140 if (DEBUG_SHOW_INFO) { 9141 Log.v(TAG, " IntentFilter:"); 9142 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9143 } 9144 removeFilter(intent); 9145 } 9146 } 9147 9148 @Override 9149 protected boolean allowFilterResult( 9150 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 9151 ActivityInfo filterAi = filter.activity.info; 9152 for (int i=dest.size()-1; i>=0; i--) { 9153 ActivityInfo destAi = dest.get(i).activityInfo; 9154 if (destAi.name == filterAi.name 9155 && destAi.packageName == filterAi.packageName) { 9156 return false; 9157 } 9158 } 9159 return true; 9160 } 9161 9162 @Override 9163 protected ActivityIntentInfo[] newArray(int size) { 9164 return new ActivityIntentInfo[size]; 9165 } 9166 9167 @Override 9168 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 9169 if (!sUserManager.exists(userId)) return true; 9170 PackageParser.Package p = filter.activity.owner; 9171 if (p != null) { 9172 PackageSetting ps = (PackageSetting)p.mExtras; 9173 if (ps != null) { 9174 // System apps are never considered stopped for purposes of 9175 // filtering, because there may be no way for the user to 9176 // actually re-launch them. 9177 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 9178 && ps.getStopped(userId); 9179 } 9180 } 9181 return false; 9182 } 9183 9184 @Override 9185 protected boolean isPackageForFilter(String packageName, 9186 PackageParser.ActivityIntentInfo info) { 9187 return packageName.equals(info.activity.owner.packageName); 9188 } 9189 9190 @Override 9191 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 9192 int match, int userId) { 9193 if (!sUserManager.exists(userId)) return null; 9194 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 9195 return null; 9196 } 9197 final PackageParser.Activity activity = info.activity; 9198 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 9199 if (ps == null) { 9200 return null; 9201 } 9202 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 9203 ps.readUserState(userId), userId); 9204 if (ai == null) { 9205 return null; 9206 } 9207 final ResolveInfo res = new ResolveInfo(); 9208 res.activityInfo = ai; 9209 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9210 res.filter = info; 9211 } 9212 if (info != null) { 9213 res.handleAllWebDataURI = info.handleAllWebDataURI(); 9214 } 9215 res.priority = info.getPriority(); 9216 res.preferredOrder = activity.owner.mPreferredOrder; 9217 //System.out.println("Result: " + res.activityInfo.className + 9218 // " = " + res.priority); 9219 res.match = match; 9220 res.isDefault = info.hasDefault; 9221 res.labelRes = info.labelRes; 9222 res.nonLocalizedLabel = info.nonLocalizedLabel; 9223 if (userNeedsBadging(userId)) { 9224 res.noResourceId = true; 9225 } else { 9226 res.icon = info.icon; 9227 } 9228 res.iconResourceId = info.icon; 9229 res.system = res.activityInfo.applicationInfo.isSystemApp(); 9230 return res; 9231 } 9232 9233 @Override 9234 protected void sortResults(List<ResolveInfo> results) { 9235 Collections.sort(results, mResolvePrioritySorter); 9236 } 9237 9238 @Override 9239 protected void dumpFilter(PrintWriter out, String prefix, 9240 PackageParser.ActivityIntentInfo filter) { 9241 out.print(prefix); out.print( 9242 Integer.toHexString(System.identityHashCode(filter.activity))); 9243 out.print(' '); 9244 filter.activity.printComponentShortName(out); 9245 out.print(" filter "); 9246 out.println(Integer.toHexString(System.identityHashCode(filter))); 9247 } 9248 9249 @Override 9250 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 9251 return filter.activity; 9252 } 9253 9254 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9255 PackageParser.Activity activity = (PackageParser.Activity)label; 9256 out.print(prefix); out.print( 9257 Integer.toHexString(System.identityHashCode(activity))); 9258 out.print(' '); 9259 activity.printComponentShortName(out); 9260 if (count > 1) { 9261 out.print(" ("); out.print(count); out.print(" filters)"); 9262 } 9263 out.println(); 9264 } 9265 9266// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9267// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9268// final List<ResolveInfo> retList = Lists.newArrayList(); 9269// while (i.hasNext()) { 9270// final ResolveInfo resolveInfo = i.next(); 9271// if (isEnabledLP(resolveInfo.activityInfo)) { 9272// retList.add(resolveInfo); 9273// } 9274// } 9275// return retList; 9276// } 9277 9278 // Keys are String (activity class name), values are Activity. 9279 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 9280 = new ArrayMap<ComponentName, PackageParser.Activity>(); 9281 private int mFlags; 9282 } 9283 9284 private final class ServiceIntentResolver 9285 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 9286 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9287 boolean defaultOnly, int userId) { 9288 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9289 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9290 } 9291 9292 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9293 int userId) { 9294 if (!sUserManager.exists(userId)) return null; 9295 mFlags = flags; 9296 return super.queryIntent(intent, resolvedType, 9297 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9298 } 9299 9300 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9301 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 9302 if (!sUserManager.exists(userId)) return null; 9303 if (packageServices == null) { 9304 return null; 9305 } 9306 mFlags = flags; 9307 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9308 final int N = packageServices.size(); 9309 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 9310 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 9311 9312 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 9313 for (int i = 0; i < N; ++i) { 9314 intentFilters = packageServices.get(i).intents; 9315 if (intentFilters != null && intentFilters.size() > 0) { 9316 PackageParser.ServiceIntentInfo[] array = 9317 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 9318 intentFilters.toArray(array); 9319 listCut.add(array); 9320 } 9321 } 9322 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9323 } 9324 9325 public final void addService(PackageParser.Service s) { 9326 mServices.put(s.getComponentName(), s); 9327 if (DEBUG_SHOW_INFO) { 9328 Log.v(TAG, " " 9329 + (s.info.nonLocalizedLabel != null 9330 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9331 Log.v(TAG, " Class=" + s.info.name); 9332 } 9333 final int NI = s.intents.size(); 9334 int j; 9335 for (j=0; j<NI; j++) { 9336 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9337 if (DEBUG_SHOW_INFO) { 9338 Log.v(TAG, " IntentFilter:"); 9339 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9340 } 9341 if (!intent.debugCheck()) { 9342 Log.w(TAG, "==> For Service " + s.info.name); 9343 } 9344 addFilter(intent); 9345 } 9346 } 9347 9348 public final void removeService(PackageParser.Service s) { 9349 mServices.remove(s.getComponentName()); 9350 if (DEBUG_SHOW_INFO) { 9351 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 9352 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9353 Log.v(TAG, " Class=" + s.info.name); 9354 } 9355 final int NI = s.intents.size(); 9356 int j; 9357 for (j=0; j<NI; j++) { 9358 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9359 if (DEBUG_SHOW_INFO) { 9360 Log.v(TAG, " IntentFilter:"); 9361 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9362 } 9363 removeFilter(intent); 9364 } 9365 } 9366 9367 @Override 9368 protected boolean allowFilterResult( 9369 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 9370 ServiceInfo filterSi = filter.service.info; 9371 for (int i=dest.size()-1; i>=0; i--) { 9372 ServiceInfo destAi = dest.get(i).serviceInfo; 9373 if (destAi.name == filterSi.name 9374 && destAi.packageName == filterSi.packageName) { 9375 return false; 9376 } 9377 } 9378 return true; 9379 } 9380 9381 @Override 9382 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 9383 return new PackageParser.ServiceIntentInfo[size]; 9384 } 9385 9386 @Override 9387 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 9388 if (!sUserManager.exists(userId)) return true; 9389 PackageParser.Package p = filter.service.owner; 9390 if (p != null) { 9391 PackageSetting ps = (PackageSetting)p.mExtras; 9392 if (ps != null) { 9393 // System apps are never considered stopped for purposes of 9394 // filtering, because there may be no way for the user to 9395 // actually re-launch them. 9396 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9397 && ps.getStopped(userId); 9398 } 9399 } 9400 return false; 9401 } 9402 9403 @Override 9404 protected boolean isPackageForFilter(String packageName, 9405 PackageParser.ServiceIntentInfo info) { 9406 return packageName.equals(info.service.owner.packageName); 9407 } 9408 9409 @Override 9410 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 9411 int match, int userId) { 9412 if (!sUserManager.exists(userId)) return null; 9413 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 9414 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 9415 return null; 9416 } 9417 final PackageParser.Service service = info.service; 9418 PackageSetting ps = (PackageSetting) service.owner.mExtras; 9419 if (ps == null) { 9420 return null; 9421 } 9422 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 9423 ps.readUserState(userId), userId); 9424 if (si == null) { 9425 return null; 9426 } 9427 final ResolveInfo res = new ResolveInfo(); 9428 res.serviceInfo = si; 9429 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9430 res.filter = filter; 9431 } 9432 res.priority = info.getPriority(); 9433 res.preferredOrder = service.owner.mPreferredOrder; 9434 res.match = match; 9435 res.isDefault = info.hasDefault; 9436 res.labelRes = info.labelRes; 9437 res.nonLocalizedLabel = info.nonLocalizedLabel; 9438 res.icon = info.icon; 9439 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 9440 return res; 9441 } 9442 9443 @Override 9444 protected void sortResults(List<ResolveInfo> results) { 9445 Collections.sort(results, mResolvePrioritySorter); 9446 } 9447 9448 @Override 9449 protected void dumpFilter(PrintWriter out, String prefix, 9450 PackageParser.ServiceIntentInfo filter) { 9451 out.print(prefix); out.print( 9452 Integer.toHexString(System.identityHashCode(filter.service))); 9453 out.print(' '); 9454 filter.service.printComponentShortName(out); 9455 out.print(" filter "); 9456 out.println(Integer.toHexString(System.identityHashCode(filter))); 9457 } 9458 9459 @Override 9460 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 9461 return filter.service; 9462 } 9463 9464 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9465 PackageParser.Service service = (PackageParser.Service)label; 9466 out.print(prefix); out.print( 9467 Integer.toHexString(System.identityHashCode(service))); 9468 out.print(' '); 9469 service.printComponentShortName(out); 9470 if (count > 1) { 9471 out.print(" ("); out.print(count); out.print(" filters)"); 9472 } 9473 out.println(); 9474 } 9475 9476// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9477// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9478// final List<ResolveInfo> retList = Lists.newArrayList(); 9479// while (i.hasNext()) { 9480// final ResolveInfo resolveInfo = (ResolveInfo) i; 9481// if (isEnabledLP(resolveInfo.serviceInfo)) { 9482// retList.add(resolveInfo); 9483// } 9484// } 9485// return retList; 9486// } 9487 9488 // Keys are String (activity class name), values are Activity. 9489 private final ArrayMap<ComponentName, PackageParser.Service> mServices 9490 = new ArrayMap<ComponentName, PackageParser.Service>(); 9491 private int mFlags; 9492 }; 9493 9494 private final class ProviderIntentResolver 9495 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 9496 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9497 boolean defaultOnly, int userId) { 9498 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9499 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9500 } 9501 9502 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9503 int userId) { 9504 if (!sUserManager.exists(userId)) 9505 return null; 9506 mFlags = flags; 9507 return super.queryIntent(intent, resolvedType, 9508 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9509 } 9510 9511 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9512 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 9513 if (!sUserManager.exists(userId)) 9514 return null; 9515 if (packageProviders == null) { 9516 return null; 9517 } 9518 mFlags = flags; 9519 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 9520 final int N = packageProviders.size(); 9521 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 9522 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 9523 9524 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 9525 for (int i = 0; i < N; ++i) { 9526 intentFilters = packageProviders.get(i).intents; 9527 if (intentFilters != null && intentFilters.size() > 0) { 9528 PackageParser.ProviderIntentInfo[] array = 9529 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 9530 intentFilters.toArray(array); 9531 listCut.add(array); 9532 } 9533 } 9534 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9535 } 9536 9537 public final void addProvider(PackageParser.Provider p) { 9538 if (mProviders.containsKey(p.getComponentName())) { 9539 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 9540 return; 9541 } 9542 9543 mProviders.put(p.getComponentName(), p); 9544 if (DEBUG_SHOW_INFO) { 9545 Log.v(TAG, " " 9546 + (p.info.nonLocalizedLabel != null 9547 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9548 Log.v(TAG, " Class=" + p.info.name); 9549 } 9550 final int NI = p.intents.size(); 9551 int j; 9552 for (j = 0; j < NI; j++) { 9553 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9554 if (DEBUG_SHOW_INFO) { 9555 Log.v(TAG, " IntentFilter:"); 9556 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9557 } 9558 if (!intent.debugCheck()) { 9559 Log.w(TAG, "==> For Provider " + p.info.name); 9560 } 9561 addFilter(intent); 9562 } 9563 } 9564 9565 public final void removeProvider(PackageParser.Provider p) { 9566 mProviders.remove(p.getComponentName()); 9567 if (DEBUG_SHOW_INFO) { 9568 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 9569 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9570 Log.v(TAG, " Class=" + p.info.name); 9571 } 9572 final int NI = p.intents.size(); 9573 int j; 9574 for (j = 0; j < NI; j++) { 9575 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9576 if (DEBUG_SHOW_INFO) { 9577 Log.v(TAG, " IntentFilter:"); 9578 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9579 } 9580 removeFilter(intent); 9581 } 9582 } 9583 9584 @Override 9585 protected boolean allowFilterResult( 9586 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 9587 ProviderInfo filterPi = filter.provider.info; 9588 for (int i = dest.size() - 1; i >= 0; i--) { 9589 ProviderInfo destPi = dest.get(i).providerInfo; 9590 if (destPi.name == filterPi.name 9591 && destPi.packageName == filterPi.packageName) { 9592 return false; 9593 } 9594 } 9595 return true; 9596 } 9597 9598 @Override 9599 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 9600 return new PackageParser.ProviderIntentInfo[size]; 9601 } 9602 9603 @Override 9604 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 9605 if (!sUserManager.exists(userId)) 9606 return true; 9607 PackageParser.Package p = filter.provider.owner; 9608 if (p != null) { 9609 PackageSetting ps = (PackageSetting) p.mExtras; 9610 if (ps != null) { 9611 // System apps are never considered stopped for purposes of 9612 // filtering, because there may be no way for the user to 9613 // actually re-launch them. 9614 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9615 && ps.getStopped(userId); 9616 } 9617 } 9618 return false; 9619 } 9620 9621 @Override 9622 protected boolean isPackageForFilter(String packageName, 9623 PackageParser.ProviderIntentInfo info) { 9624 return packageName.equals(info.provider.owner.packageName); 9625 } 9626 9627 @Override 9628 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 9629 int match, int userId) { 9630 if (!sUserManager.exists(userId)) 9631 return null; 9632 final PackageParser.ProviderIntentInfo info = filter; 9633 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 9634 return null; 9635 } 9636 final PackageParser.Provider provider = info.provider; 9637 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 9638 if (ps == null) { 9639 return null; 9640 } 9641 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 9642 ps.readUserState(userId), userId); 9643 if (pi == null) { 9644 return null; 9645 } 9646 final ResolveInfo res = new ResolveInfo(); 9647 res.providerInfo = pi; 9648 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 9649 res.filter = filter; 9650 } 9651 res.priority = info.getPriority(); 9652 res.preferredOrder = provider.owner.mPreferredOrder; 9653 res.match = match; 9654 res.isDefault = info.hasDefault; 9655 res.labelRes = info.labelRes; 9656 res.nonLocalizedLabel = info.nonLocalizedLabel; 9657 res.icon = info.icon; 9658 res.system = res.providerInfo.applicationInfo.isSystemApp(); 9659 return res; 9660 } 9661 9662 @Override 9663 protected void sortResults(List<ResolveInfo> results) { 9664 Collections.sort(results, mResolvePrioritySorter); 9665 } 9666 9667 @Override 9668 protected void dumpFilter(PrintWriter out, String prefix, 9669 PackageParser.ProviderIntentInfo filter) { 9670 out.print(prefix); 9671 out.print( 9672 Integer.toHexString(System.identityHashCode(filter.provider))); 9673 out.print(' '); 9674 filter.provider.printComponentShortName(out); 9675 out.print(" filter "); 9676 out.println(Integer.toHexString(System.identityHashCode(filter))); 9677 } 9678 9679 @Override 9680 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 9681 return filter.provider; 9682 } 9683 9684 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9685 PackageParser.Provider provider = (PackageParser.Provider)label; 9686 out.print(prefix); out.print( 9687 Integer.toHexString(System.identityHashCode(provider))); 9688 out.print(' '); 9689 provider.printComponentShortName(out); 9690 if (count > 1) { 9691 out.print(" ("); out.print(count); out.print(" filters)"); 9692 } 9693 out.println(); 9694 } 9695 9696 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 9697 = new ArrayMap<ComponentName, PackageParser.Provider>(); 9698 private int mFlags; 9699 } 9700 9701 private static final class EphemeralIntentResolver 9702 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 9703 @Override 9704 protected EphemeralResolveIntentInfo[] newArray(int size) { 9705 return new EphemeralResolveIntentInfo[size]; 9706 } 9707 9708 @Override 9709 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 9710 return true; 9711 } 9712 9713 @Override 9714 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 9715 int userId) { 9716 if (!sUserManager.exists(userId)) { 9717 return null; 9718 } 9719 return info.getEphemeralResolveInfo(); 9720 } 9721 } 9722 9723 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 9724 new Comparator<ResolveInfo>() { 9725 public int compare(ResolveInfo r1, ResolveInfo r2) { 9726 int v1 = r1.priority; 9727 int v2 = r2.priority; 9728 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 9729 if (v1 != v2) { 9730 return (v1 > v2) ? -1 : 1; 9731 } 9732 v1 = r1.preferredOrder; 9733 v2 = r2.preferredOrder; 9734 if (v1 != v2) { 9735 return (v1 > v2) ? -1 : 1; 9736 } 9737 if (r1.isDefault != r2.isDefault) { 9738 return r1.isDefault ? -1 : 1; 9739 } 9740 v1 = r1.match; 9741 v2 = r2.match; 9742 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 9743 if (v1 != v2) { 9744 return (v1 > v2) ? -1 : 1; 9745 } 9746 if (r1.system != r2.system) { 9747 return r1.system ? -1 : 1; 9748 } 9749 if (r1.activityInfo != null) { 9750 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 9751 } 9752 if (r1.serviceInfo != null) { 9753 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 9754 } 9755 if (r1.providerInfo != null) { 9756 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 9757 } 9758 return 0; 9759 } 9760 }; 9761 9762 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 9763 new Comparator<ProviderInfo>() { 9764 public int compare(ProviderInfo p1, ProviderInfo p2) { 9765 final int v1 = p1.initOrder; 9766 final int v2 = p2.initOrder; 9767 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 9768 } 9769 }; 9770 9771 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 9772 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 9773 final int[] userIds) { 9774 mHandler.post(new Runnable() { 9775 @Override 9776 public void run() { 9777 try { 9778 final IActivityManager am = ActivityManagerNative.getDefault(); 9779 if (am == null) return; 9780 final int[] resolvedUserIds; 9781 if (userIds == null) { 9782 resolvedUserIds = am.getRunningUserIds(); 9783 } else { 9784 resolvedUserIds = userIds; 9785 } 9786 for (int id : resolvedUserIds) { 9787 final Intent intent = new Intent(action, 9788 pkg != null ? Uri.fromParts("package", pkg, null) : null); 9789 if (extras != null) { 9790 intent.putExtras(extras); 9791 } 9792 if (targetPkg != null) { 9793 intent.setPackage(targetPkg); 9794 } 9795 // Modify the UID when posting to other users 9796 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 9797 if (uid > 0 && UserHandle.getUserId(uid) != id) { 9798 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 9799 intent.putExtra(Intent.EXTRA_UID, uid); 9800 } 9801 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 9802 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 9803 if (DEBUG_BROADCASTS) { 9804 RuntimeException here = new RuntimeException("here"); 9805 here.fillInStackTrace(); 9806 Slog.d(TAG, "Sending to user " + id + ": " 9807 + intent.toShortString(false, true, false, false) 9808 + " " + intent.getExtras(), here); 9809 } 9810 am.broadcastIntent(null, intent, null, finishedReceiver, 9811 0, null, null, null, android.app.AppOpsManager.OP_NONE, 9812 null, finishedReceiver != null, false, id); 9813 } 9814 } catch (RemoteException ex) { 9815 } 9816 } 9817 }); 9818 } 9819 9820 /** 9821 * Check if the external storage media is available. This is true if there 9822 * is a mounted external storage medium or if the external storage is 9823 * emulated. 9824 */ 9825 private boolean isExternalMediaAvailable() { 9826 return mMediaMounted || Environment.isExternalStorageEmulated(); 9827 } 9828 9829 @Override 9830 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 9831 // writer 9832 synchronized (mPackages) { 9833 if (!isExternalMediaAvailable()) { 9834 // If the external storage is no longer mounted at this point, 9835 // the caller may not have been able to delete all of this 9836 // packages files and can not delete any more. Bail. 9837 return null; 9838 } 9839 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 9840 if (lastPackage != null) { 9841 pkgs.remove(lastPackage); 9842 } 9843 if (pkgs.size() > 0) { 9844 return pkgs.get(0); 9845 } 9846 } 9847 return null; 9848 } 9849 9850 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 9851 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 9852 userId, andCode ? 1 : 0, packageName); 9853 if (mSystemReady) { 9854 msg.sendToTarget(); 9855 } else { 9856 if (mPostSystemReadyMessages == null) { 9857 mPostSystemReadyMessages = new ArrayList<>(); 9858 } 9859 mPostSystemReadyMessages.add(msg); 9860 } 9861 } 9862 9863 void startCleaningPackages() { 9864 // reader 9865 synchronized (mPackages) { 9866 if (!isExternalMediaAvailable()) { 9867 return; 9868 } 9869 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 9870 return; 9871 } 9872 } 9873 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 9874 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 9875 IActivityManager am = ActivityManagerNative.getDefault(); 9876 if (am != null) { 9877 try { 9878 am.startService(null, intent, null, mContext.getOpPackageName(), 9879 UserHandle.USER_SYSTEM); 9880 } catch (RemoteException e) { 9881 } 9882 } 9883 } 9884 9885 @Override 9886 public void installPackage(String originPath, IPackageInstallObserver2 observer, 9887 int installFlags, String installerPackageName, VerificationParams verificationParams, 9888 String packageAbiOverride) { 9889 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 9890 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 9891 } 9892 9893 @Override 9894 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 9895 int installFlags, String installerPackageName, VerificationParams verificationParams, 9896 String packageAbiOverride, int userId) { 9897 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 9898 9899 final int callingUid = Binder.getCallingUid(); 9900 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 9901 9902 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9903 try { 9904 if (observer != null) { 9905 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 9906 } 9907 } catch (RemoteException re) { 9908 } 9909 return; 9910 } 9911 9912 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 9913 installFlags |= PackageManager.INSTALL_FROM_ADB; 9914 9915 } else { 9916 // Caller holds INSTALL_PACKAGES permission, so we're less strict 9917 // about installerPackageName. 9918 9919 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 9920 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 9921 } 9922 9923 UserHandle user; 9924 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 9925 user = UserHandle.ALL; 9926 } else { 9927 user = new UserHandle(userId); 9928 } 9929 9930 // Only system components can circumvent runtime permissions when installing. 9931 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 9932 && mContext.checkCallingOrSelfPermission(Manifest.permission 9933 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 9934 throw new SecurityException("You need the " 9935 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 9936 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 9937 } 9938 9939 verificationParams.setInstallerUid(callingUid); 9940 9941 final File originFile = new File(originPath); 9942 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 9943 9944 final Message msg = mHandler.obtainMessage(INIT_COPY); 9945 final InstallParams params = new InstallParams(origin, null, observer, installFlags, 9946 installerPackageName, null, verificationParams, user, packageAbiOverride, null); 9947 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 9948 msg.obj = params; 9949 9950 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 9951 System.identityHashCode(msg.obj)); 9952 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 9953 System.identityHashCode(msg.obj)); 9954 9955 mHandler.sendMessage(msg); 9956 } 9957 9958 void installStage(String packageName, File stagedDir, String stagedCid, 9959 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 9960 String installerPackageName, int installerUid, UserHandle user) { 9961 if (DEBUG_EPHEMERAL) { 9962 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 9963 Slog.d(TAG, "Ephemeral install of " + packageName); 9964 } 9965 } 9966 final VerificationParams verifParams = new VerificationParams( 9967 null, sessionParams.originatingUri, sessionParams.referrerUri, 9968 sessionParams.originatingUid); 9969 verifParams.setInstallerUid(installerUid); 9970 9971 final OriginInfo origin; 9972 if (stagedDir != null) { 9973 origin = OriginInfo.fromStagedFile(stagedDir); 9974 } else { 9975 origin = OriginInfo.fromStagedContainer(stagedCid); 9976 } 9977 9978 final Message msg = mHandler.obtainMessage(INIT_COPY); 9979 final InstallParams params = new InstallParams(origin, null, observer, 9980 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 9981 verifParams, user, sessionParams.abiOverride, 9982 sessionParams.grantedRuntimePermissions); 9983 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 9984 msg.obj = params; 9985 9986 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 9987 System.identityHashCode(msg.obj)); 9988 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 9989 System.identityHashCode(msg.obj)); 9990 9991 mHandler.sendMessage(msg); 9992 } 9993 9994 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 9995 Bundle extras = new Bundle(1); 9996 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 9997 9998 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 9999 packageName, extras, 0, null, null, new int[] {userId}); 10000 try { 10001 IActivityManager am = ActivityManagerNative.getDefault(); 10002 final boolean isSystem = 10003 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 10004 if (isSystem && am.isUserRunning(userId, 0)) { 10005 // The just-installed/enabled app is bundled on the system, so presumed 10006 // to be able to run automatically without needing an explicit launch. 10007 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 10008 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 10009 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 10010 .setPackage(packageName); 10011 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 10012 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 10013 } 10014 } catch (RemoteException e) { 10015 // shouldn't happen 10016 Slog.w(TAG, "Unable to bootstrap installed package", e); 10017 } 10018 } 10019 10020 @Override 10021 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 10022 int userId) { 10023 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10024 PackageSetting pkgSetting; 10025 final int uid = Binder.getCallingUid(); 10026 enforceCrossUserPermission(uid, userId, true, true, 10027 "setApplicationHiddenSetting for user " + userId); 10028 10029 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 10030 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 10031 return false; 10032 } 10033 10034 long callingId = Binder.clearCallingIdentity(); 10035 try { 10036 boolean sendAdded = false; 10037 boolean sendRemoved = false; 10038 // writer 10039 synchronized (mPackages) { 10040 pkgSetting = mSettings.mPackages.get(packageName); 10041 if (pkgSetting == null) { 10042 return false; 10043 } 10044 if (pkgSetting.getHidden(userId) != hidden) { 10045 pkgSetting.setHidden(hidden, userId); 10046 mSettings.writePackageRestrictionsLPr(userId); 10047 if (hidden) { 10048 sendRemoved = true; 10049 } else { 10050 sendAdded = true; 10051 } 10052 } 10053 } 10054 if (sendAdded) { 10055 sendPackageAddedForUser(packageName, pkgSetting, userId); 10056 return true; 10057 } 10058 if (sendRemoved) { 10059 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 10060 "hiding pkg"); 10061 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 10062 return true; 10063 } 10064 } finally { 10065 Binder.restoreCallingIdentity(callingId); 10066 } 10067 return false; 10068 } 10069 10070 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 10071 int userId) { 10072 final PackageRemovedInfo info = new PackageRemovedInfo(); 10073 info.removedPackage = packageName; 10074 info.removedUsers = new int[] {userId}; 10075 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 10076 info.sendBroadcast(false, false, false); 10077 } 10078 10079 /** 10080 * Returns true if application is not found or there was an error. Otherwise it returns 10081 * the hidden state of the package for the given user. 10082 */ 10083 @Override 10084 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 10085 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10086 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 10087 false, "getApplicationHidden for user " + userId); 10088 PackageSetting pkgSetting; 10089 long callingId = Binder.clearCallingIdentity(); 10090 try { 10091 // writer 10092 synchronized (mPackages) { 10093 pkgSetting = mSettings.mPackages.get(packageName); 10094 if (pkgSetting == null) { 10095 return true; 10096 } 10097 return pkgSetting.getHidden(userId); 10098 } 10099 } finally { 10100 Binder.restoreCallingIdentity(callingId); 10101 } 10102 } 10103 10104 /** 10105 * @hide 10106 */ 10107 @Override 10108 public int installExistingPackageAsUser(String packageName, int userId) { 10109 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 10110 null); 10111 PackageSetting pkgSetting; 10112 final int uid = Binder.getCallingUid(); 10113 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 10114 + userId); 10115 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 10116 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 10117 } 10118 10119 long callingId = Binder.clearCallingIdentity(); 10120 try { 10121 boolean installed = false; 10122 10123 // writer 10124 synchronized (mPackages) { 10125 pkgSetting = mSettings.mPackages.get(packageName); 10126 if (pkgSetting == null) { 10127 return PackageManager.INSTALL_FAILED_INVALID_URI; 10128 } 10129 if (!pkgSetting.getInstalled(userId)) { 10130 pkgSetting.setInstalled(true, userId); 10131 pkgSetting.setHidden(false, userId); 10132 mSettings.writePackageRestrictionsLPr(userId); 10133 if (pkgSetting.pkg != null) { 10134 prepareAppDataAfterInstall(pkgSetting.pkg); 10135 } 10136 installed = true; 10137 } 10138 } 10139 10140 if (installed) { 10141 sendPackageAddedForUser(packageName, pkgSetting, userId); 10142 } 10143 } finally { 10144 Binder.restoreCallingIdentity(callingId); 10145 } 10146 10147 return PackageManager.INSTALL_SUCCEEDED; 10148 } 10149 10150 boolean isUserRestricted(int userId, String restrictionKey) { 10151 Bundle restrictions = sUserManager.getUserRestrictions(userId); 10152 if (restrictions.getBoolean(restrictionKey, false)) { 10153 Log.w(TAG, "User is restricted: " + restrictionKey); 10154 return true; 10155 } 10156 return false; 10157 } 10158 10159 @Override 10160 public boolean setPackageSuspendedAsUser(String packageName, boolean suspended, int userId) { 10161 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10162 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, true, 10163 "setPackageSuspended for user " + userId); 10164 10165 long callingId = Binder.clearCallingIdentity(); 10166 try { 10167 synchronized (mPackages) { 10168 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 10169 if (pkgSetting != null) { 10170 if (pkgSetting.getSuspended(userId) != suspended) { 10171 pkgSetting.setSuspended(suspended, userId); 10172 mSettings.writePackageRestrictionsLPr(userId); 10173 } 10174 10175 // TODO: 10176 // * broadcast a PACKAGE_(UN)SUSPENDED intent for launchers to pick up 10177 // * remove app from recents (kill app it if it is running) 10178 // * erase existing notifications for this app 10179 return true; 10180 } 10181 10182 return false; 10183 } 10184 } finally { 10185 Binder.restoreCallingIdentity(callingId); 10186 } 10187 } 10188 10189 @Override 10190 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 10191 mContext.enforceCallingOrSelfPermission( 10192 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10193 "Only package verification agents can verify applications"); 10194 10195 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 10196 final PackageVerificationResponse response = new PackageVerificationResponse( 10197 verificationCode, Binder.getCallingUid()); 10198 msg.arg1 = id; 10199 msg.obj = response; 10200 mHandler.sendMessage(msg); 10201 } 10202 10203 @Override 10204 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 10205 long millisecondsToDelay) { 10206 mContext.enforceCallingOrSelfPermission( 10207 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10208 "Only package verification agents can extend verification timeouts"); 10209 10210 final PackageVerificationState state = mPendingVerification.get(id); 10211 final PackageVerificationResponse response = new PackageVerificationResponse( 10212 verificationCodeAtTimeout, Binder.getCallingUid()); 10213 10214 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 10215 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 10216 } 10217 if (millisecondsToDelay < 0) { 10218 millisecondsToDelay = 0; 10219 } 10220 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 10221 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 10222 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 10223 } 10224 10225 if ((state != null) && !state.timeoutExtended()) { 10226 state.extendTimeout(); 10227 10228 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 10229 msg.arg1 = id; 10230 msg.obj = response; 10231 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 10232 } 10233 } 10234 10235 private void broadcastPackageVerified(int verificationId, Uri packageUri, 10236 int verificationCode, UserHandle user) { 10237 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 10238 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 10239 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10240 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10241 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 10242 10243 mContext.sendBroadcastAsUser(intent, user, 10244 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 10245 } 10246 10247 private ComponentName matchComponentForVerifier(String packageName, 10248 List<ResolveInfo> receivers) { 10249 ActivityInfo targetReceiver = null; 10250 10251 final int NR = receivers.size(); 10252 for (int i = 0; i < NR; i++) { 10253 final ResolveInfo info = receivers.get(i); 10254 if (info.activityInfo == null) { 10255 continue; 10256 } 10257 10258 if (packageName.equals(info.activityInfo.packageName)) { 10259 targetReceiver = info.activityInfo; 10260 break; 10261 } 10262 } 10263 10264 if (targetReceiver == null) { 10265 return null; 10266 } 10267 10268 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 10269 } 10270 10271 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 10272 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 10273 if (pkgInfo.verifiers.length == 0) { 10274 return null; 10275 } 10276 10277 final int N = pkgInfo.verifiers.length; 10278 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 10279 for (int i = 0; i < N; i++) { 10280 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 10281 10282 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 10283 receivers); 10284 if (comp == null) { 10285 continue; 10286 } 10287 10288 final int verifierUid = getUidForVerifier(verifierInfo); 10289 if (verifierUid == -1) { 10290 continue; 10291 } 10292 10293 if (DEBUG_VERIFY) { 10294 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 10295 + " with the correct signature"); 10296 } 10297 sufficientVerifiers.add(comp); 10298 verificationState.addSufficientVerifier(verifierUid); 10299 } 10300 10301 return sufficientVerifiers; 10302 } 10303 10304 private int getUidForVerifier(VerifierInfo verifierInfo) { 10305 synchronized (mPackages) { 10306 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 10307 if (pkg == null) { 10308 return -1; 10309 } else if (pkg.mSignatures.length != 1) { 10310 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10311 + " has more than one signature; ignoring"); 10312 return -1; 10313 } 10314 10315 /* 10316 * If the public key of the package's signature does not match 10317 * our expected public key, then this is a different package and 10318 * we should skip. 10319 */ 10320 10321 final byte[] expectedPublicKey; 10322 try { 10323 final Signature verifierSig = pkg.mSignatures[0]; 10324 final PublicKey publicKey = verifierSig.getPublicKey(); 10325 expectedPublicKey = publicKey.getEncoded(); 10326 } catch (CertificateException e) { 10327 return -1; 10328 } 10329 10330 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 10331 10332 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 10333 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10334 + " does not have the expected public key; ignoring"); 10335 return -1; 10336 } 10337 10338 return pkg.applicationInfo.uid; 10339 } 10340 } 10341 10342 @Override 10343 public void finishPackageInstall(int token) { 10344 enforceSystemOrRoot("Only the system is allowed to finish installs"); 10345 10346 if (DEBUG_INSTALL) { 10347 Slog.v(TAG, "BM finishing package install for " + token); 10348 } 10349 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10350 10351 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10352 mHandler.sendMessage(msg); 10353 } 10354 10355 /** 10356 * Get the verification agent timeout. 10357 * 10358 * @return verification timeout in milliseconds 10359 */ 10360 private long getVerificationTimeout() { 10361 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 10362 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 10363 DEFAULT_VERIFICATION_TIMEOUT); 10364 } 10365 10366 /** 10367 * Get the default verification agent response code. 10368 * 10369 * @return default verification response code 10370 */ 10371 private int getDefaultVerificationResponse() { 10372 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10373 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 10374 DEFAULT_VERIFICATION_RESPONSE); 10375 } 10376 10377 /** 10378 * Check whether or not package verification has been enabled. 10379 * 10380 * @return true if verification should be performed 10381 */ 10382 private boolean isVerificationEnabled(int userId, int installFlags) { 10383 if (!DEFAULT_VERIFY_ENABLE) { 10384 return false; 10385 } 10386 // Ephemeral apps don't get the full verification treatment 10387 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 10388 if (DEBUG_EPHEMERAL) { 10389 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 10390 } 10391 return false; 10392 } 10393 10394 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 10395 10396 // Check if installing from ADB 10397 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 10398 // Do not run verification in a test harness environment 10399 if (ActivityManager.isRunningInTestHarness()) { 10400 return false; 10401 } 10402 if (ensureVerifyAppsEnabled) { 10403 return true; 10404 } 10405 // Check if the developer does not want package verification for ADB installs 10406 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10407 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 10408 return false; 10409 } 10410 } 10411 10412 if (ensureVerifyAppsEnabled) { 10413 return true; 10414 } 10415 10416 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10417 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 10418 } 10419 10420 @Override 10421 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 10422 throws RemoteException { 10423 mContext.enforceCallingOrSelfPermission( 10424 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 10425 "Only intentfilter verification agents can verify applications"); 10426 10427 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 10428 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 10429 Binder.getCallingUid(), verificationCode, failedDomains); 10430 msg.arg1 = id; 10431 msg.obj = response; 10432 mHandler.sendMessage(msg); 10433 } 10434 10435 @Override 10436 public int getIntentVerificationStatus(String packageName, int userId) { 10437 synchronized (mPackages) { 10438 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 10439 } 10440 } 10441 10442 @Override 10443 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 10444 mContext.enforceCallingOrSelfPermission( 10445 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10446 10447 boolean result = false; 10448 synchronized (mPackages) { 10449 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 10450 } 10451 if (result) { 10452 scheduleWritePackageRestrictionsLocked(userId); 10453 } 10454 return result; 10455 } 10456 10457 @Override 10458 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 10459 synchronized (mPackages) { 10460 return mSettings.getIntentFilterVerificationsLPr(packageName); 10461 } 10462 } 10463 10464 @Override 10465 public List<IntentFilter> getAllIntentFilters(String packageName) { 10466 if (TextUtils.isEmpty(packageName)) { 10467 return Collections.<IntentFilter>emptyList(); 10468 } 10469 synchronized (mPackages) { 10470 PackageParser.Package pkg = mPackages.get(packageName); 10471 if (pkg == null || pkg.activities == null) { 10472 return Collections.<IntentFilter>emptyList(); 10473 } 10474 final int count = pkg.activities.size(); 10475 ArrayList<IntentFilter> result = new ArrayList<>(); 10476 for (int n=0; n<count; n++) { 10477 PackageParser.Activity activity = pkg.activities.get(n); 10478 if (activity.intents != null && activity.intents.size() > 0) { 10479 result.addAll(activity.intents); 10480 } 10481 } 10482 return result; 10483 } 10484 } 10485 10486 @Override 10487 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 10488 mContext.enforceCallingOrSelfPermission( 10489 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10490 10491 synchronized (mPackages) { 10492 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 10493 if (packageName != null) { 10494 result |= updateIntentVerificationStatus(packageName, 10495 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 10496 userId); 10497 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 10498 packageName, userId); 10499 } 10500 return result; 10501 } 10502 } 10503 10504 @Override 10505 public String getDefaultBrowserPackageName(int userId) { 10506 synchronized (mPackages) { 10507 return mSettings.getDefaultBrowserPackageNameLPw(userId); 10508 } 10509 } 10510 10511 /** 10512 * Get the "allow unknown sources" setting. 10513 * 10514 * @return the current "allow unknown sources" setting 10515 */ 10516 private int getUnknownSourcesSettings() { 10517 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10518 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 10519 -1); 10520 } 10521 10522 @Override 10523 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 10524 final int uid = Binder.getCallingUid(); 10525 // writer 10526 synchronized (mPackages) { 10527 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 10528 if (targetPackageSetting == null) { 10529 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 10530 } 10531 10532 PackageSetting installerPackageSetting; 10533 if (installerPackageName != null) { 10534 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 10535 if (installerPackageSetting == null) { 10536 throw new IllegalArgumentException("Unknown installer package: " 10537 + installerPackageName); 10538 } 10539 } else { 10540 installerPackageSetting = null; 10541 } 10542 10543 Signature[] callerSignature; 10544 Object obj = mSettings.getUserIdLPr(uid); 10545 if (obj != null) { 10546 if (obj instanceof SharedUserSetting) { 10547 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 10548 } else if (obj instanceof PackageSetting) { 10549 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 10550 } else { 10551 throw new SecurityException("Bad object " + obj + " for uid " + uid); 10552 } 10553 } else { 10554 throw new SecurityException("Unknown calling UID: " + uid); 10555 } 10556 10557 // Verify: can't set installerPackageName to a package that is 10558 // not signed with the same cert as the caller. 10559 if (installerPackageSetting != null) { 10560 if (compareSignatures(callerSignature, 10561 installerPackageSetting.signatures.mSignatures) 10562 != PackageManager.SIGNATURE_MATCH) { 10563 throw new SecurityException( 10564 "Caller does not have same cert as new installer package " 10565 + installerPackageName); 10566 } 10567 } 10568 10569 // Verify: if target already has an installer package, it must 10570 // be signed with the same cert as the caller. 10571 if (targetPackageSetting.installerPackageName != null) { 10572 PackageSetting setting = mSettings.mPackages.get( 10573 targetPackageSetting.installerPackageName); 10574 // If the currently set package isn't valid, then it's always 10575 // okay to change it. 10576 if (setting != null) { 10577 if (compareSignatures(callerSignature, 10578 setting.signatures.mSignatures) 10579 != PackageManager.SIGNATURE_MATCH) { 10580 throw new SecurityException( 10581 "Caller does not have same cert as old installer package " 10582 + targetPackageSetting.installerPackageName); 10583 } 10584 } 10585 } 10586 10587 // Okay! 10588 targetPackageSetting.installerPackageName = installerPackageName; 10589 scheduleWriteSettingsLocked(); 10590 } 10591 } 10592 10593 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 10594 // Queue up an async operation since the package installation may take a little while. 10595 mHandler.post(new Runnable() { 10596 public void run() { 10597 mHandler.removeCallbacks(this); 10598 // Result object to be returned 10599 PackageInstalledInfo res = new PackageInstalledInfo(); 10600 res.returnCode = currentStatus; 10601 res.uid = -1; 10602 res.pkg = null; 10603 res.removedInfo = new PackageRemovedInfo(); 10604 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10605 args.doPreInstall(res.returnCode); 10606 synchronized (mInstallLock) { 10607 installPackageTracedLI(args, res); 10608 } 10609 args.doPostInstall(res.returnCode, res.uid); 10610 } 10611 10612 // A restore should be performed at this point if (a) the install 10613 // succeeded, (b) the operation is not an update, and (c) the new 10614 // package has not opted out of backup participation. 10615 final boolean update = res.removedInfo.removedPackage != null; 10616 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 10617 boolean doRestore = !update 10618 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 10619 10620 // Set up the post-install work request bookkeeping. This will be used 10621 // and cleaned up by the post-install event handling regardless of whether 10622 // there's a restore pass performed. Token values are >= 1. 10623 int token; 10624 if (mNextInstallToken < 0) mNextInstallToken = 1; 10625 token = mNextInstallToken++; 10626 10627 PostInstallData data = new PostInstallData(args, res); 10628 mRunningInstalls.put(token, data); 10629 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 10630 10631 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 10632 // Pass responsibility to the Backup Manager. It will perform a 10633 // restore if appropriate, then pass responsibility back to the 10634 // Package Manager to run the post-install observer callbacks 10635 // and broadcasts. 10636 IBackupManager bm = IBackupManager.Stub.asInterface( 10637 ServiceManager.getService(Context.BACKUP_SERVICE)); 10638 if (bm != null) { 10639 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 10640 + " to BM for possible restore"); 10641 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10642 try { 10643 // TODO: http://b/22388012 10644 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 10645 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 10646 } else { 10647 doRestore = false; 10648 } 10649 } catch (RemoteException e) { 10650 // can't happen; the backup manager is local 10651 } catch (Exception e) { 10652 Slog.e(TAG, "Exception trying to enqueue restore", e); 10653 doRestore = false; 10654 } 10655 } else { 10656 Slog.e(TAG, "Backup Manager not found!"); 10657 doRestore = false; 10658 } 10659 } 10660 10661 if (!doRestore) { 10662 // No restore possible, or the Backup Manager was mysteriously not 10663 // available -- just fire the post-install work request directly. 10664 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 10665 10666 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 10667 10668 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10669 mHandler.sendMessage(msg); 10670 } 10671 } 10672 }); 10673 } 10674 10675 private abstract class HandlerParams { 10676 private static final int MAX_RETRIES = 4; 10677 10678 /** 10679 * Number of times startCopy() has been attempted and had a non-fatal 10680 * error. 10681 */ 10682 private int mRetries = 0; 10683 10684 /** User handle for the user requesting the information or installation. */ 10685 private final UserHandle mUser; 10686 String traceMethod; 10687 int traceCookie; 10688 10689 HandlerParams(UserHandle user) { 10690 mUser = user; 10691 } 10692 10693 UserHandle getUser() { 10694 return mUser; 10695 } 10696 10697 HandlerParams setTraceMethod(String traceMethod) { 10698 this.traceMethod = traceMethod; 10699 return this; 10700 } 10701 10702 HandlerParams setTraceCookie(int traceCookie) { 10703 this.traceCookie = traceCookie; 10704 return this; 10705 } 10706 10707 final boolean startCopy() { 10708 boolean res; 10709 try { 10710 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 10711 10712 if (++mRetries > MAX_RETRIES) { 10713 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 10714 mHandler.sendEmptyMessage(MCS_GIVE_UP); 10715 handleServiceError(); 10716 return false; 10717 } else { 10718 handleStartCopy(); 10719 res = true; 10720 } 10721 } catch (RemoteException e) { 10722 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 10723 mHandler.sendEmptyMessage(MCS_RECONNECT); 10724 res = false; 10725 } 10726 handleReturnCode(); 10727 return res; 10728 } 10729 10730 final void serviceError() { 10731 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 10732 handleServiceError(); 10733 handleReturnCode(); 10734 } 10735 10736 abstract void handleStartCopy() throws RemoteException; 10737 abstract void handleServiceError(); 10738 abstract void handleReturnCode(); 10739 } 10740 10741 class MeasureParams extends HandlerParams { 10742 private final PackageStats mStats; 10743 private boolean mSuccess; 10744 10745 private final IPackageStatsObserver mObserver; 10746 10747 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 10748 super(new UserHandle(stats.userHandle)); 10749 mObserver = observer; 10750 mStats = stats; 10751 } 10752 10753 @Override 10754 public String toString() { 10755 return "MeasureParams{" 10756 + Integer.toHexString(System.identityHashCode(this)) 10757 + " " + mStats.packageName + "}"; 10758 } 10759 10760 @Override 10761 void handleStartCopy() throws RemoteException { 10762 synchronized (mInstallLock) { 10763 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 10764 } 10765 10766 if (mSuccess) { 10767 final boolean mounted; 10768 if (Environment.isExternalStorageEmulated()) { 10769 mounted = true; 10770 } else { 10771 final String status = Environment.getExternalStorageState(); 10772 mounted = (Environment.MEDIA_MOUNTED.equals(status) 10773 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 10774 } 10775 10776 if (mounted) { 10777 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 10778 10779 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 10780 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 10781 10782 mStats.externalDataSize = calculateDirectorySize(mContainerService, 10783 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 10784 10785 // Always subtract cache size, since it's a subdirectory 10786 mStats.externalDataSize -= mStats.externalCacheSize; 10787 10788 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 10789 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 10790 10791 mStats.externalObbSize = calculateDirectorySize(mContainerService, 10792 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 10793 } 10794 } 10795 } 10796 10797 @Override 10798 void handleReturnCode() { 10799 if (mObserver != null) { 10800 try { 10801 mObserver.onGetStatsCompleted(mStats, mSuccess); 10802 } catch (RemoteException e) { 10803 Slog.i(TAG, "Observer no longer exists."); 10804 } 10805 } 10806 } 10807 10808 @Override 10809 void handleServiceError() { 10810 Slog.e(TAG, "Could not measure application " + mStats.packageName 10811 + " external storage"); 10812 } 10813 } 10814 10815 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 10816 throws RemoteException { 10817 long result = 0; 10818 for (File path : paths) { 10819 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 10820 } 10821 return result; 10822 } 10823 10824 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 10825 for (File path : paths) { 10826 try { 10827 mcs.clearDirectory(path.getAbsolutePath()); 10828 } catch (RemoteException e) { 10829 } 10830 } 10831 } 10832 10833 static class OriginInfo { 10834 /** 10835 * Location where install is coming from, before it has been 10836 * copied/renamed into place. This could be a single monolithic APK 10837 * file, or a cluster directory. This location may be untrusted. 10838 */ 10839 final File file; 10840 final String cid; 10841 10842 /** 10843 * Flag indicating that {@link #file} or {@link #cid} has already been 10844 * staged, meaning downstream users don't need to defensively copy the 10845 * contents. 10846 */ 10847 final boolean staged; 10848 10849 /** 10850 * Flag indicating that {@link #file} or {@link #cid} is an already 10851 * installed app that is being moved. 10852 */ 10853 final boolean existing; 10854 10855 final String resolvedPath; 10856 final File resolvedFile; 10857 10858 static OriginInfo fromNothing() { 10859 return new OriginInfo(null, null, false, false); 10860 } 10861 10862 static OriginInfo fromUntrustedFile(File file) { 10863 return new OriginInfo(file, null, false, false); 10864 } 10865 10866 static OriginInfo fromExistingFile(File file) { 10867 return new OriginInfo(file, null, false, true); 10868 } 10869 10870 static OriginInfo fromStagedFile(File file) { 10871 return new OriginInfo(file, null, true, false); 10872 } 10873 10874 static OriginInfo fromStagedContainer(String cid) { 10875 return new OriginInfo(null, cid, true, false); 10876 } 10877 10878 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 10879 this.file = file; 10880 this.cid = cid; 10881 this.staged = staged; 10882 this.existing = existing; 10883 10884 if (cid != null) { 10885 resolvedPath = PackageHelper.getSdDir(cid); 10886 resolvedFile = new File(resolvedPath); 10887 } else if (file != null) { 10888 resolvedPath = file.getAbsolutePath(); 10889 resolvedFile = file; 10890 } else { 10891 resolvedPath = null; 10892 resolvedFile = null; 10893 } 10894 } 10895 } 10896 10897 static class MoveInfo { 10898 final int moveId; 10899 final String fromUuid; 10900 final String toUuid; 10901 final String packageName; 10902 final String dataAppName; 10903 final int appId; 10904 final String seinfo; 10905 final int targetSdkVersion; 10906 10907 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 10908 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 10909 this.moveId = moveId; 10910 this.fromUuid = fromUuid; 10911 this.toUuid = toUuid; 10912 this.packageName = packageName; 10913 this.dataAppName = dataAppName; 10914 this.appId = appId; 10915 this.seinfo = seinfo; 10916 this.targetSdkVersion = targetSdkVersion; 10917 } 10918 } 10919 10920 class InstallParams extends HandlerParams { 10921 final OriginInfo origin; 10922 final MoveInfo move; 10923 final IPackageInstallObserver2 observer; 10924 int installFlags; 10925 final String installerPackageName; 10926 final String volumeUuid; 10927 final VerificationParams verificationParams; 10928 private InstallArgs mArgs; 10929 private int mRet; 10930 final String packageAbiOverride; 10931 final String[] grantedRuntimePermissions; 10932 10933 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10934 int installFlags, String installerPackageName, String volumeUuid, 10935 VerificationParams verificationParams, UserHandle user, String packageAbiOverride, 10936 String[] grantedPermissions) { 10937 super(user); 10938 this.origin = origin; 10939 this.move = move; 10940 this.observer = observer; 10941 this.installFlags = installFlags; 10942 this.installerPackageName = installerPackageName; 10943 this.volumeUuid = volumeUuid; 10944 this.verificationParams = verificationParams; 10945 this.packageAbiOverride = packageAbiOverride; 10946 this.grantedRuntimePermissions = grantedPermissions; 10947 } 10948 10949 @Override 10950 public String toString() { 10951 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 10952 + " file=" + origin.file + " cid=" + origin.cid + "}"; 10953 } 10954 10955 private int installLocationPolicy(PackageInfoLite pkgLite) { 10956 String packageName = pkgLite.packageName; 10957 int installLocation = pkgLite.installLocation; 10958 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10959 // reader 10960 synchronized (mPackages) { 10961 PackageParser.Package pkg = mPackages.get(packageName); 10962 if (pkg != null) { 10963 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10964 // Check for downgrading. 10965 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 10966 try { 10967 checkDowngrade(pkg, pkgLite); 10968 } catch (PackageManagerException e) { 10969 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 10970 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 10971 } 10972 } 10973 // Check for updated system application. 10974 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10975 if (onSd) { 10976 Slog.w(TAG, "Cannot install update to system app on sdcard"); 10977 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 10978 } 10979 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10980 } else { 10981 if (onSd) { 10982 // Install flag overrides everything. 10983 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10984 } 10985 // If current upgrade specifies particular preference 10986 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 10987 // Application explicitly specified internal. 10988 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10989 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 10990 // App explictly prefers external. Let policy decide 10991 } else { 10992 // Prefer previous location 10993 if (isExternal(pkg)) { 10994 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10995 } 10996 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10997 } 10998 } 10999 } else { 11000 // Invalid install. Return error code 11001 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 11002 } 11003 } 11004 } 11005 // All the special cases have been taken care of. 11006 // Return result based on recommended install location. 11007 if (onSd) { 11008 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11009 } 11010 return pkgLite.recommendedInstallLocation; 11011 } 11012 11013 /* 11014 * Invoke remote method to get package information and install 11015 * location values. Override install location based on default 11016 * policy if needed and then create install arguments based 11017 * on the install location. 11018 */ 11019 public void handleStartCopy() throws RemoteException { 11020 int ret = PackageManager.INSTALL_SUCCEEDED; 11021 11022 // If we're already staged, we've firmly committed to an install location 11023 if (origin.staged) { 11024 if (origin.file != null) { 11025 installFlags |= PackageManager.INSTALL_INTERNAL; 11026 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 11027 } else if (origin.cid != null) { 11028 installFlags |= PackageManager.INSTALL_EXTERNAL; 11029 installFlags &= ~PackageManager.INSTALL_INTERNAL; 11030 } else { 11031 throw new IllegalStateException("Invalid stage location"); 11032 } 11033 } 11034 11035 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11036 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 11037 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 11038 PackageInfoLite pkgLite = null; 11039 11040 if (onInt && onSd) { 11041 // Check if both bits are set. 11042 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 11043 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11044 } else if (onSd && ephemeral) { 11045 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 11046 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11047 } else { 11048 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 11049 packageAbiOverride); 11050 11051 if (DEBUG_EPHEMERAL && ephemeral) { 11052 Slog.v(TAG, "pkgLite for install: " + pkgLite); 11053 } 11054 11055 /* 11056 * If we have too little free space, try to free cache 11057 * before giving up. 11058 */ 11059 if (!origin.staged && pkgLite.recommendedInstallLocation 11060 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 11061 // TODO: focus freeing disk space on the target device 11062 final StorageManager storage = StorageManager.from(mContext); 11063 final long lowThreshold = storage.getStorageLowBytes( 11064 Environment.getDataDirectory()); 11065 11066 final long sizeBytes = mContainerService.calculateInstalledSize( 11067 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 11068 11069 try { 11070 mInstaller.freeCache(null, sizeBytes + lowThreshold); 11071 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 11072 installFlags, packageAbiOverride); 11073 } catch (InstallerException e) { 11074 Slog.w(TAG, "Failed to free cache", e); 11075 } 11076 11077 /* 11078 * The cache free must have deleted the file we 11079 * downloaded to install. 11080 * 11081 * TODO: fix the "freeCache" call to not delete 11082 * the file we care about. 11083 */ 11084 if (pkgLite.recommendedInstallLocation 11085 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 11086 pkgLite.recommendedInstallLocation 11087 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 11088 } 11089 } 11090 } 11091 11092 if (ret == PackageManager.INSTALL_SUCCEEDED) { 11093 int loc = pkgLite.recommendedInstallLocation; 11094 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 11095 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11096 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 11097 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 11098 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 11099 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11100 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 11101 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 11102 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 11103 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 11104 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 11105 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 11106 } else { 11107 // Override with defaults if needed. 11108 loc = installLocationPolicy(pkgLite); 11109 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 11110 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 11111 } else if (!onSd && !onInt) { 11112 // Override install location with flags 11113 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 11114 // Set the flag to install on external media. 11115 installFlags |= PackageManager.INSTALL_EXTERNAL; 11116 installFlags &= ~PackageManager.INSTALL_INTERNAL; 11117 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 11118 if (DEBUG_EPHEMERAL) { 11119 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 11120 } 11121 installFlags |= PackageManager.INSTALL_EPHEMERAL; 11122 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 11123 |PackageManager.INSTALL_INTERNAL); 11124 } else { 11125 // Make sure the flag for installing on external 11126 // media is unset 11127 installFlags |= PackageManager.INSTALL_INTERNAL; 11128 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 11129 } 11130 } 11131 } 11132 } 11133 11134 final InstallArgs args = createInstallArgs(this); 11135 mArgs = args; 11136 11137 if (ret == PackageManager.INSTALL_SUCCEEDED) { 11138 // TODO: http://b/22976637 11139 // Apps installed for "all" users use the device owner to verify the app 11140 UserHandle verifierUser = getUser(); 11141 if (verifierUser == UserHandle.ALL) { 11142 verifierUser = UserHandle.SYSTEM; 11143 } 11144 11145 /* 11146 * Determine if we have any installed package verifiers. If we 11147 * do, then we'll defer to them to verify the packages. 11148 */ 11149 final int requiredUid = mRequiredVerifierPackage == null ? -1 11150 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 11151 verifierUser.getIdentifier()); 11152 if (!origin.existing && requiredUid != -1 11153 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 11154 final Intent verification = new Intent( 11155 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 11156 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 11157 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 11158 PACKAGE_MIME_TYPE); 11159 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11160 11161 // Query all live verifiers based on current user state 11162 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 11163 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 11164 11165 if (DEBUG_VERIFY) { 11166 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 11167 + verification.toString() + " with " + pkgLite.verifiers.length 11168 + " optional verifiers"); 11169 } 11170 11171 final int verificationId = mPendingVerificationToken++; 11172 11173 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11174 11175 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 11176 installerPackageName); 11177 11178 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 11179 installFlags); 11180 11181 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 11182 pkgLite.packageName); 11183 11184 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 11185 pkgLite.versionCode); 11186 11187 if (verificationParams != null) { 11188 if (verificationParams.getVerificationURI() != null) { 11189 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 11190 verificationParams.getVerificationURI()); 11191 } 11192 if (verificationParams.getOriginatingURI() != null) { 11193 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 11194 verificationParams.getOriginatingURI()); 11195 } 11196 if (verificationParams.getReferrer() != null) { 11197 verification.putExtra(Intent.EXTRA_REFERRER, 11198 verificationParams.getReferrer()); 11199 } 11200 if (verificationParams.getOriginatingUid() >= 0) { 11201 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 11202 verificationParams.getOriginatingUid()); 11203 } 11204 if (verificationParams.getInstallerUid() >= 0) { 11205 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 11206 verificationParams.getInstallerUid()); 11207 } 11208 } 11209 11210 final PackageVerificationState verificationState = new PackageVerificationState( 11211 requiredUid, args); 11212 11213 mPendingVerification.append(verificationId, verificationState); 11214 11215 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 11216 receivers, verificationState); 11217 11218 /* 11219 * If any sufficient verifiers were listed in the package 11220 * manifest, attempt to ask them. 11221 */ 11222 if (sufficientVerifiers != null) { 11223 final int N = sufficientVerifiers.size(); 11224 if (N == 0) { 11225 Slog.i(TAG, "Additional verifiers required, but none installed."); 11226 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 11227 } else { 11228 for (int i = 0; i < N; i++) { 11229 final ComponentName verifierComponent = sufficientVerifiers.get(i); 11230 11231 final Intent sufficientIntent = new Intent(verification); 11232 sufficientIntent.setComponent(verifierComponent); 11233 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 11234 } 11235 } 11236 } 11237 11238 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 11239 mRequiredVerifierPackage, receivers); 11240 if (ret == PackageManager.INSTALL_SUCCEEDED 11241 && mRequiredVerifierPackage != null) { 11242 Trace.asyncTraceBegin( 11243 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 11244 /* 11245 * Send the intent to the required verification agent, 11246 * but only start the verification timeout after the 11247 * target BroadcastReceivers have run. 11248 */ 11249 verification.setComponent(requiredVerifierComponent); 11250 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 11251 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11252 new BroadcastReceiver() { 11253 @Override 11254 public void onReceive(Context context, Intent intent) { 11255 final Message msg = mHandler 11256 .obtainMessage(CHECK_PENDING_VERIFICATION); 11257 msg.arg1 = verificationId; 11258 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 11259 } 11260 }, null, 0, null, null); 11261 11262 /* 11263 * We don't want the copy to proceed until verification 11264 * succeeds, so null out this field. 11265 */ 11266 mArgs = null; 11267 } 11268 } else { 11269 /* 11270 * No package verification is enabled, so immediately start 11271 * the remote call to initiate copy using temporary file. 11272 */ 11273 ret = args.copyApk(mContainerService, true); 11274 } 11275 } 11276 11277 mRet = ret; 11278 } 11279 11280 @Override 11281 void handleReturnCode() { 11282 // If mArgs is null, then MCS couldn't be reached. When it 11283 // reconnects, it will try again to install. At that point, this 11284 // will succeed. 11285 if (mArgs != null) { 11286 processPendingInstall(mArgs, mRet); 11287 } 11288 } 11289 11290 @Override 11291 void handleServiceError() { 11292 mArgs = createInstallArgs(this); 11293 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11294 } 11295 11296 public boolean isForwardLocked() { 11297 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11298 } 11299 } 11300 11301 /** 11302 * Used during creation of InstallArgs 11303 * 11304 * @param installFlags package installation flags 11305 * @return true if should be installed on external storage 11306 */ 11307 private static boolean installOnExternalAsec(int installFlags) { 11308 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 11309 return false; 11310 } 11311 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 11312 return true; 11313 } 11314 return false; 11315 } 11316 11317 /** 11318 * Used during creation of InstallArgs 11319 * 11320 * @param installFlags package installation flags 11321 * @return true if should be installed as forward locked 11322 */ 11323 private static boolean installForwardLocked(int installFlags) { 11324 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11325 } 11326 11327 private InstallArgs createInstallArgs(InstallParams params) { 11328 if (params.move != null) { 11329 return new MoveInstallArgs(params); 11330 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 11331 return new AsecInstallArgs(params); 11332 } else { 11333 return new FileInstallArgs(params); 11334 } 11335 } 11336 11337 /** 11338 * Create args that describe an existing installed package. Typically used 11339 * when cleaning up old installs, or used as a move source. 11340 */ 11341 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 11342 String resourcePath, String[] instructionSets) { 11343 final boolean isInAsec; 11344 if (installOnExternalAsec(installFlags)) { 11345 /* Apps on SD card are always in ASEC containers. */ 11346 isInAsec = true; 11347 } else if (installForwardLocked(installFlags) 11348 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 11349 /* 11350 * Forward-locked apps are only in ASEC containers if they're the 11351 * new style 11352 */ 11353 isInAsec = true; 11354 } else { 11355 isInAsec = false; 11356 } 11357 11358 if (isInAsec) { 11359 return new AsecInstallArgs(codePath, instructionSets, 11360 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 11361 } else { 11362 return new FileInstallArgs(codePath, resourcePath, instructionSets); 11363 } 11364 } 11365 11366 static abstract class InstallArgs { 11367 /** @see InstallParams#origin */ 11368 final OriginInfo origin; 11369 /** @see InstallParams#move */ 11370 final MoveInfo move; 11371 11372 final IPackageInstallObserver2 observer; 11373 // Always refers to PackageManager flags only 11374 final int installFlags; 11375 final String installerPackageName; 11376 final String volumeUuid; 11377 final UserHandle user; 11378 final String abiOverride; 11379 final String[] installGrantPermissions; 11380 /** If non-null, drop an async trace when the install completes */ 11381 final String traceMethod; 11382 final int traceCookie; 11383 11384 // The list of instruction sets supported by this app. This is currently 11385 // only used during the rmdex() phase to clean up resources. We can get rid of this 11386 // if we move dex files under the common app path. 11387 /* nullable */ String[] instructionSets; 11388 11389 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 11390 int installFlags, String installerPackageName, String volumeUuid, 11391 UserHandle user, String[] instructionSets, 11392 String abiOverride, String[] installGrantPermissions, 11393 String traceMethod, int traceCookie) { 11394 this.origin = origin; 11395 this.move = move; 11396 this.installFlags = installFlags; 11397 this.observer = observer; 11398 this.installerPackageName = installerPackageName; 11399 this.volumeUuid = volumeUuid; 11400 this.user = user; 11401 this.instructionSets = instructionSets; 11402 this.abiOverride = abiOverride; 11403 this.installGrantPermissions = installGrantPermissions; 11404 this.traceMethod = traceMethod; 11405 this.traceCookie = traceCookie; 11406 } 11407 11408 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 11409 abstract int doPreInstall(int status); 11410 11411 /** 11412 * Rename package into final resting place. All paths on the given 11413 * scanned package should be updated to reflect the rename. 11414 */ 11415 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 11416 abstract int doPostInstall(int status, int uid); 11417 11418 /** @see PackageSettingBase#codePathString */ 11419 abstract String getCodePath(); 11420 /** @see PackageSettingBase#resourcePathString */ 11421 abstract String getResourcePath(); 11422 11423 // Need installer lock especially for dex file removal. 11424 abstract void cleanUpResourcesLI(); 11425 abstract boolean doPostDeleteLI(boolean delete); 11426 11427 /** 11428 * Called before the source arguments are copied. This is used mostly 11429 * for MoveParams when it needs to read the source file to put it in the 11430 * destination. 11431 */ 11432 int doPreCopy() { 11433 return PackageManager.INSTALL_SUCCEEDED; 11434 } 11435 11436 /** 11437 * Called after the source arguments are copied. This is used mostly for 11438 * MoveParams when it needs to read the source file to put it in the 11439 * destination. 11440 * 11441 * @return 11442 */ 11443 int doPostCopy(int uid) { 11444 return PackageManager.INSTALL_SUCCEEDED; 11445 } 11446 11447 protected boolean isFwdLocked() { 11448 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11449 } 11450 11451 protected boolean isExternalAsec() { 11452 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11453 } 11454 11455 protected boolean isEphemeral() { 11456 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 11457 } 11458 11459 UserHandle getUser() { 11460 return user; 11461 } 11462 } 11463 11464 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 11465 if (!allCodePaths.isEmpty()) { 11466 if (instructionSets == null) { 11467 throw new IllegalStateException("instructionSet == null"); 11468 } 11469 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 11470 for (String codePath : allCodePaths) { 11471 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 11472 try { 11473 mInstaller.rmdex(codePath, dexCodeInstructionSet); 11474 } catch (InstallerException ignored) { 11475 } 11476 } 11477 } 11478 } 11479 } 11480 11481 /** 11482 * Logic to handle installation of non-ASEC applications, including copying 11483 * and renaming logic. 11484 */ 11485 class FileInstallArgs extends InstallArgs { 11486 private File codeFile; 11487 private File resourceFile; 11488 11489 // Example topology: 11490 // /data/app/com.example/base.apk 11491 // /data/app/com.example/split_foo.apk 11492 // /data/app/com.example/lib/arm/libfoo.so 11493 // /data/app/com.example/lib/arm64/libfoo.so 11494 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 11495 11496 /** New install */ 11497 FileInstallArgs(InstallParams params) { 11498 super(params.origin, params.move, params.observer, params.installFlags, 11499 params.installerPackageName, params.volumeUuid, 11500 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11501 params.grantedRuntimePermissions, 11502 params.traceMethod, params.traceCookie); 11503 if (isFwdLocked()) { 11504 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 11505 } 11506 } 11507 11508 /** Existing install */ 11509 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 11510 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 11511 null, null, null, 0); 11512 this.codeFile = (codePath != null) ? new File(codePath) : null; 11513 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 11514 } 11515 11516 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11517 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 11518 try { 11519 return doCopyApk(imcs, temp); 11520 } finally { 11521 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11522 } 11523 } 11524 11525 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11526 if (origin.staged) { 11527 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 11528 codeFile = origin.file; 11529 resourceFile = origin.file; 11530 return PackageManager.INSTALL_SUCCEEDED; 11531 } 11532 11533 try { 11534 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 11535 final File tempDir = 11536 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 11537 codeFile = tempDir; 11538 resourceFile = tempDir; 11539 } catch (IOException e) { 11540 Slog.w(TAG, "Failed to create copy file: " + e); 11541 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11542 } 11543 11544 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 11545 @Override 11546 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 11547 if (!FileUtils.isValidExtFilename(name)) { 11548 throw new IllegalArgumentException("Invalid filename: " + name); 11549 } 11550 try { 11551 final File file = new File(codeFile, name); 11552 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 11553 O_RDWR | O_CREAT, 0644); 11554 Os.chmod(file.getAbsolutePath(), 0644); 11555 return new ParcelFileDescriptor(fd); 11556 } catch (ErrnoException e) { 11557 throw new RemoteException("Failed to open: " + e.getMessage()); 11558 } 11559 } 11560 }; 11561 11562 int ret = PackageManager.INSTALL_SUCCEEDED; 11563 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 11564 if (ret != PackageManager.INSTALL_SUCCEEDED) { 11565 Slog.e(TAG, "Failed to copy package"); 11566 return ret; 11567 } 11568 11569 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 11570 NativeLibraryHelper.Handle handle = null; 11571 try { 11572 handle = NativeLibraryHelper.Handle.create(codeFile); 11573 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 11574 abiOverride); 11575 } catch (IOException e) { 11576 Slog.e(TAG, "Copying native libraries failed", e); 11577 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11578 } finally { 11579 IoUtils.closeQuietly(handle); 11580 } 11581 11582 return ret; 11583 } 11584 11585 int doPreInstall(int status) { 11586 if (status != PackageManager.INSTALL_SUCCEEDED) { 11587 cleanUp(); 11588 } 11589 return status; 11590 } 11591 11592 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11593 if (status != PackageManager.INSTALL_SUCCEEDED) { 11594 cleanUp(); 11595 return false; 11596 } 11597 11598 final File targetDir = codeFile.getParentFile(); 11599 final File beforeCodeFile = codeFile; 11600 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 11601 11602 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 11603 try { 11604 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 11605 } catch (ErrnoException e) { 11606 Slog.w(TAG, "Failed to rename", e); 11607 return false; 11608 } 11609 11610 if (!SELinux.restoreconRecursive(afterCodeFile)) { 11611 Slog.w(TAG, "Failed to restorecon"); 11612 return false; 11613 } 11614 11615 // Reflect the rename internally 11616 codeFile = afterCodeFile; 11617 resourceFile = afterCodeFile; 11618 11619 // Reflect the rename in scanned details 11620 pkg.codePath = afterCodeFile.getAbsolutePath(); 11621 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11622 pkg.baseCodePath); 11623 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11624 pkg.splitCodePaths); 11625 11626 // Reflect the rename in app info 11627 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11628 pkg.applicationInfo.setCodePath(pkg.codePath); 11629 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11630 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11631 pkg.applicationInfo.setResourcePath(pkg.codePath); 11632 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11633 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11634 11635 return true; 11636 } 11637 11638 int doPostInstall(int status, int uid) { 11639 if (status != PackageManager.INSTALL_SUCCEEDED) { 11640 cleanUp(); 11641 } 11642 return status; 11643 } 11644 11645 @Override 11646 String getCodePath() { 11647 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11648 } 11649 11650 @Override 11651 String getResourcePath() { 11652 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11653 } 11654 11655 private boolean cleanUp() { 11656 if (codeFile == null || !codeFile.exists()) { 11657 return false; 11658 } 11659 11660 removeCodePathLI(codeFile); 11661 11662 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 11663 resourceFile.delete(); 11664 } 11665 11666 return true; 11667 } 11668 11669 void cleanUpResourcesLI() { 11670 // Try enumerating all code paths before deleting 11671 List<String> allCodePaths = Collections.EMPTY_LIST; 11672 if (codeFile != null && codeFile.exists()) { 11673 try { 11674 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11675 allCodePaths = pkg.getAllCodePaths(); 11676 } catch (PackageParserException e) { 11677 // Ignored; we tried our best 11678 } 11679 } 11680 11681 cleanUp(); 11682 removeDexFiles(allCodePaths, instructionSets); 11683 } 11684 11685 boolean doPostDeleteLI(boolean delete) { 11686 // XXX err, shouldn't we respect the delete flag? 11687 cleanUpResourcesLI(); 11688 return true; 11689 } 11690 } 11691 11692 private boolean isAsecExternal(String cid) { 11693 final String asecPath = PackageHelper.getSdFilesystem(cid); 11694 return !asecPath.startsWith(mAsecInternalPath); 11695 } 11696 11697 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 11698 PackageManagerException { 11699 if (copyRet < 0) { 11700 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 11701 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 11702 throw new PackageManagerException(copyRet, message); 11703 } 11704 } 11705 } 11706 11707 /** 11708 * Extract the MountService "container ID" from the full code path of an 11709 * .apk. 11710 */ 11711 static String cidFromCodePath(String fullCodePath) { 11712 int eidx = fullCodePath.lastIndexOf("/"); 11713 String subStr1 = fullCodePath.substring(0, eidx); 11714 int sidx = subStr1.lastIndexOf("/"); 11715 return subStr1.substring(sidx+1, eidx); 11716 } 11717 11718 /** 11719 * Logic to handle installation of ASEC applications, including copying and 11720 * renaming logic. 11721 */ 11722 class AsecInstallArgs extends InstallArgs { 11723 static final String RES_FILE_NAME = "pkg.apk"; 11724 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 11725 11726 String cid; 11727 String packagePath; 11728 String resourcePath; 11729 11730 /** New install */ 11731 AsecInstallArgs(InstallParams params) { 11732 super(params.origin, params.move, params.observer, params.installFlags, 11733 params.installerPackageName, params.volumeUuid, 11734 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11735 params.grantedRuntimePermissions, 11736 params.traceMethod, params.traceCookie); 11737 } 11738 11739 /** Existing install */ 11740 AsecInstallArgs(String fullCodePath, String[] instructionSets, 11741 boolean isExternal, boolean isForwardLocked) { 11742 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 11743 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 11744 instructionSets, null, null, null, 0); 11745 // Hackily pretend we're still looking at a full code path 11746 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 11747 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 11748 } 11749 11750 // Extract cid from fullCodePath 11751 int eidx = fullCodePath.lastIndexOf("/"); 11752 String subStr1 = fullCodePath.substring(0, eidx); 11753 int sidx = subStr1.lastIndexOf("/"); 11754 cid = subStr1.substring(sidx+1, eidx); 11755 setMountPath(subStr1); 11756 } 11757 11758 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 11759 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 11760 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 11761 instructionSets, null, null, null, 0); 11762 this.cid = cid; 11763 setMountPath(PackageHelper.getSdDir(cid)); 11764 } 11765 11766 void createCopyFile() { 11767 cid = mInstallerService.allocateExternalStageCidLegacy(); 11768 } 11769 11770 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11771 if (origin.staged && origin.cid != null) { 11772 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 11773 cid = origin.cid; 11774 setMountPath(PackageHelper.getSdDir(cid)); 11775 return PackageManager.INSTALL_SUCCEEDED; 11776 } 11777 11778 if (temp) { 11779 createCopyFile(); 11780 } else { 11781 /* 11782 * Pre-emptively destroy the container since it's destroyed if 11783 * copying fails due to it existing anyway. 11784 */ 11785 PackageHelper.destroySdDir(cid); 11786 } 11787 11788 final String newMountPath = imcs.copyPackageToContainer( 11789 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 11790 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 11791 11792 if (newMountPath != null) { 11793 setMountPath(newMountPath); 11794 return PackageManager.INSTALL_SUCCEEDED; 11795 } else { 11796 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11797 } 11798 } 11799 11800 @Override 11801 String getCodePath() { 11802 return packagePath; 11803 } 11804 11805 @Override 11806 String getResourcePath() { 11807 return resourcePath; 11808 } 11809 11810 int doPreInstall(int status) { 11811 if (status != PackageManager.INSTALL_SUCCEEDED) { 11812 // Destroy container 11813 PackageHelper.destroySdDir(cid); 11814 } else { 11815 boolean mounted = PackageHelper.isContainerMounted(cid); 11816 if (!mounted) { 11817 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 11818 Process.SYSTEM_UID); 11819 if (newMountPath != null) { 11820 setMountPath(newMountPath); 11821 } else { 11822 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11823 } 11824 } 11825 } 11826 return status; 11827 } 11828 11829 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11830 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 11831 String newMountPath = null; 11832 if (PackageHelper.isContainerMounted(cid)) { 11833 // Unmount the container 11834 if (!PackageHelper.unMountSdDir(cid)) { 11835 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 11836 return false; 11837 } 11838 } 11839 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11840 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 11841 " which might be stale. Will try to clean up."); 11842 // Clean up the stale container and proceed to recreate. 11843 if (!PackageHelper.destroySdDir(newCacheId)) { 11844 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 11845 return false; 11846 } 11847 // Successfully cleaned up stale container. Try to rename again. 11848 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11849 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 11850 + " inspite of cleaning it up."); 11851 return false; 11852 } 11853 } 11854 if (!PackageHelper.isContainerMounted(newCacheId)) { 11855 Slog.w(TAG, "Mounting container " + newCacheId); 11856 newMountPath = PackageHelper.mountSdDir(newCacheId, 11857 getEncryptKey(), Process.SYSTEM_UID); 11858 } else { 11859 newMountPath = PackageHelper.getSdDir(newCacheId); 11860 } 11861 if (newMountPath == null) { 11862 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 11863 return false; 11864 } 11865 Log.i(TAG, "Succesfully renamed " + cid + 11866 " to " + newCacheId + 11867 " at new path: " + newMountPath); 11868 cid = newCacheId; 11869 11870 final File beforeCodeFile = new File(packagePath); 11871 setMountPath(newMountPath); 11872 final File afterCodeFile = new File(packagePath); 11873 11874 // Reflect the rename in scanned details 11875 pkg.codePath = afterCodeFile.getAbsolutePath(); 11876 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11877 pkg.baseCodePath); 11878 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11879 pkg.splitCodePaths); 11880 11881 // Reflect the rename in app info 11882 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11883 pkg.applicationInfo.setCodePath(pkg.codePath); 11884 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11885 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11886 pkg.applicationInfo.setResourcePath(pkg.codePath); 11887 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11888 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11889 11890 return true; 11891 } 11892 11893 private void setMountPath(String mountPath) { 11894 final File mountFile = new File(mountPath); 11895 11896 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 11897 if (monolithicFile.exists()) { 11898 packagePath = monolithicFile.getAbsolutePath(); 11899 if (isFwdLocked()) { 11900 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 11901 } else { 11902 resourcePath = packagePath; 11903 } 11904 } else { 11905 packagePath = mountFile.getAbsolutePath(); 11906 resourcePath = packagePath; 11907 } 11908 } 11909 11910 int doPostInstall(int status, int uid) { 11911 if (status != PackageManager.INSTALL_SUCCEEDED) { 11912 cleanUp(); 11913 } else { 11914 final int groupOwner; 11915 final String protectedFile; 11916 if (isFwdLocked()) { 11917 groupOwner = UserHandle.getSharedAppGid(uid); 11918 protectedFile = RES_FILE_NAME; 11919 } else { 11920 groupOwner = -1; 11921 protectedFile = null; 11922 } 11923 11924 if (uid < Process.FIRST_APPLICATION_UID 11925 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 11926 Slog.e(TAG, "Failed to finalize " + cid); 11927 PackageHelper.destroySdDir(cid); 11928 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11929 } 11930 11931 boolean mounted = PackageHelper.isContainerMounted(cid); 11932 if (!mounted) { 11933 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 11934 } 11935 } 11936 return status; 11937 } 11938 11939 private void cleanUp() { 11940 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 11941 11942 // Destroy secure container 11943 PackageHelper.destroySdDir(cid); 11944 } 11945 11946 private List<String> getAllCodePaths() { 11947 final File codeFile = new File(getCodePath()); 11948 if (codeFile != null && codeFile.exists()) { 11949 try { 11950 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11951 return pkg.getAllCodePaths(); 11952 } catch (PackageParserException e) { 11953 // Ignored; we tried our best 11954 } 11955 } 11956 return Collections.EMPTY_LIST; 11957 } 11958 11959 void cleanUpResourcesLI() { 11960 // Enumerate all code paths before deleting 11961 cleanUpResourcesLI(getAllCodePaths()); 11962 } 11963 11964 private void cleanUpResourcesLI(List<String> allCodePaths) { 11965 cleanUp(); 11966 removeDexFiles(allCodePaths, instructionSets); 11967 } 11968 11969 String getPackageName() { 11970 return getAsecPackageName(cid); 11971 } 11972 11973 boolean doPostDeleteLI(boolean delete) { 11974 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 11975 final List<String> allCodePaths = getAllCodePaths(); 11976 boolean mounted = PackageHelper.isContainerMounted(cid); 11977 if (mounted) { 11978 // Unmount first 11979 if (PackageHelper.unMountSdDir(cid)) { 11980 mounted = false; 11981 } 11982 } 11983 if (!mounted && delete) { 11984 cleanUpResourcesLI(allCodePaths); 11985 } 11986 return !mounted; 11987 } 11988 11989 @Override 11990 int doPreCopy() { 11991 if (isFwdLocked()) { 11992 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 11993 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 11994 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11995 } 11996 } 11997 11998 return PackageManager.INSTALL_SUCCEEDED; 11999 } 12000 12001 @Override 12002 int doPostCopy(int uid) { 12003 if (isFwdLocked()) { 12004 if (uid < Process.FIRST_APPLICATION_UID 12005 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 12006 RES_FILE_NAME)) { 12007 Slog.e(TAG, "Failed to finalize " + cid); 12008 PackageHelper.destroySdDir(cid); 12009 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12010 } 12011 } 12012 12013 return PackageManager.INSTALL_SUCCEEDED; 12014 } 12015 } 12016 12017 /** 12018 * Logic to handle movement of existing installed applications. 12019 */ 12020 class MoveInstallArgs extends InstallArgs { 12021 private File codeFile; 12022 private File resourceFile; 12023 12024 /** New install */ 12025 MoveInstallArgs(InstallParams params) { 12026 super(params.origin, params.move, params.observer, params.installFlags, 12027 params.installerPackageName, params.volumeUuid, 12028 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 12029 params.grantedRuntimePermissions, 12030 params.traceMethod, params.traceCookie); 12031 } 12032 12033 int copyApk(IMediaContainerService imcs, boolean temp) { 12034 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 12035 + move.fromUuid + " to " + move.toUuid); 12036 synchronized (mInstaller) { 12037 try { 12038 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 12039 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 12040 } catch (InstallerException e) { 12041 Slog.w(TAG, "Failed to move app", e); 12042 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12043 } 12044 } 12045 12046 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 12047 resourceFile = codeFile; 12048 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 12049 12050 return PackageManager.INSTALL_SUCCEEDED; 12051 } 12052 12053 int doPreInstall(int status) { 12054 if (status != PackageManager.INSTALL_SUCCEEDED) { 12055 cleanUp(move.toUuid); 12056 } 12057 return status; 12058 } 12059 12060 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12061 if (status != PackageManager.INSTALL_SUCCEEDED) { 12062 cleanUp(move.toUuid); 12063 return false; 12064 } 12065 12066 // Reflect the move in app info 12067 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 12068 pkg.applicationInfo.setCodePath(pkg.codePath); 12069 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 12070 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 12071 pkg.applicationInfo.setResourcePath(pkg.codePath); 12072 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 12073 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 12074 12075 return true; 12076 } 12077 12078 int doPostInstall(int status, int uid) { 12079 if (status == PackageManager.INSTALL_SUCCEEDED) { 12080 cleanUp(move.fromUuid); 12081 } else { 12082 cleanUp(move.toUuid); 12083 } 12084 return status; 12085 } 12086 12087 @Override 12088 String getCodePath() { 12089 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 12090 } 12091 12092 @Override 12093 String getResourcePath() { 12094 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 12095 } 12096 12097 private boolean cleanUp(String volumeUuid) { 12098 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 12099 move.dataAppName); 12100 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 12101 synchronized (mInstallLock) { 12102 // Clean up both app data and code 12103 removeDataDirsLI(volumeUuid, move.packageName); 12104 removeCodePathLI(codeFile); 12105 } 12106 return true; 12107 } 12108 12109 void cleanUpResourcesLI() { 12110 throw new UnsupportedOperationException(); 12111 } 12112 12113 boolean doPostDeleteLI(boolean delete) { 12114 throw new UnsupportedOperationException(); 12115 } 12116 } 12117 12118 static String getAsecPackageName(String packageCid) { 12119 int idx = packageCid.lastIndexOf("-"); 12120 if (idx == -1) { 12121 return packageCid; 12122 } 12123 return packageCid.substring(0, idx); 12124 } 12125 12126 // Utility method used to create code paths based on package name and available index. 12127 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 12128 String idxStr = ""; 12129 int idx = 1; 12130 // Fall back to default value of idx=1 if prefix is not 12131 // part of oldCodePath 12132 if (oldCodePath != null) { 12133 String subStr = oldCodePath; 12134 // Drop the suffix right away 12135 if (suffix != null && subStr.endsWith(suffix)) { 12136 subStr = subStr.substring(0, subStr.length() - suffix.length()); 12137 } 12138 // If oldCodePath already contains prefix find out the 12139 // ending index to either increment or decrement. 12140 int sidx = subStr.lastIndexOf(prefix); 12141 if (sidx != -1) { 12142 subStr = subStr.substring(sidx + prefix.length()); 12143 if (subStr != null) { 12144 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 12145 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 12146 } 12147 try { 12148 idx = Integer.parseInt(subStr); 12149 if (idx <= 1) { 12150 idx++; 12151 } else { 12152 idx--; 12153 } 12154 } catch(NumberFormatException e) { 12155 } 12156 } 12157 } 12158 } 12159 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 12160 return prefix + idxStr; 12161 } 12162 12163 private File getNextCodePath(File targetDir, String packageName) { 12164 int suffix = 1; 12165 File result; 12166 do { 12167 result = new File(targetDir, packageName + "-" + suffix); 12168 suffix++; 12169 } while (result.exists()); 12170 return result; 12171 } 12172 12173 // Utility method that returns the relative package path with respect 12174 // to the installation directory. Like say for /data/data/com.test-1.apk 12175 // string com.test-1 is returned. 12176 static String deriveCodePathName(String codePath) { 12177 if (codePath == null) { 12178 return null; 12179 } 12180 final File codeFile = new File(codePath); 12181 final String name = codeFile.getName(); 12182 if (codeFile.isDirectory()) { 12183 return name; 12184 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 12185 final int lastDot = name.lastIndexOf('.'); 12186 return name.substring(0, lastDot); 12187 } else { 12188 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 12189 return null; 12190 } 12191 } 12192 12193 static class PackageInstalledInfo { 12194 String name; 12195 int uid; 12196 // The set of users that originally had this package installed. 12197 int[] origUsers; 12198 // The set of users that now have this package installed. 12199 int[] newUsers; 12200 PackageParser.Package pkg; 12201 int returnCode; 12202 String returnMsg; 12203 PackageRemovedInfo removedInfo; 12204 12205 public void setError(int code, String msg) { 12206 returnCode = code; 12207 returnMsg = msg; 12208 Slog.w(TAG, msg); 12209 } 12210 12211 public void setError(String msg, PackageParserException e) { 12212 returnCode = e.error; 12213 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 12214 Slog.w(TAG, msg, e); 12215 } 12216 12217 public void setError(String msg, PackageManagerException e) { 12218 returnCode = e.error; 12219 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 12220 Slog.w(TAG, msg, e); 12221 } 12222 12223 // In some error cases we want to convey more info back to the observer 12224 String origPackage; 12225 String origPermission; 12226 } 12227 12228 /* 12229 * Install a non-existing package. 12230 */ 12231 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 12232 UserHandle user, String installerPackageName, String volumeUuid, 12233 PackageInstalledInfo res) { 12234 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 12235 12236 // Remember this for later, in case we need to rollback this install 12237 String pkgName = pkg.packageName; 12238 12239 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 12240 // TODO: b/23350563 12241 final boolean dataDirExists = Environment 12242 .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists(); 12243 12244 synchronized(mPackages) { 12245 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 12246 // A package with the same name is already installed, though 12247 // it has been renamed to an older name. The package we 12248 // are trying to install should be installed as an update to 12249 // the existing one, but that has not been requested, so bail. 12250 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 12251 + " without first uninstalling package running as " 12252 + mSettings.mRenamedPackages.get(pkgName)); 12253 return; 12254 } 12255 if (mPackages.containsKey(pkgName)) { 12256 // Don't allow installation over an existing package with the same name. 12257 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 12258 + " without first uninstalling."); 12259 return; 12260 } 12261 } 12262 12263 try { 12264 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 12265 System.currentTimeMillis(), user); 12266 12267 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 12268 prepareAppDataAfterInstall(newPackage); 12269 12270 // delete the partially installed application. the data directory will have to be 12271 // restored if it was already existing 12272 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12273 // remove package from internal structures. Note that we want deletePackageX to 12274 // delete the package data and cache directories that it created in 12275 // scanPackageLocked, unless those directories existed before we even tried to 12276 // install. 12277 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 12278 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 12279 res.removedInfo, true); 12280 } 12281 12282 } catch (PackageManagerException e) { 12283 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12284 } 12285 12286 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12287 } 12288 12289 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 12290 // Can't rotate keys during boot or if sharedUser. 12291 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 12292 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 12293 return false; 12294 } 12295 // app is using upgradeKeySets; make sure all are valid 12296 KeySetManagerService ksms = mSettings.mKeySetManagerService; 12297 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 12298 for (int i = 0; i < upgradeKeySets.length; i++) { 12299 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 12300 Slog.wtf(TAG, "Package " 12301 + (oldPs.name != null ? oldPs.name : "<null>") 12302 + " contains upgrade-key-set reference to unknown key-set: " 12303 + upgradeKeySets[i] 12304 + " reverting to signatures check."); 12305 return false; 12306 } 12307 } 12308 return true; 12309 } 12310 12311 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 12312 // Upgrade keysets are being used. Determine if new package has a superset of the 12313 // required keys. 12314 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 12315 KeySetManagerService ksms = mSettings.mKeySetManagerService; 12316 for (int i = 0; i < upgradeKeySets.length; i++) { 12317 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 12318 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 12319 return true; 12320 } 12321 } 12322 return false; 12323 } 12324 12325 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 12326 UserHandle user, String installerPackageName, String volumeUuid, 12327 PackageInstalledInfo res) { 12328 final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 12329 12330 final PackageParser.Package oldPackage; 12331 final String pkgName = pkg.packageName; 12332 final int[] allUsers; 12333 final boolean[] perUserInstalled; 12334 12335 // First find the old package info and check signatures 12336 synchronized(mPackages) { 12337 oldPackage = mPackages.get(pkgName); 12338 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 12339 if (isEphemeral && !oldIsEphemeral) { 12340 // can't downgrade from full to ephemeral 12341 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 12342 res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 12343 return; 12344 } 12345 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 12346 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12347 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12348 if(!checkUpgradeKeySetLP(ps, pkg)) { 12349 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 12350 "New package not signed by keys specified by upgrade-keysets: " 12351 + pkgName); 12352 return; 12353 } 12354 } else { 12355 // default to original signature matching 12356 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 12357 != PackageManager.SIGNATURE_MATCH) { 12358 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 12359 "New package has a different signature: " + pkgName); 12360 return; 12361 } 12362 } 12363 12364 // In case of rollback, remember per-user/profile install state 12365 allUsers = sUserManager.getUserIds(); 12366 perUserInstalled = new boolean[allUsers.length]; 12367 for (int i = 0; i < allUsers.length; i++) { 12368 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12369 } 12370 } 12371 12372 boolean sysPkg = (isSystemApp(oldPackage)); 12373 if (sysPkg) { 12374 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 12375 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 12376 } else { 12377 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 12378 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 12379 } 12380 } 12381 12382 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 12383 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 12384 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 12385 String volumeUuid, PackageInstalledInfo res) { 12386 String pkgName = deletedPackage.packageName; 12387 boolean deletedPkg = true; 12388 boolean updatedSettings = false; 12389 12390 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 12391 + deletedPackage); 12392 long origUpdateTime; 12393 if (pkg.mExtras != null) { 12394 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 12395 } else { 12396 origUpdateTime = 0; 12397 } 12398 12399 // First delete the existing package while retaining the data directory 12400 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 12401 res.removedInfo, true)) { 12402 // If the existing package wasn't successfully deleted 12403 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 12404 deletedPkg = false; 12405 } else { 12406 // Successfully deleted the old package; proceed with replace. 12407 12408 // If deleted package lived in a container, give users a chance to 12409 // relinquish resources before killing. 12410 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 12411 if (DEBUG_INSTALL) { 12412 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 12413 } 12414 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 12415 final ArrayList<String> pkgList = new ArrayList<String>(1); 12416 pkgList.add(deletedPackage.applicationInfo.packageName); 12417 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 12418 } 12419 12420 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 12421 try { 12422 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 12423 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 12424 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12425 perUserInstalled, res, user); 12426 prepareAppDataAfterInstall(newPackage); 12427 updatedSettings = true; 12428 } catch (PackageManagerException e) { 12429 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12430 } 12431 } 12432 12433 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12434 // remove package from internal structures. Note that we want deletePackageX to 12435 // delete the package data and cache directories that it created in 12436 // scanPackageLocked, unless those directories existed before we even tried to 12437 // install. 12438 if(updatedSettings) { 12439 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 12440 deletePackageLI( 12441 pkgName, null, true, allUsers, perUserInstalled, 12442 PackageManager.DELETE_KEEP_DATA, 12443 res.removedInfo, true); 12444 } 12445 // Since we failed to install the new package we need to restore the old 12446 // package that we deleted. 12447 if (deletedPkg) { 12448 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 12449 File restoreFile = new File(deletedPackage.codePath); 12450 // Parse old package 12451 boolean oldExternal = isExternal(deletedPackage); 12452 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 12453 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 12454 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 12455 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 12456 try { 12457 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 12458 null); 12459 } catch (PackageManagerException e) { 12460 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 12461 + e.getMessage()); 12462 return; 12463 } 12464 // Restore of old package succeeded. Update permissions. 12465 // writer 12466 synchronized (mPackages) { 12467 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 12468 UPDATE_PERMISSIONS_ALL); 12469 // can downgrade to reader 12470 mSettings.writeLPr(); 12471 } 12472 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 12473 } 12474 } 12475 } 12476 12477 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 12478 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 12479 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 12480 String volumeUuid, PackageInstalledInfo res) { 12481 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 12482 + ", old=" + deletedPackage); 12483 boolean disabledSystem = false; 12484 boolean updatedSettings = false; 12485 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 12486 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 12487 != 0) { 12488 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12489 } 12490 String packageName = deletedPackage.packageName; 12491 if (packageName == null) { 12492 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12493 "Attempt to delete null packageName."); 12494 return; 12495 } 12496 PackageParser.Package oldPkg; 12497 PackageSetting oldPkgSetting; 12498 // reader 12499 synchronized (mPackages) { 12500 oldPkg = mPackages.get(packageName); 12501 oldPkgSetting = mSettings.mPackages.get(packageName); 12502 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 12503 (oldPkgSetting == null)) { 12504 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12505 "Couldn't find package " + packageName + " information"); 12506 return; 12507 } 12508 } 12509 12510 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 12511 12512 res.removedInfo.uid = oldPkg.applicationInfo.uid; 12513 res.removedInfo.removedPackage = packageName; 12514 // Remove existing system package 12515 removePackageLI(oldPkgSetting, true); 12516 // writer 12517 synchronized (mPackages) { 12518 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 12519 if (!disabledSystem && deletedPackage != null) { 12520 // We didn't need to disable the .apk as a current system package, 12521 // which means we are replacing another update that is already 12522 // installed. We need to make sure to delete the older one's .apk. 12523 res.removedInfo.args = createInstallArgsForExisting(0, 12524 deletedPackage.applicationInfo.getCodePath(), 12525 deletedPackage.applicationInfo.getResourcePath(), 12526 getAppDexInstructionSets(deletedPackage.applicationInfo)); 12527 } else { 12528 res.removedInfo.args = null; 12529 } 12530 } 12531 12532 // Successfully disabled the old package. Now proceed with re-installation 12533 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 12534 12535 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12536 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 12537 12538 PackageParser.Package newPackage = null; 12539 try { 12540 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 12541 if (newPackage.mExtras != null) { 12542 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 12543 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 12544 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 12545 12546 // is the update attempting to change shared user? that isn't going to work... 12547 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 12548 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 12549 "Forbidding shared user change from " + oldPkgSetting.sharedUser 12550 + " to " + newPkgSetting.sharedUser); 12551 updatedSettings = true; 12552 } 12553 } 12554 12555 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12556 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12557 perUserInstalled, res, user); 12558 prepareAppDataAfterInstall(newPackage); 12559 updatedSettings = true; 12560 } 12561 12562 } catch (PackageManagerException e) { 12563 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12564 } 12565 12566 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12567 // Re installation failed. Restore old information 12568 // Remove new pkg information 12569 if (newPackage != null) { 12570 removeInstalledPackageLI(newPackage, true); 12571 } 12572 // Add back the old system package 12573 try { 12574 scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 12575 } catch (PackageManagerException e) { 12576 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 12577 } 12578 // Restore the old system information in Settings 12579 synchronized (mPackages) { 12580 if (disabledSystem) { 12581 mSettings.enableSystemPackageLPw(packageName); 12582 } 12583 if (updatedSettings) { 12584 mSettings.setInstallerPackageName(packageName, 12585 oldPkgSetting.installerPackageName); 12586 } 12587 mSettings.writeLPr(); 12588 } 12589 } 12590 } 12591 12592 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 12593 // Collect all used permissions in the UID 12594 ArraySet<String> usedPermissions = new ArraySet<>(); 12595 final int packageCount = su.packages.size(); 12596 for (int i = 0; i < packageCount; i++) { 12597 PackageSetting ps = su.packages.valueAt(i); 12598 if (ps.pkg == null) { 12599 continue; 12600 } 12601 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 12602 for (int j = 0; j < requestedPermCount; j++) { 12603 String permission = ps.pkg.requestedPermissions.get(j); 12604 BasePermission bp = mSettings.mPermissions.get(permission); 12605 if (bp != null) { 12606 usedPermissions.add(permission); 12607 } 12608 } 12609 } 12610 12611 PermissionsState permissionsState = su.getPermissionsState(); 12612 // Prune install permissions 12613 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 12614 final int installPermCount = installPermStates.size(); 12615 for (int i = installPermCount - 1; i >= 0; i--) { 12616 PermissionState permissionState = installPermStates.get(i); 12617 if (!usedPermissions.contains(permissionState.getName())) { 12618 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 12619 if (bp != null) { 12620 permissionsState.revokeInstallPermission(bp); 12621 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 12622 PackageManager.MASK_PERMISSION_FLAGS, 0); 12623 } 12624 } 12625 } 12626 12627 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 12628 12629 // Prune runtime permissions 12630 for (int userId : allUserIds) { 12631 List<PermissionState> runtimePermStates = permissionsState 12632 .getRuntimePermissionStates(userId); 12633 final int runtimePermCount = runtimePermStates.size(); 12634 for (int i = runtimePermCount - 1; i >= 0; i--) { 12635 PermissionState permissionState = runtimePermStates.get(i); 12636 if (!usedPermissions.contains(permissionState.getName())) { 12637 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 12638 if (bp != null) { 12639 permissionsState.revokeRuntimePermission(bp, userId); 12640 permissionsState.updatePermissionFlags(bp, userId, 12641 PackageManager.MASK_PERMISSION_FLAGS, 0); 12642 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 12643 runtimePermissionChangedUserIds, userId); 12644 } 12645 } 12646 } 12647 } 12648 12649 return runtimePermissionChangedUserIds; 12650 } 12651 12652 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 12653 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 12654 UserHandle user) { 12655 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 12656 12657 String pkgName = newPackage.packageName; 12658 synchronized (mPackages) { 12659 //write settings. the installStatus will be incomplete at this stage. 12660 //note that the new package setting would have already been 12661 //added to mPackages. It hasn't been persisted yet. 12662 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 12663 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 12664 mSettings.writeLPr(); 12665 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12666 } 12667 12668 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 12669 synchronized (mPackages) { 12670 updatePermissionsLPw(newPackage.packageName, newPackage, 12671 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 12672 ? UPDATE_PERMISSIONS_ALL : 0)); 12673 // For system-bundled packages, we assume that installing an upgraded version 12674 // of the package implies that the user actually wants to run that new code, 12675 // so we enable the package. 12676 PackageSetting ps = mSettings.mPackages.get(pkgName); 12677 if (ps != null) { 12678 if (isSystemApp(newPackage)) { 12679 // NB: implicit assumption that system package upgrades apply to all users 12680 if (DEBUG_INSTALL) { 12681 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 12682 } 12683 if (res.origUsers != null) { 12684 for (int userHandle : res.origUsers) { 12685 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 12686 userHandle, installerPackageName); 12687 } 12688 } 12689 // Also convey the prior install/uninstall state 12690 if (allUsers != null && perUserInstalled != null) { 12691 for (int i = 0; i < allUsers.length; i++) { 12692 if (DEBUG_INSTALL) { 12693 Slog.d(TAG, " user " + allUsers[i] 12694 + " => " + perUserInstalled[i]); 12695 } 12696 ps.setInstalled(perUserInstalled[i], allUsers[i]); 12697 } 12698 // these install state changes will be persisted in the 12699 // upcoming call to mSettings.writeLPr(). 12700 } 12701 } 12702 // It's implied that when a user requests installation, they want the app to be 12703 // installed and enabled. 12704 int userId = user.getIdentifier(); 12705 if (userId != UserHandle.USER_ALL) { 12706 ps.setInstalled(true, userId); 12707 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 12708 } 12709 } 12710 res.name = pkgName; 12711 res.uid = newPackage.applicationInfo.uid; 12712 res.pkg = newPackage; 12713 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 12714 mSettings.setInstallerPackageName(pkgName, installerPackageName); 12715 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12716 //to update install status 12717 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 12718 mSettings.writeLPr(); 12719 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12720 } 12721 12722 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12723 } 12724 12725 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 12726 try { 12727 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 12728 installPackageLI(args, res); 12729 } finally { 12730 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12731 } 12732 } 12733 12734 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 12735 final int installFlags = args.installFlags; 12736 final String installerPackageName = args.installerPackageName; 12737 final String volumeUuid = args.volumeUuid; 12738 final File tmpPackageFile = new File(args.getCodePath()); 12739 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 12740 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 12741 || (args.volumeUuid != null)); 12742 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 12743 boolean replace = false; 12744 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 12745 if (args.move != null) { 12746 // moving a complete application; perfom an initial scan on the new install location 12747 scanFlags |= SCAN_INITIAL; 12748 } 12749 // Result object to be returned 12750 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12751 12752 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 12753 12754 // Sanity check 12755 if (ephemeral && (forwardLocked || onExternal)) { 12756 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 12757 + " external=" + onExternal); 12758 res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 12759 return; 12760 } 12761 12762 // Retrieve PackageSettings and parse package 12763 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 12764 | PackageParser.PARSE_ENFORCE_CODE 12765 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 12766 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 12767 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0); 12768 PackageParser pp = new PackageParser(); 12769 pp.setSeparateProcesses(mSeparateProcesses); 12770 pp.setDisplayMetrics(mMetrics); 12771 12772 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 12773 final PackageParser.Package pkg; 12774 try { 12775 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 12776 } catch (PackageParserException e) { 12777 res.setError("Failed parse during installPackageLI", e); 12778 return; 12779 } finally { 12780 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12781 } 12782 12783 // Mark that we have an install time CPU ABI override. 12784 pkg.cpuAbiOverride = args.abiOverride; 12785 12786 String pkgName = res.name = pkg.packageName; 12787 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 12788 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 12789 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 12790 return; 12791 } 12792 } 12793 12794 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 12795 try { 12796 pp.collectCertificates(pkg, parseFlags); 12797 } catch (PackageParserException e) { 12798 res.setError("Failed collect during installPackageLI", e); 12799 return; 12800 } finally { 12801 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12802 } 12803 12804 // Get rid of all references to package scan path via parser. 12805 pp = null; 12806 String oldCodePath = null; 12807 boolean systemApp = false; 12808 synchronized (mPackages) { 12809 // Check if installing already existing package 12810 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12811 String oldName = mSettings.mRenamedPackages.get(pkgName); 12812 if (pkg.mOriginalPackages != null 12813 && pkg.mOriginalPackages.contains(oldName) 12814 && mPackages.containsKey(oldName)) { 12815 // This package is derived from an original package, 12816 // and this device has been updating from that original 12817 // name. We must continue using the original name, so 12818 // rename the new package here. 12819 pkg.setPackageName(oldName); 12820 pkgName = pkg.packageName; 12821 replace = true; 12822 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 12823 + oldName + " pkgName=" + pkgName); 12824 } else if (mPackages.containsKey(pkgName)) { 12825 // This package, under its official name, already exists 12826 // on the device; we should replace it. 12827 replace = true; 12828 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 12829 } 12830 12831 // Prevent apps opting out from runtime permissions 12832 if (replace) { 12833 PackageParser.Package oldPackage = mPackages.get(pkgName); 12834 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 12835 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 12836 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 12837 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 12838 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 12839 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 12840 + " doesn't support runtime permissions but the old" 12841 + " target SDK " + oldTargetSdk + " does."); 12842 return; 12843 } 12844 } 12845 } 12846 12847 PackageSetting ps = mSettings.mPackages.get(pkgName); 12848 if (ps != null) { 12849 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 12850 12851 // Quick sanity check that we're signed correctly if updating; 12852 // we'll check this again later when scanning, but we want to 12853 // bail early here before tripping over redefined permissions. 12854 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12855 if (!checkUpgradeKeySetLP(ps, pkg)) { 12856 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 12857 + pkg.packageName + " upgrade keys do not match the " 12858 + "previously installed version"); 12859 return; 12860 } 12861 } else { 12862 try { 12863 verifySignaturesLP(ps, pkg); 12864 } catch (PackageManagerException e) { 12865 res.setError(e.error, e.getMessage()); 12866 return; 12867 } 12868 } 12869 12870 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 12871 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 12872 systemApp = (ps.pkg.applicationInfo.flags & 12873 ApplicationInfo.FLAG_SYSTEM) != 0; 12874 } 12875 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12876 } 12877 12878 // Check whether the newly-scanned package wants to define an already-defined perm 12879 int N = pkg.permissions.size(); 12880 for (int i = N-1; i >= 0; i--) { 12881 PackageParser.Permission perm = pkg.permissions.get(i); 12882 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 12883 if (bp != null) { 12884 // If the defining package is signed with our cert, it's okay. This 12885 // also includes the "updating the same package" case, of course. 12886 // "updating same package" could also involve key-rotation. 12887 final boolean sigsOk; 12888 if (bp.sourcePackage.equals(pkg.packageName) 12889 && (bp.packageSetting instanceof PackageSetting) 12890 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 12891 scanFlags))) { 12892 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 12893 } else { 12894 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 12895 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 12896 } 12897 if (!sigsOk) { 12898 // If the owning package is the system itself, we log but allow 12899 // install to proceed; we fail the install on all other permission 12900 // redefinitions. 12901 if (!bp.sourcePackage.equals("android")) { 12902 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 12903 + pkg.packageName + " attempting to redeclare permission " 12904 + perm.info.name + " already owned by " + bp.sourcePackage); 12905 res.origPermission = perm.info.name; 12906 res.origPackage = bp.sourcePackage; 12907 return; 12908 } else { 12909 Slog.w(TAG, "Package " + pkg.packageName 12910 + " attempting to redeclare system permission " 12911 + perm.info.name + "; ignoring new declaration"); 12912 pkg.permissions.remove(i); 12913 } 12914 } 12915 } 12916 } 12917 12918 } 12919 12920 if (systemApp) { 12921 if (onExternal) { 12922 // Abort update; system app can't be replaced with app on sdcard 12923 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 12924 "Cannot install updates to system apps on sdcard"); 12925 return; 12926 } else if (ephemeral) { 12927 // Abort update; system app can't be replaced with an ephemeral app 12928 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 12929 "Cannot update a system app with an ephemeral app"); 12930 return; 12931 } 12932 } 12933 12934 if (args.move != null) { 12935 // We did an in-place move, so dex is ready to roll 12936 scanFlags |= SCAN_NO_DEX; 12937 scanFlags |= SCAN_MOVE; 12938 12939 synchronized (mPackages) { 12940 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12941 if (ps == null) { 12942 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 12943 "Missing settings for moved package " + pkgName); 12944 } 12945 12946 // We moved the entire application as-is, so bring over the 12947 // previously derived ABI information. 12948 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 12949 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 12950 } 12951 12952 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 12953 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 12954 scanFlags |= SCAN_NO_DEX; 12955 12956 try { 12957 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 12958 true /* extract libs */); 12959 } catch (PackageManagerException pme) { 12960 Slog.e(TAG, "Error deriving application ABI", pme); 12961 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 12962 return; 12963 } 12964 } 12965 12966 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 12967 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 12968 return; 12969 } 12970 12971 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 12972 12973 if (replace) { 12974 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 12975 installerPackageName, volumeUuid, res); 12976 } else { 12977 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 12978 args.user, installerPackageName, volumeUuid, res); 12979 } 12980 synchronized (mPackages) { 12981 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12982 if (ps != null) { 12983 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12984 } 12985 } 12986 } 12987 12988 private void startIntentFilterVerifications(int userId, boolean replacing, 12989 PackageParser.Package pkg) { 12990 if (mIntentFilterVerifierComponent == null) { 12991 Slog.w(TAG, "No IntentFilter verification will not be done as " 12992 + "there is no IntentFilterVerifier available!"); 12993 return; 12994 } 12995 12996 final int verifierUid = getPackageUid( 12997 mIntentFilterVerifierComponent.getPackageName(), 12998 MATCH_DEBUG_TRIAGED_MISSING, 12999 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 13000 13001 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 13002 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 13003 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 13004 mHandler.sendMessage(msg); 13005 } 13006 13007 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 13008 PackageParser.Package pkg) { 13009 int size = pkg.activities.size(); 13010 if (size == 0) { 13011 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 13012 "No activity, so no need to verify any IntentFilter!"); 13013 return; 13014 } 13015 13016 final boolean hasDomainURLs = hasDomainURLs(pkg); 13017 if (!hasDomainURLs) { 13018 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 13019 "No domain URLs, so no need to verify any IntentFilter!"); 13020 return; 13021 } 13022 13023 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 13024 + " if any IntentFilter from the " + size 13025 + " Activities needs verification ..."); 13026 13027 int count = 0; 13028 final String packageName = pkg.packageName; 13029 13030 synchronized (mPackages) { 13031 // If this is a new install and we see that we've already run verification for this 13032 // package, we have nothing to do: it means the state was restored from backup. 13033 if (!replacing) { 13034 IntentFilterVerificationInfo ivi = 13035 mSettings.getIntentFilterVerificationLPr(packageName); 13036 if (ivi != null) { 13037 if (DEBUG_DOMAIN_VERIFICATION) { 13038 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 13039 + ivi.getStatusString()); 13040 } 13041 return; 13042 } 13043 } 13044 13045 // If any filters need to be verified, then all need to be. 13046 boolean needToVerify = false; 13047 for (PackageParser.Activity a : pkg.activities) { 13048 for (ActivityIntentInfo filter : a.intents) { 13049 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 13050 if (DEBUG_DOMAIN_VERIFICATION) { 13051 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 13052 } 13053 needToVerify = true; 13054 break; 13055 } 13056 } 13057 } 13058 13059 if (needToVerify) { 13060 final int verificationId = mIntentFilterVerificationToken++; 13061 for (PackageParser.Activity a : pkg.activities) { 13062 for (ActivityIntentInfo filter : a.intents) { 13063 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 13064 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 13065 "Verification needed for IntentFilter:" + filter.toString()); 13066 mIntentFilterVerifier.addOneIntentFilterVerification( 13067 verifierUid, userId, verificationId, filter, packageName); 13068 count++; 13069 } 13070 } 13071 } 13072 } 13073 } 13074 13075 if (count > 0) { 13076 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 13077 + " IntentFilter verification" + (count > 1 ? "s" : "") 13078 + " for userId:" + userId); 13079 mIntentFilterVerifier.startVerifications(userId); 13080 } else { 13081 if (DEBUG_DOMAIN_VERIFICATION) { 13082 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 13083 } 13084 } 13085 } 13086 13087 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 13088 final ComponentName cn = filter.activity.getComponentName(); 13089 final String packageName = cn.getPackageName(); 13090 13091 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 13092 packageName); 13093 if (ivi == null) { 13094 return true; 13095 } 13096 int status = ivi.getStatus(); 13097 switch (status) { 13098 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 13099 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 13100 return true; 13101 13102 default: 13103 // Nothing to do 13104 return false; 13105 } 13106 } 13107 13108 private static boolean isMultiArch(ApplicationInfo info) { 13109 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 13110 } 13111 13112 private static boolean isExternal(PackageParser.Package pkg) { 13113 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 13114 } 13115 13116 private static boolean isExternal(PackageSetting ps) { 13117 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 13118 } 13119 13120 private static boolean isEphemeral(PackageParser.Package pkg) { 13121 return pkg.applicationInfo.isEphemeralApp(); 13122 } 13123 13124 private static boolean isEphemeral(PackageSetting ps) { 13125 return ps.pkg != null && isEphemeral(ps.pkg); 13126 } 13127 13128 private static boolean isSystemApp(PackageParser.Package pkg) { 13129 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 13130 } 13131 13132 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 13133 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 13134 } 13135 13136 private static boolean hasDomainURLs(PackageParser.Package pkg) { 13137 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 13138 } 13139 13140 private static boolean isSystemApp(PackageSetting ps) { 13141 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 13142 } 13143 13144 private static boolean isUpdatedSystemApp(PackageSetting ps) { 13145 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 13146 } 13147 13148 private int packageFlagsToInstallFlags(PackageSetting ps) { 13149 int installFlags = 0; 13150 if (isEphemeral(ps)) { 13151 installFlags |= PackageManager.INSTALL_EPHEMERAL; 13152 } 13153 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 13154 // This existing package was an external ASEC install when we have 13155 // the external flag without a UUID 13156 installFlags |= PackageManager.INSTALL_EXTERNAL; 13157 } 13158 if (ps.isForwardLocked()) { 13159 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 13160 } 13161 return installFlags; 13162 } 13163 13164 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 13165 if (isExternal(pkg)) { 13166 if (TextUtils.isEmpty(pkg.volumeUuid)) { 13167 return StorageManager.UUID_PRIMARY_PHYSICAL; 13168 } else { 13169 return pkg.volumeUuid; 13170 } 13171 } else { 13172 return StorageManager.UUID_PRIVATE_INTERNAL; 13173 } 13174 } 13175 13176 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 13177 if (isExternal(pkg)) { 13178 if (TextUtils.isEmpty(pkg.volumeUuid)) { 13179 return mSettings.getExternalVersion(); 13180 } else { 13181 return mSettings.findOrCreateVersion(pkg.volumeUuid); 13182 } 13183 } else { 13184 return mSettings.getInternalVersion(); 13185 } 13186 } 13187 13188 private void deleteTempPackageFiles() { 13189 final FilenameFilter filter = new FilenameFilter() { 13190 public boolean accept(File dir, String name) { 13191 return name.startsWith("vmdl") && name.endsWith(".tmp"); 13192 } 13193 }; 13194 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 13195 file.delete(); 13196 } 13197 } 13198 13199 @Override 13200 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 13201 int flags) { 13202 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 13203 flags); 13204 } 13205 13206 @Override 13207 public void deletePackage(final String packageName, 13208 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 13209 mContext.enforceCallingOrSelfPermission( 13210 android.Manifest.permission.DELETE_PACKAGES, null); 13211 Preconditions.checkNotNull(packageName); 13212 Preconditions.checkNotNull(observer); 13213 final int uid = Binder.getCallingUid(); 13214 final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0; 13215 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 13216 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 13217 mContext.enforceCallingOrSelfPermission( 13218 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 13219 "deletePackage for user " + userId); 13220 } 13221 13222 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 13223 try { 13224 observer.onPackageDeleted(packageName, 13225 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 13226 } catch (RemoteException re) { 13227 } 13228 return; 13229 } 13230 13231 for (int currentUserId : users) { 13232 if (getBlockUninstallForUser(packageName, currentUserId)) { 13233 try { 13234 observer.onPackageDeleted(packageName, 13235 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 13236 } catch (RemoteException re) { 13237 } 13238 return; 13239 } 13240 } 13241 13242 if (DEBUG_REMOVE) { 13243 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 13244 } 13245 // Queue up an async operation since the package deletion may take a little while. 13246 mHandler.post(new Runnable() { 13247 public void run() { 13248 mHandler.removeCallbacks(this); 13249 final int returnCode = deletePackageX(packageName, userId, flags); 13250 try { 13251 observer.onPackageDeleted(packageName, returnCode, null); 13252 } catch (RemoteException e) { 13253 Log.i(TAG, "Observer no longer exists."); 13254 } //end catch 13255 } //end run 13256 }); 13257 } 13258 13259 private boolean isPackageDeviceAdmin(String packageName, int userId) { 13260 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 13261 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 13262 try { 13263 if (dpm != null) { 13264 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 13265 /* callingUserOnly =*/ false); 13266 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 13267 : deviceOwnerComponentName.getPackageName(); 13268 // Does the package contains the device owner? 13269 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 13270 // this check is probably not needed, since DO should be registered as a device 13271 // admin on some user too. (Original bug for this: b/17657954) 13272 if (packageName.equals(deviceOwnerPackageName)) { 13273 return true; 13274 } 13275 // Does it contain a device admin for any user? 13276 int[] users; 13277 if (userId == UserHandle.USER_ALL) { 13278 users = sUserManager.getUserIds(); 13279 } else { 13280 users = new int[]{userId}; 13281 } 13282 for (int i = 0; i < users.length; ++i) { 13283 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 13284 return true; 13285 } 13286 } 13287 } 13288 } catch (RemoteException e) { 13289 } 13290 return false; 13291 } 13292 13293 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 13294 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 13295 } 13296 13297 /** 13298 * This method is an internal method that could be get invoked either 13299 * to delete an installed package or to clean up a failed installation. 13300 * After deleting an installed package, a broadcast is sent to notify any 13301 * listeners that the package has been installed. For cleaning up a failed 13302 * installation, the broadcast is not necessary since the package's 13303 * installation wouldn't have sent the initial broadcast either 13304 * The key steps in deleting a package are 13305 * deleting the package information in internal structures like mPackages, 13306 * deleting the packages base directories through installd 13307 * updating mSettings to reflect current status 13308 * persisting settings for later use 13309 * sending a broadcast if necessary 13310 */ 13311 private int deletePackageX(String packageName, int userId, int flags) { 13312 final PackageRemovedInfo info = new PackageRemovedInfo(); 13313 final boolean res; 13314 13315 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 13316 ? UserHandle.ALL : new UserHandle(userId); 13317 13318 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 13319 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 13320 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 13321 } 13322 13323 boolean removedForAllUsers = false; 13324 boolean systemUpdate = false; 13325 13326 PackageParser.Package uninstalledPkg; 13327 13328 // for the uninstall-updates case and restricted profiles, remember the per- 13329 // userhandle installed state 13330 int[] allUsers; 13331 boolean[] perUserInstalled; 13332 synchronized (mPackages) { 13333 uninstalledPkg = mPackages.get(packageName); 13334 PackageSetting ps = mSettings.mPackages.get(packageName); 13335 allUsers = sUserManager.getUserIds(); 13336 perUserInstalled = new boolean[allUsers.length]; 13337 for (int i = 0; i < allUsers.length; i++) { 13338 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 13339 } 13340 } 13341 13342 synchronized (mInstallLock) { 13343 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 13344 res = deletePackageLI(packageName, removeForUser, 13345 true, allUsers, perUserInstalled, 13346 flags | REMOVE_CHATTY, info, true); 13347 systemUpdate = info.isRemovedPackageSystemUpdate; 13348 synchronized (mPackages) { 13349 if (res) { 13350 if (!systemUpdate && mPackages.get(packageName) == null) { 13351 removedForAllUsers = true; 13352 } 13353 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPkg); 13354 } 13355 } 13356 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 13357 + " removedForAllUsers=" + removedForAllUsers); 13358 } 13359 13360 if (res) { 13361 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 13362 13363 // If the removed package was a system update, the old system package 13364 // was re-enabled; we need to broadcast this information 13365 if (systemUpdate) { 13366 Bundle extras = new Bundle(1); 13367 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 13368 ? info.removedAppId : info.uid); 13369 extras.putBoolean(Intent.EXTRA_REPLACING, true); 13370 13371 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 13372 extras, 0, null, null, null); 13373 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 13374 extras, 0, null, null, null); 13375 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 13376 null, 0, packageName, null, null); 13377 } 13378 } 13379 // Force a gc here. 13380 Runtime.getRuntime().gc(); 13381 // Delete the resources here after sending the broadcast to let 13382 // other processes clean up before deleting resources. 13383 if (info.args != null) { 13384 synchronized (mInstallLock) { 13385 info.args.doPostDeleteLI(true); 13386 } 13387 } 13388 13389 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 13390 } 13391 13392 class PackageRemovedInfo { 13393 String removedPackage; 13394 int uid = -1; 13395 int removedAppId = -1; 13396 int[] removedUsers = null; 13397 boolean isRemovedPackageSystemUpdate = false; 13398 // Clean up resources deleted packages. 13399 InstallArgs args = null; 13400 13401 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 13402 Bundle extras = new Bundle(1); 13403 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 13404 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 13405 if (replacing) { 13406 extras.putBoolean(Intent.EXTRA_REPLACING, true); 13407 } 13408 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 13409 if (removedPackage != null) { 13410 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 13411 extras, 0, null, null, removedUsers); 13412 if (fullRemove && !replacing) { 13413 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 13414 extras, 0, null, null, removedUsers); 13415 } 13416 } 13417 if (removedAppId >= 0) { 13418 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 13419 removedUsers); 13420 } 13421 } 13422 } 13423 13424 /* 13425 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 13426 * flag is not set, the data directory is removed as well. 13427 * make sure this flag is set for partially installed apps. If not its meaningless to 13428 * delete a partially installed application. 13429 */ 13430 private void removePackageDataLI(PackageSetting ps, 13431 int[] allUserHandles, boolean[] perUserInstalled, 13432 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 13433 String packageName = ps.name; 13434 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 13435 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 13436 // Retrieve object to delete permissions for shared user later on 13437 final PackageSetting deletedPs; 13438 // reader 13439 synchronized (mPackages) { 13440 deletedPs = mSettings.mPackages.get(packageName); 13441 if (outInfo != null) { 13442 outInfo.removedPackage = packageName; 13443 outInfo.removedUsers = deletedPs != null 13444 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 13445 : null; 13446 } 13447 } 13448 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 13449 removeDataDirsLI(ps.volumeUuid, packageName); 13450 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 13451 } 13452 // writer 13453 synchronized (mPackages) { 13454 if (deletedPs != null) { 13455 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 13456 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 13457 clearDefaultBrowserIfNeeded(packageName); 13458 if (outInfo != null) { 13459 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 13460 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 13461 } 13462 updatePermissionsLPw(deletedPs.name, null, 0); 13463 if (deletedPs.sharedUser != null) { 13464 // Remove permissions associated with package. Since runtime 13465 // permissions are per user we have to kill the removed package 13466 // or packages running under the shared user of the removed 13467 // package if revoking the permissions requested only by the removed 13468 // package is successful and this causes a change in gids. 13469 for (int userId : UserManagerService.getInstance().getUserIds()) { 13470 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 13471 userId); 13472 if (userIdToKill == UserHandle.USER_ALL 13473 || userIdToKill >= UserHandle.USER_SYSTEM) { 13474 // If gids changed for this user, kill all affected packages. 13475 mHandler.post(new Runnable() { 13476 @Override 13477 public void run() { 13478 // This has to happen with no lock held. 13479 killApplication(deletedPs.name, deletedPs.appId, 13480 KILL_APP_REASON_GIDS_CHANGED); 13481 } 13482 }); 13483 break; 13484 } 13485 } 13486 } 13487 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 13488 } 13489 // make sure to preserve per-user disabled state if this removal was just 13490 // a downgrade of a system app to the factory package 13491 if (allUserHandles != null && perUserInstalled != null) { 13492 if (DEBUG_REMOVE) { 13493 Slog.d(TAG, "Propagating install state across downgrade"); 13494 } 13495 for (int i = 0; i < allUserHandles.length; i++) { 13496 if (DEBUG_REMOVE) { 13497 Slog.d(TAG, " user " + allUserHandles[i] 13498 + " => " + perUserInstalled[i]); 13499 } 13500 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13501 } 13502 } 13503 } 13504 // can downgrade to reader 13505 if (writeSettings) { 13506 // Save settings now 13507 mSettings.writeLPr(); 13508 } 13509 } 13510 if (outInfo != null) { 13511 // A user ID was deleted here. Go through all users and remove it 13512 // from KeyStore. 13513 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 13514 } 13515 } 13516 13517 static boolean locationIsPrivileged(File path) { 13518 try { 13519 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 13520 .getCanonicalPath(); 13521 return path.getCanonicalPath().startsWith(privilegedAppDir); 13522 } catch (IOException e) { 13523 Slog.e(TAG, "Unable to access code path " + path); 13524 } 13525 return false; 13526 } 13527 13528 /* 13529 * Tries to delete system package. 13530 */ 13531 private boolean deleteSystemPackageLI(PackageSetting newPs, 13532 int[] allUserHandles, boolean[] perUserInstalled, 13533 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 13534 final boolean applyUserRestrictions 13535 = (allUserHandles != null) && (perUserInstalled != null); 13536 PackageSetting disabledPs = null; 13537 // Confirm if the system package has been updated 13538 // An updated system app can be deleted. This will also have to restore 13539 // the system pkg from system partition 13540 // reader 13541 synchronized (mPackages) { 13542 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 13543 } 13544 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 13545 + " disabledPs=" + disabledPs); 13546 if (disabledPs == null) { 13547 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 13548 return false; 13549 } else if (DEBUG_REMOVE) { 13550 Slog.d(TAG, "Deleting system pkg from data partition"); 13551 } 13552 if (DEBUG_REMOVE) { 13553 if (applyUserRestrictions) { 13554 Slog.d(TAG, "Remembering install states:"); 13555 for (int i = 0; i < allUserHandles.length; i++) { 13556 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 13557 } 13558 } 13559 } 13560 // Delete the updated package 13561 outInfo.isRemovedPackageSystemUpdate = true; 13562 if (disabledPs.versionCode < newPs.versionCode) { 13563 // Delete data for downgrades 13564 flags &= ~PackageManager.DELETE_KEEP_DATA; 13565 } else { 13566 // Preserve data by setting flag 13567 flags |= PackageManager.DELETE_KEEP_DATA; 13568 } 13569 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 13570 allUserHandles, perUserInstalled, outInfo, writeSettings); 13571 if (!ret) { 13572 return false; 13573 } 13574 // writer 13575 synchronized (mPackages) { 13576 // Reinstate the old system package 13577 mSettings.enableSystemPackageLPw(newPs.name); 13578 // Remove any native libraries from the upgraded package. 13579 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 13580 } 13581 // Install the system package 13582 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 13583 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 13584 if (locationIsPrivileged(disabledPs.codePath)) { 13585 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 13586 } 13587 13588 final PackageParser.Package newPkg; 13589 try { 13590 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 13591 } catch (PackageManagerException e) { 13592 Slog.w(TAG, "Failed to restore system package " + newPs.name + ": " + e.getMessage()); 13593 return false; 13594 } 13595 13596 prepareAppDataAfterInstall(newPkg); 13597 13598 // writer 13599 synchronized (mPackages) { 13600 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 13601 13602 // Propagate the permissions state as we do not want to drop on the floor 13603 // runtime permissions. The update permissions method below will take 13604 // care of removing obsolete permissions and grant install permissions. 13605 ps.getPermissionsState().copyFrom(newPs.getPermissionsState()); 13606 updatePermissionsLPw(newPkg.packageName, newPkg, 13607 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 13608 13609 if (applyUserRestrictions) { 13610 if (DEBUG_REMOVE) { 13611 Slog.d(TAG, "Propagating install state across reinstall"); 13612 } 13613 for (int i = 0; i < allUserHandles.length; i++) { 13614 if (DEBUG_REMOVE) { 13615 Slog.d(TAG, " user " + allUserHandles[i] 13616 + " => " + perUserInstalled[i]); 13617 } 13618 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13619 13620 mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false); 13621 } 13622 // Regardless of writeSettings we need to ensure that this restriction 13623 // state propagation is persisted 13624 mSettings.writeAllUsersPackageRestrictionsLPr(); 13625 } 13626 // can downgrade to reader here 13627 if (writeSettings) { 13628 mSettings.writeLPr(); 13629 } 13630 } 13631 return true; 13632 } 13633 13634 private boolean deleteInstalledPackageLI(PackageSetting ps, 13635 boolean deleteCodeAndResources, int flags, 13636 int[] allUserHandles, boolean[] perUserInstalled, 13637 PackageRemovedInfo outInfo, boolean writeSettings) { 13638 if (outInfo != null) { 13639 outInfo.uid = ps.appId; 13640 } 13641 13642 // Delete package data from internal structures and also remove data if flag is set 13643 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 13644 13645 // Delete application code and resources 13646 if (deleteCodeAndResources && (outInfo != null)) { 13647 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 13648 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 13649 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 13650 } 13651 return true; 13652 } 13653 13654 @Override 13655 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 13656 int userId) { 13657 mContext.enforceCallingOrSelfPermission( 13658 android.Manifest.permission.DELETE_PACKAGES, null); 13659 synchronized (mPackages) { 13660 PackageSetting ps = mSettings.mPackages.get(packageName); 13661 if (ps == null) { 13662 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 13663 return false; 13664 } 13665 if (!ps.getInstalled(userId)) { 13666 // Can't block uninstall for an app that is not installed or enabled. 13667 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 13668 return false; 13669 } 13670 ps.setBlockUninstall(blockUninstall, userId); 13671 mSettings.writePackageRestrictionsLPr(userId); 13672 } 13673 return true; 13674 } 13675 13676 @Override 13677 public boolean getBlockUninstallForUser(String packageName, int userId) { 13678 synchronized (mPackages) { 13679 PackageSetting ps = mSettings.mPackages.get(packageName); 13680 if (ps == null) { 13681 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 13682 return false; 13683 } 13684 return ps.getBlockUninstall(userId); 13685 } 13686 } 13687 13688 @Override 13689 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 13690 int callingUid = Binder.getCallingUid(); 13691 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 13692 throw new SecurityException( 13693 "setRequiredForSystemUser can only be run by the system or root"); 13694 } 13695 synchronized (mPackages) { 13696 PackageSetting ps = mSettings.mPackages.get(packageName); 13697 if (ps == null) { 13698 Log.w(TAG, "Package doesn't exist: " + packageName); 13699 return false; 13700 } 13701 if (systemUserApp) { 13702 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 13703 } else { 13704 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 13705 } 13706 mSettings.writeLPr(); 13707 } 13708 return true; 13709 } 13710 13711 /* 13712 * This method handles package deletion in general 13713 */ 13714 private boolean deletePackageLI(String packageName, UserHandle user, 13715 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 13716 int flags, PackageRemovedInfo outInfo, 13717 boolean writeSettings) { 13718 if (packageName == null) { 13719 Slog.w(TAG, "Attempt to delete null packageName."); 13720 return false; 13721 } 13722 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 13723 PackageSetting ps; 13724 boolean dataOnly = false; 13725 int removeUser = -1; 13726 int appId = -1; 13727 synchronized (mPackages) { 13728 ps = mSettings.mPackages.get(packageName); 13729 if (ps == null) { 13730 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13731 return false; 13732 } 13733 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 13734 && user.getIdentifier() != UserHandle.USER_ALL) { 13735 // The caller is asking that the package only be deleted for a single 13736 // user. To do this, we just mark its uninstalled state and delete 13737 // its data. If this is a system app, we only allow this to happen if 13738 // they have set the special DELETE_SYSTEM_APP which requests different 13739 // semantics than normal for uninstalling system apps. 13740 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 13741 final int userId = user.getIdentifier(); 13742 ps.setUserState(userId, 13743 COMPONENT_ENABLED_STATE_DEFAULT, 13744 false, //installed 13745 true, //stopped 13746 true, //notLaunched 13747 false, //hidden 13748 false, //suspended 13749 null, null, null, 13750 false, // blockUninstall 13751 ps.readUserState(userId).domainVerificationStatus, 0); 13752 if (!isSystemApp(ps)) { 13753 // Do not uninstall the APK if an app should be cached 13754 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 13755 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 13756 // Other user still have this package installed, so all 13757 // we need to do is clear this user's data and save that 13758 // it is uninstalled. 13759 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 13760 removeUser = user.getIdentifier(); 13761 appId = ps.appId; 13762 scheduleWritePackageRestrictionsLocked(removeUser); 13763 } else { 13764 // We need to set it back to 'installed' so the uninstall 13765 // broadcasts will be sent correctly. 13766 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 13767 ps.setInstalled(true, user.getIdentifier()); 13768 } 13769 } else { 13770 // This is a system app, so we assume that the 13771 // other users still have this package installed, so all 13772 // we need to do is clear this user's data and save that 13773 // it is uninstalled. 13774 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 13775 removeUser = user.getIdentifier(); 13776 appId = ps.appId; 13777 scheduleWritePackageRestrictionsLocked(removeUser); 13778 } 13779 } 13780 } 13781 13782 if (removeUser >= 0) { 13783 // From above, we determined that we are deleting this only 13784 // for a single user. Continue the work here. 13785 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 13786 if (outInfo != null) { 13787 outInfo.removedPackage = packageName; 13788 outInfo.removedAppId = appId; 13789 outInfo.removedUsers = new int[] {removeUser}; 13790 } 13791 // TODO: triage flags as part of 26466827 13792 final int installerFlags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE; 13793 try { 13794 mInstaller.destroyAppData(ps.volumeUuid, packageName, removeUser, installerFlags); 13795 } catch (InstallerException e) { 13796 Slog.w(TAG, "Failed to delete app data", e); 13797 } 13798 removeKeystoreDataIfNeeded(removeUser, appId); 13799 schedulePackageCleaning(packageName, removeUser, false); 13800 synchronized (mPackages) { 13801 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 13802 scheduleWritePackageRestrictionsLocked(removeUser); 13803 } 13804 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser); 13805 } 13806 return true; 13807 } 13808 13809 if (dataOnly) { 13810 // Delete application data first 13811 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 13812 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 13813 return true; 13814 } 13815 13816 boolean ret = false; 13817 if (isSystemApp(ps)) { 13818 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 13819 // When an updated system application is deleted we delete the existing resources as well and 13820 // fall back to existing code in system partition 13821 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 13822 flags, outInfo, writeSettings); 13823 } else { 13824 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 13825 // Kill application pre-emptively especially for apps on sd. 13826 killApplication(packageName, ps.appId, "uninstall pkg"); 13827 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 13828 allUserHandles, perUserInstalled, 13829 outInfo, writeSettings); 13830 } 13831 13832 return ret; 13833 } 13834 13835 private final static class ClearStorageConnection implements ServiceConnection { 13836 IMediaContainerService mContainerService; 13837 13838 @Override 13839 public void onServiceConnected(ComponentName name, IBinder service) { 13840 synchronized (this) { 13841 mContainerService = IMediaContainerService.Stub.asInterface(service); 13842 notifyAll(); 13843 } 13844 } 13845 13846 @Override 13847 public void onServiceDisconnected(ComponentName name) { 13848 } 13849 } 13850 13851 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 13852 final boolean mounted; 13853 if (Environment.isExternalStorageEmulated()) { 13854 mounted = true; 13855 } else { 13856 final String status = Environment.getExternalStorageState(); 13857 13858 mounted = status.equals(Environment.MEDIA_MOUNTED) 13859 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 13860 } 13861 13862 if (!mounted) { 13863 return; 13864 } 13865 13866 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 13867 int[] users; 13868 if (userId == UserHandle.USER_ALL) { 13869 users = sUserManager.getUserIds(); 13870 } else { 13871 users = new int[] { userId }; 13872 } 13873 final ClearStorageConnection conn = new ClearStorageConnection(); 13874 if (mContext.bindServiceAsUser( 13875 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 13876 try { 13877 for (int curUser : users) { 13878 long timeout = SystemClock.uptimeMillis() + 5000; 13879 synchronized (conn) { 13880 long now = SystemClock.uptimeMillis(); 13881 while (conn.mContainerService == null && now < timeout) { 13882 try { 13883 conn.wait(timeout - now); 13884 } catch (InterruptedException e) { 13885 } 13886 } 13887 } 13888 if (conn.mContainerService == null) { 13889 return; 13890 } 13891 13892 final UserEnvironment userEnv = new UserEnvironment(curUser); 13893 clearDirectory(conn.mContainerService, 13894 userEnv.buildExternalStorageAppCacheDirs(packageName)); 13895 if (allData) { 13896 clearDirectory(conn.mContainerService, 13897 userEnv.buildExternalStorageAppDataDirs(packageName)); 13898 clearDirectory(conn.mContainerService, 13899 userEnv.buildExternalStorageAppMediaDirs(packageName)); 13900 } 13901 } 13902 } finally { 13903 mContext.unbindService(conn); 13904 } 13905 } 13906 } 13907 13908 @Override 13909 public void clearApplicationUserData(final String packageName, 13910 final IPackageDataObserver observer, final int userId) { 13911 mContext.enforceCallingOrSelfPermission( 13912 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 13913 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 13914 // Queue up an async operation since the package deletion may take a little while. 13915 mHandler.post(new Runnable() { 13916 public void run() { 13917 mHandler.removeCallbacks(this); 13918 final boolean succeeded; 13919 synchronized (mInstallLock) { 13920 succeeded = clearApplicationUserDataLI(packageName, userId); 13921 } 13922 clearExternalStorageDataSync(packageName, userId, true); 13923 if (succeeded) { 13924 // invoke DeviceStorageMonitor's update method to clear any notifications 13925 DeviceStorageMonitorInternal 13926 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13927 if (dsm != null) { 13928 dsm.checkMemory(); 13929 } 13930 } 13931 if(observer != null) { 13932 try { 13933 observer.onRemoveCompleted(packageName, succeeded); 13934 } catch (RemoteException e) { 13935 Log.i(TAG, "Observer no longer exists."); 13936 } 13937 } //end if observer 13938 } //end run 13939 }); 13940 } 13941 13942 private boolean clearApplicationUserDataLI(String packageName, int userId) { 13943 if (packageName == null) { 13944 Slog.w(TAG, "Attempt to delete null packageName."); 13945 return false; 13946 } 13947 13948 // Try finding details about the requested package 13949 PackageParser.Package pkg; 13950 synchronized (mPackages) { 13951 pkg = mPackages.get(packageName); 13952 if (pkg == null) { 13953 final PackageSetting ps = mSettings.mPackages.get(packageName); 13954 if (ps != null) { 13955 pkg = ps.pkg; 13956 } 13957 } 13958 13959 if (pkg == null) { 13960 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13961 return false; 13962 } 13963 13964 PackageSetting ps = (PackageSetting) pkg.mExtras; 13965 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 13966 } 13967 13968 // Always delete data directories for package, even if we found no other 13969 // record of app. This helps users recover from UID mismatches without 13970 // resorting to a full data wipe. 13971 // TODO: triage flags as part of 26466827 13972 final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE; 13973 try { 13974 mInstaller.clearAppData(pkg.volumeUuid, packageName, userId, flags); 13975 } catch (InstallerException e) { 13976 Slog.w(TAG, "Couldn't remove cache files for package " + packageName, e); 13977 return false; 13978 } 13979 13980 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 13981 removeKeystoreDataIfNeeded(userId, appId); 13982 13983 // Create a native library symlink only if we have native libraries 13984 // and if the native libraries are 32 bit libraries. We do not provide 13985 // this symlink for 64 bit libraries. 13986 if (pkg.applicationInfo.primaryCpuAbi != null && 13987 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 13988 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 13989 try { 13990 mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 13991 nativeLibPath, userId); 13992 } catch (InstallerException e) { 13993 Slog.w(TAG, "Failed linking native library dir", e); 13994 return false; 13995 } 13996 } 13997 13998 return true; 13999 } 14000 14001 /** 14002 * Reverts user permission state changes (permissions and flags) in 14003 * all packages for a given user. 14004 * 14005 * @param userId The device user for which to do a reset. 14006 */ 14007 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 14008 final int packageCount = mPackages.size(); 14009 for (int i = 0; i < packageCount; i++) { 14010 PackageParser.Package pkg = mPackages.valueAt(i); 14011 PackageSetting ps = (PackageSetting) pkg.mExtras; 14012 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 14013 } 14014 } 14015 14016 /** 14017 * Reverts user permission state changes (permissions and flags). 14018 * 14019 * @param ps The package for which to reset. 14020 * @param userId The device user for which to do a reset. 14021 */ 14022 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 14023 final PackageSetting ps, final int userId) { 14024 if (ps.pkg == null) { 14025 return; 14026 } 14027 14028 // These are flags that can change base on user actions. 14029 final int userSettableMask = FLAG_PERMISSION_USER_SET 14030 | FLAG_PERMISSION_USER_FIXED 14031 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 14032 | FLAG_PERMISSION_REVIEW_REQUIRED; 14033 14034 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 14035 | FLAG_PERMISSION_POLICY_FIXED; 14036 14037 boolean writeInstallPermissions = false; 14038 boolean writeRuntimePermissions = false; 14039 14040 final int permissionCount = ps.pkg.requestedPermissions.size(); 14041 for (int i = 0; i < permissionCount; i++) { 14042 String permission = ps.pkg.requestedPermissions.get(i); 14043 14044 BasePermission bp = mSettings.mPermissions.get(permission); 14045 if (bp == null) { 14046 continue; 14047 } 14048 14049 // If shared user we just reset the state to which only this app contributed. 14050 if (ps.sharedUser != null) { 14051 boolean used = false; 14052 final int packageCount = ps.sharedUser.packages.size(); 14053 for (int j = 0; j < packageCount; j++) { 14054 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 14055 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 14056 && pkg.pkg.requestedPermissions.contains(permission)) { 14057 used = true; 14058 break; 14059 } 14060 } 14061 if (used) { 14062 continue; 14063 } 14064 } 14065 14066 PermissionsState permissionsState = ps.getPermissionsState(); 14067 14068 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 14069 14070 // Always clear the user settable flags. 14071 final boolean hasInstallState = permissionsState.getInstallPermissionState( 14072 bp.name) != null; 14073 // If permission review is enabled and this is a legacy app, mark the 14074 // permission as requiring a review as this is the initial state. 14075 int flags = 0; 14076 if (Build.PERMISSIONS_REVIEW_REQUIRED 14077 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 14078 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 14079 } 14080 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 14081 if (hasInstallState) { 14082 writeInstallPermissions = true; 14083 } else { 14084 writeRuntimePermissions = true; 14085 } 14086 } 14087 14088 // Below is only runtime permission handling. 14089 if (!bp.isRuntime()) { 14090 continue; 14091 } 14092 14093 // Never clobber system or policy. 14094 if ((oldFlags & policyOrSystemFlags) != 0) { 14095 continue; 14096 } 14097 14098 // If this permission was granted by default, make sure it is. 14099 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 14100 if (permissionsState.grantRuntimePermission(bp, userId) 14101 != PERMISSION_OPERATION_FAILURE) { 14102 writeRuntimePermissions = true; 14103 } 14104 // If permission review is enabled the permissions for a legacy apps 14105 // are represented as constantly granted runtime ones, so don't revoke. 14106 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 14107 // Otherwise, reset the permission. 14108 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 14109 switch (revokeResult) { 14110 case PERMISSION_OPERATION_SUCCESS: { 14111 writeRuntimePermissions = true; 14112 } break; 14113 14114 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 14115 writeRuntimePermissions = true; 14116 final int appId = ps.appId; 14117 mHandler.post(new Runnable() { 14118 @Override 14119 public void run() { 14120 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 14121 } 14122 }); 14123 } break; 14124 } 14125 } 14126 } 14127 14128 // Synchronously write as we are taking permissions away. 14129 if (writeRuntimePermissions) { 14130 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 14131 } 14132 14133 // Synchronously write as we are taking permissions away. 14134 if (writeInstallPermissions) { 14135 mSettings.writeLPr(); 14136 } 14137 } 14138 14139 /** 14140 * Remove entries from the keystore daemon. Will only remove it if the 14141 * {@code appId} is valid. 14142 */ 14143 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 14144 if (appId < 0) { 14145 return; 14146 } 14147 14148 final KeyStore keyStore = KeyStore.getInstance(); 14149 if (keyStore != null) { 14150 if (userId == UserHandle.USER_ALL) { 14151 for (final int individual : sUserManager.getUserIds()) { 14152 keyStore.clearUid(UserHandle.getUid(individual, appId)); 14153 } 14154 } else { 14155 keyStore.clearUid(UserHandle.getUid(userId, appId)); 14156 } 14157 } else { 14158 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 14159 } 14160 } 14161 14162 @Override 14163 public void deleteApplicationCacheFiles(final String packageName, 14164 final IPackageDataObserver observer) { 14165 mContext.enforceCallingOrSelfPermission( 14166 android.Manifest.permission.DELETE_CACHE_FILES, null); 14167 // Queue up an async operation since the package deletion may take a little while. 14168 final int userId = UserHandle.getCallingUserId(); 14169 mHandler.post(new Runnable() { 14170 public void run() { 14171 mHandler.removeCallbacks(this); 14172 final boolean succeded; 14173 synchronized (mInstallLock) { 14174 succeded = deleteApplicationCacheFilesLI(packageName, userId); 14175 } 14176 clearExternalStorageDataSync(packageName, userId, false); 14177 if (observer != null) { 14178 try { 14179 observer.onRemoveCompleted(packageName, succeded); 14180 } catch (RemoteException e) { 14181 Log.i(TAG, "Observer no longer exists."); 14182 } 14183 } //end if observer 14184 } //end run 14185 }); 14186 } 14187 14188 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 14189 if (packageName == null) { 14190 Slog.w(TAG, "Attempt to delete null packageName."); 14191 return false; 14192 } 14193 PackageParser.Package p; 14194 synchronized (mPackages) { 14195 p = mPackages.get(packageName); 14196 } 14197 if (p == null) { 14198 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 14199 return false; 14200 } 14201 final ApplicationInfo applicationInfo = p.applicationInfo; 14202 if (applicationInfo == null) { 14203 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 14204 return false; 14205 } 14206 // TODO: triage flags as part of 26466827 14207 final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE; 14208 try { 14209 mInstaller.clearAppData(p.volumeUuid, packageName, userId, 14210 flags | Installer.FLAG_CLEAR_CACHE_ONLY); 14211 } catch (InstallerException e) { 14212 Slog.w(TAG, "Couldn't remove cache files for package " 14213 + packageName + " u" + userId, e); 14214 return false; 14215 } 14216 return true; 14217 } 14218 14219 @Override 14220 public void getPackageSizeInfo(final String packageName, int userHandle, 14221 final IPackageStatsObserver observer) { 14222 mContext.enforceCallingOrSelfPermission( 14223 android.Manifest.permission.GET_PACKAGE_SIZE, null); 14224 if (packageName == null) { 14225 throw new IllegalArgumentException("Attempt to get size of null packageName"); 14226 } 14227 14228 PackageStats stats = new PackageStats(packageName, userHandle); 14229 14230 /* 14231 * Queue up an async operation since the package measurement may take a 14232 * little while. 14233 */ 14234 Message msg = mHandler.obtainMessage(INIT_COPY); 14235 msg.obj = new MeasureParams(stats, observer); 14236 mHandler.sendMessage(msg); 14237 } 14238 14239 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 14240 PackageStats pStats) { 14241 if (packageName == null) { 14242 Slog.w(TAG, "Attempt to get size of null packageName."); 14243 return false; 14244 } 14245 PackageParser.Package p; 14246 boolean dataOnly = false; 14247 String libDirRoot = null; 14248 String asecPath = null; 14249 PackageSetting ps = null; 14250 synchronized (mPackages) { 14251 p = mPackages.get(packageName); 14252 ps = mSettings.mPackages.get(packageName); 14253 if(p == null) { 14254 dataOnly = true; 14255 if((ps == null) || (ps.pkg == null)) { 14256 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 14257 return false; 14258 } 14259 p = ps.pkg; 14260 } 14261 if (ps != null) { 14262 libDirRoot = ps.legacyNativeLibraryPathString; 14263 } 14264 if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) { 14265 final long token = Binder.clearCallingIdentity(); 14266 try { 14267 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 14268 if (secureContainerId != null) { 14269 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 14270 } 14271 } finally { 14272 Binder.restoreCallingIdentity(token); 14273 } 14274 } 14275 } 14276 String publicSrcDir = null; 14277 if(!dataOnly) { 14278 final ApplicationInfo applicationInfo = p.applicationInfo; 14279 if (applicationInfo == null) { 14280 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 14281 return false; 14282 } 14283 if (p.isForwardLocked()) { 14284 publicSrcDir = applicationInfo.getBaseResourcePath(); 14285 } 14286 } 14287 // TODO: extend to measure size of split APKs 14288 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 14289 // not just the first level. 14290 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 14291 // just the primary. 14292 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 14293 14294 String apkPath; 14295 File packageDir = new File(p.codePath); 14296 14297 if (packageDir.isDirectory() && p.canHaveOatDir()) { 14298 apkPath = packageDir.getAbsolutePath(); 14299 // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice 14300 if (libDirRoot != null && libDirRoot.startsWith(apkPath)) { 14301 libDirRoot = null; 14302 } 14303 } else { 14304 apkPath = p.baseCodePath; 14305 } 14306 14307 // TODO: triage flags as part of 26466827 14308 final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE; 14309 try { 14310 mInstaller.getAppSize(p.volumeUuid, packageName, userHandle, flags, apkPath, 14311 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 14312 } catch (InstallerException e) { 14313 return false; 14314 } 14315 14316 // Fix-up for forward-locked applications in ASEC containers. 14317 if (!isExternal(p)) { 14318 pStats.codeSize += pStats.externalCodeSize; 14319 pStats.externalCodeSize = 0L; 14320 } 14321 14322 return true; 14323 } 14324 14325 14326 @Override 14327 public void addPackageToPreferred(String packageName) { 14328 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 14329 } 14330 14331 @Override 14332 public void removePackageFromPreferred(String packageName) { 14333 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 14334 } 14335 14336 @Override 14337 public List<PackageInfo> getPreferredPackages(int flags) { 14338 return new ArrayList<PackageInfo>(); 14339 } 14340 14341 private int getUidTargetSdkVersionLockedLPr(int uid) { 14342 Object obj = mSettings.getUserIdLPr(uid); 14343 if (obj instanceof SharedUserSetting) { 14344 final SharedUserSetting sus = (SharedUserSetting) obj; 14345 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 14346 final Iterator<PackageSetting> it = sus.packages.iterator(); 14347 while (it.hasNext()) { 14348 final PackageSetting ps = it.next(); 14349 if (ps.pkg != null) { 14350 int v = ps.pkg.applicationInfo.targetSdkVersion; 14351 if (v < vers) vers = v; 14352 } 14353 } 14354 return vers; 14355 } else if (obj instanceof PackageSetting) { 14356 final PackageSetting ps = (PackageSetting) obj; 14357 if (ps.pkg != null) { 14358 return ps.pkg.applicationInfo.targetSdkVersion; 14359 } 14360 } 14361 return Build.VERSION_CODES.CUR_DEVELOPMENT; 14362 } 14363 14364 @Override 14365 public void addPreferredActivity(IntentFilter filter, int match, 14366 ComponentName[] set, ComponentName activity, int userId) { 14367 addPreferredActivityInternal(filter, match, set, activity, true, userId, 14368 "Adding preferred"); 14369 } 14370 14371 private void addPreferredActivityInternal(IntentFilter filter, int match, 14372 ComponentName[] set, ComponentName activity, boolean always, int userId, 14373 String opname) { 14374 // writer 14375 int callingUid = Binder.getCallingUid(); 14376 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 14377 if (filter.countActions() == 0) { 14378 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 14379 return; 14380 } 14381 synchronized (mPackages) { 14382 if (mContext.checkCallingOrSelfPermission( 14383 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14384 != PackageManager.PERMISSION_GRANTED) { 14385 if (getUidTargetSdkVersionLockedLPr(callingUid) 14386 < Build.VERSION_CODES.FROYO) { 14387 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 14388 + callingUid); 14389 return; 14390 } 14391 mContext.enforceCallingOrSelfPermission( 14392 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14393 } 14394 14395 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 14396 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 14397 + userId + ":"); 14398 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14399 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 14400 scheduleWritePackageRestrictionsLocked(userId); 14401 } 14402 } 14403 14404 @Override 14405 public void replacePreferredActivity(IntentFilter filter, int match, 14406 ComponentName[] set, ComponentName activity, int userId) { 14407 if (filter.countActions() != 1) { 14408 throw new IllegalArgumentException( 14409 "replacePreferredActivity expects filter to have only 1 action."); 14410 } 14411 if (filter.countDataAuthorities() != 0 14412 || filter.countDataPaths() != 0 14413 || filter.countDataSchemes() > 1 14414 || filter.countDataTypes() != 0) { 14415 throw new IllegalArgumentException( 14416 "replacePreferredActivity expects filter to have no data authorities, " + 14417 "paths, or types; and at most one scheme."); 14418 } 14419 14420 final int callingUid = Binder.getCallingUid(); 14421 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 14422 synchronized (mPackages) { 14423 if (mContext.checkCallingOrSelfPermission( 14424 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14425 != PackageManager.PERMISSION_GRANTED) { 14426 if (getUidTargetSdkVersionLockedLPr(callingUid) 14427 < Build.VERSION_CODES.FROYO) { 14428 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 14429 + Binder.getCallingUid()); 14430 return; 14431 } 14432 mContext.enforceCallingOrSelfPermission( 14433 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14434 } 14435 14436 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 14437 if (pir != null) { 14438 // Get all of the existing entries that exactly match this filter. 14439 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 14440 if (existing != null && existing.size() == 1) { 14441 PreferredActivity cur = existing.get(0); 14442 if (DEBUG_PREFERRED) { 14443 Slog.i(TAG, "Checking replace of preferred:"); 14444 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14445 if (!cur.mPref.mAlways) { 14446 Slog.i(TAG, " -- CUR; not mAlways!"); 14447 } else { 14448 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 14449 Slog.i(TAG, " -- CUR: mSet=" 14450 + Arrays.toString(cur.mPref.mSetComponents)); 14451 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 14452 Slog.i(TAG, " -- NEW: mMatch=" 14453 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 14454 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 14455 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 14456 } 14457 } 14458 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 14459 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 14460 && cur.mPref.sameSet(set)) { 14461 // Setting the preferred activity to what it happens to be already 14462 if (DEBUG_PREFERRED) { 14463 Slog.i(TAG, "Replacing with same preferred activity " 14464 + cur.mPref.mShortComponent + " for user " 14465 + userId + ":"); 14466 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14467 } 14468 return; 14469 } 14470 } 14471 14472 if (existing != null) { 14473 if (DEBUG_PREFERRED) { 14474 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 14475 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14476 } 14477 for (int i = 0; i < existing.size(); i++) { 14478 PreferredActivity pa = existing.get(i); 14479 if (DEBUG_PREFERRED) { 14480 Slog.i(TAG, "Removing existing preferred activity " 14481 + pa.mPref.mComponent + ":"); 14482 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 14483 } 14484 pir.removeFilter(pa); 14485 } 14486 } 14487 } 14488 addPreferredActivityInternal(filter, match, set, activity, true, userId, 14489 "Replacing preferred"); 14490 } 14491 } 14492 14493 @Override 14494 public void clearPackagePreferredActivities(String packageName) { 14495 final int uid = Binder.getCallingUid(); 14496 // writer 14497 synchronized (mPackages) { 14498 PackageParser.Package pkg = mPackages.get(packageName); 14499 if (pkg == null || pkg.applicationInfo.uid != uid) { 14500 if (mContext.checkCallingOrSelfPermission( 14501 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14502 != PackageManager.PERMISSION_GRANTED) { 14503 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 14504 < Build.VERSION_CODES.FROYO) { 14505 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 14506 + Binder.getCallingUid()); 14507 return; 14508 } 14509 mContext.enforceCallingOrSelfPermission( 14510 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14511 } 14512 } 14513 14514 int user = UserHandle.getCallingUserId(); 14515 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 14516 scheduleWritePackageRestrictionsLocked(user); 14517 } 14518 } 14519 } 14520 14521 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14522 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 14523 ArrayList<PreferredActivity> removed = null; 14524 boolean changed = false; 14525 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14526 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 14527 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14528 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 14529 continue; 14530 } 14531 Iterator<PreferredActivity> it = pir.filterIterator(); 14532 while (it.hasNext()) { 14533 PreferredActivity pa = it.next(); 14534 // Mark entry for removal only if it matches the package name 14535 // and the entry is of type "always". 14536 if (packageName == null || 14537 (pa.mPref.mComponent.getPackageName().equals(packageName) 14538 && pa.mPref.mAlways)) { 14539 if (removed == null) { 14540 removed = new ArrayList<PreferredActivity>(); 14541 } 14542 removed.add(pa); 14543 } 14544 } 14545 if (removed != null) { 14546 for (int j=0; j<removed.size(); j++) { 14547 PreferredActivity pa = removed.get(j); 14548 pir.removeFilter(pa); 14549 } 14550 changed = true; 14551 } 14552 } 14553 return changed; 14554 } 14555 14556 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14557 private void clearIntentFilterVerificationsLPw(int userId) { 14558 final int packageCount = mPackages.size(); 14559 for (int i = 0; i < packageCount; i++) { 14560 PackageParser.Package pkg = mPackages.valueAt(i); 14561 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 14562 } 14563 } 14564 14565 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14566 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 14567 if (userId == UserHandle.USER_ALL) { 14568 if (mSettings.removeIntentFilterVerificationLPw(packageName, 14569 sUserManager.getUserIds())) { 14570 for (int oneUserId : sUserManager.getUserIds()) { 14571 scheduleWritePackageRestrictionsLocked(oneUserId); 14572 } 14573 } 14574 } else { 14575 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 14576 scheduleWritePackageRestrictionsLocked(userId); 14577 } 14578 } 14579 } 14580 14581 void clearDefaultBrowserIfNeeded(String packageName) { 14582 for (int oneUserId : sUserManager.getUserIds()) { 14583 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 14584 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 14585 if (packageName.equals(defaultBrowserPackageName)) { 14586 setDefaultBrowserPackageName(null, oneUserId); 14587 } 14588 } 14589 } 14590 14591 @Override 14592 public void resetApplicationPreferences(int userId) { 14593 mContext.enforceCallingOrSelfPermission( 14594 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14595 // writer 14596 synchronized (mPackages) { 14597 final long identity = Binder.clearCallingIdentity(); 14598 try { 14599 clearPackagePreferredActivitiesLPw(null, userId); 14600 mSettings.applyDefaultPreferredAppsLPw(this, userId); 14601 // TODO: We have to reset the default SMS and Phone. This requires 14602 // significant refactoring to keep all default apps in the package 14603 // manager (cleaner but more work) or have the services provide 14604 // callbacks to the package manager to request a default app reset. 14605 applyFactoryDefaultBrowserLPw(userId); 14606 clearIntentFilterVerificationsLPw(userId); 14607 primeDomainVerificationsLPw(userId); 14608 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 14609 scheduleWritePackageRestrictionsLocked(userId); 14610 } finally { 14611 Binder.restoreCallingIdentity(identity); 14612 } 14613 } 14614 } 14615 14616 @Override 14617 public int getPreferredActivities(List<IntentFilter> outFilters, 14618 List<ComponentName> outActivities, String packageName) { 14619 14620 int num = 0; 14621 final int userId = UserHandle.getCallingUserId(); 14622 // reader 14623 synchronized (mPackages) { 14624 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 14625 if (pir != null) { 14626 final Iterator<PreferredActivity> it = pir.filterIterator(); 14627 while (it.hasNext()) { 14628 final PreferredActivity pa = it.next(); 14629 if (packageName == null 14630 || (pa.mPref.mComponent.getPackageName().equals(packageName) 14631 && pa.mPref.mAlways)) { 14632 if (outFilters != null) { 14633 outFilters.add(new IntentFilter(pa)); 14634 } 14635 if (outActivities != null) { 14636 outActivities.add(pa.mPref.mComponent); 14637 } 14638 } 14639 } 14640 } 14641 } 14642 14643 return num; 14644 } 14645 14646 @Override 14647 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 14648 int userId) { 14649 int callingUid = Binder.getCallingUid(); 14650 if (callingUid != Process.SYSTEM_UID) { 14651 throw new SecurityException( 14652 "addPersistentPreferredActivity can only be run by the system"); 14653 } 14654 if (filter.countActions() == 0) { 14655 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 14656 return; 14657 } 14658 synchronized (mPackages) { 14659 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 14660 ":"); 14661 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14662 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 14663 new PersistentPreferredActivity(filter, activity)); 14664 scheduleWritePackageRestrictionsLocked(userId); 14665 } 14666 } 14667 14668 @Override 14669 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 14670 int callingUid = Binder.getCallingUid(); 14671 if (callingUid != Process.SYSTEM_UID) { 14672 throw new SecurityException( 14673 "clearPackagePersistentPreferredActivities can only be run by the system"); 14674 } 14675 ArrayList<PersistentPreferredActivity> removed = null; 14676 boolean changed = false; 14677 synchronized (mPackages) { 14678 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 14679 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 14680 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 14681 .valueAt(i); 14682 if (userId != thisUserId) { 14683 continue; 14684 } 14685 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 14686 while (it.hasNext()) { 14687 PersistentPreferredActivity ppa = it.next(); 14688 // Mark entry for removal only if it matches the package name. 14689 if (ppa.mComponent.getPackageName().equals(packageName)) { 14690 if (removed == null) { 14691 removed = new ArrayList<PersistentPreferredActivity>(); 14692 } 14693 removed.add(ppa); 14694 } 14695 } 14696 if (removed != null) { 14697 for (int j=0; j<removed.size(); j++) { 14698 PersistentPreferredActivity ppa = removed.get(j); 14699 ppir.removeFilter(ppa); 14700 } 14701 changed = true; 14702 } 14703 } 14704 14705 if (changed) { 14706 scheduleWritePackageRestrictionsLocked(userId); 14707 } 14708 } 14709 } 14710 14711 /** 14712 * Common machinery for picking apart a restored XML blob and passing 14713 * it to a caller-supplied functor to be applied to the running system. 14714 */ 14715 private void restoreFromXml(XmlPullParser parser, int userId, 14716 String expectedStartTag, BlobXmlRestorer functor) 14717 throws IOException, XmlPullParserException { 14718 int type; 14719 while ((type = parser.next()) != XmlPullParser.START_TAG 14720 && type != XmlPullParser.END_DOCUMENT) { 14721 } 14722 if (type != XmlPullParser.START_TAG) { 14723 // oops didn't find a start tag?! 14724 if (DEBUG_BACKUP) { 14725 Slog.e(TAG, "Didn't find start tag during restore"); 14726 } 14727 return; 14728 } 14729Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 14730 // this is supposed to be TAG_PREFERRED_BACKUP 14731 if (!expectedStartTag.equals(parser.getName())) { 14732 if (DEBUG_BACKUP) { 14733 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 14734 } 14735 return; 14736 } 14737 14738 // skip interfering stuff, then we're aligned with the backing implementation 14739 while ((type = parser.next()) == XmlPullParser.TEXT) { } 14740Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 14741 functor.apply(parser, userId); 14742 } 14743 14744 private interface BlobXmlRestorer { 14745 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 14746 } 14747 14748 /** 14749 * Non-Binder method, support for the backup/restore mechanism: write the 14750 * full set of preferred activities in its canonical XML format. Returns the 14751 * XML output as a byte array, or null if there is none. 14752 */ 14753 @Override 14754 public byte[] getPreferredActivityBackup(int userId) { 14755 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14756 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 14757 } 14758 14759 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14760 try { 14761 final XmlSerializer serializer = new FastXmlSerializer(); 14762 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14763 serializer.startDocument(null, true); 14764 serializer.startTag(null, TAG_PREFERRED_BACKUP); 14765 14766 synchronized (mPackages) { 14767 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 14768 } 14769 14770 serializer.endTag(null, TAG_PREFERRED_BACKUP); 14771 serializer.endDocument(); 14772 serializer.flush(); 14773 } catch (Exception e) { 14774 if (DEBUG_BACKUP) { 14775 Slog.e(TAG, "Unable to write preferred activities for backup", e); 14776 } 14777 return null; 14778 } 14779 14780 return dataStream.toByteArray(); 14781 } 14782 14783 @Override 14784 public void restorePreferredActivities(byte[] backup, int userId) { 14785 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14786 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14787 } 14788 14789 try { 14790 final XmlPullParser parser = Xml.newPullParser(); 14791 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14792 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 14793 new BlobXmlRestorer() { 14794 @Override 14795 public void apply(XmlPullParser parser, int userId) 14796 throws XmlPullParserException, IOException { 14797 synchronized (mPackages) { 14798 mSettings.readPreferredActivitiesLPw(parser, userId); 14799 } 14800 } 14801 } ); 14802 } catch (Exception e) { 14803 if (DEBUG_BACKUP) { 14804 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14805 } 14806 } 14807 } 14808 14809 /** 14810 * Non-Binder method, support for the backup/restore mechanism: write the 14811 * default browser (etc) settings in its canonical XML format. Returns the default 14812 * browser XML representation as a byte array, or null if there is none. 14813 */ 14814 @Override 14815 public byte[] getDefaultAppsBackup(int userId) { 14816 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14817 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 14818 } 14819 14820 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14821 try { 14822 final XmlSerializer serializer = new FastXmlSerializer(); 14823 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14824 serializer.startDocument(null, true); 14825 serializer.startTag(null, TAG_DEFAULT_APPS); 14826 14827 synchronized (mPackages) { 14828 mSettings.writeDefaultAppsLPr(serializer, userId); 14829 } 14830 14831 serializer.endTag(null, TAG_DEFAULT_APPS); 14832 serializer.endDocument(); 14833 serializer.flush(); 14834 } catch (Exception e) { 14835 if (DEBUG_BACKUP) { 14836 Slog.e(TAG, "Unable to write default apps for backup", e); 14837 } 14838 return null; 14839 } 14840 14841 return dataStream.toByteArray(); 14842 } 14843 14844 @Override 14845 public void restoreDefaultApps(byte[] backup, int userId) { 14846 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14847 throw new SecurityException("Only the system may call restoreDefaultApps()"); 14848 } 14849 14850 try { 14851 final XmlPullParser parser = Xml.newPullParser(); 14852 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14853 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 14854 new BlobXmlRestorer() { 14855 @Override 14856 public void apply(XmlPullParser parser, int userId) 14857 throws XmlPullParserException, IOException { 14858 synchronized (mPackages) { 14859 mSettings.readDefaultAppsLPw(parser, userId); 14860 } 14861 } 14862 } ); 14863 } catch (Exception e) { 14864 if (DEBUG_BACKUP) { 14865 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 14866 } 14867 } 14868 } 14869 14870 @Override 14871 public byte[] getIntentFilterVerificationBackup(int userId) { 14872 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14873 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 14874 } 14875 14876 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14877 try { 14878 final XmlSerializer serializer = new FastXmlSerializer(); 14879 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14880 serializer.startDocument(null, true); 14881 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 14882 14883 synchronized (mPackages) { 14884 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 14885 } 14886 14887 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 14888 serializer.endDocument(); 14889 serializer.flush(); 14890 } catch (Exception e) { 14891 if (DEBUG_BACKUP) { 14892 Slog.e(TAG, "Unable to write default apps for backup", e); 14893 } 14894 return null; 14895 } 14896 14897 return dataStream.toByteArray(); 14898 } 14899 14900 @Override 14901 public void restoreIntentFilterVerification(byte[] backup, int userId) { 14902 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14903 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14904 } 14905 14906 try { 14907 final XmlPullParser parser = Xml.newPullParser(); 14908 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14909 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 14910 new BlobXmlRestorer() { 14911 @Override 14912 public void apply(XmlPullParser parser, int userId) 14913 throws XmlPullParserException, IOException { 14914 synchronized (mPackages) { 14915 mSettings.readAllDomainVerificationsLPr(parser, userId); 14916 mSettings.writeLPr(); 14917 } 14918 } 14919 } ); 14920 } catch (Exception e) { 14921 if (DEBUG_BACKUP) { 14922 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14923 } 14924 } 14925 } 14926 14927 @Override 14928 public byte[] getPermissionGrantBackup(int userId) { 14929 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14930 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 14931 } 14932 14933 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14934 try { 14935 final XmlSerializer serializer = new FastXmlSerializer(); 14936 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14937 serializer.startDocument(null, true); 14938 serializer.startTag(null, TAG_PERMISSION_BACKUP); 14939 14940 synchronized (mPackages) { 14941 serializeRuntimePermissionGrantsLPr(serializer, userId); 14942 } 14943 14944 serializer.endTag(null, TAG_PERMISSION_BACKUP); 14945 serializer.endDocument(); 14946 serializer.flush(); 14947 } catch (Exception e) { 14948 if (DEBUG_BACKUP) { 14949 Slog.e(TAG, "Unable to write default apps for backup", e); 14950 } 14951 return null; 14952 } 14953 14954 return dataStream.toByteArray(); 14955 } 14956 14957 @Override 14958 public void restorePermissionGrants(byte[] backup, int userId) { 14959 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14960 throw new SecurityException("Only the system may call restorePermissionGrants()"); 14961 } 14962 14963 try { 14964 final XmlPullParser parser = Xml.newPullParser(); 14965 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14966 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 14967 new BlobXmlRestorer() { 14968 @Override 14969 public void apply(XmlPullParser parser, int userId) 14970 throws XmlPullParserException, IOException { 14971 synchronized (mPackages) { 14972 processRestoredPermissionGrantsLPr(parser, userId); 14973 } 14974 } 14975 } ); 14976 } catch (Exception e) { 14977 if (DEBUG_BACKUP) { 14978 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14979 } 14980 } 14981 } 14982 14983 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 14984 throws IOException { 14985 serializer.startTag(null, TAG_ALL_GRANTS); 14986 14987 final int N = mSettings.mPackages.size(); 14988 for (int i = 0; i < N; i++) { 14989 final PackageSetting ps = mSettings.mPackages.valueAt(i); 14990 boolean pkgGrantsKnown = false; 14991 14992 PermissionsState packagePerms = ps.getPermissionsState(); 14993 14994 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 14995 final int grantFlags = state.getFlags(); 14996 // only look at grants that are not system/policy fixed 14997 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 14998 final boolean isGranted = state.isGranted(); 14999 // And only back up the user-twiddled state bits 15000 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 15001 final String packageName = mSettings.mPackages.keyAt(i); 15002 if (!pkgGrantsKnown) { 15003 serializer.startTag(null, TAG_GRANT); 15004 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 15005 pkgGrantsKnown = true; 15006 } 15007 15008 final boolean userSet = 15009 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 15010 final boolean userFixed = 15011 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 15012 final boolean revoke = 15013 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 15014 15015 serializer.startTag(null, TAG_PERMISSION); 15016 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 15017 if (isGranted) { 15018 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 15019 } 15020 if (userSet) { 15021 serializer.attribute(null, ATTR_USER_SET, "true"); 15022 } 15023 if (userFixed) { 15024 serializer.attribute(null, ATTR_USER_FIXED, "true"); 15025 } 15026 if (revoke) { 15027 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 15028 } 15029 serializer.endTag(null, TAG_PERMISSION); 15030 } 15031 } 15032 } 15033 15034 if (pkgGrantsKnown) { 15035 serializer.endTag(null, TAG_GRANT); 15036 } 15037 } 15038 15039 serializer.endTag(null, TAG_ALL_GRANTS); 15040 } 15041 15042 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 15043 throws XmlPullParserException, IOException { 15044 String pkgName = null; 15045 int outerDepth = parser.getDepth(); 15046 int type; 15047 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 15048 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 15049 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 15050 continue; 15051 } 15052 15053 final String tagName = parser.getName(); 15054 if (tagName.equals(TAG_GRANT)) { 15055 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 15056 if (DEBUG_BACKUP) { 15057 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 15058 } 15059 } else if (tagName.equals(TAG_PERMISSION)) { 15060 15061 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 15062 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 15063 15064 int newFlagSet = 0; 15065 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 15066 newFlagSet |= FLAG_PERMISSION_USER_SET; 15067 } 15068 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 15069 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 15070 } 15071 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 15072 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 15073 } 15074 if (DEBUG_BACKUP) { 15075 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 15076 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 15077 } 15078 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15079 if (ps != null) { 15080 // Already installed so we apply the grant immediately 15081 if (DEBUG_BACKUP) { 15082 Slog.v(TAG, " + already installed; applying"); 15083 } 15084 PermissionsState perms = ps.getPermissionsState(); 15085 BasePermission bp = mSettings.mPermissions.get(permName); 15086 if (bp != null) { 15087 if (isGranted) { 15088 perms.grantRuntimePermission(bp, userId); 15089 } 15090 if (newFlagSet != 0) { 15091 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 15092 } 15093 } 15094 } else { 15095 // Need to wait for post-restore install to apply the grant 15096 if (DEBUG_BACKUP) { 15097 Slog.v(TAG, " - not yet installed; saving for later"); 15098 } 15099 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 15100 isGranted, newFlagSet, userId); 15101 } 15102 } else { 15103 PackageManagerService.reportSettingsProblem(Log.WARN, 15104 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 15105 XmlUtils.skipCurrentTag(parser); 15106 } 15107 } 15108 15109 scheduleWriteSettingsLocked(); 15110 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 15111 } 15112 15113 @Override 15114 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 15115 int sourceUserId, int targetUserId, int flags) { 15116 mContext.enforceCallingOrSelfPermission( 15117 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 15118 int callingUid = Binder.getCallingUid(); 15119 enforceOwnerRights(ownerPackage, callingUid); 15120 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 15121 if (intentFilter.countActions() == 0) { 15122 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 15123 return; 15124 } 15125 synchronized (mPackages) { 15126 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 15127 ownerPackage, targetUserId, flags); 15128 CrossProfileIntentResolver resolver = 15129 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 15130 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 15131 // We have all those whose filter is equal. Now checking if the rest is equal as well. 15132 if (existing != null) { 15133 int size = existing.size(); 15134 for (int i = 0; i < size; i++) { 15135 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 15136 return; 15137 } 15138 } 15139 } 15140 resolver.addFilter(newFilter); 15141 scheduleWritePackageRestrictionsLocked(sourceUserId); 15142 } 15143 } 15144 15145 @Override 15146 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 15147 mContext.enforceCallingOrSelfPermission( 15148 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 15149 int callingUid = Binder.getCallingUid(); 15150 enforceOwnerRights(ownerPackage, callingUid); 15151 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 15152 synchronized (mPackages) { 15153 CrossProfileIntentResolver resolver = 15154 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 15155 ArraySet<CrossProfileIntentFilter> set = 15156 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 15157 for (CrossProfileIntentFilter filter : set) { 15158 if (filter.getOwnerPackage().equals(ownerPackage)) { 15159 resolver.removeFilter(filter); 15160 } 15161 } 15162 scheduleWritePackageRestrictionsLocked(sourceUserId); 15163 } 15164 } 15165 15166 // Enforcing that callingUid is owning pkg on userId 15167 private void enforceOwnerRights(String pkg, int callingUid) { 15168 // The system owns everything. 15169 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 15170 return; 15171 } 15172 int callingUserId = UserHandle.getUserId(callingUid); 15173 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 15174 if (pi == null) { 15175 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 15176 + callingUserId); 15177 } 15178 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 15179 throw new SecurityException("Calling uid " + callingUid 15180 + " does not own package " + pkg); 15181 } 15182 } 15183 15184 @Override 15185 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 15186 Intent intent = new Intent(Intent.ACTION_MAIN); 15187 intent.addCategory(Intent.CATEGORY_HOME); 15188 15189 final int callingUserId = UserHandle.getCallingUserId(); 15190 List<ResolveInfo> list = queryIntentActivities(intent, null, 15191 PackageManager.GET_META_DATA, callingUserId); 15192 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 15193 true, false, false, callingUserId); 15194 15195 allHomeCandidates.clear(); 15196 if (list != null) { 15197 for (ResolveInfo ri : list) { 15198 allHomeCandidates.add(ri); 15199 } 15200 } 15201 return (preferred == null || preferred.activityInfo == null) 15202 ? null 15203 : new ComponentName(preferred.activityInfo.packageName, 15204 preferred.activityInfo.name); 15205 } 15206 15207 @Override 15208 public void setApplicationEnabledSetting(String appPackageName, 15209 int newState, int flags, int userId, String callingPackage) { 15210 if (!sUserManager.exists(userId)) return; 15211 if (callingPackage == null) { 15212 callingPackage = Integer.toString(Binder.getCallingUid()); 15213 } 15214 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 15215 } 15216 15217 @Override 15218 public void setComponentEnabledSetting(ComponentName componentName, 15219 int newState, int flags, int userId) { 15220 if (!sUserManager.exists(userId)) return; 15221 setEnabledSetting(componentName.getPackageName(), 15222 componentName.getClassName(), newState, flags, userId, null); 15223 } 15224 15225 private void setEnabledSetting(final String packageName, String className, int newState, 15226 final int flags, int userId, String callingPackage) { 15227 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 15228 || newState == COMPONENT_ENABLED_STATE_ENABLED 15229 || newState == COMPONENT_ENABLED_STATE_DISABLED 15230 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 15231 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 15232 throw new IllegalArgumentException("Invalid new component state: " 15233 + newState); 15234 } 15235 PackageSetting pkgSetting; 15236 final int uid = Binder.getCallingUid(); 15237 final int permission = mContext.checkCallingOrSelfPermission( 15238 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 15239 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 15240 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 15241 boolean sendNow = false; 15242 boolean isApp = (className == null); 15243 String componentName = isApp ? packageName : className; 15244 int packageUid = -1; 15245 ArrayList<String> components; 15246 15247 // writer 15248 synchronized (mPackages) { 15249 pkgSetting = mSettings.mPackages.get(packageName); 15250 if (pkgSetting == null) { 15251 if (className == null) { 15252 throw new IllegalArgumentException("Unknown package: " + packageName); 15253 } 15254 throw new IllegalArgumentException( 15255 "Unknown component: " + packageName + "/" + className); 15256 } 15257 // Allow root and verify that userId is not being specified by a different user 15258 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 15259 throw new SecurityException( 15260 "Permission Denial: attempt to change component state from pid=" 15261 + Binder.getCallingPid() 15262 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 15263 } 15264 if (className == null) { 15265 // We're dealing with an application/package level state change 15266 if (pkgSetting.getEnabled(userId) == newState) { 15267 // Nothing to do 15268 return; 15269 } 15270 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 15271 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 15272 // Don't care about who enables an app. 15273 callingPackage = null; 15274 } 15275 pkgSetting.setEnabled(newState, userId, callingPackage); 15276 // pkgSetting.pkg.mSetEnabled = newState; 15277 } else { 15278 // We're dealing with a component level state change 15279 // First, verify that this is a valid class name. 15280 PackageParser.Package pkg = pkgSetting.pkg; 15281 if (pkg == null || !pkg.hasComponentClassName(className)) { 15282 if (pkg != null && 15283 pkg.applicationInfo.targetSdkVersion >= 15284 Build.VERSION_CODES.JELLY_BEAN) { 15285 throw new IllegalArgumentException("Component class " + className 15286 + " does not exist in " + packageName); 15287 } else { 15288 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 15289 + className + " does not exist in " + packageName); 15290 } 15291 } 15292 switch (newState) { 15293 case COMPONENT_ENABLED_STATE_ENABLED: 15294 if (!pkgSetting.enableComponentLPw(className, userId)) { 15295 return; 15296 } 15297 break; 15298 case COMPONENT_ENABLED_STATE_DISABLED: 15299 if (!pkgSetting.disableComponentLPw(className, userId)) { 15300 return; 15301 } 15302 break; 15303 case COMPONENT_ENABLED_STATE_DEFAULT: 15304 if (!pkgSetting.restoreComponentLPw(className, userId)) { 15305 return; 15306 } 15307 break; 15308 default: 15309 Slog.e(TAG, "Invalid new component state: " + newState); 15310 return; 15311 } 15312 } 15313 scheduleWritePackageRestrictionsLocked(userId); 15314 components = mPendingBroadcasts.get(userId, packageName); 15315 final boolean newPackage = components == null; 15316 if (newPackage) { 15317 components = new ArrayList<String>(); 15318 } 15319 if (!components.contains(componentName)) { 15320 components.add(componentName); 15321 } 15322 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 15323 sendNow = true; 15324 // Purge entry from pending broadcast list if another one exists already 15325 // since we are sending one right away. 15326 mPendingBroadcasts.remove(userId, packageName); 15327 } else { 15328 if (newPackage) { 15329 mPendingBroadcasts.put(userId, packageName, components); 15330 } 15331 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 15332 // Schedule a message 15333 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 15334 } 15335 } 15336 } 15337 15338 long callingId = Binder.clearCallingIdentity(); 15339 try { 15340 if (sendNow) { 15341 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 15342 sendPackageChangedBroadcast(packageName, 15343 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 15344 } 15345 } finally { 15346 Binder.restoreCallingIdentity(callingId); 15347 } 15348 } 15349 15350 private void sendPackageChangedBroadcast(String packageName, 15351 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 15352 if (DEBUG_INSTALL) 15353 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 15354 + componentNames); 15355 Bundle extras = new Bundle(4); 15356 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 15357 String nameList[] = new String[componentNames.size()]; 15358 componentNames.toArray(nameList); 15359 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 15360 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 15361 extras.putInt(Intent.EXTRA_UID, packageUid); 15362 // If this is not reporting a change of the overall package, then only send it 15363 // to registered receivers. We don't want to launch a swath of apps for every 15364 // little component state change. 15365 final int flags = !componentNames.contains(packageName) 15366 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 15367 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 15368 new int[] {UserHandle.getUserId(packageUid)}); 15369 } 15370 15371 @Override 15372 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 15373 if (!sUserManager.exists(userId)) return; 15374 final int uid = Binder.getCallingUid(); 15375 final int permission = mContext.checkCallingOrSelfPermission( 15376 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 15377 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 15378 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 15379 // writer 15380 synchronized (mPackages) { 15381 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 15382 allowedByPermission, uid, userId)) { 15383 scheduleWritePackageRestrictionsLocked(userId); 15384 } 15385 } 15386 } 15387 15388 @Override 15389 public String getInstallerPackageName(String packageName) { 15390 // reader 15391 synchronized (mPackages) { 15392 return mSettings.getInstallerPackageNameLPr(packageName); 15393 } 15394 } 15395 15396 @Override 15397 public int getApplicationEnabledSetting(String packageName, int userId) { 15398 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 15399 int uid = Binder.getCallingUid(); 15400 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 15401 // reader 15402 synchronized (mPackages) { 15403 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 15404 } 15405 } 15406 15407 @Override 15408 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 15409 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 15410 int uid = Binder.getCallingUid(); 15411 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 15412 // reader 15413 synchronized (mPackages) { 15414 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 15415 } 15416 } 15417 15418 @Override 15419 public void enterSafeMode() { 15420 enforceSystemOrRoot("Only the system can request entering safe mode"); 15421 15422 if (!mSystemReady) { 15423 mSafeMode = true; 15424 } 15425 } 15426 15427 @Override 15428 public void systemReady() { 15429 mSystemReady = true; 15430 15431 // Read the compatibilty setting when the system is ready. 15432 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 15433 mContext.getContentResolver(), 15434 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 15435 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 15436 if (DEBUG_SETTINGS) { 15437 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 15438 } 15439 15440 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 15441 15442 synchronized (mPackages) { 15443 // Verify that all of the preferred activity components actually 15444 // exist. It is possible for applications to be updated and at 15445 // that point remove a previously declared activity component that 15446 // had been set as a preferred activity. We try to clean this up 15447 // the next time we encounter that preferred activity, but it is 15448 // possible for the user flow to never be able to return to that 15449 // situation so here we do a sanity check to make sure we haven't 15450 // left any junk around. 15451 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 15452 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 15453 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 15454 removed.clear(); 15455 for (PreferredActivity pa : pir.filterSet()) { 15456 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 15457 removed.add(pa); 15458 } 15459 } 15460 if (removed.size() > 0) { 15461 for (int r=0; r<removed.size(); r++) { 15462 PreferredActivity pa = removed.get(r); 15463 Slog.w(TAG, "Removing dangling preferred activity: " 15464 + pa.mPref.mComponent); 15465 pir.removeFilter(pa); 15466 } 15467 mSettings.writePackageRestrictionsLPr( 15468 mSettings.mPreferredActivities.keyAt(i)); 15469 } 15470 } 15471 15472 for (int userId : UserManagerService.getInstance().getUserIds()) { 15473 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 15474 grantPermissionsUserIds = ArrayUtils.appendInt( 15475 grantPermissionsUserIds, userId); 15476 } 15477 } 15478 } 15479 sUserManager.systemReady(); 15480 15481 // If we upgraded grant all default permissions before kicking off. 15482 for (int userId : grantPermissionsUserIds) { 15483 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 15484 } 15485 15486 // Kick off any messages waiting for system ready 15487 if (mPostSystemReadyMessages != null) { 15488 for (Message msg : mPostSystemReadyMessages) { 15489 msg.sendToTarget(); 15490 } 15491 mPostSystemReadyMessages = null; 15492 } 15493 15494 // Watch for external volumes that come and go over time 15495 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15496 storage.registerListener(mStorageListener); 15497 15498 mInstallerService.systemReady(); 15499 mPackageDexOptimizer.systemReady(); 15500 15501 MountServiceInternal mountServiceInternal = LocalServices.getService( 15502 MountServiceInternal.class); 15503 mountServiceInternal.addExternalStoragePolicy( 15504 new MountServiceInternal.ExternalStorageMountPolicy() { 15505 @Override 15506 public int getMountMode(int uid, String packageName) { 15507 if (Process.isIsolated(uid)) { 15508 return Zygote.MOUNT_EXTERNAL_NONE; 15509 } 15510 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 15511 return Zygote.MOUNT_EXTERNAL_DEFAULT; 15512 } 15513 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 15514 return Zygote.MOUNT_EXTERNAL_DEFAULT; 15515 } 15516 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 15517 return Zygote.MOUNT_EXTERNAL_READ; 15518 } 15519 return Zygote.MOUNT_EXTERNAL_WRITE; 15520 } 15521 15522 @Override 15523 public boolean hasExternalStorage(int uid, String packageName) { 15524 return true; 15525 } 15526 }); 15527 } 15528 15529 @Override 15530 public boolean isSafeMode() { 15531 return mSafeMode; 15532 } 15533 15534 @Override 15535 public boolean hasSystemUidErrors() { 15536 return mHasSystemUidErrors; 15537 } 15538 15539 static String arrayToString(int[] array) { 15540 StringBuffer buf = new StringBuffer(128); 15541 buf.append('['); 15542 if (array != null) { 15543 for (int i=0; i<array.length; i++) { 15544 if (i > 0) buf.append(", "); 15545 buf.append(array[i]); 15546 } 15547 } 15548 buf.append(']'); 15549 return buf.toString(); 15550 } 15551 15552 static class DumpState { 15553 public static final int DUMP_LIBS = 1 << 0; 15554 public static final int DUMP_FEATURES = 1 << 1; 15555 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 15556 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 15557 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 15558 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 15559 public static final int DUMP_PERMISSIONS = 1 << 6; 15560 public static final int DUMP_PACKAGES = 1 << 7; 15561 public static final int DUMP_SHARED_USERS = 1 << 8; 15562 public static final int DUMP_MESSAGES = 1 << 9; 15563 public static final int DUMP_PROVIDERS = 1 << 10; 15564 public static final int DUMP_VERIFIERS = 1 << 11; 15565 public static final int DUMP_PREFERRED = 1 << 12; 15566 public static final int DUMP_PREFERRED_XML = 1 << 13; 15567 public static final int DUMP_KEYSETS = 1 << 14; 15568 public static final int DUMP_VERSION = 1 << 15; 15569 public static final int DUMP_INSTALLS = 1 << 16; 15570 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 15571 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 15572 15573 public static final int OPTION_SHOW_FILTERS = 1 << 0; 15574 15575 private int mTypes; 15576 15577 private int mOptions; 15578 15579 private boolean mTitlePrinted; 15580 15581 private SharedUserSetting mSharedUser; 15582 15583 public boolean isDumping(int type) { 15584 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 15585 return true; 15586 } 15587 15588 return (mTypes & type) != 0; 15589 } 15590 15591 public void setDump(int type) { 15592 mTypes |= type; 15593 } 15594 15595 public boolean isOptionEnabled(int option) { 15596 return (mOptions & option) != 0; 15597 } 15598 15599 public void setOptionEnabled(int option) { 15600 mOptions |= option; 15601 } 15602 15603 public boolean onTitlePrinted() { 15604 final boolean printed = mTitlePrinted; 15605 mTitlePrinted = true; 15606 return printed; 15607 } 15608 15609 public boolean getTitlePrinted() { 15610 return mTitlePrinted; 15611 } 15612 15613 public void setTitlePrinted(boolean enabled) { 15614 mTitlePrinted = enabled; 15615 } 15616 15617 public SharedUserSetting getSharedUser() { 15618 return mSharedUser; 15619 } 15620 15621 public void setSharedUser(SharedUserSetting user) { 15622 mSharedUser = user; 15623 } 15624 } 15625 15626 @Override 15627 public void onShellCommand(FileDescriptor in, FileDescriptor out, 15628 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 15629 (new PackageManagerShellCommand(this)).exec( 15630 this, in, out, err, args, resultReceiver); 15631 } 15632 15633 @Override 15634 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 15635 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 15636 != PackageManager.PERMISSION_GRANTED) { 15637 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 15638 + Binder.getCallingPid() 15639 + ", uid=" + Binder.getCallingUid() 15640 + " without permission " 15641 + android.Manifest.permission.DUMP); 15642 return; 15643 } 15644 15645 DumpState dumpState = new DumpState(); 15646 boolean fullPreferred = false; 15647 boolean checkin = false; 15648 15649 String packageName = null; 15650 ArraySet<String> permissionNames = null; 15651 15652 int opti = 0; 15653 while (opti < args.length) { 15654 String opt = args[opti]; 15655 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 15656 break; 15657 } 15658 opti++; 15659 15660 if ("-a".equals(opt)) { 15661 // Right now we only know how to print all. 15662 } else if ("-h".equals(opt)) { 15663 pw.println("Package manager dump options:"); 15664 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 15665 pw.println(" --checkin: dump for a checkin"); 15666 pw.println(" -f: print details of intent filters"); 15667 pw.println(" -h: print this help"); 15668 pw.println(" cmd may be one of:"); 15669 pw.println(" l[ibraries]: list known shared libraries"); 15670 pw.println(" f[eatures]: list device features"); 15671 pw.println(" k[eysets]: print known keysets"); 15672 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 15673 pw.println(" perm[issions]: dump permissions"); 15674 pw.println(" permission [name ...]: dump declaration and use of given permission"); 15675 pw.println(" pref[erred]: print preferred package settings"); 15676 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 15677 pw.println(" prov[iders]: dump content providers"); 15678 pw.println(" p[ackages]: dump installed packages"); 15679 pw.println(" s[hared-users]: dump shared user IDs"); 15680 pw.println(" m[essages]: print collected runtime messages"); 15681 pw.println(" v[erifiers]: print package verifier info"); 15682 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 15683 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 15684 pw.println(" version: print database version info"); 15685 pw.println(" write: write current settings now"); 15686 pw.println(" installs: details about install sessions"); 15687 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 15688 pw.println(" <package.name>: info about given package"); 15689 return; 15690 } else if ("--checkin".equals(opt)) { 15691 checkin = true; 15692 } else if ("-f".equals(opt)) { 15693 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 15694 } else { 15695 pw.println("Unknown argument: " + opt + "; use -h for help"); 15696 } 15697 } 15698 15699 // Is the caller requesting to dump a particular piece of data? 15700 if (opti < args.length) { 15701 String cmd = args[opti]; 15702 opti++; 15703 // Is this a package name? 15704 if ("android".equals(cmd) || cmd.contains(".")) { 15705 packageName = cmd; 15706 // When dumping a single package, we always dump all of its 15707 // filter information since the amount of data will be reasonable. 15708 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 15709 } else if ("check-permission".equals(cmd)) { 15710 if (opti >= args.length) { 15711 pw.println("Error: check-permission missing permission argument"); 15712 return; 15713 } 15714 String perm = args[opti]; 15715 opti++; 15716 if (opti >= args.length) { 15717 pw.println("Error: check-permission missing package argument"); 15718 return; 15719 } 15720 String pkg = args[opti]; 15721 opti++; 15722 int user = UserHandle.getUserId(Binder.getCallingUid()); 15723 if (opti < args.length) { 15724 try { 15725 user = Integer.parseInt(args[opti]); 15726 } catch (NumberFormatException e) { 15727 pw.println("Error: check-permission user argument is not a number: " 15728 + args[opti]); 15729 return; 15730 } 15731 } 15732 pw.println(checkPermission(perm, pkg, user)); 15733 return; 15734 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 15735 dumpState.setDump(DumpState.DUMP_LIBS); 15736 } else if ("f".equals(cmd) || "features".equals(cmd)) { 15737 dumpState.setDump(DumpState.DUMP_FEATURES); 15738 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 15739 if (opti >= args.length) { 15740 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 15741 | DumpState.DUMP_SERVICE_RESOLVERS 15742 | DumpState.DUMP_RECEIVER_RESOLVERS 15743 | DumpState.DUMP_CONTENT_RESOLVERS); 15744 } else { 15745 while (opti < args.length) { 15746 String name = args[opti]; 15747 if ("a".equals(name) || "activity".equals(name)) { 15748 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 15749 } else if ("s".equals(name) || "service".equals(name)) { 15750 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 15751 } else if ("r".equals(name) || "receiver".equals(name)) { 15752 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 15753 } else if ("c".equals(name) || "content".equals(name)) { 15754 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 15755 } else { 15756 pw.println("Error: unknown resolver table type: " + name); 15757 return; 15758 } 15759 opti++; 15760 } 15761 } 15762 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 15763 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 15764 } else if ("permission".equals(cmd)) { 15765 if (opti >= args.length) { 15766 pw.println("Error: permission requires permission name"); 15767 return; 15768 } 15769 permissionNames = new ArraySet<>(); 15770 while (opti < args.length) { 15771 permissionNames.add(args[opti]); 15772 opti++; 15773 } 15774 dumpState.setDump(DumpState.DUMP_PERMISSIONS 15775 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 15776 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 15777 dumpState.setDump(DumpState.DUMP_PREFERRED); 15778 } else if ("preferred-xml".equals(cmd)) { 15779 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 15780 if (opti < args.length && "--full".equals(args[opti])) { 15781 fullPreferred = true; 15782 opti++; 15783 } 15784 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 15785 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 15786 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 15787 dumpState.setDump(DumpState.DUMP_PACKAGES); 15788 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 15789 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 15790 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 15791 dumpState.setDump(DumpState.DUMP_PROVIDERS); 15792 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 15793 dumpState.setDump(DumpState.DUMP_MESSAGES); 15794 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 15795 dumpState.setDump(DumpState.DUMP_VERIFIERS); 15796 } else if ("i".equals(cmd) || "ifv".equals(cmd) 15797 || "intent-filter-verifiers".equals(cmd)) { 15798 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 15799 } else if ("version".equals(cmd)) { 15800 dumpState.setDump(DumpState.DUMP_VERSION); 15801 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 15802 dumpState.setDump(DumpState.DUMP_KEYSETS); 15803 } else if ("installs".equals(cmd)) { 15804 dumpState.setDump(DumpState.DUMP_INSTALLS); 15805 } else if ("write".equals(cmd)) { 15806 synchronized (mPackages) { 15807 mSettings.writeLPr(); 15808 pw.println("Settings written."); 15809 return; 15810 } 15811 } 15812 } 15813 15814 if (checkin) { 15815 pw.println("vers,1"); 15816 } 15817 15818 // reader 15819 synchronized (mPackages) { 15820 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 15821 if (!checkin) { 15822 if (dumpState.onTitlePrinted()) 15823 pw.println(); 15824 pw.println("Database versions:"); 15825 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 15826 } 15827 } 15828 15829 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 15830 if (!checkin) { 15831 if (dumpState.onTitlePrinted()) 15832 pw.println(); 15833 pw.println("Verifiers:"); 15834 pw.print(" Required: "); 15835 pw.print(mRequiredVerifierPackage); 15836 pw.print(" (uid="); 15837 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 15838 UserHandle.USER_SYSTEM)); 15839 pw.println(")"); 15840 } else if (mRequiredVerifierPackage != null) { 15841 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 15842 pw.print(","); 15843 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 15844 UserHandle.USER_SYSTEM)); 15845 } 15846 } 15847 15848 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 15849 packageName == null) { 15850 if (mIntentFilterVerifierComponent != null) { 15851 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 15852 if (!checkin) { 15853 if (dumpState.onTitlePrinted()) 15854 pw.println(); 15855 pw.println("Intent Filter Verifier:"); 15856 pw.print(" Using: "); 15857 pw.print(verifierPackageName); 15858 pw.print(" (uid="); 15859 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 15860 UserHandle.USER_SYSTEM)); 15861 pw.println(")"); 15862 } else if (verifierPackageName != null) { 15863 pw.print("ifv,"); pw.print(verifierPackageName); 15864 pw.print(","); 15865 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 15866 UserHandle.USER_SYSTEM)); 15867 } 15868 } else { 15869 pw.println(); 15870 pw.println("No Intent Filter Verifier available!"); 15871 } 15872 } 15873 15874 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 15875 boolean printedHeader = false; 15876 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 15877 while (it.hasNext()) { 15878 String name = it.next(); 15879 SharedLibraryEntry ent = mSharedLibraries.get(name); 15880 if (!checkin) { 15881 if (!printedHeader) { 15882 if (dumpState.onTitlePrinted()) 15883 pw.println(); 15884 pw.println("Libraries:"); 15885 printedHeader = true; 15886 } 15887 pw.print(" "); 15888 } else { 15889 pw.print("lib,"); 15890 } 15891 pw.print(name); 15892 if (!checkin) { 15893 pw.print(" -> "); 15894 } 15895 if (ent.path != null) { 15896 if (!checkin) { 15897 pw.print("(jar) "); 15898 pw.print(ent.path); 15899 } else { 15900 pw.print(",jar,"); 15901 pw.print(ent.path); 15902 } 15903 } else { 15904 if (!checkin) { 15905 pw.print("(apk) "); 15906 pw.print(ent.apk); 15907 } else { 15908 pw.print(",apk,"); 15909 pw.print(ent.apk); 15910 } 15911 } 15912 pw.println(); 15913 } 15914 } 15915 15916 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 15917 if (dumpState.onTitlePrinted()) 15918 pw.println(); 15919 if (!checkin) { 15920 pw.println("Features:"); 15921 } 15922 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 15923 while (it.hasNext()) { 15924 String name = it.next(); 15925 if (!checkin) { 15926 pw.print(" "); 15927 } else { 15928 pw.print("feat,"); 15929 } 15930 pw.println(name); 15931 } 15932 } 15933 15934 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 15935 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 15936 : "Activity Resolver Table:", " ", packageName, 15937 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15938 dumpState.setTitlePrinted(true); 15939 } 15940 } 15941 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 15942 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 15943 : "Receiver Resolver Table:", " ", packageName, 15944 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15945 dumpState.setTitlePrinted(true); 15946 } 15947 } 15948 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 15949 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 15950 : "Service Resolver Table:", " ", packageName, 15951 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15952 dumpState.setTitlePrinted(true); 15953 } 15954 } 15955 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 15956 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 15957 : "Provider Resolver Table:", " ", packageName, 15958 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15959 dumpState.setTitlePrinted(true); 15960 } 15961 } 15962 15963 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 15964 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 15965 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 15966 int user = mSettings.mPreferredActivities.keyAt(i); 15967 if (pir.dump(pw, 15968 dumpState.getTitlePrinted() 15969 ? "\nPreferred Activities User " + user + ":" 15970 : "Preferred Activities User " + user + ":", " ", 15971 packageName, true, false)) { 15972 dumpState.setTitlePrinted(true); 15973 } 15974 } 15975 } 15976 15977 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 15978 pw.flush(); 15979 FileOutputStream fout = new FileOutputStream(fd); 15980 BufferedOutputStream str = new BufferedOutputStream(fout); 15981 XmlSerializer serializer = new FastXmlSerializer(); 15982 try { 15983 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 15984 serializer.startDocument(null, true); 15985 serializer.setFeature( 15986 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 15987 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 15988 serializer.endDocument(); 15989 serializer.flush(); 15990 } catch (IllegalArgumentException e) { 15991 pw.println("Failed writing: " + e); 15992 } catch (IllegalStateException e) { 15993 pw.println("Failed writing: " + e); 15994 } catch (IOException e) { 15995 pw.println("Failed writing: " + e); 15996 } 15997 } 15998 15999 if (!checkin 16000 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 16001 && packageName == null) { 16002 pw.println(); 16003 int count = mSettings.mPackages.size(); 16004 if (count == 0) { 16005 pw.println("No applications!"); 16006 pw.println(); 16007 } else { 16008 final String prefix = " "; 16009 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 16010 if (allPackageSettings.size() == 0) { 16011 pw.println("No domain preferred apps!"); 16012 pw.println(); 16013 } else { 16014 pw.println("App verification status:"); 16015 pw.println(); 16016 count = 0; 16017 for (PackageSetting ps : allPackageSettings) { 16018 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 16019 if (ivi == null || ivi.getPackageName() == null) continue; 16020 pw.println(prefix + "Package: " + ivi.getPackageName()); 16021 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 16022 pw.println(prefix + "Status: " + ivi.getStatusString()); 16023 pw.println(); 16024 count++; 16025 } 16026 if (count == 0) { 16027 pw.println(prefix + "No app verification established."); 16028 pw.println(); 16029 } 16030 for (int userId : sUserManager.getUserIds()) { 16031 pw.println("App linkages for user " + userId + ":"); 16032 pw.println(); 16033 count = 0; 16034 for (PackageSetting ps : allPackageSettings) { 16035 final long status = ps.getDomainVerificationStatusForUser(userId); 16036 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 16037 continue; 16038 } 16039 pw.println(prefix + "Package: " + ps.name); 16040 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 16041 String statusStr = IntentFilterVerificationInfo. 16042 getStatusStringFromValue(status); 16043 pw.println(prefix + "Status: " + statusStr); 16044 pw.println(); 16045 count++; 16046 } 16047 if (count == 0) { 16048 pw.println(prefix + "No configured app linkages."); 16049 pw.println(); 16050 } 16051 } 16052 } 16053 } 16054 } 16055 16056 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 16057 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 16058 if (packageName == null && permissionNames == null) { 16059 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 16060 if (iperm == 0) { 16061 if (dumpState.onTitlePrinted()) 16062 pw.println(); 16063 pw.println("AppOp Permissions:"); 16064 } 16065 pw.print(" AppOp Permission "); 16066 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 16067 pw.println(":"); 16068 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 16069 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 16070 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 16071 } 16072 } 16073 } 16074 } 16075 16076 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 16077 boolean printedSomething = false; 16078 for (PackageParser.Provider p : mProviders.mProviders.values()) { 16079 if (packageName != null && !packageName.equals(p.info.packageName)) { 16080 continue; 16081 } 16082 if (!printedSomething) { 16083 if (dumpState.onTitlePrinted()) 16084 pw.println(); 16085 pw.println("Registered ContentProviders:"); 16086 printedSomething = true; 16087 } 16088 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 16089 pw.print(" "); pw.println(p.toString()); 16090 } 16091 printedSomething = false; 16092 for (Map.Entry<String, PackageParser.Provider> entry : 16093 mProvidersByAuthority.entrySet()) { 16094 PackageParser.Provider p = entry.getValue(); 16095 if (packageName != null && !packageName.equals(p.info.packageName)) { 16096 continue; 16097 } 16098 if (!printedSomething) { 16099 if (dumpState.onTitlePrinted()) 16100 pw.println(); 16101 pw.println("ContentProvider Authorities:"); 16102 printedSomething = true; 16103 } 16104 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 16105 pw.print(" "); pw.println(p.toString()); 16106 if (p.info != null && p.info.applicationInfo != null) { 16107 final String appInfo = p.info.applicationInfo.toString(); 16108 pw.print(" applicationInfo="); pw.println(appInfo); 16109 } 16110 } 16111 } 16112 16113 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 16114 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 16115 } 16116 16117 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 16118 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 16119 } 16120 16121 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 16122 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 16123 } 16124 16125 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 16126 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 16127 } 16128 16129 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 16130 // XXX should handle packageName != null by dumping only install data that 16131 // the given package is involved with. 16132 if (dumpState.onTitlePrinted()) pw.println(); 16133 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 16134 } 16135 16136 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 16137 if (dumpState.onTitlePrinted()) pw.println(); 16138 mSettings.dumpReadMessagesLPr(pw, dumpState); 16139 16140 pw.println(); 16141 pw.println("Package warning messages:"); 16142 BufferedReader in = null; 16143 String line = null; 16144 try { 16145 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 16146 while ((line = in.readLine()) != null) { 16147 if (line.contains("ignored: updated version")) continue; 16148 pw.println(line); 16149 } 16150 } catch (IOException ignored) { 16151 } finally { 16152 IoUtils.closeQuietly(in); 16153 } 16154 } 16155 16156 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 16157 BufferedReader in = null; 16158 String line = null; 16159 try { 16160 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 16161 while ((line = in.readLine()) != null) { 16162 if (line.contains("ignored: updated version")) continue; 16163 pw.print("msg,"); 16164 pw.println(line); 16165 } 16166 } catch (IOException ignored) { 16167 } finally { 16168 IoUtils.closeQuietly(in); 16169 } 16170 } 16171 } 16172 } 16173 16174 private String dumpDomainString(String packageName) { 16175 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName); 16176 List<IntentFilter> filters = getAllIntentFilters(packageName); 16177 16178 ArraySet<String> result = new ArraySet<>(); 16179 if (iviList.size() > 0) { 16180 for (IntentFilterVerificationInfo ivi : iviList) { 16181 for (String host : ivi.getDomains()) { 16182 result.add(host); 16183 } 16184 } 16185 } 16186 if (filters != null && filters.size() > 0) { 16187 for (IntentFilter filter : filters) { 16188 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 16189 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 16190 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 16191 result.addAll(filter.getHostsList()); 16192 } 16193 } 16194 } 16195 16196 StringBuilder sb = new StringBuilder(result.size() * 16); 16197 for (String domain : result) { 16198 if (sb.length() > 0) sb.append(" "); 16199 sb.append(domain); 16200 } 16201 return sb.toString(); 16202 } 16203 16204 // ------- apps on sdcard specific code ------- 16205 static final boolean DEBUG_SD_INSTALL = false; 16206 16207 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 16208 16209 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 16210 16211 private boolean mMediaMounted = false; 16212 16213 static String getEncryptKey() { 16214 try { 16215 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 16216 SD_ENCRYPTION_KEYSTORE_NAME); 16217 if (sdEncKey == null) { 16218 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 16219 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 16220 if (sdEncKey == null) { 16221 Slog.e(TAG, "Failed to create encryption keys"); 16222 return null; 16223 } 16224 } 16225 return sdEncKey; 16226 } catch (NoSuchAlgorithmException nsae) { 16227 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 16228 return null; 16229 } catch (IOException ioe) { 16230 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 16231 return null; 16232 } 16233 } 16234 16235 /* 16236 * Update media status on PackageManager. 16237 */ 16238 @Override 16239 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 16240 int callingUid = Binder.getCallingUid(); 16241 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 16242 throw new SecurityException("Media status can only be updated by the system"); 16243 } 16244 // reader; this apparently protects mMediaMounted, but should probably 16245 // be a different lock in that case. 16246 synchronized (mPackages) { 16247 Log.i(TAG, "Updating external media status from " 16248 + (mMediaMounted ? "mounted" : "unmounted") + " to " 16249 + (mediaStatus ? "mounted" : "unmounted")); 16250 if (DEBUG_SD_INSTALL) 16251 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 16252 + ", mMediaMounted=" + mMediaMounted); 16253 if (mediaStatus == mMediaMounted) { 16254 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 16255 : 0, -1); 16256 mHandler.sendMessage(msg); 16257 return; 16258 } 16259 mMediaMounted = mediaStatus; 16260 } 16261 // Queue up an async operation since the package installation may take a 16262 // little while. 16263 mHandler.post(new Runnable() { 16264 public void run() { 16265 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 16266 } 16267 }); 16268 } 16269 16270 /** 16271 * Called by MountService when the initial ASECs to scan are available. 16272 * Should block until all the ASEC containers are finished being scanned. 16273 */ 16274 public void scanAvailableAsecs() { 16275 updateExternalMediaStatusInner(true, false, false); 16276 } 16277 16278 /* 16279 * Collect information of applications on external media, map them against 16280 * existing containers and update information based on current mount status. 16281 * Please note that we always have to report status if reportStatus has been 16282 * set to true especially when unloading packages. 16283 */ 16284 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 16285 boolean externalStorage) { 16286 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 16287 int[] uidArr = EmptyArray.INT; 16288 16289 final String[] list = PackageHelper.getSecureContainerList(); 16290 if (ArrayUtils.isEmpty(list)) { 16291 Log.i(TAG, "No secure containers found"); 16292 } else { 16293 // Process list of secure containers and categorize them 16294 // as active or stale based on their package internal state. 16295 16296 // reader 16297 synchronized (mPackages) { 16298 for (String cid : list) { 16299 // Leave stages untouched for now; installer service owns them 16300 if (PackageInstallerService.isStageName(cid)) continue; 16301 16302 if (DEBUG_SD_INSTALL) 16303 Log.i(TAG, "Processing container " + cid); 16304 String pkgName = getAsecPackageName(cid); 16305 if (pkgName == null) { 16306 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 16307 continue; 16308 } 16309 if (DEBUG_SD_INSTALL) 16310 Log.i(TAG, "Looking for pkg : " + pkgName); 16311 16312 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16313 if (ps == null) { 16314 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 16315 continue; 16316 } 16317 16318 /* 16319 * Skip packages that are not external if we're unmounting 16320 * external storage. 16321 */ 16322 if (externalStorage && !isMounted && !isExternal(ps)) { 16323 continue; 16324 } 16325 16326 final AsecInstallArgs args = new AsecInstallArgs(cid, 16327 getAppDexInstructionSets(ps), ps.isForwardLocked()); 16328 // The package status is changed only if the code path 16329 // matches between settings and the container id. 16330 if (ps.codePathString != null 16331 && ps.codePathString.startsWith(args.getCodePath())) { 16332 if (DEBUG_SD_INSTALL) { 16333 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 16334 + " at code path: " + ps.codePathString); 16335 } 16336 16337 // We do have a valid package installed on sdcard 16338 processCids.put(args, ps.codePathString); 16339 final int uid = ps.appId; 16340 if (uid != -1) { 16341 uidArr = ArrayUtils.appendInt(uidArr, uid); 16342 } 16343 } else { 16344 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 16345 + ps.codePathString); 16346 } 16347 } 16348 } 16349 16350 Arrays.sort(uidArr); 16351 } 16352 16353 // Process packages with valid entries. 16354 if (isMounted) { 16355 if (DEBUG_SD_INSTALL) 16356 Log.i(TAG, "Loading packages"); 16357 loadMediaPackages(processCids, uidArr, externalStorage); 16358 startCleaningPackages(); 16359 mInstallerService.onSecureContainersAvailable(); 16360 } else { 16361 if (DEBUG_SD_INSTALL) 16362 Log.i(TAG, "Unloading packages"); 16363 unloadMediaPackages(processCids, uidArr, reportStatus); 16364 } 16365 } 16366 16367 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 16368 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 16369 final int size = infos.size(); 16370 final String[] packageNames = new String[size]; 16371 final int[] packageUids = new int[size]; 16372 for (int i = 0; i < size; i++) { 16373 final ApplicationInfo info = infos.get(i); 16374 packageNames[i] = info.packageName; 16375 packageUids[i] = info.uid; 16376 } 16377 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 16378 finishedReceiver); 16379 } 16380 16381 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 16382 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 16383 sendResourcesChangedBroadcast(mediaStatus, replacing, 16384 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 16385 } 16386 16387 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 16388 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 16389 int size = pkgList.length; 16390 if (size > 0) { 16391 // Send broadcasts here 16392 Bundle extras = new Bundle(); 16393 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 16394 if (uidArr != null) { 16395 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 16396 } 16397 if (replacing) { 16398 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 16399 } 16400 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 16401 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 16402 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 16403 } 16404 } 16405 16406 /* 16407 * Look at potentially valid container ids from processCids If package 16408 * information doesn't match the one on record or package scanning fails, 16409 * the cid is added to list of removeCids. We currently don't delete stale 16410 * containers. 16411 */ 16412 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 16413 boolean externalStorage) { 16414 ArrayList<String> pkgList = new ArrayList<String>(); 16415 Set<AsecInstallArgs> keys = processCids.keySet(); 16416 16417 for (AsecInstallArgs args : keys) { 16418 String codePath = processCids.get(args); 16419 if (DEBUG_SD_INSTALL) 16420 Log.i(TAG, "Loading container : " + args.cid); 16421 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 16422 try { 16423 // Make sure there are no container errors first. 16424 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 16425 Slog.e(TAG, "Failed to mount cid : " + args.cid 16426 + " when installing from sdcard"); 16427 continue; 16428 } 16429 // Check code path here. 16430 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 16431 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 16432 + " does not match one in settings " + codePath); 16433 continue; 16434 } 16435 // Parse package 16436 int parseFlags = mDefParseFlags; 16437 if (args.isExternalAsec()) { 16438 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 16439 } 16440 if (args.isFwdLocked()) { 16441 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 16442 } 16443 16444 synchronized (mInstallLock) { 16445 PackageParser.Package pkg = null; 16446 try { 16447 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null); 16448 } catch (PackageManagerException e) { 16449 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 16450 } 16451 // Scan the package 16452 if (pkg != null) { 16453 /* 16454 * TODO why is the lock being held? doPostInstall is 16455 * called in other places without the lock. This needs 16456 * to be straightened out. 16457 */ 16458 // writer 16459 synchronized (mPackages) { 16460 retCode = PackageManager.INSTALL_SUCCEEDED; 16461 pkgList.add(pkg.packageName); 16462 // Post process args 16463 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 16464 pkg.applicationInfo.uid); 16465 } 16466 } else { 16467 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 16468 } 16469 } 16470 16471 } finally { 16472 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 16473 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 16474 } 16475 } 16476 } 16477 // writer 16478 synchronized (mPackages) { 16479 // If the platform SDK has changed since the last time we booted, 16480 // we need to re-grant app permission to catch any new ones that 16481 // appear. This is really a hack, and means that apps can in some 16482 // cases get permissions that the user didn't initially explicitly 16483 // allow... it would be nice to have some better way to handle 16484 // this situation. 16485 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 16486 : mSettings.getInternalVersion(); 16487 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 16488 : StorageManager.UUID_PRIVATE_INTERNAL; 16489 16490 int updateFlags = UPDATE_PERMISSIONS_ALL; 16491 if (ver.sdkVersion != mSdkVersion) { 16492 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 16493 + mSdkVersion + "; regranting permissions for external"); 16494 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 16495 } 16496 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 16497 16498 // Yay, everything is now upgraded 16499 ver.forceCurrent(); 16500 16501 // can downgrade to reader 16502 // Persist settings 16503 mSettings.writeLPr(); 16504 } 16505 // Send a broadcast to let everyone know we are done processing 16506 if (pkgList.size() > 0) { 16507 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 16508 } 16509 } 16510 16511 /* 16512 * Utility method to unload a list of specified containers 16513 */ 16514 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 16515 // Just unmount all valid containers. 16516 for (AsecInstallArgs arg : cidArgs) { 16517 synchronized (mInstallLock) { 16518 arg.doPostDeleteLI(false); 16519 } 16520 } 16521 } 16522 16523 /* 16524 * Unload packages mounted on external media. This involves deleting package 16525 * data from internal structures, sending broadcasts about diabled packages, 16526 * gc'ing to free up references, unmounting all secure containers 16527 * corresponding to packages on external media, and posting a 16528 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 16529 * that we always have to post this message if status has been requested no 16530 * matter what. 16531 */ 16532 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 16533 final boolean reportStatus) { 16534 if (DEBUG_SD_INSTALL) 16535 Log.i(TAG, "unloading media packages"); 16536 ArrayList<String> pkgList = new ArrayList<String>(); 16537 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 16538 final Set<AsecInstallArgs> keys = processCids.keySet(); 16539 for (AsecInstallArgs args : keys) { 16540 String pkgName = args.getPackageName(); 16541 if (DEBUG_SD_INSTALL) 16542 Log.i(TAG, "Trying to unload pkg : " + pkgName); 16543 // Delete package internally 16544 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 16545 synchronized (mInstallLock) { 16546 boolean res = deletePackageLI(pkgName, null, false, null, null, 16547 PackageManager.DELETE_KEEP_DATA, outInfo, false); 16548 if (res) { 16549 pkgList.add(pkgName); 16550 } else { 16551 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 16552 failedList.add(args); 16553 } 16554 } 16555 } 16556 16557 // reader 16558 synchronized (mPackages) { 16559 // We didn't update the settings after removing each package; 16560 // write them now for all packages. 16561 mSettings.writeLPr(); 16562 } 16563 16564 // We have to absolutely send UPDATED_MEDIA_STATUS only 16565 // after confirming that all the receivers processed the ordered 16566 // broadcast when packages get disabled, force a gc to clean things up. 16567 // and unload all the containers. 16568 if (pkgList.size() > 0) { 16569 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 16570 new IIntentReceiver.Stub() { 16571 public void performReceive(Intent intent, int resultCode, String data, 16572 Bundle extras, boolean ordered, boolean sticky, 16573 int sendingUser) throws RemoteException { 16574 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 16575 reportStatus ? 1 : 0, 1, keys); 16576 mHandler.sendMessage(msg); 16577 } 16578 }); 16579 } else { 16580 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 16581 keys); 16582 mHandler.sendMessage(msg); 16583 } 16584 } 16585 16586 private void loadPrivatePackages(final VolumeInfo vol) { 16587 mHandler.post(new Runnable() { 16588 @Override 16589 public void run() { 16590 loadPrivatePackagesInner(vol); 16591 } 16592 }); 16593 } 16594 16595 private void loadPrivatePackagesInner(VolumeInfo vol) { 16596 final String volumeUuid = vol.fsUuid; 16597 if (TextUtils.isEmpty(volumeUuid)) { 16598 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 16599 return; 16600 } 16601 16602 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 16603 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 16604 16605 final VersionInfo ver; 16606 final List<PackageSetting> packages; 16607 synchronized (mPackages) { 16608 ver = mSettings.findOrCreateVersion(volumeUuid); 16609 packages = mSettings.getVolumePackagesLPr(volumeUuid); 16610 } 16611 16612 // TODO: introduce a new concept similar to "frozen" to prevent these 16613 // apps from being launched until after data has been fully reconciled 16614 for (PackageSetting ps : packages) { 16615 synchronized (mInstallLock) { 16616 final PackageParser.Package pkg; 16617 try { 16618 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 16619 loaded.add(pkg.applicationInfo); 16620 16621 } catch (PackageManagerException e) { 16622 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 16623 } 16624 16625 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 16626 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 16627 } 16628 } 16629 } 16630 16631 // Reconcile app data for all started/unlocked users 16632 final UserManager um = mContext.getSystemService(UserManager.class); 16633 for (UserInfo user : um.getUsers()) { 16634 if (um.isUserUnlocked(user.id)) { 16635 reconcileAppsData(volumeUuid, user.id, 16636 Installer.FLAG_DE_STORAGE | Installer.FLAG_CE_STORAGE); 16637 } else if (um.isUserRunning(user.id)) { 16638 reconcileAppsData(volumeUuid, user.id, Installer.FLAG_DE_STORAGE); 16639 } else { 16640 continue; 16641 } 16642 } 16643 16644 synchronized (mPackages) { 16645 int updateFlags = UPDATE_PERMISSIONS_ALL; 16646 if (ver.sdkVersion != mSdkVersion) { 16647 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 16648 + mSdkVersion + "; regranting permissions for " + volumeUuid); 16649 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 16650 } 16651 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 16652 16653 // Yay, everything is now upgraded 16654 ver.forceCurrent(); 16655 16656 mSettings.writeLPr(); 16657 } 16658 16659 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 16660 sendResourcesChangedBroadcast(true, false, loaded, null); 16661 } 16662 16663 private void unloadPrivatePackages(final VolumeInfo vol) { 16664 mHandler.post(new Runnable() { 16665 @Override 16666 public void run() { 16667 unloadPrivatePackagesInner(vol); 16668 } 16669 }); 16670 } 16671 16672 private void unloadPrivatePackagesInner(VolumeInfo vol) { 16673 final String volumeUuid = vol.fsUuid; 16674 if (TextUtils.isEmpty(volumeUuid)) { 16675 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 16676 return; 16677 } 16678 16679 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 16680 synchronized (mInstallLock) { 16681 synchronized (mPackages) { 16682 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 16683 for (PackageSetting ps : packages) { 16684 if (ps.pkg == null) continue; 16685 16686 final ApplicationInfo info = ps.pkg.applicationInfo; 16687 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 16688 if (deletePackageLI(ps.name, null, false, null, null, 16689 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 16690 unloaded.add(info); 16691 } else { 16692 Slog.w(TAG, "Failed to unload " + ps.codePath); 16693 } 16694 } 16695 16696 mSettings.writeLPr(); 16697 } 16698 } 16699 16700 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 16701 sendResourcesChangedBroadcast(false, false, unloaded, null); 16702 } 16703 16704 /** 16705 * Examine all users present on given mounted volume, and destroy data 16706 * belonging to users that are no longer valid, or whose user ID has been 16707 * recycled. 16708 */ 16709 private void reconcileUsers(String volumeUuid) { 16710 final File[] files = FileUtils 16711 .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid)); 16712 for (File file : files) { 16713 if (!file.isDirectory()) continue; 16714 16715 final int userId; 16716 final UserInfo info; 16717 try { 16718 userId = Integer.parseInt(file.getName()); 16719 info = sUserManager.getUserInfo(userId); 16720 } catch (NumberFormatException e) { 16721 Slog.w(TAG, "Invalid user directory " + file); 16722 continue; 16723 } 16724 16725 boolean destroyUser = false; 16726 if (info == null) { 16727 logCriticalInfo(Log.WARN, "Destroying user directory " + file 16728 + " because no matching user was found"); 16729 destroyUser = true; 16730 } else { 16731 try { 16732 UserManagerService.enforceSerialNumber(file, info.serialNumber); 16733 } catch (IOException e) { 16734 logCriticalInfo(Log.WARN, "Destroying user directory " + file 16735 + " because we failed to enforce serial number: " + e); 16736 destroyUser = true; 16737 } 16738 } 16739 16740 if (destroyUser) { 16741 synchronized (mInstallLock) { 16742 try { 16743 mInstaller.removeUserDataDirs(volumeUuid, userId); 16744 } catch (InstallerException e) { 16745 Slog.w(TAG, "Failed to clean up user dirs", e); 16746 } 16747 } 16748 } 16749 } 16750 16751 final StorageManager sm = mContext.getSystemService(StorageManager.class); 16752 final UserManager um = mContext.getSystemService(UserManager.class); 16753 for (UserInfo user : um.getUsers()) { 16754 final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id); 16755 if (userDir.exists()) continue; 16756 16757 try { 16758 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, user.isEphemeral()); 16759 UserManagerService.enforceSerialNumber(userDir, user.serialNumber); 16760 } catch (IOException e) { 16761 Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e); 16762 } 16763 } 16764 } 16765 16766 private void assertPackageKnown(String volumeUuid, String packageName) 16767 throws PackageManagerException { 16768 synchronized (mPackages) { 16769 final PackageSetting ps = mSettings.mPackages.get(packageName); 16770 if (ps == null) { 16771 throw new PackageManagerException("Package " + packageName + " is unknown"); 16772 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 16773 throw new PackageManagerException( 16774 "Package " + packageName + " found on unknown volume " + volumeUuid 16775 + "; expected volume " + ps.volumeUuid); 16776 } 16777 } 16778 } 16779 16780 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 16781 throws PackageManagerException { 16782 synchronized (mPackages) { 16783 final PackageSetting ps = mSettings.mPackages.get(packageName); 16784 if (ps == null) { 16785 throw new PackageManagerException("Package " + packageName + " is unknown"); 16786 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 16787 throw new PackageManagerException( 16788 "Package " + packageName + " found on unknown volume " + volumeUuid 16789 + "; expected volume " + ps.volumeUuid); 16790 } else if (!ps.getInstalled(userId)) { 16791 throw new PackageManagerException( 16792 "Package " + packageName + " not installed for user " + userId); 16793 } 16794 } 16795 } 16796 16797 /** 16798 * Examine all apps present on given mounted volume, and destroy apps that 16799 * aren't expected, either due to uninstallation or reinstallation on 16800 * another volume. 16801 */ 16802 private void reconcileApps(String volumeUuid) { 16803 final File[] files = FileUtils 16804 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 16805 for (File file : files) { 16806 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 16807 && !PackageInstallerService.isStageName(file.getName()); 16808 if (!isPackage) { 16809 // Ignore entries which are not packages 16810 continue; 16811 } 16812 16813 try { 16814 final PackageLite pkg = PackageParser.parsePackageLite(file, 16815 PackageParser.PARSE_MUST_BE_APK); 16816 assertPackageKnown(volumeUuid, pkg.packageName); 16817 16818 } catch (PackageParserException | PackageManagerException e) { 16819 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 16820 synchronized (mInstallLock) { 16821 removeCodePathLI(file); 16822 } 16823 } 16824 } 16825 } 16826 16827 /** 16828 * Reconcile all app data for the given user. 16829 * <p> 16830 * Verifies that directories exist and that ownership and labeling is 16831 * correct for all installed apps on all mounted volumes. 16832 */ 16833 void reconcileAppsData(int userId, @StorageFlags int flags) { 16834 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16835 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 16836 final String volumeUuid = vol.getFsUuid(); 16837 reconcileAppsData(volumeUuid, userId, flags); 16838 } 16839 } 16840 16841 /** 16842 * Reconcile all app data on given mounted volume. 16843 * <p> 16844 * Destroys app data that isn't expected, either due to uninstallation or 16845 * reinstallation on another volume. 16846 * <p> 16847 * Verifies that directories exist and that ownership and labeling is 16848 * correct for all installed apps. 16849 */ 16850 private void reconcileAppsData(String volumeUuid, int userId, @StorageFlags int flags) { 16851 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 16852 + Integer.toHexString(flags)); 16853 16854 final File ceDir = Environment.getDataUserCredentialEncryptedDirectory(volumeUuid, userId); 16855 final File deDir = Environment.getDataUserDeviceEncryptedDirectory(volumeUuid, userId); 16856 16857 boolean restoreconNeeded = false; 16858 16859 // First look for stale data that doesn't belong, and check if things 16860 // have changed since we did our last restorecon 16861 if ((flags & Installer.FLAG_CE_STORAGE) != 0) { 16862 if (!isUserKeyUnlocked(userId)) { 16863 throw new RuntimeException( 16864 "Yikes, someone asked us to reconcile CE storage while " + userId 16865 + " was still locked; this would have caused massive data loss!"); 16866 } 16867 16868 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 16869 16870 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 16871 for (File file : files) { 16872 final String packageName = file.getName(); 16873 try { 16874 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 16875 } catch (PackageManagerException e) { 16876 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 16877 synchronized (mInstallLock) { 16878 destroyAppDataLI(volumeUuid, packageName, userId, 16879 Installer.FLAG_CE_STORAGE); 16880 } 16881 } 16882 } 16883 } 16884 if ((flags & Installer.FLAG_DE_STORAGE) != 0) { 16885 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 16886 16887 final File[] files = FileUtils.listFilesOrEmpty(deDir); 16888 for (File file : files) { 16889 final String packageName = file.getName(); 16890 try { 16891 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 16892 } catch (PackageManagerException e) { 16893 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 16894 synchronized (mInstallLock) { 16895 destroyAppDataLI(volumeUuid, packageName, userId, 16896 Installer.FLAG_DE_STORAGE); 16897 } 16898 } 16899 } 16900 } 16901 16902 // Ensure that data directories are ready to roll for all packages 16903 // installed for this volume and user 16904 final List<PackageSetting> packages; 16905 synchronized (mPackages) { 16906 packages = mSettings.getVolumePackagesLPr(volumeUuid); 16907 } 16908 int preparedCount = 0; 16909 for (PackageSetting ps : packages) { 16910 final String packageName = ps.name; 16911 if (ps.pkg == null) { 16912 Slog.w(TAG, "Odd, missing scanned package " + packageName); 16913 // TODO: might be due to legacy ASEC apps; we should circle back 16914 // and reconcile again once they're scanned 16915 continue; 16916 } 16917 16918 if (ps.getInstalled(userId)) { 16919 prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded); 16920 preparedCount++; 16921 } 16922 } 16923 16924 if (restoreconNeeded) { 16925 if ((flags & Installer.FLAG_CE_STORAGE) != 0) { 16926 SELinuxMMAC.setRestoreconDone(ceDir); 16927 } 16928 if ((flags & Installer.FLAG_DE_STORAGE) != 0) { 16929 SELinuxMMAC.setRestoreconDone(deDir); 16930 } 16931 } 16932 16933 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 16934 + " packages; restoreconNeeded was " + restoreconNeeded); 16935 } 16936 16937 /** 16938 * Prepare app data for the given app just after it was installed or 16939 * upgraded. This method carefully only touches users that it's installed 16940 * for, and it forces a restorecon to handle any seinfo changes. 16941 * <p> 16942 * Verifies that directories exist and that ownership and labeling is 16943 * correct for all installed apps. If there is an ownership mismatch, it 16944 * will try recovering system apps by wiping data; third-party app data is 16945 * left intact. 16946 */ 16947 private void prepareAppDataAfterInstall(PackageParser.Package pkg) { 16948 final PackageSetting ps; 16949 synchronized (mPackages) { 16950 ps = mSettings.mPackages.get(pkg.packageName); 16951 } 16952 16953 final UserManager um = mContext.getSystemService(UserManager.class); 16954 for (UserInfo user : um.getUsers()) { 16955 final int flags; 16956 if (um.isUserUnlocked(user.id)) { 16957 flags = Installer.FLAG_DE_STORAGE | Installer.FLAG_CE_STORAGE; 16958 } else if (um.isUserRunning(user.id)) { 16959 flags = Installer.FLAG_DE_STORAGE; 16960 } else { 16961 continue; 16962 } 16963 16964 if (ps.getInstalled(user.id)) { 16965 // Whenever an app changes, force a restorecon of its data 16966 // TODO: when user data is locked, mark that we're still dirty 16967 prepareAppData(pkg.volumeUuid, user.id, flags, pkg, true); 16968 } 16969 } 16970 } 16971 16972 /** 16973 * Prepare app data for the given app. 16974 * <p> 16975 * Verifies that directories exist and that ownership and labeling is 16976 * correct for all installed apps. If there is an ownership mismatch, this 16977 * will try recovering system apps by wiping data; third-party app data is 16978 * left intact. 16979 */ 16980 private void prepareAppData(String volumeUuid, int userId, @StorageFlags int flags, 16981 PackageParser.Package pkg, boolean restoreconNeeded) { 16982 if (DEBUG_APP_DATA) { 16983 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 16984 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 16985 } 16986 16987 final String packageName = pkg.packageName; 16988 final ApplicationInfo app = pkg.applicationInfo; 16989 final int appId = UserHandle.getAppId(app.uid); 16990 16991 Preconditions.checkNotNull(app.seinfo); 16992 16993 synchronized (mInstallLock) { 16994 try { 16995 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 16996 appId, app.seinfo, app.targetSdkVersion); 16997 } catch (InstallerException e) { 16998 if (app.isSystemApp()) { 16999 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 17000 + ", but trying to recover: " + e); 17001 destroyAppDataLI(volumeUuid, packageName, userId, flags); 17002 try { 17003 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 17004 appId, app.seinfo, app.targetSdkVersion); 17005 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 17006 } catch (InstallerException e2) { 17007 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 17008 } 17009 } else { 17010 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 17011 } 17012 } 17013 17014 if (restoreconNeeded) { 17015 restoreconAppDataLI(volumeUuid, packageName, userId, flags, appId, app.seinfo); 17016 } 17017 17018 if ((flags & Installer.FLAG_CE_STORAGE) != 0) { 17019 // Create a native library symlink only if we have native libraries 17020 // and if the native libraries are 32 bit libraries. We do not provide 17021 // this symlink for 64 bit libraries. 17022 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 17023 final String nativeLibPath = app.nativeLibraryDir; 17024 try { 17025 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 17026 nativeLibPath, userId); 17027 } catch (InstallerException e) { 17028 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 17029 } 17030 } 17031 } 17032 } 17033 } 17034 17035 private void unfreezePackage(String packageName) { 17036 synchronized (mPackages) { 17037 final PackageSetting ps = mSettings.mPackages.get(packageName); 17038 if (ps != null) { 17039 ps.frozen = false; 17040 } 17041 } 17042 } 17043 17044 @Override 17045 public int movePackage(final String packageName, final String volumeUuid) { 17046 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 17047 17048 final int moveId = mNextMoveId.getAndIncrement(); 17049 mHandler.post(new Runnable() { 17050 @Override 17051 public void run() { 17052 try { 17053 movePackageInternal(packageName, volumeUuid, moveId); 17054 } catch (PackageManagerException e) { 17055 Slog.w(TAG, "Failed to move " + packageName, e); 17056 mMoveCallbacks.notifyStatusChanged(moveId, 17057 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 17058 } 17059 } 17060 }); 17061 return moveId; 17062 } 17063 17064 private void movePackageInternal(final String packageName, final String volumeUuid, 17065 final int moveId) throws PackageManagerException { 17066 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 17067 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17068 final PackageManager pm = mContext.getPackageManager(); 17069 17070 final boolean currentAsec; 17071 final String currentVolumeUuid; 17072 final File codeFile; 17073 final String installerPackageName; 17074 final String packageAbiOverride; 17075 final int appId; 17076 final String seinfo; 17077 final String label; 17078 final int targetSdkVersion; 17079 17080 // reader 17081 synchronized (mPackages) { 17082 final PackageParser.Package pkg = mPackages.get(packageName); 17083 final PackageSetting ps = mSettings.mPackages.get(packageName); 17084 if (pkg == null || ps == null) { 17085 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 17086 } 17087 17088 if (pkg.applicationInfo.isSystemApp()) { 17089 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 17090 "Cannot move system application"); 17091 } 17092 17093 if (pkg.applicationInfo.isExternalAsec()) { 17094 currentAsec = true; 17095 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 17096 } else if (pkg.applicationInfo.isForwardLocked()) { 17097 currentAsec = true; 17098 currentVolumeUuid = "forward_locked"; 17099 } else { 17100 currentAsec = false; 17101 currentVolumeUuid = ps.volumeUuid; 17102 17103 final File probe = new File(pkg.codePath); 17104 final File probeOat = new File(probe, "oat"); 17105 if (!probe.isDirectory() || !probeOat.isDirectory()) { 17106 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 17107 "Move only supported for modern cluster style installs"); 17108 } 17109 } 17110 17111 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 17112 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 17113 "Package already moved to " + volumeUuid); 17114 } 17115 17116 if (ps.frozen) { 17117 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 17118 "Failed to move already frozen package"); 17119 } 17120 ps.frozen = true; 17121 17122 codeFile = new File(pkg.codePath); 17123 installerPackageName = ps.installerPackageName; 17124 packageAbiOverride = ps.cpuAbiOverrideString; 17125 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 17126 seinfo = pkg.applicationInfo.seinfo; 17127 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 17128 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 17129 } 17130 17131 // Now that we're guarded by frozen state, kill app during move 17132 final long token = Binder.clearCallingIdentity(); 17133 try { 17134 killApplication(packageName, appId, "move pkg"); 17135 } finally { 17136 Binder.restoreCallingIdentity(token); 17137 } 17138 17139 final Bundle extras = new Bundle(); 17140 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 17141 extras.putString(Intent.EXTRA_TITLE, label); 17142 mMoveCallbacks.notifyCreated(moveId, extras); 17143 17144 int installFlags; 17145 final boolean moveCompleteApp; 17146 final File measurePath; 17147 17148 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 17149 installFlags = INSTALL_INTERNAL; 17150 moveCompleteApp = !currentAsec; 17151 measurePath = Environment.getDataAppDirectory(volumeUuid); 17152 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 17153 installFlags = INSTALL_EXTERNAL; 17154 moveCompleteApp = false; 17155 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 17156 } else { 17157 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 17158 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 17159 || !volume.isMountedWritable()) { 17160 unfreezePackage(packageName); 17161 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 17162 "Move location not mounted private volume"); 17163 } 17164 17165 Preconditions.checkState(!currentAsec); 17166 17167 installFlags = INSTALL_INTERNAL; 17168 moveCompleteApp = true; 17169 measurePath = Environment.getDataAppDirectory(volumeUuid); 17170 } 17171 17172 final PackageStats stats = new PackageStats(null, -1); 17173 synchronized (mInstaller) { 17174 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 17175 unfreezePackage(packageName); 17176 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 17177 "Failed to measure package size"); 17178 } 17179 } 17180 17181 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 17182 + stats.dataSize); 17183 17184 final long startFreeBytes = measurePath.getFreeSpace(); 17185 final long sizeBytes; 17186 if (moveCompleteApp) { 17187 sizeBytes = stats.codeSize + stats.dataSize; 17188 } else { 17189 sizeBytes = stats.codeSize; 17190 } 17191 17192 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 17193 unfreezePackage(packageName); 17194 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 17195 "Not enough free space to move"); 17196 } 17197 17198 mMoveCallbacks.notifyStatusChanged(moveId, 10); 17199 17200 final CountDownLatch installedLatch = new CountDownLatch(1); 17201 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 17202 @Override 17203 public void onUserActionRequired(Intent intent) throws RemoteException { 17204 throw new IllegalStateException(); 17205 } 17206 17207 @Override 17208 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 17209 Bundle extras) throws RemoteException { 17210 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 17211 + PackageManager.installStatusToString(returnCode, msg)); 17212 17213 installedLatch.countDown(); 17214 17215 // Regardless of success or failure of the move operation, 17216 // always unfreeze the package 17217 unfreezePackage(packageName); 17218 17219 final int status = PackageManager.installStatusToPublicStatus(returnCode); 17220 switch (status) { 17221 case PackageInstaller.STATUS_SUCCESS: 17222 mMoveCallbacks.notifyStatusChanged(moveId, 17223 PackageManager.MOVE_SUCCEEDED); 17224 break; 17225 case PackageInstaller.STATUS_FAILURE_STORAGE: 17226 mMoveCallbacks.notifyStatusChanged(moveId, 17227 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 17228 break; 17229 default: 17230 mMoveCallbacks.notifyStatusChanged(moveId, 17231 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 17232 break; 17233 } 17234 } 17235 }; 17236 17237 final MoveInfo move; 17238 if (moveCompleteApp) { 17239 // Kick off a thread to report progress estimates 17240 new Thread() { 17241 @Override 17242 public void run() { 17243 while (true) { 17244 try { 17245 if (installedLatch.await(1, TimeUnit.SECONDS)) { 17246 break; 17247 } 17248 } catch (InterruptedException ignored) { 17249 } 17250 17251 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 17252 final int progress = 10 + (int) MathUtils.constrain( 17253 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 17254 mMoveCallbacks.notifyStatusChanged(moveId, progress); 17255 } 17256 } 17257 }.start(); 17258 17259 final String dataAppName = codeFile.getName(); 17260 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 17261 dataAppName, appId, seinfo, targetSdkVersion); 17262 } else { 17263 move = null; 17264 } 17265 17266 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 17267 17268 final Message msg = mHandler.obtainMessage(INIT_COPY); 17269 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 17270 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 17271 installerPackageName, volumeUuid, null, user, packageAbiOverride, null); 17272 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 17273 msg.obj = params; 17274 17275 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 17276 System.identityHashCode(msg.obj)); 17277 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 17278 System.identityHashCode(msg.obj)); 17279 17280 mHandler.sendMessage(msg); 17281 } 17282 17283 @Override 17284 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 17285 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 17286 17287 final int realMoveId = mNextMoveId.getAndIncrement(); 17288 final Bundle extras = new Bundle(); 17289 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 17290 mMoveCallbacks.notifyCreated(realMoveId, extras); 17291 17292 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 17293 @Override 17294 public void onCreated(int moveId, Bundle extras) { 17295 // Ignored 17296 } 17297 17298 @Override 17299 public void onStatusChanged(int moveId, int status, long estMillis) { 17300 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 17301 } 17302 }; 17303 17304 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17305 storage.setPrimaryStorageUuid(volumeUuid, callback); 17306 return realMoveId; 17307 } 17308 17309 @Override 17310 public int getMoveStatus(int moveId) { 17311 mContext.enforceCallingOrSelfPermission( 17312 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 17313 return mMoveCallbacks.mLastStatus.get(moveId); 17314 } 17315 17316 @Override 17317 public void registerMoveCallback(IPackageMoveObserver callback) { 17318 mContext.enforceCallingOrSelfPermission( 17319 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 17320 mMoveCallbacks.register(callback); 17321 } 17322 17323 @Override 17324 public void unregisterMoveCallback(IPackageMoveObserver callback) { 17325 mContext.enforceCallingOrSelfPermission( 17326 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 17327 mMoveCallbacks.unregister(callback); 17328 } 17329 17330 @Override 17331 public boolean setInstallLocation(int loc) { 17332 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 17333 null); 17334 if (getInstallLocation() == loc) { 17335 return true; 17336 } 17337 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 17338 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 17339 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 17340 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 17341 return true; 17342 } 17343 return false; 17344 } 17345 17346 @Override 17347 public int getInstallLocation() { 17348 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 17349 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 17350 PackageHelper.APP_INSTALL_AUTO); 17351 } 17352 17353 /** Called by UserManagerService */ 17354 void cleanUpUser(UserManagerService userManager, int userHandle) { 17355 synchronized (mPackages) { 17356 mDirtyUsers.remove(userHandle); 17357 mUserNeedsBadging.delete(userHandle); 17358 mSettings.removeUserLPw(userHandle); 17359 mPendingBroadcasts.remove(userHandle); 17360 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 17361 } 17362 synchronized (mInstallLock) { 17363 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17364 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 17365 final String volumeUuid = vol.getFsUuid(); 17366 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 17367 try { 17368 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 17369 } catch (InstallerException e) { 17370 Slog.w(TAG, "Failed to remove user data", e); 17371 } 17372 } 17373 synchronized (mPackages) { 17374 removeUnusedPackagesLILPw(userManager, userHandle); 17375 } 17376 } 17377 } 17378 17379 /** 17380 * We're removing userHandle and would like to remove any downloaded packages 17381 * that are no longer in use by any other user. 17382 * @param userHandle the user being removed 17383 */ 17384 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 17385 final boolean DEBUG_CLEAN_APKS = false; 17386 int [] users = userManager.getUserIds(); 17387 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 17388 while (psit.hasNext()) { 17389 PackageSetting ps = psit.next(); 17390 if (ps.pkg == null) { 17391 continue; 17392 } 17393 final String packageName = ps.pkg.packageName; 17394 // Skip over if system app 17395 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 17396 continue; 17397 } 17398 if (DEBUG_CLEAN_APKS) { 17399 Slog.i(TAG, "Checking package " + packageName); 17400 } 17401 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 17402 if (keep) { 17403 if (DEBUG_CLEAN_APKS) { 17404 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 17405 } 17406 } else { 17407 for (int i = 0; i < users.length; i++) { 17408 if (users[i] != userHandle && ps.getInstalled(users[i])) { 17409 keep = true; 17410 if (DEBUG_CLEAN_APKS) { 17411 Slog.i(TAG, " Keeping package " + packageName + " for user " 17412 + users[i]); 17413 } 17414 break; 17415 } 17416 } 17417 } 17418 if (!keep) { 17419 if (DEBUG_CLEAN_APKS) { 17420 Slog.i(TAG, " Removing package " + packageName); 17421 } 17422 mHandler.post(new Runnable() { 17423 public void run() { 17424 deletePackageX(packageName, userHandle, 0); 17425 } //end run 17426 }); 17427 } 17428 } 17429 } 17430 17431 /** Called by UserManagerService */ 17432 void createNewUser(int userHandle) { 17433 synchronized (mInstallLock) { 17434 try { 17435 mInstaller.createUserConfig(userHandle); 17436 } catch (InstallerException e) { 17437 Slog.w(TAG, "Failed to create user config", e); 17438 } 17439 mSettings.createNewUserLI(this, mInstaller, userHandle); 17440 } 17441 synchronized (mPackages) { 17442 applyFactoryDefaultBrowserLPw(userHandle); 17443 primeDomainVerificationsLPw(userHandle); 17444 } 17445 } 17446 17447 void newUserCreated(final int userHandle) { 17448 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 17449 // If permission review for legacy apps is required, we represent 17450 // dagerous permissions for such apps as always granted runtime 17451 // permissions to keep per user flag state whether review is needed. 17452 // Hence, if a new user is added we have to propagate dangerous 17453 // permission grants for these legacy apps. 17454 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 17455 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 17456 | UPDATE_PERMISSIONS_REPLACE_ALL); 17457 } 17458 } 17459 17460 @Override 17461 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 17462 mContext.enforceCallingOrSelfPermission( 17463 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 17464 "Only package verification agents can read the verifier device identity"); 17465 17466 synchronized (mPackages) { 17467 return mSettings.getVerifierDeviceIdentityLPw(); 17468 } 17469 } 17470 17471 @Override 17472 public void setPermissionEnforced(String permission, boolean enforced) { 17473 // TODO: Now that we no longer change GID for storage, this should to away. 17474 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 17475 "setPermissionEnforced"); 17476 if (READ_EXTERNAL_STORAGE.equals(permission)) { 17477 synchronized (mPackages) { 17478 if (mSettings.mReadExternalStorageEnforced == null 17479 || mSettings.mReadExternalStorageEnforced != enforced) { 17480 mSettings.mReadExternalStorageEnforced = enforced; 17481 mSettings.writeLPr(); 17482 } 17483 } 17484 // kill any non-foreground processes so we restart them and 17485 // grant/revoke the GID. 17486 final IActivityManager am = ActivityManagerNative.getDefault(); 17487 if (am != null) { 17488 final long token = Binder.clearCallingIdentity(); 17489 try { 17490 am.killProcessesBelowForeground("setPermissionEnforcement"); 17491 } catch (RemoteException e) { 17492 } finally { 17493 Binder.restoreCallingIdentity(token); 17494 } 17495 } 17496 } else { 17497 throw new IllegalArgumentException("No selective enforcement for " + permission); 17498 } 17499 } 17500 17501 @Override 17502 @Deprecated 17503 public boolean isPermissionEnforced(String permission) { 17504 return true; 17505 } 17506 17507 @Override 17508 public boolean isStorageLow() { 17509 final long token = Binder.clearCallingIdentity(); 17510 try { 17511 final DeviceStorageMonitorInternal 17512 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 17513 if (dsm != null) { 17514 return dsm.isMemoryLow(); 17515 } else { 17516 return false; 17517 } 17518 } finally { 17519 Binder.restoreCallingIdentity(token); 17520 } 17521 } 17522 17523 @Override 17524 public IPackageInstaller getPackageInstaller() { 17525 return mInstallerService; 17526 } 17527 17528 private boolean userNeedsBadging(int userId) { 17529 int index = mUserNeedsBadging.indexOfKey(userId); 17530 if (index < 0) { 17531 final UserInfo userInfo; 17532 final long token = Binder.clearCallingIdentity(); 17533 try { 17534 userInfo = sUserManager.getUserInfo(userId); 17535 } finally { 17536 Binder.restoreCallingIdentity(token); 17537 } 17538 final boolean b; 17539 if (userInfo != null && userInfo.isManagedProfile()) { 17540 b = true; 17541 } else { 17542 b = false; 17543 } 17544 mUserNeedsBadging.put(userId, b); 17545 return b; 17546 } 17547 return mUserNeedsBadging.valueAt(index); 17548 } 17549 17550 @Override 17551 public KeySet getKeySetByAlias(String packageName, String alias) { 17552 if (packageName == null || alias == null) { 17553 return null; 17554 } 17555 synchronized(mPackages) { 17556 final PackageParser.Package pkg = mPackages.get(packageName); 17557 if (pkg == null) { 17558 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 17559 throw new IllegalArgumentException("Unknown package: " + packageName); 17560 } 17561 KeySetManagerService ksms = mSettings.mKeySetManagerService; 17562 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 17563 } 17564 } 17565 17566 @Override 17567 public KeySet getSigningKeySet(String packageName) { 17568 if (packageName == null) { 17569 return null; 17570 } 17571 synchronized(mPackages) { 17572 final PackageParser.Package pkg = mPackages.get(packageName); 17573 if (pkg == null) { 17574 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 17575 throw new IllegalArgumentException("Unknown package: " + packageName); 17576 } 17577 if (pkg.applicationInfo.uid != Binder.getCallingUid() 17578 && Process.SYSTEM_UID != Binder.getCallingUid()) { 17579 throw new SecurityException("May not access signing KeySet of other apps."); 17580 } 17581 KeySetManagerService ksms = mSettings.mKeySetManagerService; 17582 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 17583 } 17584 } 17585 17586 @Override 17587 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 17588 if (packageName == null || ks == null) { 17589 return false; 17590 } 17591 synchronized(mPackages) { 17592 final PackageParser.Package pkg = mPackages.get(packageName); 17593 if (pkg == null) { 17594 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 17595 throw new IllegalArgumentException("Unknown package: " + packageName); 17596 } 17597 IBinder ksh = ks.getToken(); 17598 if (ksh instanceof KeySetHandle) { 17599 KeySetManagerService ksms = mSettings.mKeySetManagerService; 17600 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 17601 } 17602 return false; 17603 } 17604 } 17605 17606 @Override 17607 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 17608 if (packageName == null || ks == null) { 17609 return false; 17610 } 17611 synchronized(mPackages) { 17612 final PackageParser.Package pkg = mPackages.get(packageName); 17613 if (pkg == null) { 17614 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 17615 throw new IllegalArgumentException("Unknown package: " + packageName); 17616 } 17617 IBinder ksh = ks.getToken(); 17618 if (ksh instanceof KeySetHandle) { 17619 KeySetManagerService ksms = mSettings.mKeySetManagerService; 17620 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 17621 } 17622 return false; 17623 } 17624 } 17625 17626 private void deletePackageIfUnusedLPr(final String packageName) { 17627 PackageSetting ps = mSettings.mPackages.get(packageName); 17628 if (ps == null) { 17629 return; 17630 } 17631 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 17632 // TODO Implement atomic delete if package is unused 17633 // It is currently possible that the package will be deleted even if it is installed 17634 // after this method returns. 17635 mHandler.post(new Runnable() { 17636 public void run() { 17637 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 17638 } 17639 }); 17640 } 17641 } 17642 17643 /** 17644 * Check and throw if the given before/after packages would be considered a 17645 * downgrade. 17646 */ 17647 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 17648 throws PackageManagerException { 17649 if (after.versionCode < before.mVersionCode) { 17650 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 17651 "Update version code " + after.versionCode + " is older than current " 17652 + before.mVersionCode); 17653 } else if (after.versionCode == before.mVersionCode) { 17654 if (after.baseRevisionCode < before.baseRevisionCode) { 17655 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 17656 "Update base revision code " + after.baseRevisionCode 17657 + " is older than current " + before.baseRevisionCode); 17658 } 17659 17660 if (!ArrayUtils.isEmpty(after.splitNames)) { 17661 for (int i = 0; i < after.splitNames.length; i++) { 17662 final String splitName = after.splitNames[i]; 17663 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 17664 if (j != -1) { 17665 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 17666 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 17667 "Update split " + splitName + " revision code " 17668 + after.splitRevisionCodes[i] + " is older than current " 17669 + before.splitRevisionCodes[j]); 17670 } 17671 } 17672 } 17673 } 17674 } 17675 } 17676 17677 private static class MoveCallbacks extends Handler { 17678 private static final int MSG_CREATED = 1; 17679 private static final int MSG_STATUS_CHANGED = 2; 17680 17681 private final RemoteCallbackList<IPackageMoveObserver> 17682 mCallbacks = new RemoteCallbackList<>(); 17683 17684 private final SparseIntArray mLastStatus = new SparseIntArray(); 17685 17686 public MoveCallbacks(Looper looper) { 17687 super(looper); 17688 } 17689 17690 public void register(IPackageMoveObserver callback) { 17691 mCallbacks.register(callback); 17692 } 17693 17694 public void unregister(IPackageMoveObserver callback) { 17695 mCallbacks.unregister(callback); 17696 } 17697 17698 @Override 17699 public void handleMessage(Message msg) { 17700 final SomeArgs args = (SomeArgs) msg.obj; 17701 final int n = mCallbacks.beginBroadcast(); 17702 for (int i = 0; i < n; i++) { 17703 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 17704 try { 17705 invokeCallback(callback, msg.what, args); 17706 } catch (RemoteException ignored) { 17707 } 17708 } 17709 mCallbacks.finishBroadcast(); 17710 args.recycle(); 17711 } 17712 17713 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 17714 throws RemoteException { 17715 switch (what) { 17716 case MSG_CREATED: { 17717 callback.onCreated(args.argi1, (Bundle) args.arg2); 17718 break; 17719 } 17720 case MSG_STATUS_CHANGED: { 17721 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 17722 break; 17723 } 17724 } 17725 } 17726 17727 private void notifyCreated(int moveId, Bundle extras) { 17728 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 17729 17730 final SomeArgs args = SomeArgs.obtain(); 17731 args.argi1 = moveId; 17732 args.arg2 = extras; 17733 obtainMessage(MSG_CREATED, args).sendToTarget(); 17734 } 17735 17736 private void notifyStatusChanged(int moveId, int status) { 17737 notifyStatusChanged(moveId, status, -1); 17738 } 17739 17740 private void notifyStatusChanged(int moveId, int status, long estMillis) { 17741 Slog.v(TAG, "Move " + moveId + " status " + status); 17742 17743 final SomeArgs args = SomeArgs.obtain(); 17744 args.argi1 = moveId; 17745 args.argi2 = status; 17746 args.arg3 = estMillis; 17747 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 17748 17749 synchronized (mLastStatus) { 17750 mLastStatus.put(moveId, status); 17751 } 17752 } 17753 } 17754 17755 private final static class OnPermissionChangeListeners extends Handler { 17756 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 17757 17758 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 17759 new RemoteCallbackList<>(); 17760 17761 public OnPermissionChangeListeners(Looper looper) { 17762 super(looper); 17763 } 17764 17765 @Override 17766 public void handleMessage(Message msg) { 17767 switch (msg.what) { 17768 case MSG_ON_PERMISSIONS_CHANGED: { 17769 final int uid = msg.arg1; 17770 handleOnPermissionsChanged(uid); 17771 } break; 17772 } 17773 } 17774 17775 public void addListenerLocked(IOnPermissionsChangeListener listener) { 17776 mPermissionListeners.register(listener); 17777 17778 } 17779 17780 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 17781 mPermissionListeners.unregister(listener); 17782 } 17783 17784 public void onPermissionsChanged(int uid) { 17785 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 17786 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 17787 } 17788 } 17789 17790 private void handleOnPermissionsChanged(int uid) { 17791 final int count = mPermissionListeners.beginBroadcast(); 17792 try { 17793 for (int i = 0; i < count; i++) { 17794 IOnPermissionsChangeListener callback = mPermissionListeners 17795 .getBroadcastItem(i); 17796 try { 17797 callback.onPermissionsChanged(uid); 17798 } catch (RemoteException e) { 17799 Log.e(TAG, "Permission listener is dead", e); 17800 } 17801 } 17802 } finally { 17803 mPermissionListeners.finishBroadcast(); 17804 } 17805 } 17806 } 17807 17808 private class PackageManagerInternalImpl extends PackageManagerInternal { 17809 @Override 17810 public void setLocationPackagesProvider(PackagesProvider provider) { 17811 synchronized (mPackages) { 17812 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 17813 } 17814 } 17815 17816 @Override 17817 public void setImePackagesProvider(PackagesProvider provider) { 17818 synchronized (mPackages) { 17819 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 17820 } 17821 } 17822 17823 @Override 17824 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 17825 synchronized (mPackages) { 17826 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 17827 } 17828 } 17829 17830 @Override 17831 public void setSmsAppPackagesProvider(PackagesProvider provider) { 17832 synchronized (mPackages) { 17833 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 17834 } 17835 } 17836 17837 @Override 17838 public void setDialerAppPackagesProvider(PackagesProvider provider) { 17839 synchronized (mPackages) { 17840 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 17841 } 17842 } 17843 17844 @Override 17845 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 17846 synchronized (mPackages) { 17847 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 17848 } 17849 } 17850 17851 @Override 17852 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 17853 synchronized (mPackages) { 17854 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 17855 } 17856 } 17857 17858 @Override 17859 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 17860 synchronized (mPackages) { 17861 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 17862 packageName, userId); 17863 } 17864 } 17865 17866 @Override 17867 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 17868 synchronized (mPackages) { 17869 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 17870 packageName, userId); 17871 } 17872 } 17873 17874 @Override 17875 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 17876 synchronized (mPackages) { 17877 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 17878 packageName, userId); 17879 } 17880 } 17881 17882 @Override 17883 public void setKeepUninstalledPackages(final List<String> packageList) { 17884 Preconditions.checkNotNull(packageList); 17885 List<String> removedFromList = null; 17886 synchronized (mPackages) { 17887 if (mKeepUninstalledPackages != null) { 17888 final int packagesCount = mKeepUninstalledPackages.size(); 17889 for (int i = 0; i < packagesCount; i++) { 17890 String oldPackage = mKeepUninstalledPackages.get(i); 17891 if (packageList != null && packageList.contains(oldPackage)) { 17892 continue; 17893 } 17894 if (removedFromList == null) { 17895 removedFromList = new ArrayList<>(); 17896 } 17897 removedFromList.add(oldPackage); 17898 } 17899 } 17900 mKeepUninstalledPackages = new ArrayList<>(packageList); 17901 if (removedFromList != null) { 17902 final int removedCount = removedFromList.size(); 17903 for (int i = 0; i < removedCount; i++) { 17904 deletePackageIfUnusedLPr(removedFromList.get(i)); 17905 } 17906 } 17907 } 17908 } 17909 17910 @Override 17911 public boolean isPermissionsReviewRequired(String packageName, int userId) { 17912 synchronized (mPackages) { 17913 // If we do not support permission review, done. 17914 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 17915 return false; 17916 } 17917 17918 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 17919 if (packageSetting == null) { 17920 return false; 17921 } 17922 17923 // Permission review applies only to apps not supporting the new permission model. 17924 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 17925 return false; 17926 } 17927 17928 // Legacy apps have the permission and get user consent on launch. 17929 PermissionsState permissionsState = packageSetting.getPermissionsState(); 17930 return permissionsState.isPermissionReviewRequired(userId); 17931 } 17932 } 17933 } 17934 17935 @Override 17936 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 17937 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 17938 synchronized (mPackages) { 17939 final long identity = Binder.clearCallingIdentity(); 17940 try { 17941 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 17942 packageNames, userId); 17943 } finally { 17944 Binder.restoreCallingIdentity(identity); 17945 } 17946 } 17947 } 17948 17949 private static void enforceSystemOrPhoneCaller(String tag) { 17950 int callingUid = Binder.getCallingUid(); 17951 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 17952 throw new SecurityException( 17953 "Cannot call " + tag + " from UID " + callingUid); 17954 } 17955 } 17956} 17957