PackageManagerService.java revision 1e2839188fb49575b86646d3aadb355c81ef9cc5
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_UID_CHANGED; 50import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 51import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 52import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 53import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 54import static android.content.pm.PackageManager.INSTALL_INTERNAL; 55import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_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.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 61import static android.content.pm.PackageManager.MATCH_ALL; 62import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 63import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 64import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 65import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 66import static android.content.pm.PackageManager.PERMISSION_DENIED; 67import static android.content.pm.PackageManager.PERMISSION_GRANTED; 68import static android.content.pm.PackageParser.isApkFile; 69import static android.os.Process.PACKAGE_INFO_GID; 70import static android.os.Process.SYSTEM_UID; 71import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 72import static android.system.OsConstants.O_CREAT; 73import static android.system.OsConstants.O_RDWR; 74import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 75import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 76import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 77import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 78import static com.android.internal.util.ArrayUtils.appendInt; 79import static com.android.server.pm.Installer.DEXOPT_PUBLIC; 80import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 81import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 82import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 83import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 84import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 85import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 86import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 87import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 88 89import android.Manifest; 90import android.app.ActivityManager; 91import android.app.ActivityManagerNative; 92import android.app.AppGlobals; 93import android.app.IActivityManager; 94import android.app.admin.IDevicePolicyManager; 95import android.app.backup.IBackupManager; 96import android.content.BroadcastReceiver; 97import android.content.ComponentName; 98import android.content.Context; 99import android.content.IIntentReceiver; 100import android.content.Intent; 101import android.content.IntentFilter; 102import android.content.IntentSender; 103import android.content.IntentSender.SendIntentException; 104import android.content.ServiceConnection; 105import android.content.pm.ActivityInfo; 106import android.content.pm.ApplicationInfo; 107import android.content.pm.AppsQueryHelper; 108import android.content.pm.EphemeralResolveInfo; 109import android.content.pm.EphemeralApplicationInfo; 110import android.content.pm.FeatureInfo; 111import android.content.pm.IOnPermissionsChangeListener; 112import android.content.pm.IPackageDataObserver; 113import android.content.pm.IPackageDeleteObserver; 114import android.content.pm.IPackageDeleteObserver2; 115import android.content.pm.IPackageInstallObserver2; 116import android.content.pm.IPackageInstaller; 117import android.content.pm.IPackageManager; 118import android.content.pm.IPackageMoveObserver; 119import android.content.pm.IPackageStatsObserver; 120import android.content.pm.InstrumentationInfo; 121import android.content.pm.IntentFilterVerificationInfo; 122import android.content.pm.KeySet; 123import android.content.pm.ManifestDigest; 124import android.content.pm.PackageCleanItem; 125import android.content.pm.PackageInfo; 126import android.content.pm.PackageInfoLite; 127import android.content.pm.PackageInstaller; 128import android.content.pm.PackageManager; 129import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 130import android.content.pm.PackageManagerInternal; 131import android.content.pm.PackageParser; 132import android.content.pm.PackageParser.ActivityIntentInfo; 133import android.content.pm.PackageParser.PackageLite; 134import android.content.pm.PackageParser.PackageParserException; 135import android.content.pm.PackageStats; 136import android.content.pm.PackageUserState; 137import android.content.pm.ParceledListSlice; 138import android.content.pm.PermissionGroupInfo; 139import android.content.pm.PermissionInfo; 140import android.content.pm.ProviderInfo; 141import android.content.pm.ResolveInfo; 142import android.content.pm.ServiceInfo; 143import android.content.pm.Signature; 144import android.content.pm.UserInfo; 145import android.content.pm.VerificationParams; 146import android.content.pm.VerifierDeviceIdentity; 147import android.content.pm.VerifierInfo; 148import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo; 149import android.content.res.Resources; 150import android.graphics.Bitmap; 151import android.hardware.display.DisplayManager; 152import android.net.Uri; 153import android.os.Debug; 154import android.os.Binder; 155import android.os.Build; 156import android.os.Bundle; 157import android.os.Environment; 158import android.os.Environment.UserEnvironment; 159import android.os.FileUtils; 160import android.os.Handler; 161import android.os.IBinder; 162import android.os.Looper; 163import android.os.Message; 164import android.os.Parcel; 165import android.os.ParcelFileDescriptor; 166import android.os.Process; 167import android.os.RemoteCallbackList; 168import android.os.RemoteException; 169import android.os.ResultReceiver; 170import android.os.SELinux; 171import android.os.ServiceManager; 172import android.os.SystemClock; 173import android.os.SystemProperties; 174import android.os.Trace; 175import android.os.UserHandle; 176import android.os.UserManager; 177import android.os.storage.IMountService; 178import android.os.storage.MountServiceInternal; 179import android.os.storage.StorageEventListener; 180import android.os.storage.StorageManager; 181import android.os.storage.VolumeInfo; 182import android.os.storage.VolumeRecord; 183import android.security.KeyStore; 184import android.security.SystemKeyStore; 185import android.system.ErrnoException; 186import android.system.Os; 187import android.system.StructStat; 188import android.text.TextUtils; 189import android.text.format.DateUtils; 190import android.util.ArrayMap; 191import android.util.ArraySet; 192import android.util.AtomicFile; 193import android.util.DisplayMetrics; 194import android.util.EventLog; 195import android.util.ExceptionUtils; 196import android.util.Log; 197import android.util.LogPrinter; 198import android.util.MathUtils; 199import android.util.PrintStreamPrinter; 200import android.util.Slog; 201import android.util.SparseArray; 202import android.util.SparseBooleanArray; 203import android.util.SparseIntArray; 204import android.util.Xml; 205import android.view.Display; 206 207import com.android.internal.annotations.GuardedBy; 208import dalvik.system.DexFile; 209import dalvik.system.VMRuntime; 210 211import libcore.io.IoUtils; 212import libcore.util.EmptyArray; 213 214import com.android.internal.R; 215import com.android.internal.annotations.GuardedBy; 216import com.android.internal.app.IMediaContainerService; 217import com.android.internal.app.ResolverActivity; 218import com.android.internal.content.NativeLibraryHelper; 219import com.android.internal.content.PackageHelper; 220import com.android.internal.os.IParcelFileDescriptorFactory; 221import com.android.internal.os.SomeArgs; 222import com.android.internal.os.Zygote; 223import com.android.internal.util.ArrayUtils; 224import com.android.internal.util.FastPrintWriter; 225import com.android.internal.util.FastXmlSerializer; 226import com.android.internal.util.IndentingPrintWriter; 227import com.android.internal.util.Preconditions; 228import com.android.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.PermissionsState.PermissionState; 236import com.android.server.pm.Settings.DatabaseVersion; 237import com.android.server.pm.Settings.VersionInfo; 238import com.android.server.storage.DeviceStorageMonitorInternal; 239 240import org.xmlpull.v1.XmlPullParser; 241import org.xmlpull.v1.XmlPullParserException; 242import org.xmlpull.v1.XmlSerializer; 243 244import java.io.BufferedInputStream; 245import java.io.BufferedOutputStream; 246import java.io.BufferedReader; 247import java.io.ByteArrayInputStream; 248import java.io.ByteArrayOutputStream; 249import java.io.File; 250import java.io.FileDescriptor; 251import java.io.FileNotFoundException; 252import java.io.FileOutputStream; 253import java.io.FileReader; 254import java.io.FilenameFilter; 255import java.io.IOException; 256import java.io.InputStream; 257import java.io.PrintWriter; 258import java.nio.charset.StandardCharsets; 259import java.security.MessageDigest; 260import java.security.NoSuchAlgorithmException; 261import java.security.PublicKey; 262import java.security.cert.CertificateEncodingException; 263import java.security.cert.CertificateException; 264import java.text.SimpleDateFormat; 265import java.util.ArrayList; 266import java.util.Arrays; 267import java.util.Collection; 268import java.util.Collections; 269import java.util.Comparator; 270import java.util.Date; 271import java.util.Iterator; 272import java.util.List; 273import java.util.Map; 274import java.util.Objects; 275import java.util.Set; 276import java.util.concurrent.CountDownLatch; 277import java.util.concurrent.TimeUnit; 278import java.util.concurrent.atomic.AtomicBoolean; 279import java.util.concurrent.atomic.AtomicInteger; 280import java.util.concurrent.atomic.AtomicLong; 281 282/** 283 * Keep track of all those .apks everywhere. 284 * 285 * This is very central to the platform's security; please run the unit 286 * tests whenever making modifications here: 287 * 288runtest -c android.content.pm.PackageManagerTests frameworks-core 289 * 290 * {@hide} 291 */ 292public class PackageManagerService extends IPackageManager.Stub { 293 static final String TAG = "PackageManager"; 294 static final boolean DEBUG_SETTINGS = false; 295 static final boolean DEBUG_PREFERRED = false; 296 static final boolean DEBUG_UPGRADE = false; 297 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 298 private static final boolean DEBUG_BACKUP = false; 299 private static final boolean DEBUG_INSTALL = false; 300 private static final boolean DEBUG_REMOVE = false; 301 private static final boolean DEBUG_BROADCASTS = false; 302 private static final boolean DEBUG_SHOW_INFO = false; 303 private static final boolean DEBUG_PACKAGE_INFO = false; 304 private static final boolean DEBUG_INTENT_MATCHING = false; 305 private static final boolean DEBUG_PACKAGE_SCANNING = false; 306 private static final boolean DEBUG_VERIFY = false; 307 private static final boolean DEBUG_DEXOPT = false; 308 private static final boolean DEBUG_ABI_SELECTION = false; 309 private static final boolean DEBUG_EPHEMERAL = false; 310 311 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 312 313 private static final int RADIO_UID = Process.PHONE_UID; 314 private static final int LOG_UID = Process.LOG_UID; 315 private static final int NFC_UID = Process.NFC_UID; 316 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 317 private static final int SHELL_UID = Process.SHELL_UID; 318 319 // Cap the size of permission trees that 3rd party apps can define 320 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 321 322 // Suffix used during package installation when copying/moving 323 // package apks to install directory. 324 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 325 326 static final int SCAN_NO_DEX = 1<<1; 327 static final int SCAN_FORCE_DEX = 1<<2; 328 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 329 static final int SCAN_NEW_INSTALL = 1<<4; 330 static final int SCAN_NO_PATHS = 1<<5; 331 static final int SCAN_UPDATE_TIME = 1<<6; 332 static final int SCAN_DEFER_DEX = 1<<7; 333 static final int SCAN_BOOTING = 1<<8; 334 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 335 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 336 static final int SCAN_REPLACING = 1<<11; 337 static final int SCAN_REQUIRE_KNOWN = 1<<12; 338 static final int SCAN_MOVE = 1<<13; 339 static final int SCAN_INITIAL = 1<<14; 340 341 static final int REMOVE_CHATTY = 1<<16; 342 343 private static final int[] EMPTY_INT_ARRAY = new int[0]; 344 345 /** 346 * Timeout (in milliseconds) after which the watchdog should declare that 347 * our handler thread is wedged. The usual default for such things is one 348 * minute but we sometimes do very lengthy I/O operations on this thread, 349 * such as installing multi-gigabyte applications, so ours needs to be longer. 350 */ 351 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 352 353 /** 354 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 355 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 356 * settings entry if available, otherwise we use the hardcoded default. If it's been 357 * more than this long since the last fstrim, we force one during the boot sequence. 358 * 359 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 360 * one gets run at the next available charging+idle time. This final mandatory 361 * no-fstrim check kicks in only of the other scheduling criteria is never met. 362 */ 363 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 364 365 /** 366 * Whether verification is enabled by default. 367 */ 368 private static final boolean DEFAULT_VERIFY_ENABLE = true; 369 370 /** 371 * The default maximum time to wait for the verification agent to return in 372 * milliseconds. 373 */ 374 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 375 376 /** 377 * The default response for package verification timeout. 378 * 379 * This can be either PackageManager.VERIFICATION_ALLOW or 380 * PackageManager.VERIFICATION_REJECT. 381 */ 382 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 383 384 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 385 386 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 387 DEFAULT_CONTAINER_PACKAGE, 388 "com.android.defcontainer.DefaultContainerService"); 389 390 private static final String KILL_APP_REASON_GIDS_CHANGED = 391 "permission grant or revoke changed gids"; 392 393 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 394 "permissions revoked"; 395 396 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 397 398 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 399 400 /** Permission grant: not grant the permission. */ 401 private static final int GRANT_DENIED = 1; 402 403 /** Permission grant: grant the permission as an install permission. */ 404 private static final int GRANT_INSTALL = 2; 405 406 /** Permission grant: grant the permission as a runtime one. */ 407 private static final int GRANT_RUNTIME = 3; 408 409 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 410 private static final int GRANT_UPGRADE = 4; 411 412 /** Canonical intent used to identify what counts as a "web browser" app */ 413 private static final Intent sBrowserIntent; 414 static { 415 sBrowserIntent = new Intent(); 416 sBrowserIntent.setAction(Intent.ACTION_VIEW); 417 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 418 sBrowserIntent.setData(Uri.parse("http:")); 419 } 420 421 final ServiceThread mHandlerThread; 422 423 final PackageHandler mHandler; 424 425 /** 426 * Messages for {@link #mHandler} that need to wait for system ready before 427 * being dispatched. 428 */ 429 private ArrayList<Message> mPostSystemReadyMessages; 430 431 final int mSdkVersion = Build.VERSION.SDK_INT; 432 433 final Context mContext; 434 final boolean mFactoryTest; 435 final boolean mOnlyCore; 436 final DisplayMetrics mMetrics; 437 final int mDefParseFlags; 438 final String[] mSeparateProcesses; 439 final boolean mIsUpgrade; 440 441 /** The location for ASEC container files on internal storage. */ 442 final String mAsecInternalPath; 443 444 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 445 // LOCK HELD. Can be called with mInstallLock held. 446 @GuardedBy("mInstallLock") 447 final Installer mInstaller; 448 449 /** Directory where installed third-party apps stored */ 450 final File mAppInstallDir; 451 final File mEphemeralInstallDir; 452 453 /** 454 * Directory to which applications installed internally have their 455 * 32 bit native libraries copied. 456 */ 457 private File mAppLib32InstallDir; 458 459 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 460 // apps. 461 final File mDrmAppPrivateInstallDir; 462 463 // ---------------------------------------------------------------- 464 465 // Lock for state used when installing and doing other long running 466 // operations. Methods that must be called with this lock held have 467 // the suffix "LI". 468 final Object mInstallLock = new Object(); 469 470 // ---------------------------------------------------------------- 471 472 // Keys are String (package name), values are Package. This also serves 473 // as the lock for the global state. Methods that must be called with 474 // this lock held have the prefix "LP". 475 @GuardedBy("mPackages") 476 final ArrayMap<String, PackageParser.Package> mPackages = 477 new ArrayMap<String, PackageParser.Package>(); 478 479 // Tracks available target package names -> overlay package paths. 480 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 481 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 482 483 /** 484 * Tracks new system packages [received in an OTA] that we expect to 485 * find updated user-installed versions. Keys are package name, values 486 * are package location. 487 */ 488 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 489 490 /** 491 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 492 */ 493 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 494 /** 495 * Whether or not system app permissions should be promoted from install to runtime. 496 */ 497 boolean mPromoteSystemApps; 498 499 final Settings mSettings; 500 boolean mRestoredSettings; 501 502 // System configuration read by SystemConfig. 503 final int[] mGlobalGids; 504 final SparseArray<ArraySet<String>> mSystemPermissions; 505 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 506 507 // If mac_permissions.xml was found for seinfo labeling. 508 boolean mFoundPolicyFile; 509 510 // If a recursive restorecon of /data/data/<pkg> is needed. 511 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 512 513 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 514 515 public static final class SharedLibraryEntry { 516 public final String path; 517 public final String apk; 518 519 SharedLibraryEntry(String _path, String _apk) { 520 path = _path; 521 apk = _apk; 522 } 523 } 524 525 // Currently known shared libraries. 526 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 527 new ArrayMap<String, SharedLibraryEntry>(); 528 529 // All available activities, for your resolving pleasure. 530 final ActivityIntentResolver mActivities = 531 new ActivityIntentResolver(); 532 533 // All available receivers, for your resolving pleasure. 534 final ActivityIntentResolver mReceivers = 535 new ActivityIntentResolver(); 536 537 // All available services, for your resolving pleasure. 538 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 539 540 // All available providers, for your resolving pleasure. 541 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 542 543 // Mapping from provider base names (first directory in content URI codePath) 544 // to the provider information. 545 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 546 new ArrayMap<String, PackageParser.Provider>(); 547 548 // Mapping from instrumentation class names to info about them. 549 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 550 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 551 552 // Mapping from permission names to info about them. 553 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 554 new ArrayMap<String, PackageParser.PermissionGroup>(); 555 556 // Packages whose data we have transfered into another package, thus 557 // should no longer exist. 558 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 559 560 // Broadcast actions that are only available to the system. 561 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 562 563 /** List of packages waiting for verification. */ 564 final SparseArray<PackageVerificationState> mPendingVerification 565 = new SparseArray<PackageVerificationState>(); 566 567 /** Set of packages associated with each app op permission. */ 568 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 569 570 final PackageInstallerService mInstallerService; 571 572 private final PackageDexOptimizer mPackageDexOptimizer; 573 574 private AtomicInteger mNextMoveId = new AtomicInteger(); 575 private final MoveCallbacks mMoveCallbacks; 576 577 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 578 579 // Cache of users who need badging. 580 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 581 582 /** Token for keys in mPendingVerification. */ 583 private int mPendingVerificationToken = 0; 584 585 volatile boolean mSystemReady; 586 volatile boolean mSafeMode; 587 volatile boolean mHasSystemUidErrors; 588 589 ApplicationInfo mAndroidApplication; 590 final ActivityInfo mResolveActivity = new ActivityInfo(); 591 final ResolveInfo mResolveInfo = new ResolveInfo(); 592 ComponentName mResolveComponentName; 593 PackageParser.Package mPlatformPackage; 594 ComponentName mCustomResolverComponentName; 595 596 boolean mResolverReplaced = false; 597 598 private final ComponentName mIntentFilterVerifierComponent; 599 private int mIntentFilterVerificationToken = 0; 600 601 /** Component that knows whether or not an ephemeral application exists */ 602 final ComponentName mEphemeralResolverComponent; 603 /** The service connection to the ephemeral resolver */ 604 final EphemeralResolverConnection mEphemeralResolverConnection; 605 606 /** Component used to install ephemeral applications */ 607 final ComponentName mEphemeralInstallerComponent; 608 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 609 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 610 611 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 612 = new SparseArray<IntentFilterVerificationState>(); 613 614 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 615 new DefaultPermissionGrantPolicy(this); 616 617 // List of packages names to keep cached, even if they are uninstalled for all users 618 private List<String> mKeepUninstalledPackages; 619 620 private static class IFVerificationParams { 621 PackageParser.Package pkg; 622 boolean replacing; 623 int userId; 624 int verifierUid; 625 626 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 627 int _userId, int _verifierUid) { 628 pkg = _pkg; 629 replacing = _replacing; 630 userId = _userId; 631 replacing = _replacing; 632 verifierUid = _verifierUid; 633 } 634 } 635 636 private interface IntentFilterVerifier<T extends IntentFilter> { 637 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 638 T filter, String packageName); 639 void startVerifications(int userId); 640 void receiveVerificationResponse(int verificationId); 641 } 642 643 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 644 private Context mContext; 645 private ComponentName mIntentFilterVerifierComponent; 646 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 647 648 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 649 mContext = context; 650 mIntentFilterVerifierComponent = verifierComponent; 651 } 652 653 private String getDefaultScheme() { 654 return IntentFilter.SCHEME_HTTPS; 655 } 656 657 @Override 658 public void startVerifications(int userId) { 659 // Launch verifications requests 660 int count = mCurrentIntentFilterVerifications.size(); 661 for (int n=0; n<count; n++) { 662 int verificationId = mCurrentIntentFilterVerifications.get(n); 663 final IntentFilterVerificationState ivs = 664 mIntentFilterVerificationStates.get(verificationId); 665 666 String packageName = ivs.getPackageName(); 667 668 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 669 final int filterCount = filters.size(); 670 ArraySet<String> domainsSet = new ArraySet<>(); 671 for (int m=0; m<filterCount; m++) { 672 PackageParser.ActivityIntentInfo filter = filters.get(m); 673 domainsSet.addAll(filter.getHostsList()); 674 } 675 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 676 synchronized (mPackages) { 677 if (mSettings.createIntentFilterVerificationIfNeededLPw( 678 packageName, domainsList) != null) { 679 scheduleWriteSettingsLocked(); 680 } 681 } 682 sendVerificationRequest(userId, verificationId, ivs); 683 } 684 mCurrentIntentFilterVerifications.clear(); 685 } 686 687 private void sendVerificationRequest(int userId, int verificationId, 688 IntentFilterVerificationState ivs) { 689 690 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 691 verificationIntent.putExtra( 692 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 693 verificationId); 694 verificationIntent.putExtra( 695 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 696 getDefaultScheme()); 697 verificationIntent.putExtra( 698 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 699 ivs.getHostsString()); 700 verificationIntent.putExtra( 701 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 702 ivs.getPackageName()); 703 verificationIntent.setComponent(mIntentFilterVerifierComponent); 704 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 705 706 UserHandle user = new UserHandle(userId); 707 mContext.sendBroadcastAsUser(verificationIntent, user); 708 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 709 "Sending IntentFilter verification broadcast"); 710 } 711 712 public void receiveVerificationResponse(int verificationId) { 713 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 714 715 final boolean verified = ivs.isVerified(); 716 717 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 718 final int count = filters.size(); 719 if (DEBUG_DOMAIN_VERIFICATION) { 720 Slog.i(TAG, "Received verification response " + verificationId 721 + " for " + count + " filters, verified=" + verified); 722 } 723 for (int n=0; n<count; n++) { 724 PackageParser.ActivityIntentInfo filter = filters.get(n); 725 filter.setVerified(verified); 726 727 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 728 + " verified with result:" + verified + " and hosts:" 729 + ivs.getHostsString()); 730 } 731 732 mIntentFilterVerificationStates.remove(verificationId); 733 734 final String packageName = ivs.getPackageName(); 735 IntentFilterVerificationInfo ivi = null; 736 737 synchronized (mPackages) { 738 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 739 } 740 if (ivi == null) { 741 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 742 + verificationId + " packageName:" + packageName); 743 return; 744 } 745 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 746 "Updating IntentFilterVerificationInfo for package " + packageName 747 +" verificationId:" + verificationId); 748 749 synchronized (mPackages) { 750 if (verified) { 751 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 752 } else { 753 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 754 } 755 scheduleWriteSettingsLocked(); 756 757 final int userId = ivs.getUserId(); 758 if (userId != UserHandle.USER_ALL) { 759 final int userStatus = 760 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 761 762 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 763 boolean needUpdate = false; 764 765 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 766 // already been set by the User thru the Disambiguation dialog 767 switch (userStatus) { 768 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 769 if (verified) { 770 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 771 } else { 772 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 773 } 774 needUpdate = true; 775 break; 776 777 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 778 if (verified) { 779 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 780 needUpdate = true; 781 } 782 break; 783 784 default: 785 // Nothing to do 786 } 787 788 if (needUpdate) { 789 mSettings.updateIntentFilterVerificationStatusLPw( 790 packageName, updatedStatus, userId); 791 scheduleWritePackageRestrictionsLocked(userId); 792 } 793 } 794 } 795 } 796 797 @Override 798 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 799 ActivityIntentInfo filter, String packageName) { 800 if (!hasValidDomains(filter)) { 801 return false; 802 } 803 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 804 if (ivs == null) { 805 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 806 packageName); 807 } 808 if (DEBUG_DOMAIN_VERIFICATION) { 809 Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter); 810 } 811 ivs.addFilter(filter); 812 return true; 813 } 814 815 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 816 int userId, int verificationId, String packageName) { 817 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 818 verifierUid, userId, packageName); 819 ivs.setPendingState(); 820 synchronized (mPackages) { 821 mIntentFilterVerificationStates.append(verificationId, ivs); 822 mCurrentIntentFilterVerifications.add(verificationId); 823 } 824 return ivs; 825 } 826 } 827 828 private static boolean hasValidDomains(ActivityIntentInfo filter) { 829 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 830 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 831 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 832 } 833 834 private IntentFilterVerifier mIntentFilterVerifier; 835 836 // Set of pending broadcasts for aggregating enable/disable of components. 837 static class PendingPackageBroadcasts { 838 // for each user id, a map of <package name -> components within that package> 839 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 840 841 public PendingPackageBroadcasts() { 842 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 843 } 844 845 public ArrayList<String> get(int userId, String packageName) { 846 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 847 return packages.get(packageName); 848 } 849 850 public void put(int userId, String packageName, ArrayList<String> components) { 851 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 852 packages.put(packageName, components); 853 } 854 855 public void remove(int userId, String packageName) { 856 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 857 if (packages != null) { 858 packages.remove(packageName); 859 } 860 } 861 862 public void remove(int userId) { 863 mUidMap.remove(userId); 864 } 865 866 public int userIdCount() { 867 return mUidMap.size(); 868 } 869 870 public int userIdAt(int n) { 871 return mUidMap.keyAt(n); 872 } 873 874 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 875 return mUidMap.get(userId); 876 } 877 878 public int size() { 879 // total number of pending broadcast entries across all userIds 880 int num = 0; 881 for (int i = 0; i< mUidMap.size(); i++) { 882 num += mUidMap.valueAt(i).size(); 883 } 884 return num; 885 } 886 887 public void clear() { 888 mUidMap.clear(); 889 } 890 891 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 892 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 893 if (map == null) { 894 map = new ArrayMap<String, ArrayList<String>>(); 895 mUidMap.put(userId, map); 896 } 897 return map; 898 } 899 } 900 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 901 902 // Service Connection to remote media container service to copy 903 // package uri's from external media onto secure containers 904 // or internal storage. 905 private IMediaContainerService mContainerService = null; 906 907 static final int SEND_PENDING_BROADCAST = 1; 908 static final int MCS_BOUND = 3; 909 static final int END_COPY = 4; 910 static final int INIT_COPY = 5; 911 static final int MCS_UNBIND = 6; 912 static final int START_CLEANING_PACKAGE = 7; 913 static final int FIND_INSTALL_LOC = 8; 914 static final int POST_INSTALL = 9; 915 static final int MCS_RECONNECT = 10; 916 static final int MCS_GIVE_UP = 11; 917 static final int UPDATED_MEDIA_STATUS = 12; 918 static final int WRITE_SETTINGS = 13; 919 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 920 static final int PACKAGE_VERIFIED = 15; 921 static final int CHECK_PENDING_VERIFICATION = 16; 922 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 923 static final int INTENT_FILTER_VERIFIED = 18; 924 925 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 926 927 // Delay time in millisecs 928 static final int BROADCAST_DELAY = 10 * 1000; 929 930 static UserManagerService sUserManager; 931 932 // Stores a list of users whose package restrictions file needs to be updated 933 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 934 935 final private DefaultContainerConnection mDefContainerConn = 936 new DefaultContainerConnection(); 937 class DefaultContainerConnection implements ServiceConnection { 938 public void onServiceConnected(ComponentName name, IBinder service) { 939 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 940 IMediaContainerService imcs = 941 IMediaContainerService.Stub.asInterface(service); 942 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 943 } 944 945 public void onServiceDisconnected(ComponentName name) { 946 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 947 } 948 } 949 950 // Recordkeeping of restore-after-install operations that are currently in flight 951 // between the Package Manager and the Backup Manager 952 static class PostInstallData { 953 public InstallArgs args; 954 public PackageInstalledInfo res; 955 956 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 957 args = _a; 958 res = _r; 959 } 960 } 961 962 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 963 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 964 965 // XML tags for backup/restore of various bits of state 966 private static final String TAG_PREFERRED_BACKUP = "pa"; 967 private static final String TAG_DEFAULT_APPS = "da"; 968 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 969 970 final String mRequiredVerifierPackage; 971 final String mRequiredInstallerPackage; 972 973 private final PackageUsage mPackageUsage = new PackageUsage(); 974 975 private class PackageUsage { 976 private static final int WRITE_INTERVAL 977 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 978 979 private final Object mFileLock = new Object(); 980 private final AtomicLong mLastWritten = new AtomicLong(0); 981 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 982 983 private boolean mIsHistoricalPackageUsageAvailable = true; 984 985 boolean isHistoricalPackageUsageAvailable() { 986 return mIsHistoricalPackageUsageAvailable; 987 } 988 989 void write(boolean force) { 990 if (force) { 991 writeInternal(); 992 return; 993 } 994 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 995 && !DEBUG_DEXOPT) { 996 return; 997 } 998 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 999 new Thread("PackageUsage_DiskWriter") { 1000 @Override 1001 public void run() { 1002 try { 1003 writeInternal(); 1004 } finally { 1005 mBackgroundWriteRunning.set(false); 1006 } 1007 } 1008 }.start(); 1009 } 1010 } 1011 1012 private void writeInternal() { 1013 synchronized (mPackages) { 1014 synchronized (mFileLock) { 1015 AtomicFile file = getFile(); 1016 FileOutputStream f = null; 1017 try { 1018 f = file.startWrite(); 1019 BufferedOutputStream out = new BufferedOutputStream(f); 1020 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1021 StringBuilder sb = new StringBuilder(); 1022 for (PackageParser.Package pkg : mPackages.values()) { 1023 if (pkg.mLastPackageUsageTimeInMills == 0) { 1024 continue; 1025 } 1026 sb.setLength(0); 1027 sb.append(pkg.packageName); 1028 sb.append(' '); 1029 sb.append((long)pkg.mLastPackageUsageTimeInMills); 1030 sb.append('\n'); 1031 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1032 } 1033 out.flush(); 1034 file.finishWrite(f); 1035 } catch (IOException e) { 1036 if (f != null) { 1037 file.failWrite(f); 1038 } 1039 Log.e(TAG, "Failed to write package usage times", e); 1040 } 1041 } 1042 } 1043 mLastWritten.set(SystemClock.elapsedRealtime()); 1044 } 1045 1046 void readLP() { 1047 synchronized (mFileLock) { 1048 AtomicFile file = getFile(); 1049 BufferedInputStream in = null; 1050 try { 1051 in = new BufferedInputStream(file.openRead()); 1052 StringBuffer sb = new StringBuffer(); 1053 while (true) { 1054 String packageName = readToken(in, sb, ' '); 1055 if (packageName == null) { 1056 break; 1057 } 1058 String timeInMillisString = readToken(in, sb, '\n'); 1059 if (timeInMillisString == null) { 1060 throw new IOException("Failed to find last usage time for package " 1061 + packageName); 1062 } 1063 PackageParser.Package pkg = mPackages.get(packageName); 1064 if (pkg == null) { 1065 continue; 1066 } 1067 long timeInMillis; 1068 try { 1069 timeInMillis = Long.parseLong(timeInMillisString); 1070 } catch (NumberFormatException e) { 1071 throw new IOException("Failed to parse " + timeInMillisString 1072 + " as a long.", e); 1073 } 1074 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1075 } 1076 } catch (FileNotFoundException expected) { 1077 mIsHistoricalPackageUsageAvailable = false; 1078 } catch (IOException e) { 1079 Log.w(TAG, "Failed to read package usage times", e); 1080 } finally { 1081 IoUtils.closeQuietly(in); 1082 } 1083 } 1084 mLastWritten.set(SystemClock.elapsedRealtime()); 1085 } 1086 1087 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1088 throws IOException { 1089 sb.setLength(0); 1090 while (true) { 1091 int ch = in.read(); 1092 if (ch == -1) { 1093 if (sb.length() == 0) { 1094 return null; 1095 } 1096 throw new IOException("Unexpected EOF"); 1097 } 1098 if (ch == endOfToken) { 1099 return sb.toString(); 1100 } 1101 sb.append((char)ch); 1102 } 1103 } 1104 1105 private AtomicFile getFile() { 1106 File dataDir = Environment.getDataDirectory(); 1107 File systemDir = new File(dataDir, "system"); 1108 File fname = new File(systemDir, "package-usage.list"); 1109 return new AtomicFile(fname); 1110 } 1111 } 1112 1113 class PackageHandler extends Handler { 1114 private boolean mBound = false; 1115 final ArrayList<HandlerParams> mPendingInstalls = 1116 new ArrayList<HandlerParams>(); 1117 1118 private boolean connectToService() { 1119 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1120 " DefaultContainerService"); 1121 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1122 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1123 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1124 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1125 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1126 mBound = true; 1127 return true; 1128 } 1129 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1130 return false; 1131 } 1132 1133 private void disconnectService() { 1134 mContainerService = null; 1135 mBound = false; 1136 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1137 mContext.unbindService(mDefContainerConn); 1138 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1139 } 1140 1141 PackageHandler(Looper looper) { 1142 super(looper); 1143 } 1144 1145 public void handleMessage(Message msg) { 1146 try { 1147 doHandleMessage(msg); 1148 } finally { 1149 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1150 } 1151 } 1152 1153 void doHandleMessage(Message msg) { 1154 switch (msg.what) { 1155 case INIT_COPY: { 1156 HandlerParams params = (HandlerParams) msg.obj; 1157 int idx = mPendingInstalls.size(); 1158 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1159 // If a bind was already initiated we dont really 1160 // need to do anything. The pending install 1161 // will be processed later on. 1162 if (!mBound) { 1163 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1164 System.identityHashCode(mHandler)); 1165 // If this is the only one pending we might 1166 // have to bind to the service again. 1167 if (!connectToService()) { 1168 Slog.e(TAG, "Failed to bind to media container service"); 1169 params.serviceError(); 1170 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1171 System.identityHashCode(mHandler)); 1172 if (params.traceMethod != null) { 1173 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1174 params.traceCookie); 1175 } 1176 return; 1177 } else { 1178 // Once we bind to the service, the first 1179 // pending request will be processed. 1180 mPendingInstalls.add(idx, params); 1181 } 1182 } else { 1183 mPendingInstalls.add(idx, params); 1184 // Already bound to the service. Just make 1185 // sure we trigger off processing the first request. 1186 if (idx == 0) { 1187 mHandler.sendEmptyMessage(MCS_BOUND); 1188 } 1189 } 1190 break; 1191 } 1192 case MCS_BOUND: { 1193 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1194 if (msg.obj != null) { 1195 mContainerService = (IMediaContainerService) msg.obj; 1196 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1197 System.identityHashCode(mHandler)); 1198 } 1199 if (mContainerService == null) { 1200 if (!mBound) { 1201 // Something seriously wrong since we are not bound and we are not 1202 // waiting for connection. Bail out. 1203 Slog.e(TAG, "Cannot bind to media container service"); 1204 for (HandlerParams params : mPendingInstalls) { 1205 // Indicate service bind error 1206 params.serviceError(); 1207 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1208 System.identityHashCode(params)); 1209 if (params.traceMethod != null) { 1210 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1211 params.traceMethod, params.traceCookie); 1212 } 1213 return; 1214 } 1215 mPendingInstalls.clear(); 1216 } else { 1217 Slog.w(TAG, "Waiting to connect to media container service"); 1218 } 1219 } else if (mPendingInstalls.size() > 0) { 1220 HandlerParams params = mPendingInstalls.get(0); 1221 if (params != null) { 1222 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1223 System.identityHashCode(params)); 1224 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1225 if (params.startCopy()) { 1226 // We are done... look for more work or to 1227 // go idle. 1228 if (DEBUG_SD_INSTALL) Log.i(TAG, 1229 "Checking for more work or unbind..."); 1230 // Delete pending install 1231 if (mPendingInstalls.size() > 0) { 1232 mPendingInstalls.remove(0); 1233 } 1234 if (mPendingInstalls.size() == 0) { 1235 if (mBound) { 1236 if (DEBUG_SD_INSTALL) Log.i(TAG, 1237 "Posting delayed MCS_UNBIND"); 1238 removeMessages(MCS_UNBIND); 1239 Message ubmsg = obtainMessage(MCS_UNBIND); 1240 // Unbind after a little delay, to avoid 1241 // continual thrashing. 1242 sendMessageDelayed(ubmsg, 10000); 1243 } 1244 } else { 1245 // There are more pending requests in queue. 1246 // Just post MCS_BOUND message to trigger processing 1247 // of next pending install. 1248 if (DEBUG_SD_INSTALL) Log.i(TAG, 1249 "Posting MCS_BOUND for next work"); 1250 mHandler.sendEmptyMessage(MCS_BOUND); 1251 } 1252 } 1253 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1254 } 1255 } else { 1256 // Should never happen ideally. 1257 Slog.w(TAG, "Empty queue"); 1258 } 1259 break; 1260 } 1261 case MCS_RECONNECT: { 1262 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1263 if (mPendingInstalls.size() > 0) { 1264 if (mBound) { 1265 disconnectService(); 1266 } 1267 if (!connectToService()) { 1268 Slog.e(TAG, "Failed to bind to media container service"); 1269 for (HandlerParams params : mPendingInstalls) { 1270 // Indicate service bind error 1271 params.serviceError(); 1272 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1273 System.identityHashCode(params)); 1274 } 1275 mPendingInstalls.clear(); 1276 } 1277 } 1278 break; 1279 } 1280 case MCS_UNBIND: { 1281 // If there is no actual work left, then time to unbind. 1282 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1283 1284 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1285 if (mBound) { 1286 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1287 1288 disconnectService(); 1289 } 1290 } else if (mPendingInstalls.size() > 0) { 1291 // There are more pending requests in queue. 1292 // Just post MCS_BOUND message to trigger processing 1293 // of next pending install. 1294 mHandler.sendEmptyMessage(MCS_BOUND); 1295 } 1296 1297 break; 1298 } 1299 case MCS_GIVE_UP: { 1300 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1301 HandlerParams params = mPendingInstalls.remove(0); 1302 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1303 System.identityHashCode(params)); 1304 break; 1305 } 1306 case SEND_PENDING_BROADCAST: { 1307 String packages[]; 1308 ArrayList<String> components[]; 1309 int size = 0; 1310 int uids[]; 1311 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1312 synchronized (mPackages) { 1313 if (mPendingBroadcasts == null) { 1314 return; 1315 } 1316 size = mPendingBroadcasts.size(); 1317 if (size <= 0) { 1318 // Nothing to be done. Just return 1319 return; 1320 } 1321 packages = new String[size]; 1322 components = new ArrayList[size]; 1323 uids = new int[size]; 1324 int i = 0; // filling out the above arrays 1325 1326 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1327 int packageUserId = mPendingBroadcasts.userIdAt(n); 1328 Iterator<Map.Entry<String, ArrayList<String>>> it 1329 = mPendingBroadcasts.packagesForUserId(packageUserId) 1330 .entrySet().iterator(); 1331 while (it.hasNext() && i < size) { 1332 Map.Entry<String, ArrayList<String>> ent = it.next(); 1333 packages[i] = ent.getKey(); 1334 components[i] = ent.getValue(); 1335 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1336 uids[i] = (ps != null) 1337 ? UserHandle.getUid(packageUserId, ps.appId) 1338 : -1; 1339 i++; 1340 } 1341 } 1342 size = i; 1343 mPendingBroadcasts.clear(); 1344 } 1345 // Send broadcasts 1346 for (int i = 0; i < size; i++) { 1347 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1348 } 1349 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1350 break; 1351 } 1352 case START_CLEANING_PACKAGE: { 1353 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1354 final String packageName = (String)msg.obj; 1355 final int userId = msg.arg1; 1356 final boolean andCode = msg.arg2 != 0; 1357 synchronized (mPackages) { 1358 if (userId == UserHandle.USER_ALL) { 1359 int[] users = sUserManager.getUserIds(); 1360 for (int user : users) { 1361 mSettings.addPackageToCleanLPw( 1362 new PackageCleanItem(user, packageName, andCode)); 1363 } 1364 } else { 1365 mSettings.addPackageToCleanLPw( 1366 new PackageCleanItem(userId, packageName, andCode)); 1367 } 1368 } 1369 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1370 startCleaningPackages(); 1371 } break; 1372 case POST_INSTALL: { 1373 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1374 1375 PostInstallData data = mRunningInstalls.get(msg.arg1); 1376 mRunningInstalls.delete(msg.arg1); 1377 boolean deleteOld = false; 1378 1379 if (data != null) { 1380 InstallArgs args = data.args; 1381 PackageInstalledInfo res = data.res; 1382 1383 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1384 final String packageName = res.pkg.applicationInfo.packageName; 1385 res.removedInfo.sendBroadcast(false, true, false); 1386 Bundle extras = new Bundle(1); 1387 extras.putInt(Intent.EXTRA_UID, res.uid); 1388 1389 // Now that we successfully installed the package, grant runtime 1390 // permissions if requested before broadcasting the install. 1391 if ((args.installFlags 1392 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 1393 && res.pkg.applicationInfo.targetSdkVersion 1394 >= Build.VERSION_CODES.M) { 1395 grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(), 1396 args.installGrantPermissions); 1397 } 1398 1399 synchronized (mPackages) { 1400 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1401 } 1402 1403 // Determine the set of users who are adding this 1404 // package for the first time vs. those who are seeing 1405 // an update. 1406 int[] firstUsers; 1407 int[] updateUsers = new int[0]; 1408 if (res.origUsers == null || res.origUsers.length == 0) { 1409 firstUsers = res.newUsers; 1410 } else { 1411 firstUsers = new int[0]; 1412 for (int i=0; i<res.newUsers.length; i++) { 1413 int user = res.newUsers[i]; 1414 boolean isNew = true; 1415 for (int j=0; j<res.origUsers.length; j++) { 1416 if (res.origUsers[j] == user) { 1417 isNew = false; 1418 break; 1419 } 1420 } 1421 if (isNew) { 1422 int[] newFirst = new int[firstUsers.length+1]; 1423 System.arraycopy(firstUsers, 0, newFirst, 0, 1424 firstUsers.length); 1425 newFirst[firstUsers.length] = user; 1426 firstUsers = newFirst; 1427 } else { 1428 int[] newUpdate = new int[updateUsers.length+1]; 1429 System.arraycopy(updateUsers, 0, newUpdate, 0, 1430 updateUsers.length); 1431 newUpdate[updateUsers.length] = user; 1432 updateUsers = newUpdate; 1433 } 1434 } 1435 } 1436 // don't broadcast for ephemeral installs/updates 1437 final boolean isEphemeral = isEphemeral(res.pkg); 1438 if (!isEphemeral) { 1439 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1440 extras, 0 /*flags*/, null /*targetPackage*/, 1441 null /*finishedReceiver*/, firstUsers); 1442 } 1443 final boolean update = res.removedInfo.removedPackage != null; 1444 if (update) { 1445 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1446 } 1447 if (!isEphemeral) { 1448 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1449 extras, 0 /*flags*/, null /*targetPackage*/, 1450 null /*finishedReceiver*/, updateUsers); 1451 } 1452 if (update) { 1453 if (!isEphemeral) { 1454 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1455 packageName, extras, 0 /*flags*/, 1456 null /*targetPackage*/, null /*finishedReceiver*/, 1457 updateUsers); 1458 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1459 null /*package*/, null /*extras*/, 0 /*flags*/, 1460 packageName /*targetPackage*/, 1461 null /*finishedReceiver*/, updateUsers); 1462 } 1463 1464 // treat asec-hosted packages like removable media on upgrade 1465 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1466 if (DEBUG_INSTALL) { 1467 Slog.i(TAG, "upgrading pkg " + res.pkg 1468 + " is ASEC-hosted -> AVAILABLE"); 1469 } 1470 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1471 ArrayList<String> pkgList = new ArrayList<String>(1); 1472 pkgList.add(packageName); 1473 sendResourcesChangedBroadcast(true, true, 1474 pkgList,uidArray, null); 1475 } 1476 } 1477 if (res.removedInfo.args != null) { 1478 // Remove the replaced package's older resources safely now 1479 deleteOld = true; 1480 } 1481 1482 // If this app is a browser and it's newly-installed for some 1483 // users, clear any default-browser state in those users 1484 if (firstUsers.length > 0) { 1485 // the app's nature doesn't depend on the user, so we can just 1486 // check its browser nature in any user and generalize. 1487 if (packageIsBrowser(packageName, firstUsers[0])) { 1488 synchronized (mPackages) { 1489 for (int userId : firstUsers) { 1490 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1491 } 1492 } 1493 } 1494 } 1495 // Log current value of "unknown sources" setting 1496 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1497 getUnknownSourcesSettings()); 1498 } 1499 // Force a gc to clear up things 1500 Runtime.getRuntime().gc(); 1501 // We delete after a gc for applications on sdcard. 1502 if (deleteOld) { 1503 synchronized (mInstallLock) { 1504 res.removedInfo.args.doPostDeleteLI(true); 1505 } 1506 } 1507 if (args.observer != null) { 1508 try { 1509 Bundle extras = extrasForInstallResult(res); 1510 args.observer.onPackageInstalled(res.name, res.returnCode, 1511 res.returnMsg, extras); 1512 } catch (RemoteException e) { 1513 Slog.i(TAG, "Observer no longer exists."); 1514 } 1515 } 1516 if (args.traceMethod != null) { 1517 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1518 args.traceCookie); 1519 } 1520 return; 1521 } else { 1522 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1523 } 1524 1525 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1526 } break; 1527 case UPDATED_MEDIA_STATUS: { 1528 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1529 boolean reportStatus = msg.arg1 == 1; 1530 boolean doGc = msg.arg2 == 1; 1531 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1532 if (doGc) { 1533 // Force a gc to clear up stale containers. 1534 Runtime.getRuntime().gc(); 1535 } 1536 if (msg.obj != null) { 1537 @SuppressWarnings("unchecked") 1538 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1539 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1540 // Unload containers 1541 unloadAllContainers(args); 1542 } 1543 if (reportStatus) { 1544 try { 1545 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1546 PackageHelper.getMountService().finishMediaUpdate(); 1547 } catch (RemoteException e) { 1548 Log.e(TAG, "MountService not running?"); 1549 } 1550 } 1551 } break; 1552 case WRITE_SETTINGS: { 1553 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1554 synchronized (mPackages) { 1555 removeMessages(WRITE_SETTINGS); 1556 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1557 mSettings.writeLPr(); 1558 mDirtyUsers.clear(); 1559 } 1560 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1561 } break; 1562 case WRITE_PACKAGE_RESTRICTIONS: { 1563 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1564 synchronized (mPackages) { 1565 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1566 for (int userId : mDirtyUsers) { 1567 mSettings.writePackageRestrictionsLPr(userId); 1568 } 1569 mDirtyUsers.clear(); 1570 } 1571 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1572 } break; 1573 case CHECK_PENDING_VERIFICATION: { 1574 final int verificationId = msg.arg1; 1575 final PackageVerificationState state = mPendingVerification.get(verificationId); 1576 1577 if ((state != null) && !state.timeoutExtended()) { 1578 final InstallArgs args = state.getInstallArgs(); 1579 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1580 1581 Slog.i(TAG, "Verification timed out for " + originUri); 1582 mPendingVerification.remove(verificationId); 1583 1584 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1585 1586 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1587 Slog.i(TAG, "Continuing with installation of " + originUri); 1588 state.setVerifierResponse(Binder.getCallingUid(), 1589 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1590 broadcastPackageVerified(verificationId, originUri, 1591 PackageManager.VERIFICATION_ALLOW, 1592 state.getInstallArgs().getUser()); 1593 try { 1594 ret = args.copyApk(mContainerService, true); 1595 } catch (RemoteException e) { 1596 Slog.e(TAG, "Could not contact the ContainerService"); 1597 } 1598 } else { 1599 broadcastPackageVerified(verificationId, originUri, 1600 PackageManager.VERIFICATION_REJECT, 1601 state.getInstallArgs().getUser()); 1602 } 1603 1604 Trace.asyncTraceEnd( 1605 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1606 1607 processPendingInstall(args, ret); 1608 mHandler.sendEmptyMessage(MCS_UNBIND); 1609 } 1610 break; 1611 } 1612 case PACKAGE_VERIFIED: { 1613 final int verificationId = msg.arg1; 1614 1615 final PackageVerificationState state = mPendingVerification.get(verificationId); 1616 if (state == null) { 1617 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1618 break; 1619 } 1620 1621 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1622 1623 state.setVerifierResponse(response.callerUid, response.code); 1624 1625 if (state.isVerificationComplete()) { 1626 mPendingVerification.remove(verificationId); 1627 1628 final InstallArgs args = state.getInstallArgs(); 1629 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1630 1631 int ret; 1632 if (state.isInstallAllowed()) { 1633 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1634 broadcastPackageVerified(verificationId, originUri, 1635 response.code, state.getInstallArgs().getUser()); 1636 try { 1637 ret = args.copyApk(mContainerService, true); 1638 } catch (RemoteException e) { 1639 Slog.e(TAG, "Could not contact the ContainerService"); 1640 } 1641 } else { 1642 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1643 } 1644 1645 Trace.asyncTraceEnd( 1646 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1647 1648 processPendingInstall(args, ret); 1649 mHandler.sendEmptyMessage(MCS_UNBIND); 1650 } 1651 1652 break; 1653 } 1654 case START_INTENT_FILTER_VERIFICATIONS: { 1655 IFVerificationParams params = (IFVerificationParams) msg.obj; 1656 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1657 params.replacing, params.pkg); 1658 break; 1659 } 1660 case INTENT_FILTER_VERIFIED: { 1661 final int verificationId = msg.arg1; 1662 1663 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1664 verificationId); 1665 if (state == null) { 1666 Slog.w(TAG, "Invalid IntentFilter verification token " 1667 + verificationId + " received"); 1668 break; 1669 } 1670 1671 final int userId = state.getUserId(); 1672 1673 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1674 "Processing IntentFilter verification with token:" 1675 + verificationId + " and userId:" + userId); 1676 1677 final IntentFilterVerificationResponse response = 1678 (IntentFilterVerificationResponse) msg.obj; 1679 1680 state.setVerifierResponse(response.callerUid, response.code); 1681 1682 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1683 "IntentFilter verification with token:" + verificationId 1684 + " and userId:" + userId 1685 + " is settings verifier response with response code:" 1686 + response.code); 1687 1688 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1689 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1690 + response.getFailedDomainsString()); 1691 } 1692 1693 if (state.isVerificationComplete()) { 1694 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1695 } else { 1696 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1697 "IntentFilter verification with token:" + verificationId 1698 + " was not said to be complete"); 1699 } 1700 1701 break; 1702 } 1703 } 1704 } 1705 } 1706 1707 private StorageEventListener mStorageListener = new StorageEventListener() { 1708 @Override 1709 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1710 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1711 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1712 final String volumeUuid = vol.getFsUuid(); 1713 1714 // Clean up any users or apps that were removed or recreated 1715 // while this volume was missing 1716 reconcileUsers(volumeUuid); 1717 reconcileApps(volumeUuid); 1718 1719 // Clean up any install sessions that expired or were 1720 // cancelled while this volume was missing 1721 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1722 1723 loadPrivatePackages(vol); 1724 1725 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1726 unloadPrivatePackages(vol); 1727 } 1728 } 1729 1730 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1731 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1732 updateExternalMediaStatus(true, false); 1733 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1734 updateExternalMediaStatus(false, false); 1735 } 1736 } 1737 } 1738 1739 @Override 1740 public void onVolumeForgotten(String fsUuid) { 1741 if (TextUtils.isEmpty(fsUuid)) { 1742 Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1743 return; 1744 } 1745 1746 // Remove any apps installed on the forgotten volume 1747 synchronized (mPackages) { 1748 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1749 for (PackageSetting ps : packages) { 1750 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1751 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1752 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1753 } 1754 1755 mSettings.onVolumeForgotten(fsUuid); 1756 mSettings.writeLPr(); 1757 } 1758 } 1759 }; 1760 1761 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId, 1762 String[] grantedPermissions) { 1763 if (userId >= UserHandle.USER_SYSTEM) { 1764 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1765 } else if (userId == UserHandle.USER_ALL) { 1766 final int[] userIds; 1767 synchronized (mPackages) { 1768 userIds = UserManagerService.getInstance().getUserIds(); 1769 } 1770 for (int someUserId : userIds) { 1771 grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions); 1772 } 1773 } 1774 1775 // We could have touched GID membership, so flush out packages.list 1776 synchronized (mPackages) { 1777 mSettings.writePackageListLPr(); 1778 } 1779 } 1780 1781 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1782 String[] grantedPermissions) { 1783 SettingBase sb = (SettingBase) pkg.mExtras; 1784 if (sb == null) { 1785 return; 1786 } 1787 1788 PermissionsState permissionsState = sb.getPermissionsState(); 1789 1790 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 1791 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 1792 1793 synchronized (mPackages) { 1794 for (String permission : pkg.requestedPermissions) { 1795 BasePermission bp = mSettings.mPermissions.get(permission); 1796 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 1797 && (grantedPermissions == null 1798 || ArrayUtils.contains(grantedPermissions, permission))) { 1799 final int flags = permissionsState.getPermissionFlags(permission, userId); 1800 // Installer cannot change immutable permissions. 1801 if ((flags & immutableFlags) == 0) { 1802 grantRuntimePermission(pkg.packageName, permission, userId); 1803 } 1804 } 1805 } 1806 } 1807 } 1808 1809 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1810 Bundle extras = null; 1811 switch (res.returnCode) { 1812 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1813 extras = new Bundle(); 1814 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1815 res.origPermission); 1816 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1817 res.origPackage); 1818 break; 1819 } 1820 case PackageManager.INSTALL_SUCCEEDED: { 1821 extras = new Bundle(); 1822 extras.putBoolean(Intent.EXTRA_REPLACING, 1823 res.removedInfo != null && res.removedInfo.removedPackage != null); 1824 break; 1825 } 1826 } 1827 return extras; 1828 } 1829 1830 void scheduleWriteSettingsLocked() { 1831 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1832 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1833 } 1834 } 1835 1836 void scheduleWritePackageRestrictionsLocked(int userId) { 1837 if (!sUserManager.exists(userId)) return; 1838 mDirtyUsers.add(userId); 1839 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1840 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1841 } 1842 } 1843 1844 public static PackageManagerService main(Context context, Installer installer, 1845 boolean factoryTest, boolean onlyCore) { 1846 PackageManagerService m = new PackageManagerService(context, installer, 1847 factoryTest, onlyCore); 1848 m.enableSystemUserApps(); 1849 ServiceManager.addService("package", m); 1850 return m; 1851 } 1852 1853 private void enableSystemUserApps() { 1854 if (!UserManager.isSplitSystemUser()) { 1855 return; 1856 } 1857 // For system user, enable apps based on the following conditions: 1858 // - app is whitelisted or belong to one of these groups: 1859 // -- system app which has no launcher icons 1860 // -- system app which has INTERACT_ACROSS_USERS permission 1861 // -- system IME app 1862 // - app is not in the blacklist 1863 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 1864 Set<String> enableApps = new ArraySet<>(); 1865 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 1866 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 1867 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 1868 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 1869 enableApps.addAll(wlApps); 1870 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 1871 enableApps.removeAll(blApps); 1872 1873 List<String> systemApps = queryHelper.queryApps(0, /* systemAppsOnly */ true, 1874 UserHandle.SYSTEM); 1875 final int systemAppsSize = systemApps.size(); 1876 synchronized (mPackages) { 1877 for (int i = 0; i < systemAppsSize; i++) { 1878 String pName = systemApps.get(i); 1879 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 1880 // Should not happen, but we shouldn't be failing if it does 1881 if (pkgSetting == null) { 1882 continue; 1883 } 1884 boolean installed = enableApps.contains(pName); 1885 pkgSetting.setInstalled(installed, UserHandle.USER_SYSTEM); 1886 } 1887 } 1888 } 1889 1890 static String[] splitString(String str, char sep) { 1891 int count = 1; 1892 int i = 0; 1893 while ((i=str.indexOf(sep, i)) >= 0) { 1894 count++; 1895 i++; 1896 } 1897 1898 String[] res = new String[count]; 1899 i=0; 1900 count = 0; 1901 int lastI=0; 1902 while ((i=str.indexOf(sep, i)) >= 0) { 1903 res[count] = str.substring(lastI, i); 1904 count++; 1905 i++; 1906 lastI = i; 1907 } 1908 res[count] = str.substring(lastI, str.length()); 1909 return res; 1910 } 1911 1912 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1913 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1914 Context.DISPLAY_SERVICE); 1915 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1916 } 1917 1918 public PackageManagerService(Context context, Installer installer, 1919 boolean factoryTest, boolean onlyCore) { 1920 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1921 SystemClock.uptimeMillis()); 1922 1923 if (mSdkVersion <= 0) { 1924 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1925 } 1926 1927 mContext = context; 1928 mFactoryTest = factoryTest; 1929 mOnlyCore = onlyCore; 1930 mMetrics = new DisplayMetrics(); 1931 mSettings = new Settings(mPackages); 1932 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1933 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1934 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1935 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1936 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1937 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1938 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1939 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1940 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1941 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1942 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1943 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1944 1945 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1946 if (separateProcesses != null && separateProcesses.length() > 0) { 1947 if ("*".equals(separateProcesses)) { 1948 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1949 mSeparateProcesses = null; 1950 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1951 } else { 1952 mDefParseFlags = 0; 1953 mSeparateProcesses = separateProcesses.split(","); 1954 Slog.w(TAG, "Running with debug.separate_processes: " 1955 + separateProcesses); 1956 } 1957 } else { 1958 mDefParseFlags = 0; 1959 mSeparateProcesses = null; 1960 } 1961 1962 mInstaller = installer; 1963 mPackageDexOptimizer = new PackageDexOptimizer(this); 1964 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1965 1966 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 1967 FgThread.get().getLooper()); 1968 1969 getDefaultDisplayMetrics(context, mMetrics); 1970 1971 SystemConfig systemConfig = SystemConfig.getInstance(); 1972 mGlobalGids = systemConfig.getGlobalGids(); 1973 mSystemPermissions = systemConfig.getSystemPermissions(); 1974 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1975 1976 synchronized (mInstallLock) { 1977 // writer 1978 synchronized (mPackages) { 1979 mHandlerThread = new ServiceThread(TAG, 1980 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1981 mHandlerThread.start(); 1982 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1983 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1984 1985 File dataDir = Environment.getDataDirectory(); 1986 mAppInstallDir = new File(dataDir, "app"); 1987 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1988 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 1989 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1990 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1991 1992 sUserManager = new UserManagerService(context, this, mPackages); 1993 1994 // Propagate permission configuration in to package manager. 1995 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1996 = systemConfig.getPermissions(); 1997 for (int i=0; i<permConfig.size(); i++) { 1998 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1999 BasePermission bp = mSettings.mPermissions.get(perm.name); 2000 if (bp == null) { 2001 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2002 mSettings.mPermissions.put(perm.name, bp); 2003 } 2004 if (perm.gids != null) { 2005 bp.setGids(perm.gids, perm.perUser); 2006 } 2007 } 2008 2009 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2010 for (int i=0; i<libConfig.size(); i++) { 2011 mSharedLibraries.put(libConfig.keyAt(i), 2012 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2013 } 2014 2015 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2016 2017 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 2018 2019 String customResolverActivity = Resources.getSystem().getString( 2020 R.string.config_customResolverActivity); 2021 if (TextUtils.isEmpty(customResolverActivity)) { 2022 customResolverActivity = null; 2023 } else { 2024 mCustomResolverComponentName = ComponentName.unflattenFromString( 2025 customResolverActivity); 2026 } 2027 2028 long startTime = SystemClock.uptimeMillis(); 2029 2030 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2031 startTime); 2032 2033 // Set flag to monitor and not change apk file paths when 2034 // scanning install directories. 2035 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2036 2037 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2038 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2039 2040 if (bootClassPath == null) { 2041 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2042 } 2043 2044 if (systemServerClassPath == null) { 2045 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2046 } 2047 2048 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2049 final String[] dexCodeInstructionSets = 2050 getDexCodeInstructionSets( 2051 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2052 2053 /** 2054 * Ensure all external libraries have had dexopt run on them. 2055 */ 2056 if (mSharedLibraries.size() > 0) { 2057 // NOTE: For now, we're compiling these system "shared libraries" 2058 // (and framework jars) into all available architectures. It's possible 2059 // to compile them only when we come across an app that uses them (there's 2060 // already logic for that in scanPackageLI) but that adds some complexity. 2061 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2062 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2063 final String lib = libEntry.path; 2064 if (lib == null) { 2065 continue; 2066 } 2067 2068 try { 2069 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 2070 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2071 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2072 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/); 2073 } 2074 } catch (FileNotFoundException e) { 2075 Slog.w(TAG, "Library not found: " + lib); 2076 } catch (IOException e) { 2077 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2078 + e.getMessage()); 2079 } 2080 } 2081 } 2082 } 2083 2084 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2085 2086 final VersionInfo ver = mSettings.getInternalVersion(); 2087 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2088 // when upgrading from pre-M, promote system app permissions from install to runtime 2089 mPromoteSystemApps = 2090 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2091 2092 // save off the names of pre-existing system packages prior to scanning; we don't 2093 // want to automatically grant runtime permissions for new system apps 2094 if (mPromoteSystemApps) { 2095 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2096 while (pkgSettingIter.hasNext()) { 2097 PackageSetting ps = pkgSettingIter.next(); 2098 if (isSystemApp(ps)) { 2099 mExistingSystemPackages.add(ps.name); 2100 } 2101 } 2102 } 2103 2104 // Collect vendor overlay packages. 2105 // (Do this before scanning any apps.) 2106 // For security and version matching reason, only consider 2107 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2108 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2109 scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2110 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2111 2112 // Find base frameworks (resource packages without code). 2113 scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2114 | PackageParser.PARSE_IS_SYSTEM_DIR 2115 | PackageParser.PARSE_IS_PRIVILEGED, 2116 scanFlags | SCAN_NO_DEX, 0); 2117 2118 // Collected privileged system packages. 2119 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2120 scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2121 | PackageParser.PARSE_IS_SYSTEM_DIR 2122 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2123 2124 // Collect ordinary system packages. 2125 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2126 scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2127 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2128 2129 // Collect all vendor packages. 2130 File vendorAppDir = new File("/vendor/app"); 2131 try { 2132 vendorAppDir = vendorAppDir.getCanonicalFile(); 2133 } catch (IOException e) { 2134 // failed to look up canonical path, continue with original one 2135 } 2136 scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2137 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2138 2139 // Collect all OEM packages. 2140 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2141 scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2142 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2143 2144 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 2145 mInstaller.moveFiles(); 2146 2147 // Prune any system packages that no longer exist. 2148 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2149 if (!mOnlyCore) { 2150 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2151 while (psit.hasNext()) { 2152 PackageSetting ps = psit.next(); 2153 2154 /* 2155 * If this is not a system app, it can't be a 2156 * disable system app. 2157 */ 2158 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2159 continue; 2160 } 2161 2162 /* 2163 * If the package is scanned, it's not erased. 2164 */ 2165 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2166 if (scannedPkg != null) { 2167 /* 2168 * If the system app is both scanned and in the 2169 * disabled packages list, then it must have been 2170 * added via OTA. Remove it from the currently 2171 * scanned package so the previously user-installed 2172 * application can be scanned. 2173 */ 2174 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2175 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2176 + ps.name + "; removing system app. Last known codePath=" 2177 + ps.codePathString + ", installStatus=" + ps.installStatus 2178 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2179 + scannedPkg.mVersionCode); 2180 removePackageLI(ps, true); 2181 mExpectingBetter.put(ps.name, ps.codePath); 2182 } 2183 2184 continue; 2185 } 2186 2187 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2188 psit.remove(); 2189 logCriticalInfo(Log.WARN, "System package " + ps.name 2190 + " no longer exists; wiping its data"); 2191 removeDataDirsLI(null, ps.name); 2192 } else { 2193 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2194 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2195 possiblyDeletedUpdatedSystemApps.add(ps.name); 2196 } 2197 } 2198 } 2199 } 2200 2201 //look for any incomplete package installations 2202 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2203 //clean up list 2204 for(int i = 0; i < deletePkgsList.size(); i++) { 2205 //clean up here 2206 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2207 } 2208 //delete tmp files 2209 deleteTempPackageFiles(); 2210 2211 // Remove any shared userIDs that have no associated packages 2212 mSettings.pruneSharedUsersLPw(); 2213 2214 if (!mOnlyCore) { 2215 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2216 SystemClock.uptimeMillis()); 2217 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2218 2219 scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2220 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2221 2222 scanDirLI(mEphemeralInstallDir, PackageParser.PARSE_IS_EPHEMERAL, 2223 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2224 2225 /** 2226 * Remove disable package settings for any updated system 2227 * apps that were removed via an OTA. If they're not a 2228 * previously-updated app, remove them completely. 2229 * Otherwise, just revoke their system-level permissions. 2230 */ 2231 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2232 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2233 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2234 2235 String msg; 2236 if (deletedPkg == null) { 2237 msg = "Updated system package " + deletedAppName 2238 + " no longer exists; wiping its data"; 2239 removeDataDirsLI(null, deletedAppName); 2240 } else { 2241 msg = "Updated system app + " + deletedAppName 2242 + " no longer present; removing system privileges for " 2243 + deletedAppName; 2244 2245 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2246 2247 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2248 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2249 } 2250 logCriticalInfo(Log.WARN, msg); 2251 } 2252 2253 /** 2254 * Make sure all system apps that we expected to appear on 2255 * the userdata partition actually showed up. If they never 2256 * appeared, crawl back and revive the system version. 2257 */ 2258 for (int i = 0; i < mExpectingBetter.size(); i++) { 2259 final String packageName = mExpectingBetter.keyAt(i); 2260 if (!mPackages.containsKey(packageName)) { 2261 final File scanFile = mExpectingBetter.valueAt(i); 2262 2263 logCriticalInfo(Log.WARN, "Expected better " + packageName 2264 + " but never showed up; reverting to system"); 2265 2266 final int reparseFlags; 2267 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2268 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2269 | PackageParser.PARSE_IS_SYSTEM_DIR 2270 | PackageParser.PARSE_IS_PRIVILEGED; 2271 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2272 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2273 | PackageParser.PARSE_IS_SYSTEM_DIR; 2274 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2275 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2276 | PackageParser.PARSE_IS_SYSTEM_DIR; 2277 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2278 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2279 | PackageParser.PARSE_IS_SYSTEM_DIR; 2280 } else { 2281 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2282 continue; 2283 } 2284 2285 mSettings.enableSystemPackageLPw(packageName); 2286 2287 try { 2288 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2289 } catch (PackageManagerException e) { 2290 Slog.e(TAG, "Failed to parse original system package: " 2291 + e.getMessage()); 2292 } 2293 } 2294 } 2295 } 2296 mExpectingBetter.clear(); 2297 2298 // Now that we know all of the shared libraries, update all clients to have 2299 // the correct library paths. 2300 updateAllSharedLibrariesLPw(); 2301 2302 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2303 // NOTE: We ignore potential failures here during a system scan (like 2304 // the rest of the commands above) because there's precious little we 2305 // can do about it. A settings error is reported, though. 2306 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2307 false /* boot complete */); 2308 } 2309 2310 // Now that we know all the packages we are keeping, 2311 // read and update their last usage times. 2312 mPackageUsage.readLP(); 2313 2314 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2315 SystemClock.uptimeMillis()); 2316 Slog.i(TAG, "Time to scan packages: " 2317 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2318 + " seconds"); 2319 2320 // If the platform SDK has changed since the last time we booted, 2321 // we need to re-grant app permission to catch any new ones that 2322 // appear. This is really a hack, and means that apps can in some 2323 // cases get permissions that the user didn't initially explicitly 2324 // allow... it would be nice to have some better way to handle 2325 // this situation. 2326 int updateFlags = UPDATE_PERMISSIONS_ALL; 2327 if (ver.sdkVersion != mSdkVersion) { 2328 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2329 + mSdkVersion + "; regranting permissions for internal storage"); 2330 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2331 } 2332 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2333 ver.sdkVersion = mSdkVersion; 2334 2335 // If this is the first boot or an update from pre-M, and it is a normal 2336 // boot, then we need to initialize the default preferred apps across 2337 // all defined users. 2338 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2339 for (UserInfo user : sUserManager.getUsers(true)) { 2340 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2341 applyFactoryDefaultBrowserLPw(user.id); 2342 primeDomainVerificationsLPw(user.id); 2343 } 2344 } 2345 2346 // If this is first boot after an OTA, and a normal boot, then 2347 // we need to clear code cache directories. 2348 if (mIsUpgrade && !onlyCore) { 2349 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2350 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2351 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2352 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2353 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2354 } 2355 } 2356 ver.fingerprint = Build.FINGERPRINT; 2357 } 2358 2359 checkDefaultBrowser(); 2360 2361 // clear only after permissions and other defaults have been updated 2362 mExistingSystemPackages.clear(); 2363 mPromoteSystemApps = false; 2364 2365 // All the changes are done during package scanning. 2366 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2367 2368 // can downgrade to reader 2369 mSettings.writeLPr(); 2370 2371 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2372 SystemClock.uptimeMillis()); 2373 2374 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2375 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2376 2377 mInstallerService = new PackageInstallerService(context, this); 2378 2379 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2380 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2381 mIntentFilterVerifierComponent); 2382 2383 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2384 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2385 // both the installer and resolver must be present to enable ephemeral 2386 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2387 if (DEBUG_EPHEMERAL) { 2388 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2389 + " installer:" + ephemeralInstallerComponent); 2390 } 2391 mEphemeralResolverComponent = ephemeralResolverComponent; 2392 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2393 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2394 mEphemeralResolverConnection = 2395 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2396 } else { 2397 if (DEBUG_EPHEMERAL) { 2398 final String missingComponent = 2399 (ephemeralResolverComponent == null) 2400 ? (ephemeralInstallerComponent == null) 2401 ? "resolver and installer" 2402 : "resolver" 2403 : "installer"; 2404 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2405 } 2406 mEphemeralResolverComponent = null; 2407 mEphemeralInstallerComponent = null; 2408 mEphemeralResolverConnection = null; 2409 } 2410 2411 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2412 } // synchronized (mPackages) 2413 } // synchronized (mInstallLock) 2414 2415 // Now after opening every single application zip, make sure they 2416 // are all flushed. Not really needed, but keeps things nice and 2417 // tidy. 2418 Runtime.getRuntime().gc(); 2419 2420 // The initial scanning above does many calls into installd while 2421 // holding the mPackages lock, but we're mostly interested in yelling 2422 // once we have a booted system. 2423 mInstaller.setWarnIfHeld(mPackages); 2424 2425 // Expose private service for system components to use. 2426 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2427 } 2428 2429 @Override 2430 public boolean isFirstBoot() { 2431 return !mRestoredSettings; 2432 } 2433 2434 @Override 2435 public boolean isOnlyCoreApps() { 2436 return mOnlyCore; 2437 } 2438 2439 @Override 2440 public boolean isUpgrade() { 2441 return mIsUpgrade; 2442 } 2443 2444 private String getRequiredVerifierLPr() { 2445 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2446 // We only care about verifier that's installed under system user. 2447 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2448 PackageManager.GET_DISABLED_COMPONENTS, UserHandle.USER_SYSTEM); 2449 2450 String requiredVerifier = null; 2451 2452 final int N = receivers.size(); 2453 for (int i = 0; i < N; i++) { 2454 final ResolveInfo info = receivers.get(i); 2455 2456 if (info.activityInfo == null) { 2457 continue; 2458 } 2459 2460 final String packageName = info.activityInfo.packageName; 2461 2462 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2463 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2464 continue; 2465 } 2466 2467 if (requiredVerifier != null) { 2468 throw new RuntimeException("There can be only one required verifier"); 2469 } 2470 2471 requiredVerifier = packageName; 2472 } 2473 2474 return requiredVerifier; 2475 } 2476 2477 private String getRequiredInstallerLPr() { 2478 Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2479 installerIntent.addCategory(Intent.CATEGORY_DEFAULT); 2480 installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2481 2482 final List<ResolveInfo> installers = queryIntentActivities(installerIntent, 2483 PACKAGE_MIME_TYPE, 0, UserHandle.USER_SYSTEM); 2484 2485 String requiredInstaller = null; 2486 2487 final int N = installers.size(); 2488 for (int i = 0; i < N; i++) { 2489 final ResolveInfo info = installers.get(i); 2490 final String packageName = info.activityInfo.packageName; 2491 2492 if (!info.activityInfo.applicationInfo.isSystemApp()) { 2493 continue; 2494 } 2495 2496 if (requiredInstaller != null) { 2497 throw new RuntimeException("There must be one required installer"); 2498 } 2499 2500 requiredInstaller = packageName; 2501 } 2502 2503 if (requiredInstaller == null) { 2504 throw new RuntimeException("There must be one required installer"); 2505 } 2506 2507 return requiredInstaller; 2508 } 2509 2510 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2511 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2512 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2513 PackageManager.GET_DISABLED_COMPONENTS, UserHandle.USER_SYSTEM); 2514 2515 ComponentName verifierComponentName = null; 2516 2517 int priority = -1000; 2518 final int N = receivers.size(); 2519 for (int i = 0; i < N; i++) { 2520 final ResolveInfo info = receivers.get(i); 2521 2522 if (info.activityInfo == null) { 2523 continue; 2524 } 2525 2526 final String packageName = info.activityInfo.packageName; 2527 2528 final PackageSetting ps = mSettings.mPackages.get(packageName); 2529 if (ps == null) { 2530 continue; 2531 } 2532 2533 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2534 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2535 continue; 2536 } 2537 2538 // Select the IntentFilterVerifier with the highest priority 2539 if (priority < info.priority) { 2540 priority = info.priority; 2541 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2542 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: " 2543 + verifierComponentName + " with priority: " + info.priority); 2544 } 2545 } 2546 2547 return verifierComponentName; 2548 } 2549 2550 private ComponentName getEphemeralResolverLPr() { 2551 final String[] packageArray = 2552 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2553 if (packageArray.length == 0) { 2554 if (DEBUG_EPHEMERAL) { 2555 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2556 } 2557 return null; 2558 } 2559 2560 Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2561 final List<ResolveInfo> resolvers = queryIntentServices(resolverIntent, 2562 null /*resolvedType*/, 0 /*flags*/, UserHandle.USER_SYSTEM); 2563 2564 final int N = resolvers.size(); 2565 if (N == 0) { 2566 if (DEBUG_EPHEMERAL) { 2567 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2568 } 2569 return null; 2570 } 2571 2572 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2573 for (int i = 0; i < N; i++) { 2574 final ResolveInfo info = resolvers.get(i); 2575 2576 if (info.serviceInfo == null) { 2577 continue; 2578 } 2579 2580 final String packageName = info.serviceInfo.packageName; 2581 if (!possiblePackages.contains(packageName)) { 2582 if (DEBUG_EPHEMERAL) { 2583 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2584 + " pkg: " + packageName + ", info:" + info); 2585 } 2586 continue; 2587 } 2588 2589 if (DEBUG_EPHEMERAL) { 2590 Slog.v(TAG, "Ephemeral resolver found;" 2591 + " pkg: " + packageName + ", info:" + info); 2592 } 2593 return new ComponentName(packageName, info.serviceInfo.name); 2594 } 2595 if (DEBUG_EPHEMERAL) { 2596 Slog.v(TAG, "Ephemeral resolver NOT found"); 2597 } 2598 return null; 2599 } 2600 2601 private ComponentName getEphemeralInstallerLPr() { 2602 Intent installerIntent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2603 installerIntent.addCategory(Intent.CATEGORY_DEFAULT); 2604 installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2605 final List<ResolveInfo> installers = queryIntentActivities(installerIntent, 2606 PACKAGE_MIME_TYPE, 0 /*flags*/, 0 /*userId*/); 2607 2608 ComponentName ephemeralInstaller = null; 2609 2610 final int N = installers.size(); 2611 for (int i = 0; i < N; i++) { 2612 final ResolveInfo info = installers.get(i); 2613 final String packageName = info.activityInfo.packageName; 2614 2615 if (!info.activityInfo.applicationInfo.isSystemApp()) { 2616 if (DEBUG_EPHEMERAL) { 2617 Slog.d(TAG, "Ephemeral installer is not system app;" 2618 + " pkg: " + packageName + ", info:" + info); 2619 } 2620 continue; 2621 } 2622 2623 if (ephemeralInstaller != null) { 2624 throw new RuntimeException("There must only be one ephemeral installer"); 2625 } 2626 2627 ephemeralInstaller = new ComponentName(packageName, info.activityInfo.name); 2628 } 2629 2630 return ephemeralInstaller; 2631 } 2632 2633 private void primeDomainVerificationsLPw(int userId) { 2634 if (DEBUG_DOMAIN_VERIFICATION) { 2635 Slog.d(TAG, "Priming domain verifications in user " + userId); 2636 } 2637 2638 SystemConfig systemConfig = SystemConfig.getInstance(); 2639 ArraySet<String> packages = systemConfig.getLinkedApps(); 2640 ArraySet<String> domains = new ArraySet<String>(); 2641 2642 for (String packageName : packages) { 2643 PackageParser.Package pkg = mPackages.get(packageName); 2644 if (pkg != null) { 2645 if (!pkg.isSystemApp()) { 2646 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2647 continue; 2648 } 2649 2650 domains.clear(); 2651 for (PackageParser.Activity a : pkg.activities) { 2652 for (ActivityIntentInfo filter : a.intents) { 2653 if (hasValidDomains(filter)) { 2654 domains.addAll(filter.getHostsList()); 2655 } 2656 } 2657 } 2658 2659 if (domains.size() > 0) { 2660 if (DEBUG_DOMAIN_VERIFICATION) { 2661 Slog.v(TAG, " + " + packageName); 2662 } 2663 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2664 // state w.r.t. the formal app-linkage "no verification attempted" state; 2665 // and then 'always' in the per-user state actually used for intent resolution. 2666 final IntentFilterVerificationInfo ivi; 2667 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2668 new ArrayList<String>(domains)); 2669 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2670 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2671 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2672 } else { 2673 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2674 + "' does not handle web links"); 2675 } 2676 } else { 2677 Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>"); 2678 } 2679 } 2680 2681 scheduleWritePackageRestrictionsLocked(userId); 2682 scheduleWriteSettingsLocked(); 2683 } 2684 2685 private void applyFactoryDefaultBrowserLPw(int userId) { 2686 // The default browser app's package name is stored in a string resource, 2687 // with a product-specific overlay used for vendor customization. 2688 String browserPkg = mContext.getResources().getString( 2689 com.android.internal.R.string.default_browser); 2690 if (!TextUtils.isEmpty(browserPkg)) { 2691 // non-empty string => required to be a known package 2692 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2693 if (ps == null) { 2694 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2695 browserPkg = null; 2696 } else { 2697 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2698 } 2699 } 2700 2701 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2702 // default. If there's more than one, just leave everything alone. 2703 if (browserPkg == null) { 2704 calculateDefaultBrowserLPw(userId); 2705 } 2706 } 2707 2708 private void calculateDefaultBrowserLPw(int userId) { 2709 List<String> allBrowsers = resolveAllBrowserApps(userId); 2710 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2711 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2712 } 2713 2714 private List<String> resolveAllBrowserApps(int userId) { 2715 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2716 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2717 PackageManager.MATCH_ALL, userId); 2718 2719 final int count = list.size(); 2720 List<String> result = new ArrayList<String>(count); 2721 for (int i=0; i<count; i++) { 2722 ResolveInfo info = list.get(i); 2723 if (info.activityInfo == null 2724 || !info.handleAllWebDataURI 2725 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2726 || result.contains(info.activityInfo.packageName)) { 2727 continue; 2728 } 2729 result.add(info.activityInfo.packageName); 2730 } 2731 2732 return result; 2733 } 2734 2735 private boolean packageIsBrowser(String packageName, int userId) { 2736 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2737 PackageManager.MATCH_ALL, userId); 2738 final int N = list.size(); 2739 for (int i = 0; i < N; i++) { 2740 ResolveInfo info = list.get(i); 2741 if (packageName.equals(info.activityInfo.packageName)) { 2742 return true; 2743 } 2744 } 2745 return false; 2746 } 2747 2748 private void checkDefaultBrowser() { 2749 final int myUserId = UserHandle.myUserId(); 2750 final String packageName = getDefaultBrowserPackageName(myUserId); 2751 if (packageName != null) { 2752 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2753 if (info == null) { 2754 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2755 synchronized (mPackages) { 2756 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2757 } 2758 } 2759 } 2760 } 2761 2762 @Override 2763 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2764 throws RemoteException { 2765 try { 2766 return super.onTransact(code, data, reply, flags); 2767 } catch (RuntimeException e) { 2768 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2769 Slog.wtf(TAG, "Package Manager Crash", e); 2770 } 2771 throw e; 2772 } 2773 } 2774 2775 void cleanupInstallFailedPackage(PackageSetting ps) { 2776 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2777 2778 removeDataDirsLI(ps.volumeUuid, ps.name); 2779 if (ps.codePath != null) { 2780 if (ps.codePath.isDirectory()) { 2781 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2782 } else { 2783 ps.codePath.delete(); 2784 } 2785 } 2786 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2787 if (ps.resourcePath.isDirectory()) { 2788 FileUtils.deleteContents(ps.resourcePath); 2789 } 2790 ps.resourcePath.delete(); 2791 } 2792 mSettings.removePackageLPw(ps.name); 2793 } 2794 2795 static int[] appendInts(int[] cur, int[] add) { 2796 if (add == null) return cur; 2797 if (cur == null) return add; 2798 final int N = add.length; 2799 for (int i=0; i<N; i++) { 2800 cur = appendInt(cur, add[i]); 2801 } 2802 return cur; 2803 } 2804 2805 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2806 if (!sUserManager.exists(userId)) return null; 2807 final PackageSetting ps = (PackageSetting) p.mExtras; 2808 if (ps == null) { 2809 return null; 2810 } 2811 2812 final PermissionsState permissionsState = ps.getPermissionsState(); 2813 2814 final int[] gids = permissionsState.computeGids(userId); 2815 final Set<String> permissions = permissionsState.getPermissions(userId); 2816 final PackageUserState state = ps.readUserState(userId); 2817 2818 return PackageParser.generatePackageInfo(p, gids, flags, 2819 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2820 } 2821 2822 @Override 2823 public void checkPackageStartable(String packageName, int userId) { 2824 final boolean userKeyUnlocked = isUserKeyUnlocked(userId); 2825 2826 synchronized (mPackages) { 2827 final PackageSetting ps = mSettings.mPackages.get(packageName); 2828 if (ps == null) { 2829 throw new SecurityException("Package " + packageName + " was not found!"); 2830 } 2831 2832 if (ps.frozen) { 2833 throw new SecurityException("Package " + packageName + " is currently frozen!"); 2834 } 2835 2836 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isEncryptionAware() 2837 || ps.pkg.applicationInfo.isPartiallyEncryptionAware())) { 2838 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 2839 } 2840 } 2841 } 2842 2843 @Override 2844 public boolean isPackageAvailable(String packageName, int userId) { 2845 if (!sUserManager.exists(userId)) return false; 2846 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2847 synchronized (mPackages) { 2848 PackageParser.Package p = mPackages.get(packageName); 2849 if (p != null) { 2850 final PackageSetting ps = (PackageSetting) p.mExtras; 2851 if (ps != null) { 2852 final PackageUserState state = ps.readUserState(userId); 2853 if (state != null) { 2854 return PackageParser.isAvailable(state); 2855 } 2856 } 2857 } 2858 } 2859 return false; 2860 } 2861 2862 @Override 2863 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2864 if (!sUserManager.exists(userId)) return null; 2865 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2866 // reader 2867 synchronized (mPackages) { 2868 PackageParser.Package p = mPackages.get(packageName); 2869 if (DEBUG_PACKAGE_INFO) 2870 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2871 if (p != null) { 2872 return generatePackageInfo(p, flags, userId); 2873 } 2874 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2875 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2876 } 2877 } 2878 return null; 2879 } 2880 2881 @Override 2882 public String[] currentToCanonicalPackageNames(String[] names) { 2883 String[] out = new String[names.length]; 2884 // reader 2885 synchronized (mPackages) { 2886 for (int i=names.length-1; i>=0; i--) { 2887 PackageSetting ps = mSettings.mPackages.get(names[i]); 2888 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2889 } 2890 } 2891 return out; 2892 } 2893 2894 @Override 2895 public String[] canonicalToCurrentPackageNames(String[] names) { 2896 String[] out = new String[names.length]; 2897 // reader 2898 synchronized (mPackages) { 2899 for (int i=names.length-1; i>=0; i--) { 2900 String cur = mSettings.mRenamedPackages.get(names[i]); 2901 out[i] = cur != null ? cur : names[i]; 2902 } 2903 } 2904 return out; 2905 } 2906 2907 @Override 2908 public int getPackageUid(String packageName, int userId) { 2909 return getPackageUidEtc(packageName, 0, userId); 2910 } 2911 2912 @Override 2913 public int getPackageUidEtc(String packageName, int flags, int userId) { 2914 if (!sUserManager.exists(userId)) return -1; 2915 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2916 2917 // reader 2918 synchronized (mPackages) { 2919 final PackageParser.Package p = mPackages.get(packageName); 2920 if (p != null) { 2921 return UserHandle.getUid(userId, p.applicationInfo.uid); 2922 } 2923 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2924 final PackageSetting ps = mSettings.mPackages.get(packageName); 2925 if (ps != null) { 2926 return UserHandle.getUid(userId, ps.appId); 2927 } 2928 } 2929 } 2930 2931 return -1; 2932 } 2933 2934 @Override 2935 public int[] getPackageGids(String packageName, int userId) { 2936 return getPackageGidsEtc(packageName, 0, userId); 2937 } 2938 2939 @Override 2940 public int[] getPackageGidsEtc(String packageName, int flags, int userId) { 2941 if (!sUserManager.exists(userId)) { 2942 return null; 2943 } 2944 2945 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2946 "getPackageGids"); 2947 2948 // reader 2949 synchronized (mPackages) { 2950 final PackageParser.Package p = mPackages.get(packageName); 2951 if (p != null) { 2952 PackageSetting ps = (PackageSetting) p.mExtras; 2953 return ps.getPermissionsState().computeGids(userId); 2954 } 2955 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2956 final PackageSetting ps = mSettings.mPackages.get(packageName); 2957 if (ps != null) { 2958 return ps.getPermissionsState().computeGids(userId); 2959 } 2960 } 2961 } 2962 2963 return null; 2964 } 2965 2966 static PermissionInfo generatePermissionInfo( 2967 BasePermission bp, int flags) { 2968 if (bp.perm != null) { 2969 return PackageParser.generatePermissionInfo(bp.perm, flags); 2970 } 2971 PermissionInfo pi = new PermissionInfo(); 2972 pi.name = bp.name; 2973 pi.packageName = bp.sourcePackage; 2974 pi.nonLocalizedLabel = bp.name; 2975 pi.protectionLevel = bp.protectionLevel; 2976 return pi; 2977 } 2978 2979 @Override 2980 public PermissionInfo getPermissionInfo(String name, int flags) { 2981 // reader 2982 synchronized (mPackages) { 2983 final BasePermission p = mSettings.mPermissions.get(name); 2984 if (p != null) { 2985 return generatePermissionInfo(p, flags); 2986 } 2987 return null; 2988 } 2989 } 2990 2991 @Override 2992 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2993 // reader 2994 synchronized (mPackages) { 2995 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2996 for (BasePermission p : mSettings.mPermissions.values()) { 2997 if (group == null) { 2998 if (p.perm == null || p.perm.info.group == null) { 2999 out.add(generatePermissionInfo(p, flags)); 3000 } 3001 } else { 3002 if (p.perm != null && group.equals(p.perm.info.group)) { 3003 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3004 } 3005 } 3006 } 3007 3008 if (out.size() > 0) { 3009 return out; 3010 } 3011 return mPermissionGroups.containsKey(group) ? out : null; 3012 } 3013 } 3014 3015 @Override 3016 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3017 // reader 3018 synchronized (mPackages) { 3019 return PackageParser.generatePermissionGroupInfo( 3020 mPermissionGroups.get(name), flags); 3021 } 3022 } 3023 3024 @Override 3025 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3026 // reader 3027 synchronized (mPackages) { 3028 final int N = mPermissionGroups.size(); 3029 ArrayList<PermissionGroupInfo> out 3030 = new ArrayList<PermissionGroupInfo>(N); 3031 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3032 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3033 } 3034 return out; 3035 } 3036 } 3037 3038 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3039 int userId) { 3040 if (!sUserManager.exists(userId)) return null; 3041 PackageSetting ps = mSettings.mPackages.get(packageName); 3042 if (ps != null) { 3043 if (ps.pkg == null) { 3044 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 3045 flags, userId); 3046 if (pInfo != null) { 3047 return pInfo.applicationInfo; 3048 } 3049 return null; 3050 } 3051 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3052 ps.readUserState(userId), userId); 3053 } 3054 return null; 3055 } 3056 3057 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 3058 int userId) { 3059 if (!sUserManager.exists(userId)) return null; 3060 PackageSetting ps = mSettings.mPackages.get(packageName); 3061 if (ps != null) { 3062 PackageParser.Package pkg = ps.pkg; 3063 if (pkg == null) { 3064 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 3065 return null; 3066 } 3067 // Only data remains, so we aren't worried about code paths 3068 pkg = new PackageParser.Package(packageName); 3069 pkg.applicationInfo.packageName = packageName; 3070 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 3071 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 3072 pkg.applicationInfo.uid = ps.appId; 3073 pkg.applicationInfo.initForUser(userId); 3074 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 3075 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 3076 } 3077 return generatePackageInfo(pkg, flags, userId); 3078 } 3079 return null; 3080 } 3081 3082 @Override 3083 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3084 if (!sUserManager.exists(userId)) return null; 3085 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 3086 // writer 3087 synchronized (mPackages) { 3088 PackageParser.Package p = mPackages.get(packageName); 3089 if (DEBUG_PACKAGE_INFO) Log.v( 3090 TAG, "getApplicationInfo " + packageName 3091 + ": " + p); 3092 if (p != null) { 3093 PackageSetting ps = mSettings.mPackages.get(packageName); 3094 if (ps == null) return null; 3095 // Note: isEnabledLP() does not apply here - always return info 3096 return PackageParser.generateApplicationInfo( 3097 p, flags, ps.readUserState(userId), userId); 3098 } 3099 if ("android".equals(packageName)||"system".equals(packageName)) { 3100 return mAndroidApplication; 3101 } 3102 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 3103 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3104 } 3105 } 3106 return null; 3107 } 3108 3109 @Override 3110 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3111 final IPackageDataObserver observer) { 3112 mContext.enforceCallingOrSelfPermission( 3113 android.Manifest.permission.CLEAR_APP_CACHE, null); 3114 // Queue up an async operation since clearing cache may take a little while. 3115 mHandler.post(new Runnable() { 3116 public void run() { 3117 mHandler.removeCallbacks(this); 3118 int retCode = -1; 3119 synchronized (mInstallLock) { 3120 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 3121 if (retCode < 0) { 3122 Slog.w(TAG, "Couldn't clear application caches"); 3123 } 3124 } 3125 if (observer != null) { 3126 try { 3127 observer.onRemoveCompleted(null, (retCode >= 0)); 3128 } catch (RemoteException e) { 3129 Slog.w(TAG, "RemoveException when invoking call back"); 3130 } 3131 } 3132 } 3133 }); 3134 } 3135 3136 @Override 3137 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3138 final IntentSender pi) { 3139 mContext.enforceCallingOrSelfPermission( 3140 android.Manifest.permission.CLEAR_APP_CACHE, null); 3141 // Queue up an async operation since clearing cache may take a little while. 3142 mHandler.post(new Runnable() { 3143 public void run() { 3144 mHandler.removeCallbacks(this); 3145 int retCode = -1; 3146 synchronized (mInstallLock) { 3147 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 3148 if (retCode < 0) { 3149 Slog.w(TAG, "Couldn't clear application caches"); 3150 } 3151 } 3152 if(pi != null) { 3153 try { 3154 // Callback via pending intent 3155 int code = (retCode >= 0) ? 1 : 0; 3156 pi.sendIntent(null, code, null, 3157 null, null); 3158 } catch (SendIntentException e1) { 3159 Slog.i(TAG, "Failed to send pending intent"); 3160 } 3161 } 3162 } 3163 }); 3164 } 3165 3166 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3167 synchronized (mInstallLock) { 3168 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 3169 throw new IOException("Failed to free enough space"); 3170 } 3171 } 3172 } 3173 3174 /** 3175 * Return if the user key is currently unlocked. 3176 */ 3177 private boolean isUserKeyUnlocked(int userId) { 3178 if (StorageManager.isFileBasedEncryptionEnabled()) { 3179 final IMountService mount = IMountService.Stub 3180 .asInterface(ServiceManager.getService("mount")); 3181 if (mount == null) { 3182 Slog.w(TAG, "Early during boot, assuming locked"); 3183 return false; 3184 } 3185 final long token = Binder.clearCallingIdentity(); 3186 try { 3187 return mount.isUserKeyUnlocked(userId); 3188 } catch (RemoteException e) { 3189 throw e.rethrowAsRuntimeException(); 3190 } finally { 3191 Binder.restoreCallingIdentity(token); 3192 } 3193 } else { 3194 return true; 3195 } 3196 } 3197 3198 /** 3199 * Augment the given flags depending on current user running state. This is 3200 * purposefully done before acquiring {@link #mPackages} lock. 3201 */ 3202 private int augmentFlagsForUser(int flags, int userId) { 3203 if (!isUserKeyUnlocked(userId)) { 3204 flags |= PackageManager.MATCH_ENCRYPTION_AWARE_ONLY; 3205 } 3206 return flags; 3207 } 3208 3209 @Override 3210 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3211 if (!sUserManager.exists(userId)) return null; 3212 flags = augmentFlagsForUser(flags, userId); 3213 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 3214 synchronized (mPackages) { 3215 PackageParser.Activity a = mActivities.mActivities.get(component); 3216 3217 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3218 if (a != null && mSettings.isEnabledAndVisibleLPr(a.info, flags, userId)) { 3219 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3220 if (ps == null) return null; 3221 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3222 userId); 3223 } 3224 if (mResolveComponentName.equals(component)) { 3225 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3226 new PackageUserState(), userId); 3227 } 3228 } 3229 return null; 3230 } 3231 3232 @Override 3233 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3234 String resolvedType) { 3235 synchronized (mPackages) { 3236 if (component.equals(mResolveComponentName)) { 3237 // The resolver supports EVERYTHING! 3238 return true; 3239 } 3240 PackageParser.Activity a = mActivities.mActivities.get(component); 3241 if (a == null) { 3242 return false; 3243 } 3244 for (int i=0; i<a.intents.size(); i++) { 3245 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3246 intent.getData(), intent.getCategories(), TAG) >= 0) { 3247 return true; 3248 } 3249 } 3250 return false; 3251 } 3252 } 3253 3254 @Override 3255 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3256 if (!sUserManager.exists(userId)) return null; 3257 flags = augmentFlagsForUser(flags, userId); 3258 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 3259 synchronized (mPackages) { 3260 PackageParser.Activity a = mReceivers.mActivities.get(component); 3261 if (DEBUG_PACKAGE_INFO) Log.v( 3262 TAG, "getReceiverInfo " + component + ": " + a); 3263 if (a != null && mSettings.isEnabledAndVisibleLPr(a.info, flags, userId)) { 3264 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3265 if (ps == null) return null; 3266 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3267 userId); 3268 } 3269 } 3270 return null; 3271 } 3272 3273 @Override 3274 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3275 if (!sUserManager.exists(userId)) return null; 3276 flags = augmentFlagsForUser(flags, userId); 3277 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 3278 synchronized (mPackages) { 3279 PackageParser.Service s = mServices.mServices.get(component); 3280 if (DEBUG_PACKAGE_INFO) Log.v( 3281 TAG, "getServiceInfo " + component + ": " + s); 3282 if (s != null && mSettings.isEnabledAndVisibleLPr(s.info, flags, userId)) { 3283 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3284 if (ps == null) return null; 3285 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3286 userId); 3287 } 3288 } 3289 return null; 3290 } 3291 3292 @Override 3293 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3294 if (!sUserManager.exists(userId)) return null; 3295 flags = augmentFlagsForUser(flags, userId); 3296 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 3297 synchronized (mPackages) { 3298 PackageParser.Provider p = mProviders.mProviders.get(component); 3299 if (DEBUG_PACKAGE_INFO) Log.v( 3300 TAG, "getProviderInfo " + component + ": " + p); 3301 if (p != null && mSettings.isEnabledAndVisibleLPr(p.info, flags, userId)) { 3302 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3303 if (ps == null) return null; 3304 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3305 userId); 3306 } 3307 } 3308 return null; 3309 } 3310 3311 @Override 3312 public String[] getSystemSharedLibraryNames() { 3313 Set<String> libSet; 3314 synchronized (mPackages) { 3315 libSet = mSharedLibraries.keySet(); 3316 int size = libSet.size(); 3317 if (size > 0) { 3318 String[] libs = new String[size]; 3319 libSet.toArray(libs); 3320 return libs; 3321 } 3322 } 3323 return null; 3324 } 3325 3326 /** 3327 * @hide 3328 */ 3329 PackageParser.Package findSharedNonSystemLibrary(String libName) { 3330 synchronized (mPackages) { 3331 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 3332 if (lib != null && lib.apk != null) { 3333 return mPackages.get(lib.apk); 3334 } 3335 } 3336 return null; 3337 } 3338 3339 @Override 3340 public FeatureInfo[] getSystemAvailableFeatures() { 3341 Collection<FeatureInfo> featSet; 3342 synchronized (mPackages) { 3343 featSet = mAvailableFeatures.values(); 3344 int size = featSet.size(); 3345 if (size > 0) { 3346 FeatureInfo[] features = new FeatureInfo[size+1]; 3347 featSet.toArray(features); 3348 FeatureInfo fi = new FeatureInfo(); 3349 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3350 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3351 features[size] = fi; 3352 return features; 3353 } 3354 } 3355 return null; 3356 } 3357 3358 @Override 3359 public boolean hasSystemFeature(String name) { 3360 synchronized (mPackages) { 3361 return mAvailableFeatures.containsKey(name); 3362 } 3363 } 3364 3365 @Override 3366 public int checkPermission(String permName, String pkgName, int userId) { 3367 if (!sUserManager.exists(userId)) { 3368 return PackageManager.PERMISSION_DENIED; 3369 } 3370 3371 synchronized (mPackages) { 3372 final PackageParser.Package p = mPackages.get(pkgName); 3373 if (p != null && p.mExtras != null) { 3374 final PackageSetting ps = (PackageSetting) p.mExtras; 3375 final PermissionsState permissionsState = ps.getPermissionsState(); 3376 if (permissionsState.hasPermission(permName, userId)) { 3377 return PackageManager.PERMISSION_GRANTED; 3378 } 3379 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3380 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3381 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3382 return PackageManager.PERMISSION_GRANTED; 3383 } 3384 } 3385 } 3386 3387 return PackageManager.PERMISSION_DENIED; 3388 } 3389 3390 @Override 3391 public int checkUidPermission(String permName, int uid) { 3392 final int userId = UserHandle.getUserId(uid); 3393 3394 if (!sUserManager.exists(userId)) { 3395 return PackageManager.PERMISSION_DENIED; 3396 } 3397 3398 synchronized (mPackages) { 3399 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3400 if (obj != null) { 3401 final SettingBase ps = (SettingBase) obj; 3402 final PermissionsState permissionsState = ps.getPermissionsState(); 3403 if (permissionsState.hasPermission(permName, userId)) { 3404 return PackageManager.PERMISSION_GRANTED; 3405 } 3406 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3407 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3408 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3409 return PackageManager.PERMISSION_GRANTED; 3410 } 3411 } else { 3412 ArraySet<String> perms = mSystemPermissions.get(uid); 3413 if (perms != null) { 3414 if (perms.contains(permName)) { 3415 return PackageManager.PERMISSION_GRANTED; 3416 } 3417 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3418 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3419 return PackageManager.PERMISSION_GRANTED; 3420 } 3421 } 3422 } 3423 } 3424 3425 return PackageManager.PERMISSION_DENIED; 3426 } 3427 3428 @Override 3429 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3430 if (UserHandle.getCallingUserId() != userId) { 3431 mContext.enforceCallingPermission( 3432 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3433 "isPermissionRevokedByPolicy for user " + userId); 3434 } 3435 3436 if (checkPermission(permission, packageName, userId) 3437 == PackageManager.PERMISSION_GRANTED) { 3438 return false; 3439 } 3440 3441 final long identity = Binder.clearCallingIdentity(); 3442 try { 3443 final int flags = getPermissionFlags(permission, packageName, userId); 3444 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3445 } finally { 3446 Binder.restoreCallingIdentity(identity); 3447 } 3448 } 3449 3450 @Override 3451 public String getPermissionControllerPackageName() { 3452 synchronized (mPackages) { 3453 return mRequiredInstallerPackage; 3454 } 3455 } 3456 3457 /** 3458 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3459 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3460 * @param checkShell TODO(yamasani): 3461 * @param message the message to log on security exception 3462 */ 3463 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3464 boolean checkShell, String message) { 3465 if (userId < 0) { 3466 throw new IllegalArgumentException("Invalid userId " + userId); 3467 } 3468 if (checkShell) { 3469 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3470 } 3471 if (userId == UserHandle.getUserId(callingUid)) return; 3472 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3473 if (requireFullPermission) { 3474 mContext.enforceCallingOrSelfPermission( 3475 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3476 } else { 3477 try { 3478 mContext.enforceCallingOrSelfPermission( 3479 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3480 } catch (SecurityException se) { 3481 mContext.enforceCallingOrSelfPermission( 3482 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3483 } 3484 } 3485 } 3486 } 3487 3488 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3489 if (callingUid == Process.SHELL_UID) { 3490 if (userHandle >= 0 3491 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3492 throw new SecurityException("Shell does not have permission to access user " 3493 + userHandle); 3494 } else if (userHandle < 0) { 3495 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3496 + Debug.getCallers(3)); 3497 } 3498 } 3499 } 3500 3501 private BasePermission findPermissionTreeLP(String permName) { 3502 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3503 if (permName.startsWith(bp.name) && 3504 permName.length() > bp.name.length() && 3505 permName.charAt(bp.name.length()) == '.') { 3506 return bp; 3507 } 3508 } 3509 return null; 3510 } 3511 3512 private BasePermission checkPermissionTreeLP(String permName) { 3513 if (permName != null) { 3514 BasePermission bp = findPermissionTreeLP(permName); 3515 if (bp != null) { 3516 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3517 return bp; 3518 } 3519 throw new SecurityException("Calling uid " 3520 + Binder.getCallingUid() 3521 + " is not allowed to add to permission tree " 3522 + bp.name + " owned by uid " + bp.uid); 3523 } 3524 } 3525 throw new SecurityException("No permission tree found for " + permName); 3526 } 3527 3528 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3529 if (s1 == null) { 3530 return s2 == null; 3531 } 3532 if (s2 == null) { 3533 return false; 3534 } 3535 if (s1.getClass() != s2.getClass()) { 3536 return false; 3537 } 3538 return s1.equals(s2); 3539 } 3540 3541 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3542 if (pi1.icon != pi2.icon) return false; 3543 if (pi1.logo != pi2.logo) return false; 3544 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3545 if (!compareStrings(pi1.name, pi2.name)) return false; 3546 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3547 // We'll take care of setting this one. 3548 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3549 // These are not currently stored in settings. 3550 //if (!compareStrings(pi1.group, pi2.group)) return false; 3551 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3552 //if (pi1.labelRes != pi2.labelRes) return false; 3553 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3554 return true; 3555 } 3556 3557 int permissionInfoFootprint(PermissionInfo info) { 3558 int size = info.name.length(); 3559 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3560 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3561 return size; 3562 } 3563 3564 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3565 int size = 0; 3566 for (BasePermission perm : mSettings.mPermissions.values()) { 3567 if (perm.uid == tree.uid) { 3568 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3569 } 3570 } 3571 return size; 3572 } 3573 3574 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3575 // We calculate the max size of permissions defined by this uid and throw 3576 // if that plus the size of 'info' would exceed our stated maximum. 3577 if (tree.uid != Process.SYSTEM_UID) { 3578 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3579 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3580 throw new SecurityException("Permission tree size cap exceeded"); 3581 } 3582 } 3583 } 3584 3585 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3586 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3587 throw new SecurityException("Label must be specified in permission"); 3588 } 3589 BasePermission tree = checkPermissionTreeLP(info.name); 3590 BasePermission bp = mSettings.mPermissions.get(info.name); 3591 boolean added = bp == null; 3592 boolean changed = true; 3593 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3594 if (added) { 3595 enforcePermissionCapLocked(info, tree); 3596 bp = new BasePermission(info.name, tree.sourcePackage, 3597 BasePermission.TYPE_DYNAMIC); 3598 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3599 throw new SecurityException( 3600 "Not allowed to modify non-dynamic permission " 3601 + info.name); 3602 } else { 3603 if (bp.protectionLevel == fixedLevel 3604 && bp.perm.owner.equals(tree.perm.owner) 3605 && bp.uid == tree.uid 3606 && comparePermissionInfos(bp.perm.info, info)) { 3607 changed = false; 3608 } 3609 } 3610 bp.protectionLevel = fixedLevel; 3611 info = new PermissionInfo(info); 3612 info.protectionLevel = fixedLevel; 3613 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3614 bp.perm.info.packageName = tree.perm.info.packageName; 3615 bp.uid = tree.uid; 3616 if (added) { 3617 mSettings.mPermissions.put(info.name, bp); 3618 } 3619 if (changed) { 3620 if (!async) { 3621 mSettings.writeLPr(); 3622 } else { 3623 scheduleWriteSettingsLocked(); 3624 } 3625 } 3626 return added; 3627 } 3628 3629 @Override 3630 public boolean addPermission(PermissionInfo info) { 3631 synchronized (mPackages) { 3632 return addPermissionLocked(info, false); 3633 } 3634 } 3635 3636 @Override 3637 public boolean addPermissionAsync(PermissionInfo info) { 3638 synchronized (mPackages) { 3639 return addPermissionLocked(info, true); 3640 } 3641 } 3642 3643 @Override 3644 public void removePermission(String name) { 3645 synchronized (mPackages) { 3646 checkPermissionTreeLP(name); 3647 BasePermission bp = mSettings.mPermissions.get(name); 3648 if (bp != null) { 3649 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3650 throw new SecurityException( 3651 "Not allowed to modify non-dynamic permission " 3652 + name); 3653 } 3654 mSettings.mPermissions.remove(name); 3655 mSettings.writeLPr(); 3656 } 3657 } 3658 } 3659 3660 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 3661 BasePermission bp) { 3662 int index = pkg.requestedPermissions.indexOf(bp.name); 3663 if (index == -1) { 3664 throw new SecurityException("Package " + pkg.packageName 3665 + " has not requested permission " + bp.name); 3666 } 3667 if (!bp.isRuntime() && !bp.isDevelopment()) { 3668 throw new SecurityException("Permission " + bp.name 3669 + " is not a changeable permission type"); 3670 } 3671 } 3672 3673 @Override 3674 public void grantRuntimePermission(String packageName, String name, final int userId) { 3675 if (!sUserManager.exists(userId)) { 3676 Log.e(TAG, "No such user:" + userId); 3677 return; 3678 } 3679 3680 mContext.enforceCallingOrSelfPermission( 3681 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3682 "grantRuntimePermission"); 3683 3684 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3685 "grantRuntimePermission"); 3686 3687 final int uid; 3688 final SettingBase sb; 3689 3690 synchronized (mPackages) { 3691 final PackageParser.Package pkg = mPackages.get(packageName); 3692 if (pkg == null) { 3693 throw new IllegalArgumentException("Unknown package: " + packageName); 3694 } 3695 3696 final BasePermission bp = mSettings.mPermissions.get(name); 3697 if (bp == null) { 3698 throw new IllegalArgumentException("Unknown permission: " + name); 3699 } 3700 3701 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3702 3703 // If a permission review is required for legacy apps we represent 3704 // their permissions as always granted runtime ones since we need 3705 // to keep the review required permission flag per user while an 3706 // install permission's state is shared across all users. 3707 if (Build.PERMISSIONS_REVIEW_REQUIRED 3708 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 3709 && bp.isRuntime()) { 3710 return; 3711 } 3712 3713 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3714 sb = (SettingBase) pkg.mExtras; 3715 if (sb == null) { 3716 throw new IllegalArgumentException("Unknown package: " + packageName); 3717 } 3718 3719 final PermissionsState permissionsState = sb.getPermissionsState(); 3720 3721 final int flags = permissionsState.getPermissionFlags(name, userId); 3722 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3723 throw new SecurityException("Cannot grant system fixed permission: " 3724 + name + " for package: " + packageName); 3725 } 3726 3727 if (bp.isDevelopment()) { 3728 // Development permissions must be handled specially, since they are not 3729 // normal runtime permissions. For now they apply to all users. 3730 if (permissionsState.grantInstallPermission(bp) != 3731 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3732 scheduleWriteSettingsLocked(); 3733 } 3734 return; 3735 } 3736 3737 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 3738 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 3739 return; 3740 } 3741 3742 final int result = permissionsState.grantRuntimePermission(bp, userId); 3743 switch (result) { 3744 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3745 return; 3746 } 3747 3748 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3749 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3750 mHandler.post(new Runnable() { 3751 @Override 3752 public void run() { 3753 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 3754 } 3755 }); 3756 } 3757 break; 3758 } 3759 3760 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3761 3762 // Not critical if that is lost - app has to request again. 3763 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3764 } 3765 3766 // Only need to do this if user is initialized. Otherwise it's a new user 3767 // and there are no processes running as the user yet and there's no need 3768 // to make an expensive call to remount processes for the changed permissions. 3769 if (READ_EXTERNAL_STORAGE.equals(name) 3770 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3771 final long token = Binder.clearCallingIdentity(); 3772 try { 3773 if (sUserManager.isInitialized(userId)) { 3774 MountServiceInternal mountServiceInternal = LocalServices.getService( 3775 MountServiceInternal.class); 3776 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 3777 } 3778 } finally { 3779 Binder.restoreCallingIdentity(token); 3780 } 3781 } 3782 } 3783 3784 @Override 3785 public void revokeRuntimePermission(String packageName, String name, int userId) { 3786 if (!sUserManager.exists(userId)) { 3787 Log.e(TAG, "No such user:" + userId); 3788 return; 3789 } 3790 3791 mContext.enforceCallingOrSelfPermission( 3792 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3793 "revokeRuntimePermission"); 3794 3795 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3796 "revokeRuntimePermission"); 3797 3798 final int appId; 3799 3800 synchronized (mPackages) { 3801 final PackageParser.Package pkg = mPackages.get(packageName); 3802 if (pkg == null) { 3803 throw new IllegalArgumentException("Unknown package: " + packageName); 3804 } 3805 3806 final BasePermission bp = mSettings.mPermissions.get(name); 3807 if (bp == null) { 3808 throw new IllegalArgumentException("Unknown permission: " + name); 3809 } 3810 3811 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3812 3813 // If a permission review is required for legacy apps we represent 3814 // their permissions as always granted runtime ones since we need 3815 // to keep the review required permission flag per user while an 3816 // install permission's state is shared across all users. 3817 if (Build.PERMISSIONS_REVIEW_REQUIRED 3818 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 3819 && bp.isRuntime()) { 3820 return; 3821 } 3822 3823 SettingBase sb = (SettingBase) pkg.mExtras; 3824 if (sb == null) { 3825 throw new IllegalArgumentException("Unknown package: " + packageName); 3826 } 3827 3828 final PermissionsState permissionsState = sb.getPermissionsState(); 3829 3830 final int flags = permissionsState.getPermissionFlags(name, userId); 3831 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3832 throw new SecurityException("Cannot revoke system fixed permission: " 3833 + name + " for package: " + packageName); 3834 } 3835 3836 if (bp.isDevelopment()) { 3837 // Development permissions must be handled specially, since they are not 3838 // normal runtime permissions. For now they apply to all users. 3839 if (permissionsState.revokeInstallPermission(bp) != 3840 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3841 scheduleWriteSettingsLocked(); 3842 } 3843 return; 3844 } 3845 3846 if (permissionsState.revokeRuntimePermission(bp, userId) == 3847 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3848 return; 3849 } 3850 3851 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3852 3853 // Critical, after this call app should never have the permission. 3854 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3855 3856 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3857 } 3858 3859 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3860 } 3861 3862 @Override 3863 public void resetRuntimePermissions() { 3864 mContext.enforceCallingOrSelfPermission( 3865 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3866 "revokeRuntimePermission"); 3867 3868 int callingUid = Binder.getCallingUid(); 3869 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3870 mContext.enforceCallingOrSelfPermission( 3871 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3872 "resetRuntimePermissions"); 3873 } 3874 3875 synchronized (mPackages) { 3876 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 3877 for (int userId : UserManagerService.getInstance().getUserIds()) { 3878 final int packageCount = mPackages.size(); 3879 for (int i = 0; i < packageCount; i++) { 3880 PackageParser.Package pkg = mPackages.valueAt(i); 3881 if (!(pkg.mExtras instanceof PackageSetting)) { 3882 continue; 3883 } 3884 PackageSetting ps = (PackageSetting) pkg.mExtras; 3885 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 3886 } 3887 } 3888 } 3889 } 3890 3891 @Override 3892 public int getPermissionFlags(String name, String packageName, int userId) { 3893 if (!sUserManager.exists(userId)) { 3894 return 0; 3895 } 3896 3897 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 3898 3899 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3900 "getPermissionFlags"); 3901 3902 synchronized (mPackages) { 3903 final PackageParser.Package pkg = mPackages.get(packageName); 3904 if (pkg == null) { 3905 throw new IllegalArgumentException("Unknown package: " + packageName); 3906 } 3907 3908 final BasePermission bp = mSettings.mPermissions.get(name); 3909 if (bp == null) { 3910 throw new IllegalArgumentException("Unknown permission: " + name); 3911 } 3912 3913 SettingBase sb = (SettingBase) pkg.mExtras; 3914 if (sb == null) { 3915 throw new IllegalArgumentException("Unknown package: " + packageName); 3916 } 3917 3918 PermissionsState permissionsState = sb.getPermissionsState(); 3919 return permissionsState.getPermissionFlags(name, userId); 3920 } 3921 } 3922 3923 @Override 3924 public void updatePermissionFlags(String name, String packageName, int flagMask, 3925 int flagValues, int userId) { 3926 if (!sUserManager.exists(userId)) { 3927 return; 3928 } 3929 3930 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 3931 3932 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3933 "updatePermissionFlags"); 3934 3935 // Only the system can change these flags and nothing else. 3936 if (getCallingUid() != Process.SYSTEM_UID) { 3937 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3938 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3939 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3940 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3941 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 3942 } 3943 3944 synchronized (mPackages) { 3945 final PackageParser.Package pkg = mPackages.get(packageName); 3946 if (pkg == null) { 3947 throw new IllegalArgumentException("Unknown package: " + packageName); 3948 } 3949 3950 final BasePermission bp = mSettings.mPermissions.get(name); 3951 if (bp == null) { 3952 throw new IllegalArgumentException("Unknown permission: " + name); 3953 } 3954 3955 SettingBase sb = (SettingBase) pkg.mExtras; 3956 if (sb == null) { 3957 throw new IllegalArgumentException("Unknown package: " + packageName); 3958 } 3959 3960 PermissionsState permissionsState = sb.getPermissionsState(); 3961 3962 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 3963 3964 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3965 // Install and runtime permissions are stored in different places, 3966 // so figure out what permission changed and persist the change. 3967 if (permissionsState.getInstallPermissionState(name) != null) { 3968 scheduleWriteSettingsLocked(); 3969 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 3970 || hadState) { 3971 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3972 } 3973 } 3974 } 3975 } 3976 3977 /** 3978 * Update the permission flags for all packages and runtime permissions of a user in order 3979 * to allow device or profile owner to remove POLICY_FIXED. 3980 */ 3981 @Override 3982 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 3983 if (!sUserManager.exists(userId)) { 3984 return; 3985 } 3986 3987 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 3988 3989 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3990 "updatePermissionFlagsForAllApps"); 3991 3992 // Only the system can change system fixed flags. 3993 if (getCallingUid() != Process.SYSTEM_UID) { 3994 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3995 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3996 } 3997 3998 synchronized (mPackages) { 3999 boolean changed = false; 4000 final int packageCount = mPackages.size(); 4001 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4002 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4003 SettingBase sb = (SettingBase) pkg.mExtras; 4004 if (sb == null) { 4005 continue; 4006 } 4007 PermissionsState permissionsState = sb.getPermissionsState(); 4008 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4009 userId, flagMask, flagValues); 4010 } 4011 if (changed) { 4012 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4013 } 4014 } 4015 } 4016 4017 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4018 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4019 != PackageManager.PERMISSION_GRANTED 4020 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4021 != PackageManager.PERMISSION_GRANTED) { 4022 throw new SecurityException(message + " requires " 4023 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4024 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4025 } 4026 } 4027 4028 @Override 4029 public boolean shouldShowRequestPermissionRationale(String permissionName, 4030 String packageName, int userId) { 4031 if (UserHandle.getCallingUserId() != userId) { 4032 mContext.enforceCallingPermission( 4033 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4034 "canShowRequestPermissionRationale for user " + userId); 4035 } 4036 4037 final int uid = getPackageUid(packageName, userId); 4038 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4039 return false; 4040 } 4041 4042 if (checkPermission(permissionName, packageName, userId) 4043 == PackageManager.PERMISSION_GRANTED) { 4044 return false; 4045 } 4046 4047 final int flags; 4048 4049 final long identity = Binder.clearCallingIdentity(); 4050 try { 4051 flags = getPermissionFlags(permissionName, 4052 packageName, userId); 4053 } finally { 4054 Binder.restoreCallingIdentity(identity); 4055 } 4056 4057 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4058 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4059 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4060 4061 if ((flags & fixedFlags) != 0) { 4062 return false; 4063 } 4064 4065 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4066 } 4067 4068 @Override 4069 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4070 mContext.enforceCallingOrSelfPermission( 4071 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4072 "addOnPermissionsChangeListener"); 4073 4074 synchronized (mPackages) { 4075 mOnPermissionChangeListeners.addListenerLocked(listener); 4076 } 4077 } 4078 4079 @Override 4080 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4081 synchronized (mPackages) { 4082 mOnPermissionChangeListeners.removeListenerLocked(listener); 4083 } 4084 } 4085 4086 @Override 4087 public boolean isProtectedBroadcast(String actionName) { 4088 synchronized (mPackages) { 4089 if (mProtectedBroadcasts.contains(actionName)) { 4090 return true; 4091 } else if (actionName != null) { 4092 // TODO: remove these terrible hacks 4093 if (actionName.startsWith("android.net.netmon.lingerExpired") 4094 || actionName.startsWith("com.android.server.sip.SipWakeupTimer")) { 4095 return true; 4096 } 4097 } 4098 } 4099 return false; 4100 } 4101 4102 @Override 4103 public int checkSignatures(String pkg1, String pkg2) { 4104 synchronized (mPackages) { 4105 final PackageParser.Package p1 = mPackages.get(pkg1); 4106 final PackageParser.Package p2 = mPackages.get(pkg2); 4107 if (p1 == null || p1.mExtras == null 4108 || p2 == null || p2.mExtras == null) { 4109 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4110 } 4111 return compareSignatures(p1.mSignatures, p2.mSignatures); 4112 } 4113 } 4114 4115 @Override 4116 public int checkUidSignatures(int uid1, int uid2) { 4117 // Map to base uids. 4118 uid1 = UserHandle.getAppId(uid1); 4119 uid2 = UserHandle.getAppId(uid2); 4120 // reader 4121 synchronized (mPackages) { 4122 Signature[] s1; 4123 Signature[] s2; 4124 Object obj = mSettings.getUserIdLPr(uid1); 4125 if (obj != null) { 4126 if (obj instanceof SharedUserSetting) { 4127 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4128 } else if (obj instanceof PackageSetting) { 4129 s1 = ((PackageSetting)obj).signatures.mSignatures; 4130 } else { 4131 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4132 } 4133 } else { 4134 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4135 } 4136 obj = mSettings.getUserIdLPr(uid2); 4137 if (obj != null) { 4138 if (obj instanceof SharedUserSetting) { 4139 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4140 } else if (obj instanceof PackageSetting) { 4141 s2 = ((PackageSetting)obj).signatures.mSignatures; 4142 } else { 4143 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4144 } 4145 } else { 4146 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4147 } 4148 return compareSignatures(s1, s2); 4149 } 4150 } 4151 4152 private void killUid(int appId, int userId, String reason) { 4153 final long identity = Binder.clearCallingIdentity(); 4154 try { 4155 IActivityManager am = ActivityManagerNative.getDefault(); 4156 if (am != null) { 4157 try { 4158 am.killUid(appId, userId, reason); 4159 } catch (RemoteException e) { 4160 /* ignore - same process */ 4161 } 4162 } 4163 } finally { 4164 Binder.restoreCallingIdentity(identity); 4165 } 4166 } 4167 4168 /** 4169 * Compares two sets of signatures. Returns: 4170 * <br /> 4171 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4172 * <br /> 4173 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4174 * <br /> 4175 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4176 * <br /> 4177 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4178 * <br /> 4179 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4180 */ 4181 static int compareSignatures(Signature[] s1, Signature[] s2) { 4182 if (s1 == null) { 4183 return s2 == null 4184 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4185 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4186 } 4187 4188 if (s2 == null) { 4189 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4190 } 4191 4192 if (s1.length != s2.length) { 4193 return PackageManager.SIGNATURE_NO_MATCH; 4194 } 4195 4196 // Since both signature sets are of size 1, we can compare without HashSets. 4197 if (s1.length == 1) { 4198 return s1[0].equals(s2[0]) ? 4199 PackageManager.SIGNATURE_MATCH : 4200 PackageManager.SIGNATURE_NO_MATCH; 4201 } 4202 4203 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4204 for (Signature sig : s1) { 4205 set1.add(sig); 4206 } 4207 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4208 for (Signature sig : s2) { 4209 set2.add(sig); 4210 } 4211 // Make sure s2 contains all signatures in s1. 4212 if (set1.equals(set2)) { 4213 return PackageManager.SIGNATURE_MATCH; 4214 } 4215 return PackageManager.SIGNATURE_NO_MATCH; 4216 } 4217 4218 /** 4219 * If the database version for this type of package (internal storage or 4220 * external storage) is less than the version where package signatures 4221 * were updated, return true. 4222 */ 4223 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4224 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4225 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4226 } 4227 4228 /** 4229 * Used for backward compatibility to make sure any packages with 4230 * certificate chains get upgraded to the new style. {@code existingSigs} 4231 * will be in the old format (since they were stored on disk from before the 4232 * system upgrade) and {@code scannedSigs} will be in the newer format. 4233 */ 4234 private int compareSignaturesCompat(PackageSignatures existingSigs, 4235 PackageParser.Package scannedPkg) { 4236 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4237 return PackageManager.SIGNATURE_NO_MATCH; 4238 } 4239 4240 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4241 for (Signature sig : existingSigs.mSignatures) { 4242 existingSet.add(sig); 4243 } 4244 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4245 for (Signature sig : scannedPkg.mSignatures) { 4246 try { 4247 Signature[] chainSignatures = sig.getChainSignatures(); 4248 for (Signature chainSig : chainSignatures) { 4249 scannedCompatSet.add(chainSig); 4250 } 4251 } catch (CertificateEncodingException e) { 4252 scannedCompatSet.add(sig); 4253 } 4254 } 4255 /* 4256 * Make sure the expanded scanned set contains all signatures in the 4257 * existing one. 4258 */ 4259 if (scannedCompatSet.equals(existingSet)) { 4260 // Migrate the old signatures to the new scheme. 4261 existingSigs.assignSignatures(scannedPkg.mSignatures); 4262 // The new KeySets will be re-added later in the scanning process. 4263 synchronized (mPackages) { 4264 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4265 } 4266 return PackageManager.SIGNATURE_MATCH; 4267 } 4268 return PackageManager.SIGNATURE_NO_MATCH; 4269 } 4270 4271 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4272 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4273 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4274 } 4275 4276 private int compareSignaturesRecover(PackageSignatures existingSigs, 4277 PackageParser.Package scannedPkg) { 4278 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4279 return PackageManager.SIGNATURE_NO_MATCH; 4280 } 4281 4282 String msg = null; 4283 try { 4284 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4285 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4286 + scannedPkg.packageName); 4287 return PackageManager.SIGNATURE_MATCH; 4288 } 4289 } catch (CertificateException e) { 4290 msg = e.getMessage(); 4291 } 4292 4293 logCriticalInfo(Log.INFO, 4294 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4295 return PackageManager.SIGNATURE_NO_MATCH; 4296 } 4297 4298 @Override 4299 public String[] getPackagesForUid(int uid) { 4300 uid = UserHandle.getAppId(uid); 4301 // reader 4302 synchronized (mPackages) { 4303 Object obj = mSettings.getUserIdLPr(uid); 4304 if (obj instanceof SharedUserSetting) { 4305 final SharedUserSetting sus = (SharedUserSetting) obj; 4306 final int N = sus.packages.size(); 4307 final String[] res = new String[N]; 4308 final Iterator<PackageSetting> it = sus.packages.iterator(); 4309 int i = 0; 4310 while (it.hasNext()) { 4311 res[i++] = it.next().name; 4312 } 4313 return res; 4314 } else if (obj instanceof PackageSetting) { 4315 final PackageSetting ps = (PackageSetting) obj; 4316 return new String[] { ps.name }; 4317 } 4318 } 4319 return null; 4320 } 4321 4322 @Override 4323 public String getNameForUid(int uid) { 4324 // reader 4325 synchronized (mPackages) { 4326 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4327 if (obj instanceof SharedUserSetting) { 4328 final SharedUserSetting sus = (SharedUserSetting) obj; 4329 return sus.name + ":" + sus.userId; 4330 } else if (obj instanceof PackageSetting) { 4331 final PackageSetting ps = (PackageSetting) obj; 4332 return ps.name; 4333 } 4334 } 4335 return null; 4336 } 4337 4338 @Override 4339 public int getUidForSharedUser(String sharedUserName) { 4340 if(sharedUserName == null) { 4341 return -1; 4342 } 4343 // reader 4344 synchronized (mPackages) { 4345 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4346 if (suid == null) { 4347 return -1; 4348 } 4349 return suid.userId; 4350 } 4351 } 4352 4353 @Override 4354 public int getFlagsForUid(int uid) { 4355 synchronized (mPackages) { 4356 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4357 if (obj instanceof SharedUserSetting) { 4358 final SharedUserSetting sus = (SharedUserSetting) obj; 4359 return sus.pkgFlags; 4360 } else if (obj instanceof PackageSetting) { 4361 final PackageSetting ps = (PackageSetting) obj; 4362 return ps.pkgFlags; 4363 } 4364 } 4365 return 0; 4366 } 4367 4368 @Override 4369 public int getPrivateFlagsForUid(int uid) { 4370 synchronized (mPackages) { 4371 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4372 if (obj instanceof SharedUserSetting) { 4373 final SharedUserSetting sus = (SharedUserSetting) obj; 4374 return sus.pkgPrivateFlags; 4375 } else if (obj instanceof PackageSetting) { 4376 final PackageSetting ps = (PackageSetting) obj; 4377 return ps.pkgPrivateFlags; 4378 } 4379 } 4380 return 0; 4381 } 4382 4383 @Override 4384 public boolean isUidPrivileged(int uid) { 4385 uid = UserHandle.getAppId(uid); 4386 // reader 4387 synchronized (mPackages) { 4388 Object obj = mSettings.getUserIdLPr(uid); 4389 if (obj instanceof SharedUserSetting) { 4390 final SharedUserSetting sus = (SharedUserSetting) obj; 4391 final Iterator<PackageSetting> it = sus.packages.iterator(); 4392 while (it.hasNext()) { 4393 if (it.next().isPrivileged()) { 4394 return true; 4395 } 4396 } 4397 } else if (obj instanceof PackageSetting) { 4398 final PackageSetting ps = (PackageSetting) obj; 4399 return ps.isPrivileged(); 4400 } 4401 } 4402 return false; 4403 } 4404 4405 @Override 4406 public String[] getAppOpPermissionPackages(String permissionName) { 4407 synchronized (mPackages) { 4408 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4409 if (pkgs == null) { 4410 return null; 4411 } 4412 return pkgs.toArray(new String[pkgs.size()]); 4413 } 4414 } 4415 4416 @Override 4417 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4418 int flags, int userId) { 4419 if (!sUserManager.exists(userId)) return null; 4420 flags = augmentFlagsForUser(flags, userId); 4421 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 4422 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4423 final ResolveInfo bestChoice = 4424 chooseBestActivity(intent, resolvedType, flags, query, userId); 4425 4426 if (isEphemeralAllowed(intent, query, userId)) { 4427 final EphemeralResolveInfo ai = 4428 getEphemeralResolveInfo(intent, resolvedType, userId); 4429 if (ai != null) { 4430 if (DEBUG_EPHEMERAL) { 4431 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4432 } 4433 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4434 bestChoice.ephemeralResolveInfo = ai; 4435 } 4436 } 4437 return bestChoice; 4438 } 4439 4440 @Override 4441 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4442 IntentFilter filter, int match, ComponentName activity) { 4443 final int userId = UserHandle.getCallingUserId(); 4444 if (DEBUG_PREFERRED) { 4445 Log.v(TAG, "setLastChosenActivity intent=" + intent 4446 + " resolvedType=" + resolvedType 4447 + " flags=" + flags 4448 + " filter=" + filter 4449 + " match=" + match 4450 + " activity=" + activity); 4451 filter.dump(new PrintStreamPrinter(System.out), " "); 4452 } 4453 intent.setComponent(null); 4454 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4455 // Find any earlier preferred or last chosen entries and nuke them 4456 findPreferredActivity(intent, resolvedType, 4457 flags, query, 0, false, true, false, userId); 4458 // Add the new activity as the last chosen for this filter 4459 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4460 "Setting last chosen"); 4461 } 4462 4463 @Override 4464 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4465 final int userId = UserHandle.getCallingUserId(); 4466 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4467 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4468 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4469 false, false, false, userId); 4470 } 4471 4472 4473 private boolean isEphemeralAllowed( 4474 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4475 // Short circuit and return early if possible. 4476 final int callingUser = UserHandle.getCallingUserId(); 4477 if (callingUser != UserHandle.USER_SYSTEM) { 4478 return false; 4479 } 4480 if (mEphemeralResolverConnection == null) { 4481 return false; 4482 } 4483 if (intent.getComponent() != null) { 4484 return false; 4485 } 4486 if (intent.getPackage() != null) { 4487 return false; 4488 } 4489 final boolean isWebUri = hasWebURI(intent); 4490 if (!isWebUri) { 4491 return false; 4492 } 4493 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4494 synchronized (mPackages) { 4495 final int count = resolvedActivites.size(); 4496 for (int n = 0; n < count; n++) { 4497 ResolveInfo info = resolvedActivites.get(n); 4498 String packageName = info.activityInfo.packageName; 4499 PackageSetting ps = mSettings.mPackages.get(packageName); 4500 if (ps != null) { 4501 // Try to get the status from User settings first 4502 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4503 int status = (int) (packedStatus >> 32); 4504 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4505 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4506 if (DEBUG_EPHEMERAL) { 4507 Slog.v(TAG, "DENY ephemeral apps;" 4508 + " pkg: " + packageName + ", status: " + status); 4509 } 4510 return false; 4511 } 4512 } 4513 } 4514 } 4515 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4516 return true; 4517 } 4518 4519 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 4520 int userId) { 4521 MessageDigest digest = null; 4522 try { 4523 digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM); 4524 } catch (NoSuchAlgorithmException e) { 4525 // If we can't create a digest, ignore ephemeral apps. 4526 return null; 4527 } 4528 4529 final byte[] hostBytes = intent.getData().getHost().getBytes(); 4530 final byte[] digestBytes = digest.digest(hostBytes); 4531 int shaPrefix = 4532 digestBytes[0] << 24 4533 | digestBytes[1] << 16 4534 | digestBytes[2] << 8 4535 | digestBytes[3] << 0; 4536 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4537 mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix); 4538 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4539 // No hash prefix match; there are no ephemeral apps for this domain. 4540 return null; 4541 } 4542 for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) { 4543 EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i); 4544 if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) { 4545 continue; 4546 } 4547 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4548 // No filters; this should never happen. 4549 if (filters.isEmpty()) { 4550 continue; 4551 } 4552 // We have a domain match; resolve the filters to see if anything matches. 4553 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4554 for (int j = filters.size() - 1; j >= 0; --j) { 4555 final EphemeralResolveIntentInfo intentInfo = 4556 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 4557 ephemeralResolver.addFilter(intentInfo); 4558 } 4559 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 4560 intent, resolvedType, false /*defaultOnly*/, userId); 4561 if (!matchedResolveInfoList.isEmpty()) { 4562 return matchedResolveInfoList.get(0); 4563 } 4564 } 4565 // Hash or filter mis-match; no ephemeral apps for this domain. 4566 return null; 4567 } 4568 4569 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4570 int flags, List<ResolveInfo> query, int userId) { 4571 if (query != null) { 4572 final int N = query.size(); 4573 if (N == 1) { 4574 return query.get(0); 4575 } else if (N > 1) { 4576 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4577 // If there is more than one activity with the same priority, 4578 // then let the user decide between them. 4579 ResolveInfo r0 = query.get(0); 4580 ResolveInfo r1 = query.get(1); 4581 if (DEBUG_INTENT_MATCHING || debug) { 4582 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4583 + r1.activityInfo.name + "=" + r1.priority); 4584 } 4585 // If the first activity has a higher priority, or a different 4586 // default, then it is always desirable to pick it. 4587 if (r0.priority != r1.priority 4588 || r0.preferredOrder != r1.preferredOrder 4589 || r0.isDefault != r1.isDefault) { 4590 return query.get(0); 4591 } 4592 // If we have saved a preference for a preferred activity for 4593 // this Intent, use that. 4594 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4595 flags, query, r0.priority, true, false, debug, userId); 4596 if (ri != null) { 4597 return ri; 4598 } 4599 ri = new ResolveInfo(mResolveInfo); 4600 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4601 ri.activityInfo.applicationInfo = new ApplicationInfo( 4602 ri.activityInfo.applicationInfo); 4603 if (userId != 0) { 4604 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4605 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4606 } 4607 // Make sure that the resolver is displayable in car mode 4608 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 4609 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 4610 return ri; 4611 } 4612 } 4613 return null; 4614 } 4615 4616 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4617 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4618 final int N = query.size(); 4619 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4620 .get(userId); 4621 // Get the list of persistent preferred activities that handle the intent 4622 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4623 List<PersistentPreferredActivity> pprefs = ppir != null 4624 ? ppir.queryIntent(intent, resolvedType, 4625 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4626 : null; 4627 if (pprefs != null && pprefs.size() > 0) { 4628 final int M = pprefs.size(); 4629 for (int i=0; i<M; i++) { 4630 final PersistentPreferredActivity ppa = pprefs.get(i); 4631 if (DEBUG_PREFERRED || debug) { 4632 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4633 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4634 + "\n component=" + ppa.mComponent); 4635 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4636 } 4637 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4638 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4639 if (DEBUG_PREFERRED || debug) { 4640 Slog.v(TAG, "Found persistent preferred activity:"); 4641 if (ai != null) { 4642 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4643 } else { 4644 Slog.v(TAG, " null"); 4645 } 4646 } 4647 if (ai == null) { 4648 // This previously registered persistent preferred activity 4649 // component is no longer known. Ignore it and do NOT remove it. 4650 continue; 4651 } 4652 for (int j=0; j<N; j++) { 4653 final ResolveInfo ri = query.get(j); 4654 if (!ri.activityInfo.applicationInfo.packageName 4655 .equals(ai.applicationInfo.packageName)) { 4656 continue; 4657 } 4658 if (!ri.activityInfo.name.equals(ai.name)) { 4659 continue; 4660 } 4661 // Found a persistent preference that can handle the intent. 4662 if (DEBUG_PREFERRED || debug) { 4663 Slog.v(TAG, "Returning persistent preferred activity: " + 4664 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4665 } 4666 return ri; 4667 } 4668 } 4669 } 4670 return null; 4671 } 4672 4673 // TODO: handle preferred activities missing while user has amnesia 4674 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4675 List<ResolveInfo> query, int priority, boolean always, 4676 boolean removeMatches, boolean debug, int userId) { 4677 if (!sUserManager.exists(userId)) return null; 4678 flags = augmentFlagsForUser(flags, userId); 4679 // writer 4680 synchronized (mPackages) { 4681 if (intent.getSelector() != null) { 4682 intent = intent.getSelector(); 4683 } 4684 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4685 4686 // Try to find a matching persistent preferred activity. 4687 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4688 debug, userId); 4689 4690 // If a persistent preferred activity matched, use it. 4691 if (pri != null) { 4692 return pri; 4693 } 4694 4695 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4696 // Get the list of preferred activities that handle the intent 4697 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4698 List<PreferredActivity> prefs = pir != null 4699 ? pir.queryIntent(intent, resolvedType, 4700 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4701 : null; 4702 if (prefs != null && prefs.size() > 0) { 4703 boolean changed = false; 4704 try { 4705 // First figure out how good the original match set is. 4706 // We will only allow preferred activities that came 4707 // from the same match quality. 4708 int match = 0; 4709 4710 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4711 4712 final int N = query.size(); 4713 for (int j=0; j<N; j++) { 4714 final ResolveInfo ri = query.get(j); 4715 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4716 + ": 0x" + Integer.toHexString(match)); 4717 if (ri.match > match) { 4718 match = ri.match; 4719 } 4720 } 4721 4722 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4723 + Integer.toHexString(match)); 4724 4725 match &= IntentFilter.MATCH_CATEGORY_MASK; 4726 final int M = prefs.size(); 4727 for (int i=0; i<M; i++) { 4728 final PreferredActivity pa = prefs.get(i); 4729 if (DEBUG_PREFERRED || debug) { 4730 Slog.v(TAG, "Checking PreferredActivity ds=" 4731 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4732 + "\n component=" + pa.mPref.mComponent); 4733 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4734 } 4735 if (pa.mPref.mMatch != match) { 4736 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4737 + Integer.toHexString(pa.mPref.mMatch)); 4738 continue; 4739 } 4740 // If it's not an "always" type preferred activity and that's what we're 4741 // looking for, skip it. 4742 if (always && !pa.mPref.mAlways) { 4743 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4744 continue; 4745 } 4746 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4747 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4748 if (DEBUG_PREFERRED || debug) { 4749 Slog.v(TAG, "Found preferred activity:"); 4750 if (ai != null) { 4751 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4752 } else { 4753 Slog.v(TAG, " null"); 4754 } 4755 } 4756 if (ai == null) { 4757 // This previously registered preferred activity 4758 // component is no longer known. Most likely an update 4759 // to the app was installed and in the new version this 4760 // component no longer exists. Clean it up by removing 4761 // it from the preferred activities list, and skip it. 4762 Slog.w(TAG, "Removing dangling preferred activity: " 4763 + pa.mPref.mComponent); 4764 pir.removeFilter(pa); 4765 changed = true; 4766 continue; 4767 } 4768 for (int j=0; j<N; j++) { 4769 final ResolveInfo ri = query.get(j); 4770 if (!ri.activityInfo.applicationInfo.packageName 4771 .equals(ai.applicationInfo.packageName)) { 4772 continue; 4773 } 4774 if (!ri.activityInfo.name.equals(ai.name)) { 4775 continue; 4776 } 4777 4778 if (removeMatches) { 4779 pir.removeFilter(pa); 4780 changed = true; 4781 if (DEBUG_PREFERRED) { 4782 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4783 } 4784 break; 4785 } 4786 4787 // Okay we found a previously set preferred or last chosen app. 4788 // If the result set is different from when this 4789 // was created, we need to clear it and re-ask the 4790 // user their preference, if we're looking for an "always" type entry. 4791 if (always && !pa.mPref.sameSet(query)) { 4792 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4793 + intent + " type " + resolvedType); 4794 if (DEBUG_PREFERRED) { 4795 Slog.v(TAG, "Removing preferred activity since set changed " 4796 + pa.mPref.mComponent); 4797 } 4798 pir.removeFilter(pa); 4799 // Re-add the filter as a "last chosen" entry (!always) 4800 PreferredActivity lastChosen = new PreferredActivity( 4801 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4802 pir.addFilter(lastChosen); 4803 changed = true; 4804 return null; 4805 } 4806 4807 // Yay! Either the set matched or we're looking for the last chosen 4808 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4809 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4810 return ri; 4811 } 4812 } 4813 } finally { 4814 if (changed) { 4815 if (DEBUG_PREFERRED) { 4816 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4817 } 4818 scheduleWritePackageRestrictionsLocked(userId); 4819 } 4820 } 4821 } 4822 } 4823 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4824 return null; 4825 } 4826 4827 /* 4828 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4829 */ 4830 @Override 4831 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4832 int targetUserId) { 4833 mContext.enforceCallingOrSelfPermission( 4834 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4835 List<CrossProfileIntentFilter> matches = 4836 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4837 if (matches != null) { 4838 int size = matches.size(); 4839 for (int i = 0; i < size; i++) { 4840 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4841 } 4842 } 4843 if (hasWebURI(intent)) { 4844 // cross-profile app linking works only towards the parent. 4845 final UserInfo parent = getProfileParent(sourceUserId); 4846 synchronized(mPackages) { 4847 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 4848 intent, resolvedType, 0, sourceUserId, parent.id); 4849 return xpDomainInfo != null; 4850 } 4851 } 4852 return false; 4853 } 4854 4855 private UserInfo getProfileParent(int userId) { 4856 final long identity = Binder.clearCallingIdentity(); 4857 try { 4858 return sUserManager.getProfileParent(userId); 4859 } finally { 4860 Binder.restoreCallingIdentity(identity); 4861 } 4862 } 4863 4864 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4865 String resolvedType, int userId) { 4866 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4867 if (resolver != null) { 4868 return resolver.queryIntent(intent, resolvedType, false, userId); 4869 } 4870 return null; 4871 } 4872 4873 @Override 4874 public List<ResolveInfo> queryIntentActivities(Intent intent, 4875 String resolvedType, int flags, int userId) { 4876 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4877 flags = augmentFlagsForUser(flags, userId); 4878 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4879 ComponentName comp = intent.getComponent(); 4880 if (comp == null) { 4881 if (intent.getSelector() != null) { 4882 intent = intent.getSelector(); 4883 comp = intent.getComponent(); 4884 } 4885 } 4886 4887 if (comp != null) { 4888 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4889 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4890 if (ai != null) { 4891 final ResolveInfo ri = new ResolveInfo(); 4892 ri.activityInfo = ai; 4893 list.add(ri); 4894 } 4895 return list; 4896 } 4897 4898 // reader 4899 synchronized (mPackages) { 4900 final String pkgName = intent.getPackage(); 4901 if (pkgName == null) { 4902 List<CrossProfileIntentFilter> matchingFilters = 4903 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4904 // Check for results that need to skip the current profile. 4905 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4906 resolvedType, flags, userId); 4907 if (xpResolveInfo != null) { 4908 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4909 result.add(xpResolveInfo); 4910 return filterIfNotSystemUser(result, userId); 4911 } 4912 4913 // Check for results in the current profile. 4914 List<ResolveInfo> result = mActivities.queryIntent( 4915 intent, resolvedType, flags, userId); 4916 result = filterIfNotSystemUser(result, userId); 4917 4918 // Check for cross profile results. 4919 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 4920 xpResolveInfo = queryCrossProfileIntents( 4921 matchingFilters, intent, resolvedType, flags, userId, 4922 hasNonNegativePriorityResult); 4923 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4924 boolean isVisibleToUser = filterIfNotSystemUser( 4925 Collections.singletonList(xpResolveInfo), userId).size() > 0; 4926 if (isVisibleToUser) { 4927 result.add(xpResolveInfo); 4928 Collections.sort(result, mResolvePrioritySorter); 4929 } 4930 } 4931 if (hasWebURI(intent)) { 4932 CrossProfileDomainInfo xpDomainInfo = null; 4933 final UserInfo parent = getProfileParent(userId); 4934 if (parent != null) { 4935 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 4936 flags, userId, parent.id); 4937 } 4938 if (xpDomainInfo != null) { 4939 if (xpResolveInfo != null) { 4940 // If we didn't remove it, the cross-profile ResolveInfo would be twice 4941 // in the result. 4942 result.remove(xpResolveInfo); 4943 } 4944 if (result.size() == 0) { 4945 result.add(xpDomainInfo.resolveInfo); 4946 return result; 4947 } 4948 } else if (result.size() <= 1) { 4949 return result; 4950 } 4951 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 4952 xpDomainInfo, userId); 4953 Collections.sort(result, mResolvePrioritySorter); 4954 } 4955 return result; 4956 } 4957 final PackageParser.Package pkg = mPackages.get(pkgName); 4958 if (pkg != null) { 4959 return filterIfNotSystemUser( 4960 mActivities.queryIntentForPackage( 4961 intent, resolvedType, flags, pkg.activities, userId), 4962 userId); 4963 } 4964 return new ArrayList<ResolveInfo>(); 4965 } 4966 } 4967 4968 private static class CrossProfileDomainInfo { 4969 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 4970 ResolveInfo resolveInfo; 4971 /* Best domain verification status of the activities found in the other profile */ 4972 int bestDomainVerificationStatus; 4973 } 4974 4975 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 4976 String resolvedType, int flags, int sourceUserId, int parentUserId) { 4977 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 4978 sourceUserId)) { 4979 return null; 4980 } 4981 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4982 resolvedType, flags, parentUserId); 4983 4984 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 4985 return null; 4986 } 4987 CrossProfileDomainInfo result = null; 4988 int size = resultTargetUser.size(); 4989 for (int i = 0; i < size; i++) { 4990 ResolveInfo riTargetUser = resultTargetUser.get(i); 4991 // Intent filter verification is only for filters that specify a host. So don't return 4992 // those that handle all web uris. 4993 if (riTargetUser.handleAllWebDataURI) { 4994 continue; 4995 } 4996 String packageName = riTargetUser.activityInfo.packageName; 4997 PackageSetting ps = mSettings.mPackages.get(packageName); 4998 if (ps == null) { 4999 continue; 5000 } 5001 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5002 int status = (int)(verificationState >> 32); 5003 if (result == null) { 5004 result = new CrossProfileDomainInfo(); 5005 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5006 sourceUserId, parentUserId); 5007 result.bestDomainVerificationStatus = status; 5008 } else { 5009 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5010 result.bestDomainVerificationStatus); 5011 } 5012 } 5013 // Don't consider matches with status NEVER across profiles. 5014 if (result != null && result.bestDomainVerificationStatus 5015 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5016 return null; 5017 } 5018 return result; 5019 } 5020 5021 /** 5022 * Verification statuses are ordered from the worse to the best, except for 5023 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5024 */ 5025 private int bestDomainVerificationStatus(int status1, int status2) { 5026 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5027 return status2; 5028 } 5029 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5030 return status1; 5031 } 5032 return (int) MathUtils.max(status1, status2); 5033 } 5034 5035 private boolean isUserEnabled(int userId) { 5036 long callingId = Binder.clearCallingIdentity(); 5037 try { 5038 UserInfo userInfo = sUserManager.getUserInfo(userId); 5039 return userInfo != null && userInfo.isEnabled(); 5040 } finally { 5041 Binder.restoreCallingIdentity(callingId); 5042 } 5043 } 5044 5045 /** 5046 * Filter out activities with systemUserOnly flag set, when current user is not System. 5047 * 5048 * @return filtered list 5049 */ 5050 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5051 if (userId == UserHandle.USER_SYSTEM) { 5052 return resolveInfos; 5053 } 5054 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5055 ResolveInfo info = resolveInfos.get(i); 5056 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5057 resolveInfos.remove(i); 5058 } 5059 } 5060 return resolveInfos; 5061 } 5062 5063 /** 5064 * @param resolveInfos list of resolve infos in descending priority order 5065 * @return if the list contains a resolve info with non-negative priority 5066 */ 5067 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5068 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5069 } 5070 5071 private static boolean hasWebURI(Intent intent) { 5072 if (intent.getData() == null) { 5073 return false; 5074 } 5075 final String scheme = intent.getScheme(); 5076 if (TextUtils.isEmpty(scheme)) { 5077 return false; 5078 } 5079 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5080 } 5081 5082 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5083 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5084 int userId) { 5085 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5086 5087 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5088 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5089 candidates.size()); 5090 } 5091 5092 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5093 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5094 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5095 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5096 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5097 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5098 5099 synchronized (mPackages) { 5100 final int count = candidates.size(); 5101 // First, try to use linked apps. Partition the candidates into four lists: 5102 // one for the final results, one for the "do not use ever", one for "undefined status" 5103 // and finally one for "browser app type". 5104 for (int n=0; n<count; n++) { 5105 ResolveInfo info = candidates.get(n); 5106 String packageName = info.activityInfo.packageName; 5107 PackageSetting ps = mSettings.mPackages.get(packageName); 5108 if (ps != null) { 5109 // Add to the special match all list (Browser use case) 5110 if (info.handleAllWebDataURI) { 5111 matchAllList.add(info); 5112 continue; 5113 } 5114 // Try to get the status from User settings first 5115 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5116 int status = (int)(packedStatus >> 32); 5117 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5118 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5119 if (DEBUG_DOMAIN_VERIFICATION) { 5120 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5121 + " : linkgen=" + linkGeneration); 5122 } 5123 // Use link-enabled generation as preferredOrder, i.e. 5124 // prefer newly-enabled over earlier-enabled. 5125 info.preferredOrder = linkGeneration; 5126 alwaysList.add(info); 5127 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5128 if (DEBUG_DOMAIN_VERIFICATION) { 5129 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5130 } 5131 neverList.add(info); 5132 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5133 if (DEBUG_DOMAIN_VERIFICATION) { 5134 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5135 } 5136 alwaysAskList.add(info); 5137 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5138 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5139 if (DEBUG_DOMAIN_VERIFICATION) { 5140 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5141 } 5142 undefinedList.add(info); 5143 } 5144 } 5145 } 5146 5147 // We'll want to include browser possibilities in a few cases 5148 boolean includeBrowser = false; 5149 5150 // First try to add the "always" resolution(s) for the current user, if any 5151 if (alwaysList.size() > 0) { 5152 result.addAll(alwaysList); 5153 } else { 5154 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5155 result.addAll(undefinedList); 5156 // Maybe add one for the other profile. 5157 if (xpDomainInfo != null && ( 5158 xpDomainInfo.bestDomainVerificationStatus 5159 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5160 result.add(xpDomainInfo.resolveInfo); 5161 } 5162 includeBrowser = true; 5163 } 5164 5165 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5166 // If there were 'always' entries their preferred order has been set, so we also 5167 // back that off to make the alternatives equivalent 5168 if (alwaysAskList.size() > 0) { 5169 for (ResolveInfo i : result) { 5170 i.preferredOrder = 0; 5171 } 5172 result.addAll(alwaysAskList); 5173 includeBrowser = true; 5174 } 5175 5176 if (includeBrowser) { 5177 // Also add browsers (all of them or only the default one) 5178 if (DEBUG_DOMAIN_VERIFICATION) { 5179 Slog.v(TAG, " ...including browsers in candidate set"); 5180 } 5181 if ((matchFlags & MATCH_ALL) != 0) { 5182 result.addAll(matchAllList); 5183 } else { 5184 // Browser/generic handling case. If there's a default browser, go straight 5185 // to that (but only if there is no other higher-priority match). 5186 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5187 int maxMatchPrio = 0; 5188 ResolveInfo defaultBrowserMatch = null; 5189 final int numCandidates = matchAllList.size(); 5190 for (int n = 0; n < numCandidates; n++) { 5191 ResolveInfo info = matchAllList.get(n); 5192 // track the highest overall match priority... 5193 if (info.priority > maxMatchPrio) { 5194 maxMatchPrio = info.priority; 5195 } 5196 // ...and the highest-priority default browser match 5197 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5198 if (defaultBrowserMatch == null 5199 || (defaultBrowserMatch.priority < info.priority)) { 5200 if (debug) { 5201 Slog.v(TAG, "Considering default browser match " + info); 5202 } 5203 defaultBrowserMatch = info; 5204 } 5205 } 5206 } 5207 if (defaultBrowserMatch != null 5208 && defaultBrowserMatch.priority >= maxMatchPrio 5209 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5210 { 5211 if (debug) { 5212 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5213 } 5214 result.add(defaultBrowserMatch); 5215 } else { 5216 result.addAll(matchAllList); 5217 } 5218 } 5219 5220 // If there is nothing selected, add all candidates and remove the ones that the user 5221 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5222 if (result.size() == 0) { 5223 result.addAll(candidates); 5224 result.removeAll(neverList); 5225 } 5226 } 5227 } 5228 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5229 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5230 result.size()); 5231 for (ResolveInfo info : result) { 5232 Slog.v(TAG, " + " + info.activityInfo); 5233 } 5234 } 5235 return result; 5236 } 5237 5238 // Returns a packed value as a long: 5239 // 5240 // high 'int'-sized word: link status: undefined/ask/never/always. 5241 // low 'int'-sized word: relative priority among 'always' results. 5242 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5243 long result = ps.getDomainVerificationStatusForUser(userId); 5244 // if none available, get the master status 5245 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5246 if (ps.getIntentFilterVerificationInfo() != null) { 5247 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5248 } 5249 } 5250 return result; 5251 } 5252 5253 private ResolveInfo querySkipCurrentProfileIntents( 5254 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5255 int flags, int sourceUserId) { 5256 if (matchingFilters != null) { 5257 int size = matchingFilters.size(); 5258 for (int i = 0; i < size; i ++) { 5259 CrossProfileIntentFilter filter = matchingFilters.get(i); 5260 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5261 // Checking if there are activities in the target user that can handle the 5262 // intent. 5263 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5264 resolvedType, flags, sourceUserId); 5265 if (resolveInfo != null) { 5266 return resolveInfo; 5267 } 5268 } 5269 } 5270 } 5271 return null; 5272 } 5273 5274 // Return matching ResolveInfo in target user if any. 5275 private ResolveInfo queryCrossProfileIntents( 5276 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5277 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5278 if (matchingFilters != null) { 5279 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5280 // match the same intent. For performance reasons, it is better not to 5281 // run queryIntent twice for the same userId 5282 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5283 int size = matchingFilters.size(); 5284 for (int i = 0; i < size; i++) { 5285 CrossProfileIntentFilter filter = matchingFilters.get(i); 5286 int targetUserId = filter.getTargetUserId(); 5287 boolean skipCurrentProfile = 5288 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5289 boolean skipCurrentProfileIfNoMatchFound = 5290 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5291 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5292 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5293 // Checking if there are activities in the target user that can handle the 5294 // intent. 5295 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5296 resolvedType, flags, sourceUserId); 5297 if (resolveInfo != null) return resolveInfo; 5298 alreadyTriedUserIds.put(targetUserId, true); 5299 } 5300 } 5301 } 5302 return null; 5303 } 5304 5305 /** 5306 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5307 * will forward the intent to the filter's target user. 5308 * Otherwise, returns null. 5309 */ 5310 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5311 String resolvedType, int flags, int sourceUserId) { 5312 int targetUserId = filter.getTargetUserId(); 5313 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5314 resolvedType, flags, targetUserId); 5315 if (resultTargetUser != null && !resultTargetUser.isEmpty() 5316 && isUserEnabled(targetUserId)) { 5317 return createForwardingResolveInfoUnchecked(filter, sourceUserId, targetUserId); 5318 } 5319 return null; 5320 } 5321 5322 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5323 int sourceUserId, int targetUserId) { 5324 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5325 long ident = Binder.clearCallingIdentity(); 5326 boolean targetIsProfile; 5327 try { 5328 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5329 } finally { 5330 Binder.restoreCallingIdentity(ident); 5331 } 5332 String className; 5333 if (targetIsProfile) { 5334 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5335 } else { 5336 className = FORWARD_INTENT_TO_PARENT; 5337 } 5338 ComponentName forwardingActivityComponentName = new ComponentName( 5339 mAndroidApplication.packageName, className); 5340 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5341 sourceUserId); 5342 if (!targetIsProfile) { 5343 forwardingActivityInfo.showUserIcon = targetUserId; 5344 forwardingResolveInfo.noResourceId = true; 5345 } 5346 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5347 forwardingResolveInfo.priority = 0; 5348 forwardingResolveInfo.preferredOrder = 0; 5349 forwardingResolveInfo.match = 0; 5350 forwardingResolveInfo.isDefault = true; 5351 forwardingResolveInfo.filter = filter; 5352 forwardingResolveInfo.targetUserId = targetUserId; 5353 return forwardingResolveInfo; 5354 } 5355 5356 @Override 5357 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5358 Intent[] specifics, String[] specificTypes, Intent intent, 5359 String resolvedType, int flags, int userId) { 5360 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5361 flags = augmentFlagsForUser(flags, userId); 5362 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 5363 false, "query intent activity options"); 5364 final String resultsAction = intent.getAction(); 5365 5366 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 5367 | PackageManager.GET_RESOLVED_FILTER, userId); 5368 5369 if (DEBUG_INTENT_MATCHING) { 5370 Log.v(TAG, "Query " + intent + ": " + results); 5371 } 5372 5373 int specificsPos = 0; 5374 int N; 5375 5376 // todo: note that the algorithm used here is O(N^2). This 5377 // isn't a problem in our current environment, but if we start running 5378 // into situations where we have more than 5 or 10 matches then this 5379 // should probably be changed to something smarter... 5380 5381 // First we go through and resolve each of the specific items 5382 // that were supplied, taking care of removing any corresponding 5383 // duplicate items in the generic resolve list. 5384 if (specifics != null) { 5385 for (int i=0; i<specifics.length; i++) { 5386 final Intent sintent = specifics[i]; 5387 if (sintent == null) { 5388 continue; 5389 } 5390 5391 if (DEBUG_INTENT_MATCHING) { 5392 Log.v(TAG, "Specific #" + i + ": " + sintent); 5393 } 5394 5395 String action = sintent.getAction(); 5396 if (resultsAction != null && resultsAction.equals(action)) { 5397 // If this action was explicitly requested, then don't 5398 // remove things that have it. 5399 action = null; 5400 } 5401 5402 ResolveInfo ri = null; 5403 ActivityInfo ai = null; 5404 5405 ComponentName comp = sintent.getComponent(); 5406 if (comp == null) { 5407 ri = resolveIntent( 5408 sintent, 5409 specificTypes != null ? specificTypes[i] : null, 5410 flags, userId); 5411 if (ri == null) { 5412 continue; 5413 } 5414 if (ri == mResolveInfo) { 5415 // ACK! Must do something better with this. 5416 } 5417 ai = ri.activityInfo; 5418 comp = new ComponentName(ai.applicationInfo.packageName, 5419 ai.name); 5420 } else { 5421 ai = getActivityInfo(comp, flags, userId); 5422 if (ai == null) { 5423 continue; 5424 } 5425 } 5426 5427 // Look for any generic query activities that are duplicates 5428 // of this specific one, and remove them from the results. 5429 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5430 N = results.size(); 5431 int j; 5432 for (j=specificsPos; j<N; j++) { 5433 ResolveInfo sri = results.get(j); 5434 if ((sri.activityInfo.name.equals(comp.getClassName()) 5435 && sri.activityInfo.applicationInfo.packageName.equals( 5436 comp.getPackageName())) 5437 || (action != null && sri.filter.matchAction(action))) { 5438 results.remove(j); 5439 if (DEBUG_INTENT_MATCHING) Log.v( 5440 TAG, "Removing duplicate item from " + j 5441 + " due to specific " + specificsPos); 5442 if (ri == null) { 5443 ri = sri; 5444 } 5445 j--; 5446 N--; 5447 } 5448 } 5449 5450 // Add this specific item to its proper place. 5451 if (ri == null) { 5452 ri = new ResolveInfo(); 5453 ri.activityInfo = ai; 5454 } 5455 results.add(specificsPos, ri); 5456 ri.specificIndex = i; 5457 specificsPos++; 5458 } 5459 } 5460 5461 // Now we go through the remaining generic results and remove any 5462 // duplicate actions that are found here. 5463 N = results.size(); 5464 for (int i=specificsPos; i<N-1; i++) { 5465 final ResolveInfo rii = results.get(i); 5466 if (rii.filter == null) { 5467 continue; 5468 } 5469 5470 // Iterate over all of the actions of this result's intent 5471 // filter... typically this should be just one. 5472 final Iterator<String> it = rii.filter.actionsIterator(); 5473 if (it == null) { 5474 continue; 5475 } 5476 while (it.hasNext()) { 5477 final String action = it.next(); 5478 if (resultsAction != null && resultsAction.equals(action)) { 5479 // If this action was explicitly requested, then don't 5480 // remove things that have it. 5481 continue; 5482 } 5483 for (int j=i+1; j<N; j++) { 5484 final ResolveInfo rij = results.get(j); 5485 if (rij.filter != null && rij.filter.hasAction(action)) { 5486 results.remove(j); 5487 if (DEBUG_INTENT_MATCHING) Log.v( 5488 TAG, "Removing duplicate item from " + j 5489 + " due to action " + action + " at " + i); 5490 j--; 5491 N--; 5492 } 5493 } 5494 } 5495 5496 // If the caller didn't request filter information, drop it now 5497 // so we don't have to marshall/unmarshall it. 5498 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5499 rii.filter = null; 5500 } 5501 } 5502 5503 // Filter out the caller activity if so requested. 5504 if (caller != null) { 5505 N = results.size(); 5506 for (int i=0; i<N; i++) { 5507 ActivityInfo ainfo = results.get(i).activityInfo; 5508 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5509 && caller.getClassName().equals(ainfo.name)) { 5510 results.remove(i); 5511 break; 5512 } 5513 } 5514 } 5515 5516 // If the caller didn't request filter information, 5517 // drop them now so we don't have to 5518 // marshall/unmarshall it. 5519 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5520 N = results.size(); 5521 for (int i=0; i<N; i++) { 5522 results.get(i).filter = null; 5523 } 5524 } 5525 5526 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5527 return results; 5528 } 5529 5530 @Override 5531 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 5532 int userId) { 5533 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5534 flags = augmentFlagsForUser(flags, userId); 5535 ComponentName comp = intent.getComponent(); 5536 if (comp == null) { 5537 if (intent.getSelector() != null) { 5538 intent = intent.getSelector(); 5539 comp = intent.getComponent(); 5540 } 5541 } 5542 if (comp != null) { 5543 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5544 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5545 if (ai != null) { 5546 ResolveInfo ri = new ResolveInfo(); 5547 ri.activityInfo = ai; 5548 list.add(ri); 5549 } 5550 return list; 5551 } 5552 5553 // reader 5554 synchronized (mPackages) { 5555 String pkgName = intent.getPackage(); 5556 if (pkgName == null) { 5557 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5558 } 5559 final PackageParser.Package pkg = mPackages.get(pkgName); 5560 if (pkg != null) { 5561 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5562 userId); 5563 } 5564 return null; 5565 } 5566 } 5567 5568 @Override 5569 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5570 if (!sUserManager.exists(userId)) return null; 5571 flags = augmentFlagsForUser(flags, userId); 5572 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 5573 if (query != null) { 5574 if (query.size() >= 1) { 5575 // If there is more than one service with the same priority, 5576 // just arbitrarily pick the first one. 5577 return query.get(0); 5578 } 5579 } 5580 return null; 5581 } 5582 5583 @Override 5584 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 5585 int userId) { 5586 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5587 flags = augmentFlagsForUser(flags, userId); 5588 ComponentName comp = intent.getComponent(); 5589 if (comp == null) { 5590 if (intent.getSelector() != null) { 5591 intent = intent.getSelector(); 5592 comp = intent.getComponent(); 5593 } 5594 } 5595 if (comp != null) { 5596 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5597 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5598 if (si != null) { 5599 final ResolveInfo ri = new ResolveInfo(); 5600 ri.serviceInfo = si; 5601 list.add(ri); 5602 } 5603 return list; 5604 } 5605 5606 // reader 5607 synchronized (mPackages) { 5608 String pkgName = intent.getPackage(); 5609 if (pkgName == null) { 5610 return mServices.queryIntent(intent, resolvedType, flags, userId); 5611 } 5612 final PackageParser.Package pkg = mPackages.get(pkgName); 5613 if (pkg != null) { 5614 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5615 userId); 5616 } 5617 return null; 5618 } 5619 } 5620 5621 @Override 5622 public List<ResolveInfo> queryIntentContentProviders( 5623 Intent intent, String resolvedType, int flags, int userId) { 5624 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5625 flags = augmentFlagsForUser(flags, userId); 5626 ComponentName comp = intent.getComponent(); 5627 if (comp == null) { 5628 if (intent.getSelector() != null) { 5629 intent = intent.getSelector(); 5630 comp = intent.getComponent(); 5631 } 5632 } 5633 if (comp != null) { 5634 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5635 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5636 if (pi != null) { 5637 final ResolveInfo ri = new ResolveInfo(); 5638 ri.providerInfo = pi; 5639 list.add(ri); 5640 } 5641 return list; 5642 } 5643 5644 // reader 5645 synchronized (mPackages) { 5646 String pkgName = intent.getPackage(); 5647 if (pkgName == null) { 5648 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5649 } 5650 final PackageParser.Package pkg = mPackages.get(pkgName); 5651 if (pkg != null) { 5652 return mProviders.queryIntentForPackage( 5653 intent, resolvedType, flags, pkg.providers, userId); 5654 } 5655 return null; 5656 } 5657 } 5658 5659 @Override 5660 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5661 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5662 5663 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 5664 5665 // writer 5666 synchronized (mPackages) { 5667 ArrayList<PackageInfo> list; 5668 if (listUninstalled) { 5669 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5670 for (PackageSetting ps : mSettings.mPackages.values()) { 5671 PackageInfo pi; 5672 if (ps.pkg != null) { 5673 pi = generatePackageInfo(ps.pkg, flags, userId); 5674 } else { 5675 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5676 } 5677 if (pi != null) { 5678 list.add(pi); 5679 } 5680 } 5681 } else { 5682 list = new ArrayList<PackageInfo>(mPackages.size()); 5683 for (PackageParser.Package p : mPackages.values()) { 5684 PackageInfo pi = generatePackageInfo(p, flags, userId); 5685 if (pi != null) { 5686 list.add(pi); 5687 } 5688 } 5689 } 5690 5691 return new ParceledListSlice<PackageInfo>(list); 5692 } 5693 } 5694 5695 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5696 String[] permissions, boolean[] tmp, int flags, int userId) { 5697 int numMatch = 0; 5698 final PermissionsState permissionsState = ps.getPermissionsState(); 5699 for (int i=0; i<permissions.length; i++) { 5700 final String permission = permissions[i]; 5701 if (permissionsState.hasPermission(permission, userId)) { 5702 tmp[i] = true; 5703 numMatch++; 5704 } else { 5705 tmp[i] = false; 5706 } 5707 } 5708 if (numMatch == 0) { 5709 return; 5710 } 5711 PackageInfo pi; 5712 if (ps.pkg != null) { 5713 pi = generatePackageInfo(ps.pkg, flags, userId); 5714 } else { 5715 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5716 } 5717 // The above might return null in cases of uninstalled apps or install-state 5718 // skew across users/profiles. 5719 if (pi != null) { 5720 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5721 if (numMatch == permissions.length) { 5722 pi.requestedPermissions = permissions; 5723 } else { 5724 pi.requestedPermissions = new String[numMatch]; 5725 numMatch = 0; 5726 for (int i=0; i<permissions.length; i++) { 5727 if (tmp[i]) { 5728 pi.requestedPermissions[numMatch] = permissions[i]; 5729 numMatch++; 5730 } 5731 } 5732 } 5733 } 5734 list.add(pi); 5735 } 5736 } 5737 5738 @Override 5739 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5740 String[] permissions, int flags, int userId) { 5741 if (!sUserManager.exists(userId)) return null; 5742 flags = augmentFlagsForUser(flags, userId); 5743 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5744 5745 // writer 5746 synchronized (mPackages) { 5747 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5748 boolean[] tmpBools = new boolean[permissions.length]; 5749 if (listUninstalled) { 5750 for (PackageSetting ps : mSettings.mPackages.values()) { 5751 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5752 } 5753 } else { 5754 for (PackageParser.Package pkg : mPackages.values()) { 5755 PackageSetting ps = (PackageSetting)pkg.mExtras; 5756 if (ps != null) { 5757 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5758 userId); 5759 } 5760 } 5761 } 5762 5763 return new ParceledListSlice<PackageInfo>(list); 5764 } 5765 } 5766 5767 @Override 5768 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5769 if (!sUserManager.exists(userId)) return null; 5770 flags = augmentFlagsForUser(flags, userId); 5771 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5772 5773 // writer 5774 synchronized (mPackages) { 5775 ArrayList<ApplicationInfo> list; 5776 if (listUninstalled) { 5777 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5778 for (PackageSetting ps : mSettings.mPackages.values()) { 5779 ApplicationInfo ai; 5780 if (ps.pkg != null) { 5781 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5782 ps.readUserState(userId), userId); 5783 } else { 5784 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5785 } 5786 if (ai != null) { 5787 list.add(ai); 5788 } 5789 } 5790 } else { 5791 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5792 for (PackageParser.Package p : mPackages.values()) { 5793 if (p.mExtras != null) { 5794 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5795 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5796 if (ai != null) { 5797 list.add(ai); 5798 } 5799 } 5800 } 5801 } 5802 5803 return new ParceledListSlice<ApplicationInfo>(list); 5804 } 5805 } 5806 5807 @Override 5808 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 5809 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 5810 "getEphemeralApplications"); 5811 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5812 "getEphemeralApplications"); 5813 synchronized (mPackages) { 5814 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 5815 .getEphemeralApplicationsLPw(userId); 5816 if (ephemeralApps != null) { 5817 return new ParceledListSlice<>(ephemeralApps); 5818 } 5819 } 5820 return null; 5821 } 5822 5823 @Override 5824 public boolean isEphemeralApplication(String packageName, int userId) { 5825 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5826 "isEphemeral"); 5827 if (!isCallerSameApp(packageName)) { 5828 return false; 5829 } 5830 synchronized (mPackages) { 5831 PackageParser.Package pkg = mPackages.get(packageName); 5832 if (pkg != null) { 5833 return pkg.applicationInfo.isEphemeralApp(); 5834 } 5835 } 5836 return false; 5837 } 5838 5839 @Override 5840 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 5841 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5842 "getCookie"); 5843 if (!isCallerSameApp(packageName)) { 5844 return null; 5845 } 5846 synchronized (mPackages) { 5847 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 5848 packageName, userId); 5849 } 5850 } 5851 5852 @Override 5853 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 5854 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5855 "setCookie"); 5856 if (!isCallerSameApp(packageName)) { 5857 return false; 5858 } 5859 synchronized (mPackages) { 5860 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 5861 packageName, cookie, userId); 5862 } 5863 } 5864 5865 @Override 5866 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 5867 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 5868 "getEphemeralApplicationIcon"); 5869 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5870 "getEphemeralApplicationIcon"); 5871 synchronized (mPackages) { 5872 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 5873 packageName, userId); 5874 } 5875 } 5876 5877 private boolean isCallerSameApp(String packageName) { 5878 PackageParser.Package pkg = mPackages.get(packageName); 5879 return pkg != null 5880 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 5881 } 5882 5883 public List<ApplicationInfo> getPersistentApplications(int flags) { 5884 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 5885 5886 // reader 5887 synchronized (mPackages) { 5888 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 5889 final int userId = UserHandle.getCallingUserId(); 5890 while (i.hasNext()) { 5891 final PackageParser.Package p = i.next(); 5892 if (p.applicationInfo != null 5893 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 5894 && (!mSafeMode || isSystemApp(p))) { 5895 PackageSetting ps = mSettings.mPackages.get(p.packageName); 5896 if (ps != null) { 5897 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5898 ps.readUserState(userId), userId); 5899 if (ai != null) { 5900 finalList.add(ai); 5901 } 5902 } 5903 } 5904 } 5905 } 5906 5907 return finalList; 5908 } 5909 5910 @Override 5911 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 5912 if (!sUserManager.exists(userId)) return null; 5913 flags = augmentFlagsForUser(flags, userId); 5914 // reader 5915 synchronized (mPackages) { 5916 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 5917 PackageSetting ps = provider != null 5918 ? mSettings.mPackages.get(provider.owner.packageName) 5919 : null; 5920 return ps != null 5921 && mSettings.isEnabledAndVisibleLPr(provider.info, flags, userId) 5922 && (!mSafeMode || (provider.info.applicationInfo.flags 5923 &ApplicationInfo.FLAG_SYSTEM) != 0) 5924 ? PackageParser.generateProviderInfo(provider, flags, 5925 ps.readUserState(userId), userId) 5926 : null; 5927 } 5928 } 5929 5930 /** 5931 * @deprecated 5932 */ 5933 @Deprecated 5934 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 5935 // reader 5936 synchronized (mPackages) { 5937 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 5938 .entrySet().iterator(); 5939 final int userId = UserHandle.getCallingUserId(); 5940 while (i.hasNext()) { 5941 Map.Entry<String, PackageParser.Provider> entry = i.next(); 5942 PackageParser.Provider p = entry.getValue(); 5943 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5944 5945 if (ps != null && p.syncable 5946 && (!mSafeMode || (p.info.applicationInfo.flags 5947 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 5948 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 5949 ps.readUserState(userId), userId); 5950 if (info != null) { 5951 outNames.add(entry.getKey()); 5952 outInfo.add(info); 5953 } 5954 } 5955 } 5956 } 5957 } 5958 5959 @Override 5960 public ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 5961 int uid, int flags) { 5962 final int userId = processName != null ? UserHandle.getUserId(uid) 5963 : UserHandle.getCallingUserId(); 5964 if (!sUserManager.exists(userId)) return null; 5965 flags = augmentFlagsForUser(flags, userId); 5966 5967 ArrayList<ProviderInfo> finalList = null; 5968 // reader 5969 synchronized (mPackages) { 5970 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 5971 while (i.hasNext()) { 5972 final PackageParser.Provider p = i.next(); 5973 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5974 if (ps != null && p.info.authority != null 5975 && (processName == null 5976 || (p.info.processName.equals(processName) 5977 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 5978 && mSettings.isEnabledAndVisibleLPr(p.info, flags, userId) 5979 && (!mSafeMode 5980 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 5981 if (finalList == null) { 5982 finalList = new ArrayList<ProviderInfo>(3); 5983 } 5984 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 5985 ps.readUserState(userId), userId); 5986 if (info != null) { 5987 finalList.add(info); 5988 } 5989 } 5990 } 5991 } 5992 5993 if (finalList != null) { 5994 Collections.sort(finalList, mProviderInitOrderSorter); 5995 return new ParceledListSlice<ProviderInfo>(finalList); 5996 } 5997 5998 return null; 5999 } 6000 6001 @Override 6002 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 6003 int flags) { 6004 // reader 6005 synchronized (mPackages) { 6006 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6007 return PackageParser.generateInstrumentationInfo(i, flags); 6008 } 6009 } 6010 6011 @Override 6012 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 6013 int flags) { 6014 ArrayList<InstrumentationInfo> finalList = 6015 new ArrayList<InstrumentationInfo>(); 6016 6017 // reader 6018 synchronized (mPackages) { 6019 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6020 while (i.hasNext()) { 6021 final PackageParser.Instrumentation p = i.next(); 6022 if (targetPackage == null 6023 || targetPackage.equals(p.info.targetPackage)) { 6024 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6025 flags); 6026 if (ii != null) { 6027 finalList.add(ii); 6028 } 6029 } 6030 } 6031 } 6032 6033 return finalList; 6034 } 6035 6036 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6037 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6038 if (overlays == null) { 6039 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6040 return; 6041 } 6042 for (PackageParser.Package opkg : overlays.values()) { 6043 // Not much to do if idmap fails: we already logged the error 6044 // and we certainly don't want to abort installation of pkg simply 6045 // because an overlay didn't fit properly. For these reasons, 6046 // ignore the return value of createIdmapForPackagePairLI. 6047 createIdmapForPackagePairLI(pkg, opkg); 6048 } 6049 } 6050 6051 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6052 PackageParser.Package opkg) { 6053 if (!opkg.mTrustedOverlay) { 6054 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6055 opkg.baseCodePath + ": overlay not trusted"); 6056 return false; 6057 } 6058 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6059 if (overlaySet == null) { 6060 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6061 opkg.baseCodePath + " but target package has no known overlays"); 6062 return false; 6063 } 6064 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6065 // TODO: generate idmap for split APKs 6066 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 6067 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6068 + opkg.baseCodePath); 6069 return false; 6070 } 6071 PackageParser.Package[] overlayArray = 6072 overlaySet.values().toArray(new PackageParser.Package[0]); 6073 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6074 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6075 return p1.mOverlayPriority - p2.mOverlayPriority; 6076 } 6077 }; 6078 Arrays.sort(overlayArray, cmp); 6079 6080 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6081 int i = 0; 6082 for (PackageParser.Package p : overlayArray) { 6083 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6084 } 6085 return true; 6086 } 6087 6088 private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6089 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6090 try { 6091 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6092 } finally { 6093 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6094 } 6095 } 6096 6097 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6098 final File[] files = dir.listFiles(); 6099 if (ArrayUtils.isEmpty(files)) { 6100 Log.d(TAG, "No files in app dir " + dir); 6101 return; 6102 } 6103 6104 if (DEBUG_PACKAGE_SCANNING) { 6105 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6106 + " flags=0x" + Integer.toHexString(parseFlags)); 6107 } 6108 6109 for (File file : files) { 6110 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6111 && !PackageInstallerService.isStageName(file.getName()); 6112 if (!isPackage) { 6113 // Ignore entries which are not packages 6114 continue; 6115 } 6116 try { 6117 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6118 scanFlags, currentTime, null); 6119 } catch (PackageManagerException e) { 6120 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6121 6122 // Delete invalid userdata apps 6123 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6124 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6125 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6126 if (file.isDirectory()) { 6127 mInstaller.rmPackageDir(file.getAbsolutePath()); 6128 } else { 6129 file.delete(); 6130 } 6131 } 6132 } 6133 } 6134 } 6135 6136 private static File getSettingsProblemFile() { 6137 File dataDir = Environment.getDataDirectory(); 6138 File systemDir = new File(dataDir, "system"); 6139 File fname = new File(systemDir, "uiderrors.txt"); 6140 return fname; 6141 } 6142 6143 static void reportSettingsProblem(int priority, String msg) { 6144 logCriticalInfo(priority, msg); 6145 } 6146 6147 static void logCriticalInfo(int priority, String msg) { 6148 Slog.println(priority, TAG, msg); 6149 EventLogTags.writePmCriticalInfo(msg); 6150 try { 6151 File fname = getSettingsProblemFile(); 6152 FileOutputStream out = new FileOutputStream(fname, true); 6153 PrintWriter pw = new FastPrintWriter(out); 6154 SimpleDateFormat formatter = new SimpleDateFormat(); 6155 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6156 pw.println(dateString + ": " + msg); 6157 pw.close(); 6158 FileUtils.setPermissions( 6159 fname.toString(), 6160 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6161 -1, -1); 6162 } catch (java.io.IOException e) { 6163 } 6164 } 6165 6166 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 6167 PackageParser.Package pkg, File srcFile, int parseFlags) 6168 throws PackageManagerException { 6169 if (ps != null 6170 && ps.codePath.equals(srcFile) 6171 && ps.timeStamp == srcFile.lastModified() 6172 && !isCompatSignatureUpdateNeeded(pkg) 6173 && !isRecoverSignatureUpdateNeeded(pkg)) { 6174 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6175 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6176 ArraySet<PublicKey> signingKs; 6177 synchronized (mPackages) { 6178 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6179 } 6180 if (ps.signatures.mSignatures != null 6181 && ps.signatures.mSignatures.length != 0 6182 && signingKs != null) { 6183 // Optimization: reuse the existing cached certificates 6184 // if the package appears to be unchanged. 6185 pkg.mSignatures = ps.signatures.mSignatures; 6186 pkg.mSigningKeys = signingKs; 6187 return; 6188 } 6189 6190 Slog.w(TAG, "PackageSetting for " + ps.name 6191 + " is missing signatures. Collecting certs again to recover them."); 6192 } else { 6193 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6194 } 6195 6196 try { 6197 pp.collectCertificates(pkg, parseFlags); 6198 pp.collectManifestDigest(pkg); 6199 } catch (PackageParserException e) { 6200 throw PackageManagerException.from(e); 6201 } 6202 } 6203 6204 /** 6205 * Traces a package scan. 6206 * @see #scanPackageLI(File, int, int, long, UserHandle) 6207 */ 6208 private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags, 6209 long currentTime, UserHandle user) throws PackageManagerException { 6210 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6211 try { 6212 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6213 } finally { 6214 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6215 } 6216 } 6217 6218 /** 6219 * Scans a package and returns the newly parsed package. 6220 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6221 */ 6222 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6223 long currentTime, UserHandle user) throws PackageManagerException { 6224 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6225 parseFlags |= mDefParseFlags; 6226 PackageParser pp = new PackageParser(); 6227 pp.setSeparateProcesses(mSeparateProcesses); 6228 pp.setOnlyCoreApps(mOnlyCore); 6229 pp.setDisplayMetrics(mMetrics); 6230 6231 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6232 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6233 } 6234 6235 final PackageParser.Package pkg; 6236 try { 6237 pkg = pp.parsePackage(scanFile, parseFlags); 6238 } catch (PackageParserException e) { 6239 throw PackageManagerException.from(e); 6240 } 6241 6242 PackageSetting ps = null; 6243 PackageSetting updatedPkg; 6244 // reader 6245 synchronized (mPackages) { 6246 // Look to see if we already know about this package. 6247 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6248 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6249 // This package has been renamed to its original name. Let's 6250 // use that. 6251 ps = mSettings.peekPackageLPr(oldName); 6252 } 6253 // If there was no original package, see one for the real package name. 6254 if (ps == null) { 6255 ps = mSettings.peekPackageLPr(pkg.packageName); 6256 } 6257 // Check to see if this package could be hiding/updating a system 6258 // package. Must look for it either under the original or real 6259 // package name depending on our state. 6260 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6261 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6262 } 6263 boolean updatedPkgBetter = false; 6264 // First check if this is a system package that may involve an update 6265 if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6266 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6267 // it needs to drop FLAG_PRIVILEGED. 6268 if (locationIsPrivileged(scanFile)) { 6269 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6270 } else { 6271 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6272 } 6273 6274 if (ps != null && !ps.codePath.equals(scanFile)) { 6275 // The path has changed from what was last scanned... check the 6276 // version of the new path against what we have stored to determine 6277 // what to do. 6278 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6279 if (pkg.mVersionCode <= ps.versionCode) { 6280 // The system package has been updated and the code path does not match 6281 // Ignore entry. Skip it. 6282 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6283 + " ignored: updated version " + ps.versionCode 6284 + " better than this " + pkg.mVersionCode); 6285 if (!updatedPkg.codePath.equals(scanFile)) { 6286 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 6287 + ps.name + " changing from " + updatedPkg.codePathString 6288 + " to " + scanFile); 6289 updatedPkg.codePath = scanFile; 6290 updatedPkg.codePathString = scanFile.toString(); 6291 updatedPkg.resourcePath = scanFile; 6292 updatedPkg.resourcePathString = scanFile.toString(); 6293 } 6294 updatedPkg.pkg = pkg; 6295 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6296 "Package " + ps.name + " at " + scanFile 6297 + " ignored: updated version " + ps.versionCode 6298 + " better than this " + pkg.mVersionCode); 6299 } else { 6300 // The current app on the system partition is better than 6301 // what we have updated to on the data partition; switch 6302 // back to the system partition version. 6303 // At this point, its safely assumed that package installation for 6304 // apps in system partition will go through. If not there won't be a working 6305 // version of the app 6306 // writer 6307 synchronized (mPackages) { 6308 // Just remove the loaded entries from package lists. 6309 mPackages.remove(ps.name); 6310 } 6311 6312 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6313 + " reverting from " + ps.codePathString 6314 + ": new version " + pkg.mVersionCode 6315 + " better than installed " + ps.versionCode); 6316 6317 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6318 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6319 synchronized (mInstallLock) { 6320 args.cleanUpResourcesLI(); 6321 } 6322 synchronized (mPackages) { 6323 mSettings.enableSystemPackageLPw(ps.name); 6324 } 6325 updatedPkgBetter = true; 6326 } 6327 } 6328 } 6329 6330 if (updatedPkg != null) { 6331 // An updated system app will not have the PARSE_IS_SYSTEM flag set 6332 // initially 6333 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 6334 6335 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 6336 // flag set initially 6337 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 6338 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 6339 } 6340 } 6341 6342 // Verify certificates against what was last scanned 6343 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 6344 6345 /* 6346 * A new system app appeared, but we already had a non-system one of the 6347 * same name installed earlier. 6348 */ 6349 boolean shouldHideSystemApp = false; 6350 if (updatedPkg == null && ps != null 6351 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 6352 /* 6353 * Check to make sure the signatures match first. If they don't, 6354 * wipe the installed application and its data. 6355 */ 6356 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 6357 != PackageManager.SIGNATURE_MATCH) { 6358 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 6359 + " signatures don't match existing userdata copy; removing"); 6360 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 6361 ps = null; 6362 } else { 6363 /* 6364 * If the newly-added system app is an older version than the 6365 * already installed version, hide it. It will be scanned later 6366 * and re-added like an update. 6367 */ 6368 if (pkg.mVersionCode <= ps.versionCode) { 6369 shouldHideSystemApp = true; 6370 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 6371 + " but new version " + pkg.mVersionCode + " better than installed " 6372 + ps.versionCode + "; hiding system"); 6373 } else { 6374 /* 6375 * The newly found system app is a newer version that the 6376 * one previously installed. Simply remove the 6377 * already-installed application and replace it with our own 6378 * while keeping the application data. 6379 */ 6380 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6381 + " reverting from " + ps.codePathString + ": new version " 6382 + pkg.mVersionCode + " better than installed " + ps.versionCode); 6383 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6384 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6385 synchronized (mInstallLock) { 6386 args.cleanUpResourcesLI(); 6387 } 6388 } 6389 } 6390 } 6391 6392 // The apk is forward locked (not public) if its code and resources 6393 // are kept in different files. (except for app in either system or 6394 // vendor path). 6395 // TODO grab this value from PackageSettings 6396 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6397 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 6398 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 6399 } 6400 } 6401 6402 // TODO: extend to support forward-locked splits 6403 String resourcePath = null; 6404 String baseResourcePath = null; 6405 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 6406 if (ps != null && ps.resourcePathString != null) { 6407 resourcePath = ps.resourcePathString; 6408 baseResourcePath = ps.resourcePathString; 6409 } else { 6410 // Should not happen at all. Just log an error. 6411 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 6412 } 6413 } else { 6414 resourcePath = pkg.codePath; 6415 baseResourcePath = pkg.baseCodePath; 6416 } 6417 6418 // Set application objects path explicitly. 6419 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 6420 pkg.applicationInfo.setCodePath(pkg.codePath); 6421 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 6422 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 6423 pkg.applicationInfo.setResourcePath(resourcePath); 6424 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 6425 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 6426 6427 // Note that we invoke the following method only if we are about to unpack an application 6428 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 6429 | SCAN_UPDATE_SIGNATURE, currentTime, user); 6430 6431 /* 6432 * If the system app should be overridden by a previously installed 6433 * data, hide the system app now and let the /data/app scan pick it up 6434 * again. 6435 */ 6436 if (shouldHideSystemApp) { 6437 synchronized (mPackages) { 6438 mSettings.disableSystemPackageLPw(pkg.packageName); 6439 } 6440 } 6441 6442 return scannedPkg; 6443 } 6444 6445 private static String fixProcessName(String defProcessName, 6446 String processName, int uid) { 6447 if (processName == null) { 6448 return defProcessName; 6449 } 6450 return processName; 6451 } 6452 6453 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 6454 throws PackageManagerException { 6455 if (pkgSetting.signatures.mSignatures != null) { 6456 // Already existing package. Make sure signatures match 6457 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 6458 == PackageManager.SIGNATURE_MATCH; 6459 if (!match) { 6460 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 6461 == PackageManager.SIGNATURE_MATCH; 6462 } 6463 if (!match) { 6464 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 6465 == PackageManager.SIGNATURE_MATCH; 6466 } 6467 if (!match) { 6468 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 6469 + pkg.packageName + " signatures do not match the " 6470 + "previously installed version; ignoring!"); 6471 } 6472 } 6473 6474 // Check for shared user signatures 6475 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 6476 // Already existing package. Make sure signatures match 6477 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6478 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 6479 if (!match) { 6480 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 6481 == PackageManager.SIGNATURE_MATCH; 6482 } 6483 if (!match) { 6484 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 6485 == PackageManager.SIGNATURE_MATCH; 6486 } 6487 if (!match) { 6488 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 6489 "Package " + pkg.packageName 6490 + " has no signatures that match those in shared user " 6491 + pkgSetting.sharedUser.name + "; ignoring!"); 6492 } 6493 } 6494 } 6495 6496 /** 6497 * Enforces that only the system UID or root's UID can call a method exposed 6498 * via Binder. 6499 * 6500 * @param message used as message if SecurityException is thrown 6501 * @throws SecurityException if the caller is not system or root 6502 */ 6503 private static final void enforceSystemOrRoot(String message) { 6504 final int uid = Binder.getCallingUid(); 6505 if (uid != Process.SYSTEM_UID && uid != 0) { 6506 throw new SecurityException(message); 6507 } 6508 } 6509 6510 @Override 6511 public void performFstrimIfNeeded() { 6512 enforceSystemOrRoot("Only the system can request fstrim"); 6513 6514 // Before everything else, see whether we need to fstrim. 6515 try { 6516 IMountService ms = PackageHelper.getMountService(); 6517 if (ms != null) { 6518 final boolean isUpgrade = isUpgrade(); 6519 boolean doTrim = isUpgrade; 6520 if (doTrim) { 6521 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 6522 } else { 6523 final long interval = android.provider.Settings.Global.getLong( 6524 mContext.getContentResolver(), 6525 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 6526 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 6527 if (interval > 0) { 6528 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 6529 if (timeSinceLast > interval) { 6530 doTrim = true; 6531 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 6532 + "; running immediately"); 6533 } 6534 } 6535 } 6536 if (doTrim) { 6537 if (!isFirstBoot()) { 6538 try { 6539 ActivityManagerNative.getDefault().showBootMessage( 6540 mContext.getResources().getString( 6541 R.string.android_upgrading_fstrim), true); 6542 } catch (RemoteException e) { 6543 } 6544 } 6545 ms.runMaintenance(); 6546 } 6547 } else { 6548 Slog.e(TAG, "Mount service unavailable!"); 6549 } 6550 } catch (RemoteException e) { 6551 // Can't happen; MountService is local 6552 } 6553 } 6554 6555 private ArraySet<String> getPackageNamesForIntent(Intent intent, int userId) { 6556 List<ResolveInfo> ris = null; 6557 try { 6558 ris = AppGlobals.getPackageManager().queryIntentReceivers( 6559 intent, null, 0, userId); 6560 } catch (RemoteException e) { 6561 } 6562 ArraySet<String> pkgNames = new ArraySet<String>(); 6563 if (ris != null) { 6564 for (ResolveInfo ri : ris) { 6565 pkgNames.add(ri.activityInfo.packageName); 6566 } 6567 } 6568 return pkgNames; 6569 } 6570 6571 @Override 6572 public void notifyPackageUse(String packageName) { 6573 synchronized (mPackages) { 6574 PackageParser.Package p = mPackages.get(packageName); 6575 if (p == null) { 6576 return; 6577 } 6578 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6579 } 6580 } 6581 6582 @Override 6583 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6584 return performDexOptTraced(packageName, instructionSet); 6585 } 6586 6587 public boolean performDexOpt(String packageName, String instructionSet) { 6588 return performDexOptTraced(packageName, instructionSet); 6589 } 6590 6591 private boolean performDexOptTraced(String packageName, String instructionSet) { 6592 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 6593 try { 6594 return performDexOptInternal(packageName, instructionSet); 6595 } finally { 6596 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6597 } 6598 } 6599 6600 private boolean performDexOptInternal(String packageName, String instructionSet) { 6601 PackageParser.Package p; 6602 final String targetInstructionSet; 6603 synchronized (mPackages) { 6604 p = mPackages.get(packageName); 6605 if (p == null) { 6606 return false; 6607 } 6608 mPackageUsage.write(false); 6609 6610 targetInstructionSet = instructionSet != null ? instructionSet : 6611 getPrimaryInstructionSet(p.applicationInfo); 6612 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 6613 return false; 6614 } 6615 } 6616 long callingId = Binder.clearCallingIdentity(); 6617 try { 6618 synchronized (mInstallLock) { 6619 final String[] instructionSets = new String[] { targetInstructionSet }; 6620 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 6621 true /* inclDependencies */); 6622 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6623 } 6624 } finally { 6625 Binder.restoreCallingIdentity(callingId); 6626 } 6627 } 6628 6629 public ArraySet<String> getPackagesThatNeedDexOpt() { 6630 ArraySet<String> pkgs = null; 6631 synchronized (mPackages) { 6632 for (PackageParser.Package p : mPackages.values()) { 6633 if (DEBUG_DEXOPT) { 6634 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 6635 } 6636 if (!p.mDexOptPerformed.isEmpty()) { 6637 continue; 6638 } 6639 if (pkgs == null) { 6640 pkgs = new ArraySet<String>(); 6641 } 6642 pkgs.add(p.packageName); 6643 } 6644 } 6645 return pkgs; 6646 } 6647 6648 public void shutdown() { 6649 mPackageUsage.write(true); 6650 } 6651 6652 @Override 6653 public void forceDexOpt(String packageName) { 6654 enforceSystemOrRoot("forceDexOpt"); 6655 6656 PackageParser.Package pkg; 6657 synchronized (mPackages) { 6658 pkg = mPackages.get(packageName); 6659 if (pkg == null) { 6660 throw new IllegalArgumentException("Missing package: " + packageName); 6661 } 6662 } 6663 6664 synchronized (mInstallLock) { 6665 final String[] instructionSets = new String[] { 6666 getPrimaryInstructionSet(pkg.applicationInfo) }; 6667 6668 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 6669 6670 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 6671 true /* inclDependencies */); 6672 6673 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6674 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 6675 throw new IllegalStateException("Failed to dexopt: " + res); 6676 } 6677 } 6678 } 6679 6680 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 6681 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 6682 Slog.w(TAG, "Unable to update from " + oldPkg.name 6683 + " to " + newPkg.packageName 6684 + ": old package not in system partition"); 6685 return false; 6686 } else if (mPackages.get(oldPkg.name) != null) { 6687 Slog.w(TAG, "Unable to update from " + oldPkg.name 6688 + " to " + newPkg.packageName 6689 + ": old package still exists"); 6690 return false; 6691 } 6692 return true; 6693 } 6694 6695 private void createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) 6696 throws PackageManagerException { 6697 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 6698 if (res != 0) { 6699 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6700 "Failed to install " + packageName + ": " + res); 6701 } 6702 6703 final int[] users = sUserManager.getUserIds(); 6704 for (int user : users) { 6705 if (user != 0) { 6706 res = mInstaller.createUserData(volumeUuid, packageName, 6707 UserHandle.getUid(user, uid), user, seinfo); 6708 if (res != 0) { 6709 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6710 "Failed to createUserData " + packageName + ": " + res); 6711 } 6712 } 6713 } 6714 } 6715 6716 private int removeDataDirsLI(String volumeUuid, String packageName) { 6717 int[] users = sUserManager.getUserIds(); 6718 int res = 0; 6719 for (int user : users) { 6720 int resInner = mInstaller.remove(volumeUuid, packageName, user); 6721 if (resInner < 0) { 6722 res = resInner; 6723 } 6724 } 6725 6726 return res; 6727 } 6728 6729 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 6730 int[] users = sUserManager.getUserIds(); 6731 int res = 0; 6732 for (int user : users) { 6733 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 6734 if (resInner < 0) { 6735 res = resInner; 6736 } 6737 } 6738 return res; 6739 } 6740 6741 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 6742 PackageParser.Package changingLib) { 6743 if (file.path != null) { 6744 usesLibraryFiles.add(file.path); 6745 return; 6746 } 6747 PackageParser.Package p = mPackages.get(file.apk); 6748 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 6749 // If we are doing this while in the middle of updating a library apk, 6750 // then we need to make sure to use that new apk for determining the 6751 // dependencies here. (We haven't yet finished committing the new apk 6752 // to the package manager state.) 6753 if (p == null || p.packageName.equals(changingLib.packageName)) { 6754 p = changingLib; 6755 } 6756 } 6757 if (p != null) { 6758 usesLibraryFiles.addAll(p.getAllCodePaths()); 6759 } 6760 } 6761 6762 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 6763 PackageParser.Package changingLib) throws PackageManagerException { 6764 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 6765 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 6766 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 6767 for (int i=0; i<N; i++) { 6768 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 6769 if (file == null) { 6770 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 6771 "Package " + pkg.packageName + " requires unavailable shared library " 6772 + pkg.usesLibraries.get(i) + "; failing!"); 6773 } 6774 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6775 } 6776 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 6777 for (int i=0; i<N; i++) { 6778 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 6779 if (file == null) { 6780 Slog.w(TAG, "Package " + pkg.packageName 6781 + " desires unavailable shared library " 6782 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 6783 } else { 6784 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6785 } 6786 } 6787 N = usesLibraryFiles.size(); 6788 if (N > 0) { 6789 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 6790 } else { 6791 pkg.usesLibraryFiles = null; 6792 } 6793 } 6794 } 6795 6796 private static boolean hasString(List<String> list, List<String> which) { 6797 if (list == null) { 6798 return false; 6799 } 6800 for (int i=list.size()-1; i>=0; i--) { 6801 for (int j=which.size()-1; j>=0; j--) { 6802 if (which.get(j).equals(list.get(i))) { 6803 return true; 6804 } 6805 } 6806 } 6807 return false; 6808 } 6809 6810 private void updateAllSharedLibrariesLPw() { 6811 for (PackageParser.Package pkg : mPackages.values()) { 6812 try { 6813 updateSharedLibrariesLPw(pkg, null); 6814 } catch (PackageManagerException e) { 6815 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6816 } 6817 } 6818 } 6819 6820 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 6821 PackageParser.Package changingPkg) { 6822 ArrayList<PackageParser.Package> res = null; 6823 for (PackageParser.Package pkg : mPackages.values()) { 6824 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 6825 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 6826 if (res == null) { 6827 res = new ArrayList<PackageParser.Package>(); 6828 } 6829 res.add(pkg); 6830 try { 6831 updateSharedLibrariesLPw(pkg, changingPkg); 6832 } catch (PackageManagerException e) { 6833 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6834 } 6835 } 6836 } 6837 return res; 6838 } 6839 6840 /** 6841 * Derive the value of the {@code cpuAbiOverride} based on the provided 6842 * value and an optional stored value from the package settings. 6843 */ 6844 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 6845 String cpuAbiOverride = null; 6846 6847 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 6848 cpuAbiOverride = null; 6849 } else if (abiOverride != null) { 6850 cpuAbiOverride = abiOverride; 6851 } else if (settings != null) { 6852 cpuAbiOverride = settings.cpuAbiOverrideString; 6853 } 6854 6855 return cpuAbiOverride; 6856 } 6857 6858 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags, 6859 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6860 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6861 try { 6862 return scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user); 6863 } finally { 6864 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6865 } 6866 } 6867 6868 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 6869 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6870 boolean success = false; 6871 try { 6872 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 6873 currentTime, user); 6874 success = true; 6875 return res; 6876 } finally { 6877 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 6878 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 6879 } 6880 } 6881 } 6882 6883 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 6884 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6885 final File scanFile = new File(pkg.codePath); 6886 if (pkg.applicationInfo.getCodePath() == null || 6887 pkg.applicationInfo.getResourcePath() == null) { 6888 // Bail out. The resource and code paths haven't been set. 6889 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 6890 "Code and resource paths haven't been set correctly"); 6891 } 6892 6893 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 6894 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 6895 } else { 6896 // Only allow system apps to be flagged as core apps. 6897 pkg.coreApp = false; 6898 } 6899 6900 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 6901 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6902 } 6903 6904 if (mCustomResolverComponentName != null && 6905 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 6906 setUpCustomResolverActivity(pkg); 6907 } 6908 6909 if (pkg.packageName.equals("android")) { 6910 synchronized (mPackages) { 6911 if (mAndroidApplication != null) { 6912 Slog.w(TAG, "*************************************************"); 6913 Slog.w(TAG, "Core android package being redefined. Skipping."); 6914 Slog.w(TAG, " file=" + scanFile); 6915 Slog.w(TAG, "*************************************************"); 6916 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6917 "Core android package being redefined. Skipping."); 6918 } 6919 6920 // Set up information for our fall-back user intent resolution activity. 6921 mPlatformPackage = pkg; 6922 pkg.mVersionCode = mSdkVersion; 6923 mAndroidApplication = pkg.applicationInfo; 6924 6925 if (!mResolverReplaced) { 6926 mResolveActivity.applicationInfo = mAndroidApplication; 6927 mResolveActivity.name = ResolverActivity.class.getName(); 6928 mResolveActivity.packageName = mAndroidApplication.packageName; 6929 mResolveActivity.processName = "system:ui"; 6930 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6931 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 6932 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 6933 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 6934 mResolveActivity.exported = true; 6935 mResolveActivity.enabled = true; 6936 mResolveInfo.activityInfo = mResolveActivity; 6937 mResolveInfo.priority = 0; 6938 mResolveInfo.preferredOrder = 0; 6939 mResolveInfo.match = 0; 6940 mResolveComponentName = new ComponentName( 6941 mAndroidApplication.packageName, mResolveActivity.name); 6942 } 6943 } 6944 } 6945 6946 if (DEBUG_PACKAGE_SCANNING) { 6947 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6948 Log.d(TAG, "Scanning package " + pkg.packageName); 6949 } 6950 6951 if (mPackages.containsKey(pkg.packageName) 6952 || mSharedLibraries.containsKey(pkg.packageName)) { 6953 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6954 "Application package " + pkg.packageName 6955 + " already installed. Skipping duplicate."); 6956 } 6957 6958 // If we're only installing presumed-existing packages, require that the 6959 // scanned APK is both already known and at the path previously established 6960 // for it. Previously unknown packages we pick up normally, but if we have an 6961 // a priori expectation about this package's install presence, enforce it. 6962 // With a singular exception for new system packages. When an OTA contains 6963 // a new system package, we allow the codepath to change from a system location 6964 // to the user-installed location. If we don't allow this change, any newer, 6965 // user-installed version of the application will be ignored. 6966 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 6967 if (mExpectingBetter.containsKey(pkg.packageName)) { 6968 logCriticalInfo(Log.WARN, 6969 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 6970 } else { 6971 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 6972 if (known != null) { 6973 if (DEBUG_PACKAGE_SCANNING) { 6974 Log.d(TAG, "Examining " + pkg.codePath 6975 + " and requiring known paths " + known.codePathString 6976 + " & " + known.resourcePathString); 6977 } 6978 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6979 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6980 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6981 "Application package " + pkg.packageName 6982 + " found at " + pkg.applicationInfo.getCodePath() 6983 + " but expected at " + known.codePathString + "; ignoring."); 6984 } 6985 } 6986 } 6987 } 6988 6989 // Initialize package source and resource directories 6990 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6991 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6992 6993 SharedUserSetting suid = null; 6994 PackageSetting pkgSetting = null; 6995 6996 if (!isSystemApp(pkg)) { 6997 // Only system apps can use these features. 6998 pkg.mOriginalPackages = null; 6999 pkg.mRealPackage = null; 7000 pkg.mAdoptPermissions = null; 7001 } 7002 7003 // writer 7004 synchronized (mPackages) { 7005 if (pkg.mSharedUserId != null) { 7006 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 7007 if (suid == null) { 7008 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7009 "Creating application package " + pkg.packageName 7010 + " for shared user failed"); 7011 } 7012 if (DEBUG_PACKAGE_SCANNING) { 7013 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7014 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 7015 + "): packages=" + suid.packages); 7016 } 7017 } 7018 7019 // Check if we are renaming from an original package name. 7020 PackageSetting origPackage = null; 7021 String realName = null; 7022 if (pkg.mOriginalPackages != null) { 7023 // This package may need to be renamed to a previously 7024 // installed name. Let's check on that... 7025 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 7026 if (pkg.mOriginalPackages.contains(renamed)) { 7027 // This package had originally been installed as the 7028 // original name, and we have already taken care of 7029 // transitioning to the new one. Just update the new 7030 // one to continue using the old name. 7031 realName = pkg.mRealPackage; 7032 if (!pkg.packageName.equals(renamed)) { 7033 // Callers into this function may have already taken 7034 // care of renaming the package; only do it here if 7035 // it is not already done. 7036 pkg.setPackageName(renamed); 7037 } 7038 7039 } else { 7040 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 7041 if ((origPackage = mSettings.peekPackageLPr( 7042 pkg.mOriginalPackages.get(i))) != null) { 7043 // We do have the package already installed under its 7044 // original name... should we use it? 7045 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 7046 // New package is not compatible with original. 7047 origPackage = null; 7048 continue; 7049 } else if (origPackage.sharedUser != null) { 7050 // Make sure uid is compatible between packages. 7051 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 7052 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 7053 + " to " + pkg.packageName + ": old uid " 7054 + origPackage.sharedUser.name 7055 + " differs from " + pkg.mSharedUserId); 7056 origPackage = null; 7057 continue; 7058 } 7059 } else { 7060 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 7061 + pkg.packageName + " to old name " + origPackage.name); 7062 } 7063 break; 7064 } 7065 } 7066 } 7067 } 7068 7069 if (mTransferedPackages.contains(pkg.packageName)) { 7070 Slog.w(TAG, "Package " + pkg.packageName 7071 + " was transferred to another, but its .apk remains"); 7072 } 7073 7074 // Just create the setting, don't add it yet. For already existing packages 7075 // the PkgSetting exists already and doesn't have to be created. 7076 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 7077 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 7078 pkg.applicationInfo.primaryCpuAbi, 7079 pkg.applicationInfo.secondaryCpuAbi, 7080 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 7081 user, false); 7082 if (pkgSetting == null) { 7083 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7084 "Creating application package " + pkg.packageName + " failed"); 7085 } 7086 7087 if (pkgSetting.origPackage != null) { 7088 // If we are first transitioning from an original package, 7089 // fix up the new package's name now. We need to do this after 7090 // looking up the package under its new name, so getPackageLP 7091 // can take care of fiddling things correctly. 7092 pkg.setPackageName(origPackage.name); 7093 7094 // File a report about this. 7095 String msg = "New package " + pkgSetting.realName 7096 + " renamed to replace old package " + pkgSetting.name; 7097 reportSettingsProblem(Log.WARN, msg); 7098 7099 // Make a note of it. 7100 mTransferedPackages.add(origPackage.name); 7101 7102 // No longer need to retain this. 7103 pkgSetting.origPackage = null; 7104 } 7105 7106 if (realName != null) { 7107 // Make a note of it. 7108 mTransferedPackages.add(pkg.packageName); 7109 } 7110 7111 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 7112 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 7113 } 7114 7115 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7116 // Check all shared libraries and map to their actual file path. 7117 // We only do this here for apps not on a system dir, because those 7118 // are the only ones that can fail an install due to this. We 7119 // will take care of the system apps by updating all of their 7120 // library paths after the scan is done. 7121 updateSharedLibrariesLPw(pkg, null); 7122 } 7123 7124 if (mFoundPolicyFile) { 7125 SELinuxMMAC.assignSeinfoValue(pkg); 7126 } 7127 7128 pkg.applicationInfo.uid = pkgSetting.appId; 7129 pkg.mExtras = pkgSetting; 7130 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 7131 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 7132 // We just determined the app is signed correctly, so bring 7133 // over the latest parsed certs. 7134 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7135 } else { 7136 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7137 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7138 "Package " + pkg.packageName + " upgrade keys do not match the " 7139 + "previously installed version"); 7140 } else { 7141 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7142 String msg = "System package " + pkg.packageName 7143 + " signature changed; retaining data."; 7144 reportSettingsProblem(Log.WARN, msg); 7145 } 7146 } 7147 } else { 7148 try { 7149 verifySignaturesLP(pkgSetting, pkg); 7150 // We just determined the app is signed correctly, so bring 7151 // over the latest parsed certs. 7152 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7153 } catch (PackageManagerException e) { 7154 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7155 throw e; 7156 } 7157 // The signature has changed, but this package is in the system 7158 // image... let's recover! 7159 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7160 // However... if this package is part of a shared user, but it 7161 // doesn't match the signature of the shared user, let's fail. 7162 // What this means is that you can't change the signatures 7163 // associated with an overall shared user, which doesn't seem all 7164 // that unreasonable. 7165 if (pkgSetting.sharedUser != null) { 7166 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7167 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 7168 throw new PackageManagerException( 7169 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 7170 "Signature mismatch for shared user : " 7171 + pkgSetting.sharedUser); 7172 } 7173 } 7174 // File a report about this. 7175 String msg = "System package " + pkg.packageName 7176 + " signature changed; retaining data."; 7177 reportSettingsProblem(Log.WARN, msg); 7178 } 7179 } 7180 // Verify that this new package doesn't have any content providers 7181 // that conflict with existing packages. Only do this if the 7182 // package isn't already installed, since we don't want to break 7183 // things that are installed. 7184 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 7185 final int N = pkg.providers.size(); 7186 int i; 7187 for (i=0; i<N; i++) { 7188 PackageParser.Provider p = pkg.providers.get(i); 7189 if (p.info.authority != null) { 7190 String names[] = p.info.authority.split(";"); 7191 for (int j = 0; j < names.length; j++) { 7192 if (mProvidersByAuthority.containsKey(names[j])) { 7193 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7194 final String otherPackageName = 7195 ((other != null && other.getComponentName() != null) ? 7196 other.getComponentName().getPackageName() : "?"); 7197 throw new PackageManagerException( 7198 INSTALL_FAILED_CONFLICTING_PROVIDER, 7199 "Can't install because provider name " + names[j] 7200 + " (in package " + pkg.applicationInfo.packageName 7201 + ") is already used by " + otherPackageName); 7202 } 7203 } 7204 } 7205 } 7206 } 7207 7208 if (pkg.mAdoptPermissions != null) { 7209 // This package wants to adopt ownership of permissions from 7210 // another package. 7211 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 7212 final String origName = pkg.mAdoptPermissions.get(i); 7213 final PackageSetting orig = mSettings.peekPackageLPr(origName); 7214 if (orig != null) { 7215 if (verifyPackageUpdateLPr(orig, pkg)) { 7216 Slog.i(TAG, "Adopting permissions from " + origName + " to " 7217 + pkg.packageName); 7218 mSettings.transferPermissionsLPw(origName, pkg.packageName); 7219 } 7220 } 7221 } 7222 } 7223 } 7224 7225 final String pkgName = pkg.packageName; 7226 7227 final long scanFileTime = scanFile.lastModified(); 7228 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 7229 pkg.applicationInfo.processName = fixProcessName( 7230 pkg.applicationInfo.packageName, 7231 pkg.applicationInfo.processName, 7232 pkg.applicationInfo.uid); 7233 7234 if (pkg != mPlatformPackage) { 7235 // This is a normal package, need to make its data directory. 7236 final File dataPath = Environment.getDataUserCredentialEncryptedPackageDirectory( 7237 pkg.volumeUuid, UserHandle.USER_SYSTEM, pkg.packageName); 7238 7239 boolean uidError = false; 7240 if (dataPath.exists()) { 7241 int currentUid = 0; 7242 try { 7243 StructStat stat = Os.stat(dataPath.getPath()); 7244 currentUid = stat.st_uid; 7245 } catch (ErrnoException e) { 7246 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 7247 } 7248 7249 // If we have mismatched owners for the data path, we have a problem. 7250 if (currentUid != pkg.applicationInfo.uid) { 7251 boolean recovered = false; 7252 if (currentUid == 0) { 7253 // The directory somehow became owned by root. Wow. 7254 // This is probably because the system was stopped while 7255 // installd was in the middle of messing with its libs 7256 // directory. Ask installd to fix that. 7257 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 7258 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 7259 if (ret >= 0) { 7260 recovered = true; 7261 String msg = "Package " + pkg.packageName 7262 + " unexpectedly changed to uid 0; recovered to " + 7263 + pkg.applicationInfo.uid; 7264 reportSettingsProblem(Log.WARN, msg); 7265 } 7266 } 7267 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 7268 || (scanFlags&SCAN_BOOTING) != 0)) { 7269 // If this is a system app, we can at least delete its 7270 // current data so the application will still work. 7271 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 7272 if (ret >= 0) { 7273 // TODO: Kill the processes first 7274 // Old data gone! 7275 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 7276 ? "System package " : "Third party package "; 7277 String msg = prefix + pkg.packageName 7278 + " has changed from uid: " 7279 + currentUid + " to " 7280 + pkg.applicationInfo.uid + "; old data erased"; 7281 reportSettingsProblem(Log.WARN, msg); 7282 recovered = true; 7283 } 7284 if (!recovered) { 7285 mHasSystemUidErrors = true; 7286 } 7287 } else if (!recovered) { 7288 // If we allow this install to proceed, we will be broken. 7289 // Abort, abort! 7290 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 7291 "scanPackageLI"); 7292 } 7293 if (!recovered) { 7294 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 7295 + pkg.applicationInfo.uid + "/fs_" 7296 + currentUid; 7297 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 7298 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 7299 String msg = "Package " + pkg.packageName 7300 + " has mismatched uid: " 7301 + currentUid + " on disk, " 7302 + pkg.applicationInfo.uid + " in settings"; 7303 // writer 7304 synchronized (mPackages) { 7305 mSettings.mReadMessages.append(msg); 7306 mSettings.mReadMessages.append('\n'); 7307 uidError = true; 7308 if (!pkgSetting.uidError) { 7309 reportSettingsProblem(Log.ERROR, msg); 7310 } 7311 } 7312 } 7313 } 7314 7315 // Ensure that directories are prepared 7316 createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 7317 pkg.applicationInfo.seinfo); 7318 7319 if (mShouldRestoreconData) { 7320 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 7321 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 7322 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 7323 } 7324 } else { 7325 if (DEBUG_PACKAGE_SCANNING) { 7326 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7327 Log.v(TAG, "Want this data dir: " + dataPath); 7328 } 7329 createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 7330 pkg.applicationInfo.seinfo); 7331 } 7332 7333 // Get all of our default paths setup 7334 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 7335 7336 pkgSetting.uidError = uidError; 7337 } 7338 7339 final String path = scanFile.getPath(); 7340 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 7341 7342 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 7343 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 7344 7345 // Some system apps still use directory structure for native libraries 7346 // in which case we might end up not detecting abi solely based on apk 7347 // structure. Try to detect abi based on directory structure. 7348 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 7349 pkg.applicationInfo.primaryCpuAbi == null) { 7350 setBundledAppAbisAndRoots(pkg, pkgSetting); 7351 setNativeLibraryPaths(pkg); 7352 } 7353 7354 } else { 7355 if ((scanFlags & SCAN_MOVE) != 0) { 7356 // We haven't run dex-opt for this move (since we've moved the compiled output too) 7357 // but we already have this packages package info in the PackageSetting. We just 7358 // use that and derive the native library path based on the new codepath. 7359 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 7360 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 7361 } 7362 7363 // Set native library paths again. For moves, the path will be updated based on the 7364 // ABIs we've determined above. For non-moves, the path will be updated based on the 7365 // ABIs we determined during compilation, but the path will depend on the final 7366 // package path (after the rename away from the stage path). 7367 setNativeLibraryPaths(pkg); 7368 } 7369 7370 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 7371 final int[] userIds = sUserManager.getUserIds(); 7372 synchronized (mInstallLock) { 7373 // Make sure all user data directories are ready to roll; we're okay 7374 // if they already exist 7375 if (!TextUtils.isEmpty(pkg.volumeUuid)) { 7376 for (int userId : userIds) { 7377 if (userId != UserHandle.USER_SYSTEM) { 7378 mInstaller.createUserData(pkg.volumeUuid, pkg.packageName, 7379 UserHandle.getUid(userId, pkg.applicationInfo.uid), userId, 7380 pkg.applicationInfo.seinfo); 7381 } 7382 } 7383 } 7384 7385 // Create a native library symlink only if we have native libraries 7386 // and if the native libraries are 32 bit libraries. We do not provide 7387 // this symlink for 64 bit libraries. 7388 if (pkg.applicationInfo.primaryCpuAbi != null && 7389 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 7390 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "linkNativeLib"); 7391 try { 7392 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 7393 for (int userId : userIds) { 7394 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 7395 nativeLibPath, userId) < 0) { 7396 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7397 "Failed linking native library dir (user=" + userId + ")"); 7398 } 7399 } 7400 } finally { 7401 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7402 } 7403 } 7404 } 7405 7406 // This is a special case for the "system" package, where the ABI is 7407 // dictated by the zygote configuration (and init.rc). We should keep track 7408 // of this ABI so that we can deal with "normal" applications that run under 7409 // the same UID correctly. 7410 if (mPlatformPackage == pkg) { 7411 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 7412 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 7413 } 7414 7415 // If there's a mismatch between the abi-override in the package setting 7416 // and the abiOverride specified for the install. Warn about this because we 7417 // would've already compiled the app without taking the package setting into 7418 // account. 7419 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 7420 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 7421 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 7422 " for package: " + pkg.packageName); 7423 } 7424 } 7425 7426 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7427 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7428 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 7429 7430 // Copy the derived override back to the parsed package, so that we can 7431 // update the package settings accordingly. 7432 pkg.cpuAbiOverride = cpuAbiOverride; 7433 7434 if (DEBUG_ABI_SELECTION) { 7435 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 7436 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 7437 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 7438 } 7439 7440 // Push the derived path down into PackageSettings so we know what to 7441 // clean up at uninstall time. 7442 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 7443 7444 if (DEBUG_ABI_SELECTION) { 7445 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 7446 " primary=" + pkg.applicationInfo.primaryCpuAbi + 7447 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 7448 } 7449 7450 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 7451 // We don't do this here during boot because we can do it all 7452 // at once after scanning all existing packages. 7453 // 7454 // We also do this *before* we perform dexopt on this package, so that 7455 // we can avoid redundant dexopts, and also to make sure we've got the 7456 // code and package path correct. 7457 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 7458 pkg, true /* boot complete */); 7459 } 7460 7461 if (mFactoryTest && pkg.requestedPermissions.contains( 7462 android.Manifest.permission.FACTORY_TEST)) { 7463 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 7464 } 7465 7466 ArrayList<PackageParser.Package> clientLibPkgs = null; 7467 7468 // writer 7469 synchronized (mPackages) { 7470 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7471 // Only system apps can add new shared libraries. 7472 if (pkg.libraryNames != null) { 7473 for (int i=0; i<pkg.libraryNames.size(); i++) { 7474 String name = pkg.libraryNames.get(i); 7475 boolean allowed = false; 7476 if (pkg.isUpdatedSystemApp()) { 7477 // New library entries can only be added through the 7478 // system image. This is important to get rid of a lot 7479 // of nasty edge cases: for example if we allowed a non- 7480 // system update of the app to add a library, then uninstalling 7481 // the update would make the library go away, and assumptions 7482 // we made such as through app install filtering would now 7483 // have allowed apps on the device which aren't compatible 7484 // with it. Better to just have the restriction here, be 7485 // conservative, and create many fewer cases that can negatively 7486 // impact the user experience. 7487 final PackageSetting sysPs = mSettings 7488 .getDisabledSystemPkgLPr(pkg.packageName); 7489 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 7490 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 7491 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 7492 allowed = true; 7493 break; 7494 } 7495 } 7496 } 7497 } else { 7498 allowed = true; 7499 } 7500 if (allowed) { 7501 if (!mSharedLibraries.containsKey(name)) { 7502 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 7503 } else if (!name.equals(pkg.packageName)) { 7504 Slog.w(TAG, "Package " + pkg.packageName + " library " 7505 + name + " already exists; skipping"); 7506 } 7507 } else { 7508 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 7509 + name + " that is not declared on system image; skipping"); 7510 } 7511 } 7512 if ((scanFlags & SCAN_BOOTING) == 0) { 7513 // If we are not booting, we need to update any applications 7514 // that are clients of our shared library. If we are booting, 7515 // this will all be done once the scan is complete. 7516 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 7517 } 7518 } 7519 } 7520 } 7521 7522 // Request the ActivityManager to kill the process(only for existing packages) 7523 // so that we do not end up in a confused state while the user is still using the older 7524 // version of the application while the new one gets installed. 7525 if ((scanFlags & SCAN_REPLACING) != 0) { 7526 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication"); 7527 7528 killApplication(pkg.applicationInfo.packageName, 7529 pkg.applicationInfo.uid, "replace pkg"); 7530 7531 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7532 } 7533 7534 // Also need to kill any apps that are dependent on the library. 7535 if (clientLibPkgs != null) { 7536 for (int i=0; i<clientLibPkgs.size(); i++) { 7537 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7538 killApplication(clientPkg.applicationInfo.packageName, 7539 clientPkg.applicationInfo.uid, "update lib"); 7540 } 7541 } 7542 7543 // Make sure we're not adding any bogus keyset info 7544 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7545 ksms.assertScannedPackageValid(pkg); 7546 7547 // writer 7548 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 7549 7550 boolean createIdmapFailed = false; 7551 synchronized (mPackages) { 7552 // We don't expect installation to fail beyond this point 7553 7554 // Add the new setting to mSettings 7555 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 7556 // Add the new setting to mPackages 7557 mPackages.put(pkg.applicationInfo.packageName, pkg); 7558 // Make sure we don't accidentally delete its data. 7559 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 7560 while (iter.hasNext()) { 7561 PackageCleanItem item = iter.next(); 7562 if (pkgName.equals(item.packageName)) { 7563 iter.remove(); 7564 } 7565 } 7566 7567 // Take care of first install / last update times. 7568 if (currentTime != 0) { 7569 if (pkgSetting.firstInstallTime == 0) { 7570 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7571 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7572 pkgSetting.lastUpdateTime = currentTime; 7573 } 7574 } else if (pkgSetting.firstInstallTime == 0) { 7575 // We need *something*. Take time time stamp of the file. 7576 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7577 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7578 if (scanFileTime != pkgSetting.timeStamp) { 7579 // A package on the system image has changed; consider this 7580 // to be an update. 7581 pkgSetting.lastUpdateTime = scanFileTime; 7582 } 7583 } 7584 7585 // Add the package's KeySets to the global KeySetManagerService 7586 ksms.addScannedPackageLPw(pkg); 7587 7588 int N = pkg.providers.size(); 7589 StringBuilder r = null; 7590 int i; 7591 for (i=0; i<N; i++) { 7592 PackageParser.Provider p = pkg.providers.get(i); 7593 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7594 p.info.processName, pkg.applicationInfo.uid); 7595 mProviders.addProvider(p); 7596 p.syncable = p.info.isSyncable; 7597 if (p.info.authority != null) { 7598 String names[] = p.info.authority.split(";"); 7599 p.info.authority = null; 7600 for (int j = 0; j < names.length; j++) { 7601 if (j == 1 && p.syncable) { 7602 // We only want the first authority for a provider to possibly be 7603 // syncable, so if we already added this provider using a different 7604 // authority clear the syncable flag. We copy the provider before 7605 // changing it because the mProviders object contains a reference 7606 // to a provider that we don't want to change. 7607 // Only do this for the second authority since the resulting provider 7608 // object can be the same for all future authorities for this provider. 7609 p = new PackageParser.Provider(p); 7610 p.syncable = false; 7611 } 7612 if (!mProvidersByAuthority.containsKey(names[j])) { 7613 mProvidersByAuthority.put(names[j], p); 7614 if (p.info.authority == null) { 7615 p.info.authority = names[j]; 7616 } else { 7617 p.info.authority = p.info.authority + ";" + names[j]; 7618 } 7619 if (DEBUG_PACKAGE_SCANNING) { 7620 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7621 Log.d(TAG, "Registered content provider: " + names[j] 7622 + ", className = " + p.info.name + ", isSyncable = " 7623 + p.info.isSyncable); 7624 } 7625 } else { 7626 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7627 Slog.w(TAG, "Skipping provider name " + names[j] + 7628 " (in package " + pkg.applicationInfo.packageName + 7629 "): name already used by " 7630 + ((other != null && other.getComponentName() != null) 7631 ? other.getComponentName().getPackageName() : "?")); 7632 } 7633 } 7634 } 7635 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7636 if (r == null) { 7637 r = new StringBuilder(256); 7638 } else { 7639 r.append(' '); 7640 } 7641 r.append(p.info.name); 7642 } 7643 } 7644 if (r != null) { 7645 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7646 } 7647 7648 N = pkg.services.size(); 7649 r = null; 7650 for (i=0; i<N; i++) { 7651 PackageParser.Service s = pkg.services.get(i); 7652 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 7653 s.info.processName, pkg.applicationInfo.uid); 7654 mServices.addService(s); 7655 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7656 if (r == null) { 7657 r = new StringBuilder(256); 7658 } else { 7659 r.append(' '); 7660 } 7661 r.append(s.info.name); 7662 } 7663 } 7664 if (r != null) { 7665 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 7666 } 7667 7668 N = pkg.receivers.size(); 7669 r = null; 7670 for (i=0; i<N; i++) { 7671 PackageParser.Activity a = pkg.receivers.get(i); 7672 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7673 a.info.processName, pkg.applicationInfo.uid); 7674 mReceivers.addActivity(a, "receiver"); 7675 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7676 if (r == null) { 7677 r = new StringBuilder(256); 7678 } else { 7679 r.append(' '); 7680 } 7681 r.append(a.info.name); 7682 } 7683 } 7684 if (r != null) { 7685 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 7686 } 7687 7688 N = pkg.activities.size(); 7689 r = null; 7690 for (i=0; i<N; i++) { 7691 PackageParser.Activity a = pkg.activities.get(i); 7692 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7693 a.info.processName, pkg.applicationInfo.uid); 7694 mActivities.addActivity(a, "activity"); 7695 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7696 if (r == null) { 7697 r = new StringBuilder(256); 7698 } else { 7699 r.append(' '); 7700 } 7701 r.append(a.info.name); 7702 } 7703 } 7704 if (r != null) { 7705 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 7706 } 7707 7708 N = pkg.permissionGroups.size(); 7709 r = null; 7710 for (i=0; i<N; i++) { 7711 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 7712 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 7713 if (cur == null) { 7714 mPermissionGroups.put(pg.info.name, pg); 7715 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7716 if (r == null) { 7717 r = new StringBuilder(256); 7718 } else { 7719 r.append(' '); 7720 } 7721 r.append(pg.info.name); 7722 } 7723 } else { 7724 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 7725 + pg.info.packageName + " ignored: original from " 7726 + cur.info.packageName); 7727 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7728 if (r == null) { 7729 r = new StringBuilder(256); 7730 } else { 7731 r.append(' '); 7732 } 7733 r.append("DUP:"); 7734 r.append(pg.info.name); 7735 } 7736 } 7737 } 7738 if (r != null) { 7739 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 7740 } 7741 7742 N = pkg.permissions.size(); 7743 r = null; 7744 for (i=0; i<N; i++) { 7745 PackageParser.Permission p = pkg.permissions.get(i); 7746 7747 // Assume by default that we did not install this permission into the system. 7748 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 7749 7750 // Now that permission groups have a special meaning, we ignore permission 7751 // groups for legacy apps to prevent unexpected behavior. In particular, 7752 // permissions for one app being granted to someone just becuase they happen 7753 // to be in a group defined by another app (before this had no implications). 7754 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 7755 p.group = mPermissionGroups.get(p.info.group); 7756 // Warn for a permission in an unknown group. 7757 if (p.info.group != null && p.group == null) { 7758 Slog.w(TAG, "Permission " + p.info.name + " from package " 7759 + p.info.packageName + " in an unknown group " + p.info.group); 7760 } 7761 } 7762 7763 ArrayMap<String, BasePermission> permissionMap = 7764 p.tree ? mSettings.mPermissionTrees 7765 : mSettings.mPermissions; 7766 BasePermission bp = permissionMap.get(p.info.name); 7767 7768 // Allow system apps to redefine non-system permissions 7769 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 7770 final boolean currentOwnerIsSystem = (bp.perm != null 7771 && isSystemApp(bp.perm.owner)); 7772 if (isSystemApp(p.owner)) { 7773 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 7774 // It's a built-in permission and no owner, take ownership now 7775 bp.packageSetting = pkgSetting; 7776 bp.perm = p; 7777 bp.uid = pkg.applicationInfo.uid; 7778 bp.sourcePackage = p.info.packageName; 7779 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7780 } else if (!currentOwnerIsSystem) { 7781 String msg = "New decl " + p.owner + " of permission " 7782 + p.info.name + " is system; overriding " + bp.sourcePackage; 7783 reportSettingsProblem(Log.WARN, msg); 7784 bp = null; 7785 } 7786 } 7787 } 7788 7789 if (bp == null) { 7790 bp = new BasePermission(p.info.name, p.info.packageName, 7791 BasePermission.TYPE_NORMAL); 7792 permissionMap.put(p.info.name, bp); 7793 } 7794 7795 if (bp.perm == null) { 7796 if (bp.sourcePackage == null 7797 || bp.sourcePackage.equals(p.info.packageName)) { 7798 BasePermission tree = findPermissionTreeLP(p.info.name); 7799 if (tree == null 7800 || tree.sourcePackage.equals(p.info.packageName)) { 7801 bp.packageSetting = pkgSetting; 7802 bp.perm = p; 7803 bp.uid = pkg.applicationInfo.uid; 7804 bp.sourcePackage = p.info.packageName; 7805 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7806 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7807 if (r == null) { 7808 r = new StringBuilder(256); 7809 } else { 7810 r.append(' '); 7811 } 7812 r.append(p.info.name); 7813 } 7814 } else { 7815 Slog.w(TAG, "Permission " + p.info.name + " from package " 7816 + p.info.packageName + " ignored: base tree " 7817 + tree.name + " is from package " 7818 + tree.sourcePackage); 7819 } 7820 } else { 7821 Slog.w(TAG, "Permission " + p.info.name + " from package " 7822 + p.info.packageName + " ignored: original from " 7823 + bp.sourcePackage); 7824 } 7825 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7826 if (r == null) { 7827 r = new StringBuilder(256); 7828 } else { 7829 r.append(' '); 7830 } 7831 r.append("DUP:"); 7832 r.append(p.info.name); 7833 } 7834 if (bp.perm == p) { 7835 bp.protectionLevel = p.info.protectionLevel; 7836 } 7837 } 7838 7839 if (r != null) { 7840 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 7841 } 7842 7843 N = pkg.instrumentation.size(); 7844 r = null; 7845 for (i=0; i<N; i++) { 7846 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7847 a.info.packageName = pkg.applicationInfo.packageName; 7848 a.info.sourceDir = pkg.applicationInfo.sourceDir; 7849 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 7850 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 7851 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 7852 a.info.dataDir = pkg.applicationInfo.dataDir; 7853 a.info.deviceEncryptedDataDir = pkg.applicationInfo.deviceEncryptedDataDir; 7854 a.info.credentialEncryptedDataDir = pkg.applicationInfo.credentialEncryptedDataDir; 7855 7856 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 7857 // need other information about the application, like the ABI and what not ? 7858 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 7859 mInstrumentation.put(a.getComponentName(), a); 7860 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7861 if (r == null) { 7862 r = new StringBuilder(256); 7863 } else { 7864 r.append(' '); 7865 } 7866 r.append(a.info.name); 7867 } 7868 } 7869 if (r != null) { 7870 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 7871 } 7872 7873 if (pkg.protectedBroadcasts != null) { 7874 N = pkg.protectedBroadcasts.size(); 7875 for (i=0; i<N; i++) { 7876 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 7877 } 7878 } 7879 7880 pkgSetting.setTimeStamp(scanFileTime); 7881 7882 // Create idmap files for pairs of (packages, overlay packages). 7883 // Note: "android", ie framework-res.apk, is handled by native layers. 7884 if (pkg.mOverlayTarget != null) { 7885 // This is an overlay package. 7886 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 7887 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 7888 mOverlays.put(pkg.mOverlayTarget, 7889 new ArrayMap<String, PackageParser.Package>()); 7890 } 7891 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 7892 map.put(pkg.packageName, pkg); 7893 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 7894 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 7895 createIdmapFailed = true; 7896 } 7897 } 7898 } else if (mOverlays.containsKey(pkg.packageName) && 7899 !pkg.packageName.equals("android")) { 7900 // This is a regular package, with one or more known overlay packages. 7901 createIdmapsForPackageLI(pkg); 7902 } 7903 } 7904 7905 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7906 7907 if (createIdmapFailed) { 7908 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7909 "scanPackageLI failed to createIdmap"); 7910 } 7911 return pkg; 7912 } 7913 7914 /** 7915 * Derive the ABI of a non-system package located at {@code scanFile}. This information 7916 * is derived purely on the basis of the contents of {@code scanFile} and 7917 * {@code cpuAbiOverride}. 7918 * 7919 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 7920 */ 7921 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 7922 String cpuAbiOverride, boolean extractLibs) 7923 throws PackageManagerException { 7924 // TODO: We can probably be smarter about this stuff. For installed apps, 7925 // we can calculate this information at install time once and for all. For 7926 // system apps, we can probably assume that this information doesn't change 7927 // after the first boot scan. As things stand, we do lots of unnecessary work. 7928 7929 // Give ourselves some initial paths; we'll come back for another 7930 // pass once we've determined ABI below. 7931 setNativeLibraryPaths(pkg); 7932 7933 // We would never need to extract libs for forward-locked and external packages, 7934 // since the container service will do it for us. We shouldn't attempt to 7935 // extract libs from system app when it was not updated. 7936 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 7937 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 7938 extractLibs = false; 7939 } 7940 7941 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7942 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7943 7944 NativeLibraryHelper.Handle handle = null; 7945 try { 7946 handle = NativeLibraryHelper.Handle.create(pkg); 7947 // TODO(multiArch): This can be null for apps that didn't go through the 7948 // usual installation process. We can calculate it again, like we 7949 // do during install time. 7950 // 7951 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7952 // unnecessary. 7953 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7954 7955 // Null out the abis so that they can be recalculated. 7956 pkg.applicationInfo.primaryCpuAbi = null; 7957 pkg.applicationInfo.secondaryCpuAbi = null; 7958 if (isMultiArch(pkg.applicationInfo)) { 7959 // Warn if we've set an abiOverride for multi-lib packages.. 7960 // By definition, we need to copy both 32 and 64 bit libraries for 7961 // such packages. 7962 if (pkg.cpuAbiOverride != null 7963 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7964 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7965 } 7966 7967 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7968 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7969 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7970 if (extractLibs) { 7971 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7972 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7973 useIsaSpecificSubdirs); 7974 } else { 7975 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7976 } 7977 } 7978 7979 maybeThrowExceptionForMultiArchCopy( 7980 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7981 7982 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7983 if (extractLibs) { 7984 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7985 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7986 useIsaSpecificSubdirs); 7987 } else { 7988 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7989 } 7990 } 7991 7992 maybeThrowExceptionForMultiArchCopy( 7993 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7994 7995 if (abi64 >= 0) { 7996 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7997 } 7998 7999 if (abi32 >= 0) { 8000 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 8001 if (abi64 >= 0) { 8002 pkg.applicationInfo.secondaryCpuAbi = abi; 8003 } else { 8004 pkg.applicationInfo.primaryCpuAbi = abi; 8005 } 8006 } 8007 } else { 8008 String[] abiList = (cpuAbiOverride != null) ? 8009 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 8010 8011 // Enable gross and lame hacks for apps that are built with old 8012 // SDK tools. We must scan their APKs for renderscript bitcode and 8013 // not launch them if it's present. Don't bother checking on devices 8014 // that don't have 64 bit support. 8015 boolean needsRenderScriptOverride = false; 8016 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 8017 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 8018 abiList = Build.SUPPORTED_32_BIT_ABIS; 8019 needsRenderScriptOverride = true; 8020 } 8021 8022 final int copyRet; 8023 if (extractLibs) { 8024 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8025 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 8026 } else { 8027 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 8028 } 8029 8030 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 8031 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 8032 "Error unpackaging native libs for app, errorCode=" + copyRet); 8033 } 8034 8035 if (copyRet >= 0) { 8036 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 8037 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 8038 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 8039 } else if (needsRenderScriptOverride) { 8040 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 8041 } 8042 } 8043 } catch (IOException ioe) { 8044 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 8045 } finally { 8046 IoUtils.closeQuietly(handle); 8047 } 8048 8049 // Now that we've calculated the ABIs and determined if it's an internal app, 8050 // we will go ahead and populate the nativeLibraryPath. 8051 setNativeLibraryPaths(pkg); 8052 } 8053 8054 /** 8055 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 8056 * i.e, so that all packages can be run inside a single process if required. 8057 * 8058 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 8059 * this function will either try and make the ABI for all packages in {@code packagesForUser} 8060 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 8061 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 8062 * updating a package that belongs to a shared user. 8063 * 8064 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 8065 * adds unnecessary complexity. 8066 */ 8067 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 8068 PackageParser.Package scannedPackage, boolean bootComplete) { 8069 String requiredInstructionSet = null; 8070 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 8071 requiredInstructionSet = VMRuntime.getInstructionSet( 8072 scannedPackage.applicationInfo.primaryCpuAbi); 8073 } 8074 8075 PackageSetting requirer = null; 8076 for (PackageSetting ps : packagesForUser) { 8077 // If packagesForUser contains scannedPackage, we skip it. This will happen 8078 // when scannedPackage is an update of an existing package. Without this check, 8079 // we will never be able to change the ABI of any package belonging to a shared 8080 // user, even if it's compatible with other packages. 8081 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8082 if (ps.primaryCpuAbiString == null) { 8083 continue; 8084 } 8085 8086 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 8087 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 8088 // We have a mismatch between instruction sets (say arm vs arm64) warn about 8089 // this but there's not much we can do. 8090 String errorMessage = "Instruction set mismatch, " 8091 + ((requirer == null) ? "[caller]" : requirer) 8092 + " requires " + requiredInstructionSet + " whereas " + ps 8093 + " requires " + instructionSet; 8094 Slog.w(TAG, errorMessage); 8095 } 8096 8097 if (requiredInstructionSet == null) { 8098 requiredInstructionSet = instructionSet; 8099 requirer = ps; 8100 } 8101 } 8102 } 8103 8104 if (requiredInstructionSet != null) { 8105 String adjustedAbi; 8106 if (requirer != null) { 8107 // requirer != null implies that either scannedPackage was null or that scannedPackage 8108 // did not require an ABI, in which case we have to adjust scannedPackage to match 8109 // the ABI of the set (which is the same as requirer's ABI) 8110 adjustedAbi = requirer.primaryCpuAbiString; 8111 if (scannedPackage != null) { 8112 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 8113 } 8114 } else { 8115 // requirer == null implies that we're updating all ABIs in the set to 8116 // match scannedPackage. 8117 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 8118 } 8119 8120 for (PackageSetting ps : packagesForUser) { 8121 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8122 if (ps.primaryCpuAbiString != null) { 8123 continue; 8124 } 8125 8126 ps.primaryCpuAbiString = adjustedAbi; 8127 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 8128 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 8129 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 8130 mInstaller.rmdex(ps.codePathString, 8131 getDexCodeInstructionSet(getPreferredInstructionSet())); 8132 } 8133 } 8134 } 8135 } 8136 } 8137 8138 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 8139 synchronized (mPackages) { 8140 mResolverReplaced = true; 8141 // Set up information for custom user intent resolution activity. 8142 mResolveActivity.applicationInfo = pkg.applicationInfo; 8143 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 8144 mResolveActivity.packageName = pkg.applicationInfo.packageName; 8145 mResolveActivity.processName = pkg.applicationInfo.packageName; 8146 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8147 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8148 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8149 mResolveActivity.theme = 0; 8150 mResolveActivity.exported = true; 8151 mResolveActivity.enabled = true; 8152 mResolveInfo.activityInfo = mResolveActivity; 8153 mResolveInfo.priority = 0; 8154 mResolveInfo.preferredOrder = 0; 8155 mResolveInfo.match = 0; 8156 mResolveComponentName = mCustomResolverComponentName; 8157 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 8158 mResolveComponentName); 8159 } 8160 } 8161 8162 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 8163 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 8164 8165 // Set up information for ephemeral installer activity 8166 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 8167 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 8168 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 8169 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 8170 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8171 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8172 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8173 mEphemeralInstallerActivity.theme = 0; 8174 mEphemeralInstallerActivity.exported = true; 8175 mEphemeralInstallerActivity.enabled = true; 8176 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 8177 mEphemeralInstallerInfo.priority = 0; 8178 mEphemeralInstallerInfo.preferredOrder = 0; 8179 mEphemeralInstallerInfo.match = 0; 8180 8181 if (DEBUG_EPHEMERAL) { 8182 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 8183 } 8184 } 8185 8186 private static String calculateBundledApkRoot(final String codePathString) { 8187 final File codePath = new File(codePathString); 8188 final File codeRoot; 8189 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 8190 codeRoot = Environment.getRootDirectory(); 8191 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 8192 codeRoot = Environment.getOemDirectory(); 8193 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 8194 codeRoot = Environment.getVendorDirectory(); 8195 } else { 8196 // Unrecognized code path; take its top real segment as the apk root: 8197 // e.g. /something/app/blah.apk => /something 8198 try { 8199 File f = codePath.getCanonicalFile(); 8200 File parent = f.getParentFile(); // non-null because codePath is a file 8201 File tmp; 8202 while ((tmp = parent.getParentFile()) != null) { 8203 f = parent; 8204 parent = tmp; 8205 } 8206 codeRoot = f; 8207 Slog.w(TAG, "Unrecognized code path " 8208 + codePath + " - using " + codeRoot); 8209 } catch (IOException e) { 8210 // Can't canonicalize the code path -- shenanigans? 8211 Slog.w(TAG, "Can't canonicalize code path " + codePath); 8212 return Environment.getRootDirectory().getPath(); 8213 } 8214 } 8215 return codeRoot.getPath(); 8216 } 8217 8218 /** 8219 * Derive and set the location of native libraries for the given package, 8220 * which varies depending on where and how the package was installed. 8221 */ 8222 private void setNativeLibraryPaths(PackageParser.Package pkg) { 8223 final ApplicationInfo info = pkg.applicationInfo; 8224 final String codePath = pkg.codePath; 8225 final File codeFile = new File(codePath); 8226 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 8227 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 8228 8229 info.nativeLibraryRootDir = null; 8230 info.nativeLibraryRootRequiresIsa = false; 8231 info.nativeLibraryDir = null; 8232 info.secondaryNativeLibraryDir = null; 8233 8234 if (isApkFile(codeFile)) { 8235 // Monolithic install 8236 if (bundledApp) { 8237 // If "/system/lib64/apkname" exists, assume that is the per-package 8238 // native library directory to use; otherwise use "/system/lib/apkname". 8239 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 8240 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 8241 getPrimaryInstructionSet(info)); 8242 8243 // This is a bundled system app so choose the path based on the ABI. 8244 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 8245 // is just the default path. 8246 final String apkName = deriveCodePathName(codePath); 8247 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 8248 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 8249 apkName).getAbsolutePath(); 8250 8251 if (info.secondaryCpuAbi != null) { 8252 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 8253 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 8254 secondaryLibDir, apkName).getAbsolutePath(); 8255 } 8256 } else if (asecApp) { 8257 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 8258 .getAbsolutePath(); 8259 } else { 8260 final String apkName = deriveCodePathName(codePath); 8261 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 8262 .getAbsolutePath(); 8263 } 8264 8265 info.nativeLibraryRootRequiresIsa = false; 8266 info.nativeLibraryDir = info.nativeLibraryRootDir; 8267 } else { 8268 // Cluster install 8269 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 8270 info.nativeLibraryRootRequiresIsa = true; 8271 8272 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 8273 getPrimaryInstructionSet(info)).getAbsolutePath(); 8274 8275 if (info.secondaryCpuAbi != null) { 8276 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 8277 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 8278 } 8279 } 8280 } 8281 8282 /** 8283 * Calculate the abis and roots for a bundled app. These can uniquely 8284 * be determined from the contents of the system partition, i.e whether 8285 * it contains 64 or 32 bit shared libraries etc. We do not validate any 8286 * of this information, and instead assume that the system was built 8287 * sensibly. 8288 */ 8289 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 8290 PackageSetting pkgSetting) { 8291 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 8292 8293 // If "/system/lib64/apkname" exists, assume that is the per-package 8294 // native library directory to use; otherwise use "/system/lib/apkname". 8295 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 8296 setBundledAppAbi(pkg, apkRoot, apkName); 8297 // pkgSetting might be null during rescan following uninstall of updates 8298 // to a bundled app, so accommodate that possibility. The settings in 8299 // that case will be established later from the parsed package. 8300 // 8301 // If the settings aren't null, sync them up with what we've just derived. 8302 // note that apkRoot isn't stored in the package settings. 8303 if (pkgSetting != null) { 8304 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8305 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8306 } 8307 } 8308 8309 /** 8310 * Deduces the ABI of a bundled app and sets the relevant fields on the 8311 * parsed pkg object. 8312 * 8313 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 8314 * under which system libraries are installed. 8315 * @param apkName the name of the installed package. 8316 */ 8317 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 8318 final File codeFile = new File(pkg.codePath); 8319 8320 final boolean has64BitLibs; 8321 final boolean has32BitLibs; 8322 if (isApkFile(codeFile)) { 8323 // Monolithic install 8324 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 8325 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 8326 } else { 8327 // Cluster install 8328 final File rootDir = new File(codeFile, LIB_DIR_NAME); 8329 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 8330 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 8331 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 8332 has64BitLibs = (new File(rootDir, isa)).exists(); 8333 } else { 8334 has64BitLibs = false; 8335 } 8336 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 8337 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 8338 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 8339 has32BitLibs = (new File(rootDir, isa)).exists(); 8340 } else { 8341 has32BitLibs = false; 8342 } 8343 } 8344 8345 if (has64BitLibs && !has32BitLibs) { 8346 // The package has 64 bit libs, but not 32 bit libs. Its primary 8347 // ABI should be 64 bit. We can safely assume here that the bundled 8348 // native libraries correspond to the most preferred ABI in the list. 8349 8350 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8351 pkg.applicationInfo.secondaryCpuAbi = null; 8352 } else if (has32BitLibs && !has64BitLibs) { 8353 // The package has 32 bit libs but not 64 bit libs. Its primary 8354 // ABI should be 32 bit. 8355 8356 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8357 pkg.applicationInfo.secondaryCpuAbi = null; 8358 } else if (has32BitLibs && has64BitLibs) { 8359 // The application has both 64 and 32 bit bundled libraries. We check 8360 // here that the app declares multiArch support, and warn if it doesn't. 8361 // 8362 // We will be lenient here and record both ABIs. The primary will be the 8363 // ABI that's higher on the list, i.e, a device that's configured to prefer 8364 // 64 bit apps will see a 64 bit primary ABI, 8365 8366 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 8367 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 8368 } 8369 8370 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 8371 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8372 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8373 } else { 8374 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8375 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8376 } 8377 } else { 8378 pkg.applicationInfo.primaryCpuAbi = null; 8379 pkg.applicationInfo.secondaryCpuAbi = null; 8380 } 8381 } 8382 8383 private void killApplication(String pkgName, int appId, String reason) { 8384 // Request the ActivityManager to kill the process(only for existing packages) 8385 // so that we do not end up in a confused state while the user is still using the older 8386 // version of the application while the new one gets installed. 8387 IActivityManager am = ActivityManagerNative.getDefault(); 8388 if (am != null) { 8389 try { 8390 am.killApplicationWithAppId(pkgName, appId, reason); 8391 } catch (RemoteException e) { 8392 } 8393 } 8394 } 8395 8396 void removePackageLI(PackageSetting ps, boolean chatty) { 8397 if (DEBUG_INSTALL) { 8398 if (chatty) 8399 Log.d(TAG, "Removing package " + ps.name); 8400 } 8401 8402 // writer 8403 synchronized (mPackages) { 8404 mPackages.remove(ps.name); 8405 final PackageParser.Package pkg = ps.pkg; 8406 if (pkg != null) { 8407 cleanPackageDataStructuresLILPw(pkg, chatty); 8408 } 8409 } 8410 } 8411 8412 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 8413 if (DEBUG_INSTALL) { 8414 if (chatty) 8415 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 8416 } 8417 8418 // writer 8419 synchronized (mPackages) { 8420 mPackages.remove(pkg.applicationInfo.packageName); 8421 cleanPackageDataStructuresLILPw(pkg, chatty); 8422 } 8423 } 8424 8425 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 8426 int N = pkg.providers.size(); 8427 StringBuilder r = null; 8428 int i; 8429 for (i=0; i<N; i++) { 8430 PackageParser.Provider p = pkg.providers.get(i); 8431 mProviders.removeProvider(p); 8432 if (p.info.authority == null) { 8433 8434 /* There was another ContentProvider with this authority when 8435 * this app was installed so this authority is null, 8436 * Ignore it as we don't have to unregister the provider. 8437 */ 8438 continue; 8439 } 8440 String names[] = p.info.authority.split(";"); 8441 for (int j = 0; j < names.length; j++) { 8442 if (mProvidersByAuthority.get(names[j]) == p) { 8443 mProvidersByAuthority.remove(names[j]); 8444 if (DEBUG_REMOVE) { 8445 if (chatty) 8446 Log.d(TAG, "Unregistered content provider: " + names[j] 8447 + ", className = " + p.info.name + ", isSyncable = " 8448 + p.info.isSyncable); 8449 } 8450 } 8451 } 8452 if (DEBUG_REMOVE && chatty) { 8453 if (r == null) { 8454 r = new StringBuilder(256); 8455 } else { 8456 r.append(' '); 8457 } 8458 r.append(p.info.name); 8459 } 8460 } 8461 if (r != null) { 8462 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 8463 } 8464 8465 N = pkg.services.size(); 8466 r = null; 8467 for (i=0; i<N; i++) { 8468 PackageParser.Service s = pkg.services.get(i); 8469 mServices.removeService(s); 8470 if (chatty) { 8471 if (r == null) { 8472 r = new StringBuilder(256); 8473 } else { 8474 r.append(' '); 8475 } 8476 r.append(s.info.name); 8477 } 8478 } 8479 if (r != null) { 8480 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 8481 } 8482 8483 N = pkg.receivers.size(); 8484 r = null; 8485 for (i=0; i<N; i++) { 8486 PackageParser.Activity a = pkg.receivers.get(i); 8487 mReceivers.removeActivity(a, "receiver"); 8488 if (DEBUG_REMOVE && chatty) { 8489 if (r == null) { 8490 r = new StringBuilder(256); 8491 } else { 8492 r.append(' '); 8493 } 8494 r.append(a.info.name); 8495 } 8496 } 8497 if (r != null) { 8498 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 8499 } 8500 8501 N = pkg.activities.size(); 8502 r = null; 8503 for (i=0; i<N; i++) { 8504 PackageParser.Activity a = pkg.activities.get(i); 8505 mActivities.removeActivity(a, "activity"); 8506 if (DEBUG_REMOVE && chatty) { 8507 if (r == null) { 8508 r = new StringBuilder(256); 8509 } else { 8510 r.append(' '); 8511 } 8512 r.append(a.info.name); 8513 } 8514 } 8515 if (r != null) { 8516 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 8517 } 8518 8519 N = pkg.permissions.size(); 8520 r = null; 8521 for (i=0; i<N; i++) { 8522 PackageParser.Permission p = pkg.permissions.get(i); 8523 BasePermission bp = mSettings.mPermissions.get(p.info.name); 8524 if (bp == null) { 8525 bp = mSettings.mPermissionTrees.get(p.info.name); 8526 } 8527 if (bp != null && bp.perm == p) { 8528 bp.perm = null; 8529 if (DEBUG_REMOVE && chatty) { 8530 if (r == null) { 8531 r = new StringBuilder(256); 8532 } else { 8533 r.append(' '); 8534 } 8535 r.append(p.info.name); 8536 } 8537 } 8538 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8539 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 8540 if (appOpPkgs != null) { 8541 appOpPkgs.remove(pkg.packageName); 8542 } 8543 } 8544 } 8545 if (r != null) { 8546 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8547 } 8548 8549 N = pkg.requestedPermissions.size(); 8550 r = null; 8551 for (i=0; i<N; i++) { 8552 String perm = pkg.requestedPermissions.get(i); 8553 BasePermission bp = mSettings.mPermissions.get(perm); 8554 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8555 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 8556 if (appOpPkgs != null) { 8557 appOpPkgs.remove(pkg.packageName); 8558 if (appOpPkgs.isEmpty()) { 8559 mAppOpPermissionPackages.remove(perm); 8560 } 8561 } 8562 } 8563 } 8564 if (r != null) { 8565 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8566 } 8567 8568 N = pkg.instrumentation.size(); 8569 r = null; 8570 for (i=0; i<N; i++) { 8571 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8572 mInstrumentation.remove(a.getComponentName()); 8573 if (DEBUG_REMOVE && chatty) { 8574 if (r == null) { 8575 r = new StringBuilder(256); 8576 } else { 8577 r.append(' '); 8578 } 8579 r.append(a.info.name); 8580 } 8581 } 8582 if (r != null) { 8583 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 8584 } 8585 8586 r = null; 8587 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8588 // Only system apps can hold shared libraries. 8589 if (pkg.libraryNames != null) { 8590 for (i=0; i<pkg.libraryNames.size(); i++) { 8591 String name = pkg.libraryNames.get(i); 8592 SharedLibraryEntry cur = mSharedLibraries.get(name); 8593 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 8594 mSharedLibraries.remove(name); 8595 if (DEBUG_REMOVE && chatty) { 8596 if (r == null) { 8597 r = new StringBuilder(256); 8598 } else { 8599 r.append(' '); 8600 } 8601 r.append(name); 8602 } 8603 } 8604 } 8605 } 8606 } 8607 if (r != null) { 8608 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 8609 } 8610 } 8611 8612 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 8613 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 8614 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 8615 return true; 8616 } 8617 } 8618 return false; 8619 } 8620 8621 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 8622 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 8623 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 8624 8625 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 8626 int flags) { 8627 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 8628 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 8629 } 8630 8631 private void updatePermissionsLPw(String changingPkg, 8632 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 8633 // Make sure there are no dangling permission trees. 8634 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 8635 while (it.hasNext()) { 8636 final BasePermission bp = it.next(); 8637 if (bp.packageSetting == null) { 8638 // We may not yet have parsed the package, so just see if 8639 // we still know about its settings. 8640 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8641 } 8642 if (bp.packageSetting == null) { 8643 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 8644 + " from package " + bp.sourcePackage); 8645 it.remove(); 8646 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8647 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8648 Slog.i(TAG, "Removing old permission tree: " + bp.name 8649 + " from package " + bp.sourcePackage); 8650 flags |= UPDATE_PERMISSIONS_ALL; 8651 it.remove(); 8652 } 8653 } 8654 } 8655 8656 // Make sure all dynamic permissions have been assigned to a package, 8657 // and make sure there are no dangling permissions. 8658 it = mSettings.mPermissions.values().iterator(); 8659 while (it.hasNext()) { 8660 final BasePermission bp = it.next(); 8661 if (bp.type == BasePermission.TYPE_DYNAMIC) { 8662 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 8663 + bp.name + " pkg=" + bp.sourcePackage 8664 + " info=" + bp.pendingInfo); 8665 if (bp.packageSetting == null && bp.pendingInfo != null) { 8666 final BasePermission tree = findPermissionTreeLP(bp.name); 8667 if (tree != null && tree.perm != null) { 8668 bp.packageSetting = tree.packageSetting; 8669 bp.perm = new PackageParser.Permission(tree.perm.owner, 8670 new PermissionInfo(bp.pendingInfo)); 8671 bp.perm.info.packageName = tree.perm.info.packageName; 8672 bp.perm.info.name = bp.name; 8673 bp.uid = tree.uid; 8674 } 8675 } 8676 } 8677 if (bp.packageSetting == null) { 8678 // We may not yet have parsed the package, so just see if 8679 // we still know about its settings. 8680 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8681 } 8682 if (bp.packageSetting == null) { 8683 Slog.w(TAG, "Removing dangling permission: " + bp.name 8684 + " from package " + bp.sourcePackage); 8685 it.remove(); 8686 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8687 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8688 Slog.i(TAG, "Removing old permission: " + bp.name 8689 + " from package " + bp.sourcePackage); 8690 flags |= UPDATE_PERMISSIONS_ALL; 8691 it.remove(); 8692 } 8693 } 8694 } 8695 8696 // Now update the permissions for all packages, in particular 8697 // replace the granted permissions of the system packages. 8698 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 8699 for (PackageParser.Package pkg : mPackages.values()) { 8700 if (pkg != pkgInfo) { 8701 // Only replace for packages on requested volume 8702 final String volumeUuid = getVolumeUuidForPackage(pkg); 8703 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 8704 && Objects.equals(replaceVolumeUuid, volumeUuid); 8705 grantPermissionsLPw(pkg, replace, changingPkg); 8706 } 8707 } 8708 } 8709 8710 if (pkgInfo != null) { 8711 // Only replace for packages on requested volume 8712 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 8713 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 8714 && Objects.equals(replaceVolumeUuid, volumeUuid); 8715 grantPermissionsLPw(pkgInfo, replace, changingPkg); 8716 } 8717 } 8718 8719 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 8720 String packageOfInterest) { 8721 // IMPORTANT: There are two types of permissions: install and runtime. 8722 // Install time permissions are granted when the app is installed to 8723 // all device users and users added in the future. Runtime permissions 8724 // are granted at runtime explicitly to specific users. Normal and signature 8725 // protected permissions are install time permissions. Dangerous permissions 8726 // are install permissions if the app's target SDK is Lollipop MR1 or older, 8727 // otherwise they are runtime permissions. This function does not manage 8728 // runtime permissions except for the case an app targeting Lollipop MR1 8729 // being upgraded to target a newer SDK, in which case dangerous permissions 8730 // are transformed from install time to runtime ones. 8731 8732 final PackageSetting ps = (PackageSetting) pkg.mExtras; 8733 if (ps == null) { 8734 return; 8735 } 8736 8737 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 8738 8739 PermissionsState permissionsState = ps.getPermissionsState(); 8740 PermissionsState origPermissions = permissionsState; 8741 8742 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 8743 8744 boolean runtimePermissionsRevoked = false; 8745 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 8746 8747 boolean changedInstallPermission = false; 8748 8749 if (replace) { 8750 ps.installPermissionsFixed = false; 8751 if (!ps.isSharedUser()) { 8752 origPermissions = new PermissionsState(permissionsState); 8753 permissionsState.reset(); 8754 } else { 8755 // We need to know only about runtime permission changes since the 8756 // calling code always writes the install permissions state but 8757 // the runtime ones are written only if changed. The only cases of 8758 // changed runtime permissions here are promotion of an install to 8759 // runtime and revocation of a runtime from a shared user. 8760 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 8761 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 8762 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 8763 runtimePermissionsRevoked = true; 8764 } 8765 } 8766 } 8767 8768 permissionsState.setGlobalGids(mGlobalGids); 8769 8770 final int N = pkg.requestedPermissions.size(); 8771 for (int i=0; i<N; i++) { 8772 final String name = pkg.requestedPermissions.get(i); 8773 final BasePermission bp = mSettings.mPermissions.get(name); 8774 8775 if (DEBUG_INSTALL) { 8776 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 8777 } 8778 8779 if (bp == null || bp.packageSetting == null) { 8780 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8781 Slog.w(TAG, "Unknown permission " + name 8782 + " in package " + pkg.packageName); 8783 } 8784 continue; 8785 } 8786 8787 final String perm = bp.name; 8788 boolean allowedSig = false; 8789 int grant = GRANT_DENIED; 8790 8791 // Keep track of app op permissions. 8792 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8793 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 8794 if (pkgs == null) { 8795 pkgs = new ArraySet<>(); 8796 mAppOpPermissionPackages.put(bp.name, pkgs); 8797 } 8798 pkgs.add(pkg.packageName); 8799 } 8800 8801 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 8802 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 8803 >= Build.VERSION_CODES.M; 8804 switch (level) { 8805 case PermissionInfo.PROTECTION_NORMAL: { 8806 // For all apps normal permissions are install time ones. 8807 grant = GRANT_INSTALL; 8808 } break; 8809 8810 case PermissionInfo.PROTECTION_DANGEROUS: { 8811 // If a permission review is required for legacy apps we represent 8812 // their permissions as always granted runtime ones since we need 8813 // to keep the review required permission flag per user while an 8814 // install permission's state is shared across all users. 8815 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 8816 // For legacy apps dangerous permissions are install time ones. 8817 grant = GRANT_INSTALL; 8818 } else if (origPermissions.hasInstallPermission(bp.name)) { 8819 // For legacy apps that became modern, install becomes runtime. 8820 grant = GRANT_UPGRADE; 8821 } else if (mPromoteSystemApps 8822 && isSystemApp(ps) 8823 && mExistingSystemPackages.contains(ps.name)) { 8824 // For legacy system apps, install becomes runtime. 8825 // We cannot check hasInstallPermission() for system apps since those 8826 // permissions were granted implicitly and not persisted pre-M. 8827 grant = GRANT_UPGRADE; 8828 } else { 8829 // For modern apps keep runtime permissions unchanged. 8830 grant = GRANT_RUNTIME; 8831 } 8832 } break; 8833 8834 case PermissionInfo.PROTECTION_SIGNATURE: { 8835 // For all apps signature permissions are install time ones. 8836 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 8837 if (allowedSig) { 8838 grant = GRANT_INSTALL; 8839 } 8840 } break; 8841 } 8842 8843 if (DEBUG_INSTALL) { 8844 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 8845 } 8846 8847 if (grant != GRANT_DENIED) { 8848 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 8849 // If this is an existing, non-system package, then 8850 // we can't add any new permissions to it. 8851 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 8852 // Except... if this is a permission that was added 8853 // to the platform (note: need to only do this when 8854 // updating the platform). 8855 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 8856 grant = GRANT_DENIED; 8857 } 8858 } 8859 } 8860 8861 switch (grant) { 8862 case GRANT_INSTALL: { 8863 // Revoke this as runtime permission to handle the case of 8864 // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps 8865 for (int userId : UserManagerService.getInstance().getUserIds()) { 8866 if (origPermissions.getRuntimePermissionState( 8867 bp.name, userId) != null) { 8868 // Revoke the runtime permission and clear the flags. 8869 origPermissions.revokeRuntimePermission(bp, userId); 8870 origPermissions.updatePermissionFlags(bp, userId, 8871 PackageManager.MASK_PERMISSION_FLAGS, 0); 8872 // If we revoked a permission permission, we have to write. 8873 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8874 changedRuntimePermissionUserIds, userId); 8875 } 8876 } 8877 // Grant an install permission. 8878 if (permissionsState.grantInstallPermission(bp) != 8879 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8880 changedInstallPermission = true; 8881 } 8882 } break; 8883 8884 case GRANT_RUNTIME: { 8885 // Grant previously granted runtime permissions. 8886 for (int userId : UserManagerService.getInstance().getUserIds()) { 8887 PermissionState permissionState = origPermissions 8888 .getRuntimePermissionState(bp.name, userId); 8889 int flags = permissionState != null 8890 ? permissionState.getFlags() : 0; 8891 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8892 if (permissionsState.grantRuntimePermission(bp, userId) == 8893 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8894 // If we cannot put the permission as it was, we have to write. 8895 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8896 changedRuntimePermissionUserIds, userId); 8897 } 8898 // If the app supports runtime permissions no need for a review. 8899 if (Build.PERMISSIONS_REVIEW_REQUIRED 8900 && appSupportsRuntimePermissions 8901 && (flags & PackageManager 8902 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 8903 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 8904 // Since we changed the flags, we have to write. 8905 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8906 changedRuntimePermissionUserIds, userId); 8907 } 8908 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 8909 && !appSupportsRuntimePermissions) { 8910 // For legacy apps that need a permission review, every new 8911 // runtime permission is granted but it is pending a review. 8912 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 8913 permissionsState.grantRuntimePermission(bp, userId); 8914 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 8915 // We changed the permission and flags, hence have to write. 8916 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8917 changedRuntimePermissionUserIds, userId); 8918 } 8919 } 8920 // Propagate the permission flags. 8921 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 8922 } 8923 } break; 8924 8925 case GRANT_UPGRADE: { 8926 // Grant runtime permissions for a previously held install permission. 8927 PermissionState permissionState = origPermissions 8928 .getInstallPermissionState(bp.name); 8929 final int flags = permissionState != null ? permissionState.getFlags() : 0; 8930 8931 if (origPermissions.revokeInstallPermission(bp) 8932 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 8933 // We will be transferring the permission flags, so clear them. 8934 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 8935 PackageManager.MASK_PERMISSION_FLAGS, 0); 8936 changedInstallPermission = true; 8937 } 8938 8939 // If the permission is not to be promoted to runtime we ignore it and 8940 // also its other flags as they are not applicable to install permissions. 8941 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 8942 for (int userId : currentUserIds) { 8943 if (permissionsState.grantRuntimePermission(bp, userId) != 8944 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8945 // Transfer the permission flags. 8946 permissionsState.updatePermissionFlags(bp, userId, 8947 flags, flags); 8948 // If we granted the permission, we have to write. 8949 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8950 changedRuntimePermissionUserIds, userId); 8951 } 8952 } 8953 } 8954 } break; 8955 8956 default: { 8957 if (packageOfInterest == null 8958 || packageOfInterest.equals(pkg.packageName)) { 8959 Slog.w(TAG, "Not granting permission " + perm 8960 + " to package " + pkg.packageName 8961 + " because it was previously installed without"); 8962 } 8963 } break; 8964 } 8965 } else { 8966 if (permissionsState.revokeInstallPermission(bp) != 8967 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8968 // Also drop the permission flags. 8969 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 8970 PackageManager.MASK_PERMISSION_FLAGS, 0); 8971 changedInstallPermission = true; 8972 Slog.i(TAG, "Un-granting permission " + perm 8973 + " from package " + pkg.packageName 8974 + " (protectionLevel=" + bp.protectionLevel 8975 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8976 + ")"); 8977 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 8978 // Don't print warning for app op permissions, since it is fine for them 8979 // not to be granted, there is a UI for the user to decide. 8980 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8981 Slog.w(TAG, "Not granting permission " + perm 8982 + " to package " + pkg.packageName 8983 + " (protectionLevel=" + bp.protectionLevel 8984 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8985 + ")"); 8986 } 8987 } 8988 } 8989 } 8990 8991 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 8992 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 8993 // This is the first that we have heard about this package, so the 8994 // permissions we have now selected are fixed until explicitly 8995 // changed. 8996 ps.installPermissionsFixed = true; 8997 } 8998 8999 // Persist the runtime permissions state for users with changes. If permissions 9000 // were revoked because no app in the shared user declares them we have to 9001 // write synchronously to avoid losing runtime permissions state. 9002 for (int userId : changedRuntimePermissionUserIds) { 9003 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 9004 } 9005 9006 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9007 } 9008 9009 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 9010 boolean allowed = false; 9011 final int NP = PackageParser.NEW_PERMISSIONS.length; 9012 for (int ip=0; ip<NP; ip++) { 9013 final PackageParser.NewPermissionInfo npi 9014 = PackageParser.NEW_PERMISSIONS[ip]; 9015 if (npi.name.equals(perm) 9016 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 9017 allowed = true; 9018 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 9019 + pkg.packageName); 9020 break; 9021 } 9022 } 9023 return allowed; 9024 } 9025 9026 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 9027 BasePermission bp, PermissionsState origPermissions) { 9028 boolean allowed; 9029 allowed = (compareSignatures( 9030 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 9031 == PackageManager.SIGNATURE_MATCH) 9032 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 9033 == PackageManager.SIGNATURE_MATCH); 9034 if (!allowed && (bp.protectionLevel 9035 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 9036 if (isSystemApp(pkg)) { 9037 // For updated system applications, a system permission 9038 // is granted only if it had been defined by the original application. 9039 if (pkg.isUpdatedSystemApp()) { 9040 final PackageSetting sysPs = mSettings 9041 .getDisabledSystemPkgLPr(pkg.packageName); 9042 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 9043 // If the original was granted this permission, we take 9044 // that grant decision as read and propagate it to the 9045 // update. 9046 if (sysPs.isPrivileged()) { 9047 allowed = true; 9048 } 9049 } else { 9050 // The system apk may have been updated with an older 9051 // version of the one on the data partition, but which 9052 // granted a new system permission that it didn't have 9053 // before. In this case we do want to allow the app to 9054 // now get the new permission if the ancestral apk is 9055 // privileged to get it. 9056 if (sysPs.pkg != null && sysPs.isPrivileged()) { 9057 for (int j=0; 9058 j<sysPs.pkg.requestedPermissions.size(); j++) { 9059 if (perm.equals( 9060 sysPs.pkg.requestedPermissions.get(j))) { 9061 allowed = true; 9062 break; 9063 } 9064 } 9065 } 9066 } 9067 } else { 9068 allowed = isPrivilegedApp(pkg); 9069 } 9070 } 9071 } 9072 if (!allowed) { 9073 if (!allowed && (bp.protectionLevel 9074 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 9075 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 9076 // If this was a previously normal/dangerous permission that got moved 9077 // to a system permission as part of the runtime permission redesign, then 9078 // we still want to blindly grant it to old apps. 9079 allowed = true; 9080 } 9081 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 9082 && pkg.packageName.equals(mRequiredInstallerPackage)) { 9083 // If this permission is to be granted to the system installer and 9084 // this app is an installer, then it gets the permission. 9085 allowed = true; 9086 } 9087 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 9088 && pkg.packageName.equals(mRequiredVerifierPackage)) { 9089 // If this permission is to be granted to the system verifier and 9090 // this app is a verifier, then it gets the permission. 9091 allowed = true; 9092 } 9093 if (!allowed && (bp.protectionLevel 9094 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 9095 && isSystemApp(pkg)) { 9096 // Any pre-installed system app is allowed to get this permission. 9097 allowed = true; 9098 } 9099 if (!allowed && (bp.protectionLevel 9100 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 9101 // For development permissions, a development permission 9102 // is granted only if it was already granted. 9103 allowed = origPermissions.hasInstallPermission(perm); 9104 } 9105 } 9106 return allowed; 9107 } 9108 9109 final class ActivityIntentResolver 9110 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 9111 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9112 boolean defaultOnly, int userId) { 9113 if (!sUserManager.exists(userId)) return null; 9114 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9115 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9116 } 9117 9118 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9119 int userId) { 9120 if (!sUserManager.exists(userId)) return null; 9121 mFlags = flags; 9122 return super.queryIntent(intent, resolvedType, 9123 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9124 } 9125 9126 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9127 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 9128 if (!sUserManager.exists(userId)) return null; 9129 if (packageActivities == null) { 9130 return null; 9131 } 9132 mFlags = flags; 9133 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9134 final int N = packageActivities.size(); 9135 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 9136 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 9137 9138 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 9139 for (int i = 0; i < N; ++i) { 9140 intentFilters = packageActivities.get(i).intents; 9141 if (intentFilters != null && intentFilters.size() > 0) { 9142 PackageParser.ActivityIntentInfo[] array = 9143 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 9144 intentFilters.toArray(array); 9145 listCut.add(array); 9146 } 9147 } 9148 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9149 } 9150 9151 public final void addActivity(PackageParser.Activity a, String type) { 9152 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 9153 mActivities.put(a.getComponentName(), a); 9154 if (DEBUG_SHOW_INFO) 9155 Log.v( 9156 TAG, " " + type + " " + 9157 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 9158 if (DEBUG_SHOW_INFO) 9159 Log.v(TAG, " Class=" + a.info.name); 9160 final int NI = a.intents.size(); 9161 for (int j=0; j<NI; j++) { 9162 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 9163 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 9164 intent.setPriority(0); 9165 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 9166 + a.className + " with priority > 0, forcing to 0"); 9167 } 9168 if (DEBUG_SHOW_INFO) { 9169 Log.v(TAG, " IntentFilter:"); 9170 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9171 } 9172 if (!intent.debugCheck()) { 9173 Log.w(TAG, "==> For Activity " + a.info.name); 9174 } 9175 addFilter(intent); 9176 } 9177 } 9178 9179 public final void removeActivity(PackageParser.Activity a, String type) { 9180 mActivities.remove(a.getComponentName()); 9181 if (DEBUG_SHOW_INFO) { 9182 Log.v(TAG, " " + type + " " 9183 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 9184 : a.info.name) + ":"); 9185 Log.v(TAG, " Class=" + a.info.name); 9186 } 9187 final int NI = a.intents.size(); 9188 for (int j=0; j<NI; j++) { 9189 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 9190 if (DEBUG_SHOW_INFO) { 9191 Log.v(TAG, " IntentFilter:"); 9192 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9193 } 9194 removeFilter(intent); 9195 } 9196 } 9197 9198 @Override 9199 protected boolean allowFilterResult( 9200 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 9201 ActivityInfo filterAi = filter.activity.info; 9202 for (int i=dest.size()-1; i>=0; i--) { 9203 ActivityInfo destAi = dest.get(i).activityInfo; 9204 if (destAi.name == filterAi.name 9205 && destAi.packageName == filterAi.packageName) { 9206 return false; 9207 } 9208 } 9209 return true; 9210 } 9211 9212 @Override 9213 protected ActivityIntentInfo[] newArray(int size) { 9214 return new ActivityIntentInfo[size]; 9215 } 9216 9217 @Override 9218 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 9219 if (!sUserManager.exists(userId)) return true; 9220 PackageParser.Package p = filter.activity.owner; 9221 if (p != null) { 9222 PackageSetting ps = (PackageSetting)p.mExtras; 9223 if (ps != null) { 9224 // System apps are never considered stopped for purposes of 9225 // filtering, because there may be no way for the user to 9226 // actually re-launch them. 9227 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 9228 && ps.getStopped(userId); 9229 } 9230 } 9231 return false; 9232 } 9233 9234 @Override 9235 protected boolean isPackageForFilter(String packageName, 9236 PackageParser.ActivityIntentInfo info) { 9237 return packageName.equals(info.activity.owner.packageName); 9238 } 9239 9240 @Override 9241 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 9242 int match, int userId) { 9243 if (!sUserManager.exists(userId)) return null; 9244 if (!mSettings.isEnabledAndVisibleLPr(info.activity.info, mFlags, userId)) { 9245 return null; 9246 } 9247 final PackageParser.Activity activity = info.activity; 9248 if (mSafeMode && (activity.info.applicationInfo.flags 9249 &ApplicationInfo.FLAG_SYSTEM) == 0) { 9250 return null; 9251 } 9252 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 9253 if (ps == null) { 9254 return null; 9255 } 9256 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 9257 ps.readUserState(userId), userId); 9258 if (ai == null) { 9259 return null; 9260 } 9261 final ResolveInfo res = new ResolveInfo(); 9262 res.activityInfo = ai; 9263 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9264 res.filter = info; 9265 } 9266 if (info != null) { 9267 res.handleAllWebDataURI = info.handleAllWebDataURI(); 9268 } 9269 res.priority = info.getPriority(); 9270 res.preferredOrder = activity.owner.mPreferredOrder; 9271 //System.out.println("Result: " + res.activityInfo.className + 9272 // " = " + res.priority); 9273 res.match = match; 9274 res.isDefault = info.hasDefault; 9275 res.labelRes = info.labelRes; 9276 res.nonLocalizedLabel = info.nonLocalizedLabel; 9277 if (userNeedsBadging(userId)) { 9278 res.noResourceId = true; 9279 } else { 9280 res.icon = info.icon; 9281 } 9282 res.iconResourceId = info.icon; 9283 res.system = res.activityInfo.applicationInfo.isSystemApp(); 9284 return res; 9285 } 9286 9287 @Override 9288 protected void sortResults(List<ResolveInfo> results) { 9289 Collections.sort(results, mResolvePrioritySorter); 9290 } 9291 9292 @Override 9293 protected void dumpFilter(PrintWriter out, String prefix, 9294 PackageParser.ActivityIntentInfo filter) { 9295 out.print(prefix); out.print( 9296 Integer.toHexString(System.identityHashCode(filter.activity))); 9297 out.print(' '); 9298 filter.activity.printComponentShortName(out); 9299 out.print(" filter "); 9300 out.println(Integer.toHexString(System.identityHashCode(filter))); 9301 } 9302 9303 @Override 9304 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 9305 return filter.activity; 9306 } 9307 9308 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9309 PackageParser.Activity activity = (PackageParser.Activity)label; 9310 out.print(prefix); out.print( 9311 Integer.toHexString(System.identityHashCode(activity))); 9312 out.print(' '); 9313 activity.printComponentShortName(out); 9314 if (count > 1) { 9315 out.print(" ("); out.print(count); out.print(" filters)"); 9316 } 9317 out.println(); 9318 } 9319 9320// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9321// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9322// final List<ResolveInfo> retList = Lists.newArrayList(); 9323// while (i.hasNext()) { 9324// final ResolveInfo resolveInfo = i.next(); 9325// if (isEnabledLP(resolveInfo.activityInfo)) { 9326// retList.add(resolveInfo); 9327// } 9328// } 9329// return retList; 9330// } 9331 9332 // Keys are String (activity class name), values are Activity. 9333 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 9334 = new ArrayMap<ComponentName, PackageParser.Activity>(); 9335 private int mFlags; 9336 } 9337 9338 private final class ServiceIntentResolver 9339 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 9340 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9341 boolean defaultOnly, int userId) { 9342 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9343 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9344 } 9345 9346 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9347 int userId) { 9348 if (!sUserManager.exists(userId)) return null; 9349 mFlags = flags; 9350 return super.queryIntent(intent, resolvedType, 9351 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9352 } 9353 9354 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9355 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 9356 if (!sUserManager.exists(userId)) return null; 9357 if (packageServices == null) { 9358 return null; 9359 } 9360 mFlags = flags; 9361 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9362 final int N = packageServices.size(); 9363 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 9364 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 9365 9366 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 9367 for (int i = 0; i < N; ++i) { 9368 intentFilters = packageServices.get(i).intents; 9369 if (intentFilters != null && intentFilters.size() > 0) { 9370 PackageParser.ServiceIntentInfo[] array = 9371 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 9372 intentFilters.toArray(array); 9373 listCut.add(array); 9374 } 9375 } 9376 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9377 } 9378 9379 public final void addService(PackageParser.Service s) { 9380 mServices.put(s.getComponentName(), s); 9381 if (DEBUG_SHOW_INFO) { 9382 Log.v(TAG, " " 9383 + (s.info.nonLocalizedLabel != null 9384 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9385 Log.v(TAG, " Class=" + s.info.name); 9386 } 9387 final int NI = s.intents.size(); 9388 int j; 9389 for (j=0; j<NI; j++) { 9390 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9391 if (DEBUG_SHOW_INFO) { 9392 Log.v(TAG, " IntentFilter:"); 9393 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9394 } 9395 if (!intent.debugCheck()) { 9396 Log.w(TAG, "==> For Service " + s.info.name); 9397 } 9398 addFilter(intent); 9399 } 9400 } 9401 9402 public final void removeService(PackageParser.Service s) { 9403 mServices.remove(s.getComponentName()); 9404 if (DEBUG_SHOW_INFO) { 9405 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 9406 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9407 Log.v(TAG, " Class=" + s.info.name); 9408 } 9409 final int NI = s.intents.size(); 9410 int j; 9411 for (j=0; j<NI; j++) { 9412 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9413 if (DEBUG_SHOW_INFO) { 9414 Log.v(TAG, " IntentFilter:"); 9415 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9416 } 9417 removeFilter(intent); 9418 } 9419 } 9420 9421 @Override 9422 protected boolean allowFilterResult( 9423 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 9424 ServiceInfo filterSi = filter.service.info; 9425 for (int i=dest.size()-1; i>=0; i--) { 9426 ServiceInfo destAi = dest.get(i).serviceInfo; 9427 if (destAi.name == filterSi.name 9428 && destAi.packageName == filterSi.packageName) { 9429 return false; 9430 } 9431 } 9432 return true; 9433 } 9434 9435 @Override 9436 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 9437 return new PackageParser.ServiceIntentInfo[size]; 9438 } 9439 9440 @Override 9441 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 9442 if (!sUserManager.exists(userId)) return true; 9443 PackageParser.Package p = filter.service.owner; 9444 if (p != null) { 9445 PackageSetting ps = (PackageSetting)p.mExtras; 9446 if (ps != null) { 9447 // System apps are never considered stopped for purposes of 9448 // filtering, because there may be no way for the user to 9449 // actually re-launch them. 9450 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9451 && ps.getStopped(userId); 9452 } 9453 } 9454 return false; 9455 } 9456 9457 @Override 9458 protected boolean isPackageForFilter(String packageName, 9459 PackageParser.ServiceIntentInfo info) { 9460 return packageName.equals(info.service.owner.packageName); 9461 } 9462 9463 @Override 9464 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 9465 int match, int userId) { 9466 if (!sUserManager.exists(userId)) return null; 9467 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 9468 if (!mSettings.isEnabledAndVisibleLPr(info.service.info, mFlags, userId)) { 9469 return null; 9470 } 9471 final PackageParser.Service service = info.service; 9472 if (mSafeMode && (service.info.applicationInfo.flags 9473 &ApplicationInfo.FLAG_SYSTEM) == 0) { 9474 return null; 9475 } 9476 PackageSetting ps = (PackageSetting) service.owner.mExtras; 9477 if (ps == null) { 9478 return null; 9479 } 9480 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 9481 ps.readUserState(userId), userId); 9482 if (si == null) { 9483 return null; 9484 } 9485 final ResolveInfo res = new ResolveInfo(); 9486 res.serviceInfo = si; 9487 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9488 res.filter = filter; 9489 } 9490 res.priority = info.getPriority(); 9491 res.preferredOrder = service.owner.mPreferredOrder; 9492 res.match = match; 9493 res.isDefault = info.hasDefault; 9494 res.labelRes = info.labelRes; 9495 res.nonLocalizedLabel = info.nonLocalizedLabel; 9496 res.icon = info.icon; 9497 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 9498 return res; 9499 } 9500 9501 @Override 9502 protected void sortResults(List<ResolveInfo> results) { 9503 Collections.sort(results, mResolvePrioritySorter); 9504 } 9505 9506 @Override 9507 protected void dumpFilter(PrintWriter out, String prefix, 9508 PackageParser.ServiceIntentInfo filter) { 9509 out.print(prefix); out.print( 9510 Integer.toHexString(System.identityHashCode(filter.service))); 9511 out.print(' '); 9512 filter.service.printComponentShortName(out); 9513 out.print(" filter "); 9514 out.println(Integer.toHexString(System.identityHashCode(filter))); 9515 } 9516 9517 @Override 9518 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 9519 return filter.service; 9520 } 9521 9522 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9523 PackageParser.Service service = (PackageParser.Service)label; 9524 out.print(prefix); out.print( 9525 Integer.toHexString(System.identityHashCode(service))); 9526 out.print(' '); 9527 service.printComponentShortName(out); 9528 if (count > 1) { 9529 out.print(" ("); out.print(count); out.print(" filters)"); 9530 } 9531 out.println(); 9532 } 9533 9534// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9535// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9536// final List<ResolveInfo> retList = Lists.newArrayList(); 9537// while (i.hasNext()) { 9538// final ResolveInfo resolveInfo = (ResolveInfo) i; 9539// if (isEnabledLP(resolveInfo.serviceInfo)) { 9540// retList.add(resolveInfo); 9541// } 9542// } 9543// return retList; 9544// } 9545 9546 // Keys are String (activity class name), values are Activity. 9547 private final ArrayMap<ComponentName, PackageParser.Service> mServices 9548 = new ArrayMap<ComponentName, PackageParser.Service>(); 9549 private int mFlags; 9550 }; 9551 9552 private final class ProviderIntentResolver 9553 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 9554 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9555 boolean defaultOnly, int userId) { 9556 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9557 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9558 } 9559 9560 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9561 int userId) { 9562 if (!sUserManager.exists(userId)) 9563 return null; 9564 mFlags = flags; 9565 return super.queryIntent(intent, resolvedType, 9566 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9567 } 9568 9569 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9570 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 9571 if (!sUserManager.exists(userId)) 9572 return null; 9573 if (packageProviders == null) { 9574 return null; 9575 } 9576 mFlags = flags; 9577 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 9578 final int N = packageProviders.size(); 9579 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 9580 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 9581 9582 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 9583 for (int i = 0; i < N; ++i) { 9584 intentFilters = packageProviders.get(i).intents; 9585 if (intentFilters != null && intentFilters.size() > 0) { 9586 PackageParser.ProviderIntentInfo[] array = 9587 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 9588 intentFilters.toArray(array); 9589 listCut.add(array); 9590 } 9591 } 9592 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9593 } 9594 9595 public final void addProvider(PackageParser.Provider p) { 9596 if (mProviders.containsKey(p.getComponentName())) { 9597 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 9598 return; 9599 } 9600 9601 mProviders.put(p.getComponentName(), p); 9602 if (DEBUG_SHOW_INFO) { 9603 Log.v(TAG, " " 9604 + (p.info.nonLocalizedLabel != null 9605 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9606 Log.v(TAG, " Class=" + p.info.name); 9607 } 9608 final int NI = p.intents.size(); 9609 int j; 9610 for (j = 0; j < NI; j++) { 9611 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9612 if (DEBUG_SHOW_INFO) { 9613 Log.v(TAG, " IntentFilter:"); 9614 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9615 } 9616 if (!intent.debugCheck()) { 9617 Log.w(TAG, "==> For Provider " + p.info.name); 9618 } 9619 addFilter(intent); 9620 } 9621 } 9622 9623 public final void removeProvider(PackageParser.Provider p) { 9624 mProviders.remove(p.getComponentName()); 9625 if (DEBUG_SHOW_INFO) { 9626 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 9627 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9628 Log.v(TAG, " Class=" + p.info.name); 9629 } 9630 final int NI = p.intents.size(); 9631 int j; 9632 for (j = 0; j < NI; j++) { 9633 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9634 if (DEBUG_SHOW_INFO) { 9635 Log.v(TAG, " IntentFilter:"); 9636 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9637 } 9638 removeFilter(intent); 9639 } 9640 } 9641 9642 @Override 9643 protected boolean allowFilterResult( 9644 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 9645 ProviderInfo filterPi = filter.provider.info; 9646 for (int i = dest.size() - 1; i >= 0; i--) { 9647 ProviderInfo destPi = dest.get(i).providerInfo; 9648 if (destPi.name == filterPi.name 9649 && destPi.packageName == filterPi.packageName) { 9650 return false; 9651 } 9652 } 9653 return true; 9654 } 9655 9656 @Override 9657 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 9658 return new PackageParser.ProviderIntentInfo[size]; 9659 } 9660 9661 @Override 9662 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 9663 if (!sUserManager.exists(userId)) 9664 return true; 9665 PackageParser.Package p = filter.provider.owner; 9666 if (p != null) { 9667 PackageSetting ps = (PackageSetting) p.mExtras; 9668 if (ps != null) { 9669 // System apps are never considered stopped for purposes of 9670 // filtering, because there may be no way for the user to 9671 // actually re-launch them. 9672 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9673 && ps.getStopped(userId); 9674 } 9675 } 9676 return false; 9677 } 9678 9679 @Override 9680 protected boolean isPackageForFilter(String packageName, 9681 PackageParser.ProviderIntentInfo info) { 9682 return packageName.equals(info.provider.owner.packageName); 9683 } 9684 9685 @Override 9686 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 9687 int match, int userId) { 9688 if (!sUserManager.exists(userId)) 9689 return null; 9690 final PackageParser.ProviderIntentInfo info = filter; 9691 if (!mSettings.isEnabledAndVisibleLPr(info.provider.info, mFlags, userId)) { 9692 return null; 9693 } 9694 final PackageParser.Provider provider = info.provider; 9695 if (mSafeMode && (provider.info.applicationInfo.flags 9696 & ApplicationInfo.FLAG_SYSTEM) == 0) { 9697 return null; 9698 } 9699 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 9700 if (ps == null) { 9701 return null; 9702 } 9703 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 9704 ps.readUserState(userId), userId); 9705 if (pi == null) { 9706 return null; 9707 } 9708 final ResolveInfo res = new ResolveInfo(); 9709 res.providerInfo = pi; 9710 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 9711 res.filter = filter; 9712 } 9713 res.priority = info.getPriority(); 9714 res.preferredOrder = provider.owner.mPreferredOrder; 9715 res.match = match; 9716 res.isDefault = info.hasDefault; 9717 res.labelRes = info.labelRes; 9718 res.nonLocalizedLabel = info.nonLocalizedLabel; 9719 res.icon = info.icon; 9720 res.system = res.providerInfo.applicationInfo.isSystemApp(); 9721 return res; 9722 } 9723 9724 @Override 9725 protected void sortResults(List<ResolveInfo> results) { 9726 Collections.sort(results, mResolvePrioritySorter); 9727 } 9728 9729 @Override 9730 protected void dumpFilter(PrintWriter out, String prefix, 9731 PackageParser.ProviderIntentInfo filter) { 9732 out.print(prefix); 9733 out.print( 9734 Integer.toHexString(System.identityHashCode(filter.provider))); 9735 out.print(' '); 9736 filter.provider.printComponentShortName(out); 9737 out.print(" filter "); 9738 out.println(Integer.toHexString(System.identityHashCode(filter))); 9739 } 9740 9741 @Override 9742 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 9743 return filter.provider; 9744 } 9745 9746 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9747 PackageParser.Provider provider = (PackageParser.Provider)label; 9748 out.print(prefix); out.print( 9749 Integer.toHexString(System.identityHashCode(provider))); 9750 out.print(' '); 9751 provider.printComponentShortName(out); 9752 if (count > 1) { 9753 out.print(" ("); out.print(count); out.print(" filters)"); 9754 } 9755 out.println(); 9756 } 9757 9758 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 9759 = new ArrayMap<ComponentName, PackageParser.Provider>(); 9760 private int mFlags; 9761 } 9762 9763 private static final class EphemeralIntentResolver 9764 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 9765 @Override 9766 protected EphemeralResolveIntentInfo[] newArray(int size) { 9767 return new EphemeralResolveIntentInfo[size]; 9768 } 9769 9770 @Override 9771 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 9772 return true; 9773 } 9774 9775 @Override 9776 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 9777 int userId) { 9778 if (!sUserManager.exists(userId)) { 9779 return null; 9780 } 9781 return info.getEphemeralResolveInfo(); 9782 } 9783 } 9784 9785 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 9786 new Comparator<ResolveInfo>() { 9787 public int compare(ResolveInfo r1, ResolveInfo r2) { 9788 int v1 = r1.priority; 9789 int v2 = r2.priority; 9790 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 9791 if (v1 != v2) { 9792 return (v1 > v2) ? -1 : 1; 9793 } 9794 v1 = r1.preferredOrder; 9795 v2 = r2.preferredOrder; 9796 if (v1 != v2) { 9797 return (v1 > v2) ? -1 : 1; 9798 } 9799 if (r1.isDefault != r2.isDefault) { 9800 return r1.isDefault ? -1 : 1; 9801 } 9802 v1 = r1.match; 9803 v2 = r2.match; 9804 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 9805 if (v1 != v2) { 9806 return (v1 > v2) ? -1 : 1; 9807 } 9808 if (r1.system != r2.system) { 9809 return r1.system ? -1 : 1; 9810 } 9811 if (r1.activityInfo != null) { 9812 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 9813 } 9814 if (r1.serviceInfo != null) { 9815 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 9816 } 9817 if (r1.providerInfo != null) { 9818 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 9819 } 9820 return 0; 9821 } 9822 }; 9823 9824 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 9825 new Comparator<ProviderInfo>() { 9826 public int compare(ProviderInfo p1, ProviderInfo p2) { 9827 final int v1 = p1.initOrder; 9828 final int v2 = p2.initOrder; 9829 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 9830 } 9831 }; 9832 9833 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 9834 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 9835 final int[] userIds) { 9836 mHandler.post(new Runnable() { 9837 @Override 9838 public void run() { 9839 try { 9840 final IActivityManager am = ActivityManagerNative.getDefault(); 9841 if (am == null) return; 9842 final int[] resolvedUserIds; 9843 if (userIds == null) { 9844 resolvedUserIds = am.getRunningUserIds(); 9845 } else { 9846 resolvedUserIds = userIds; 9847 } 9848 for (int id : resolvedUserIds) { 9849 final Intent intent = new Intent(action, 9850 pkg != null ? Uri.fromParts("package", pkg, null) : null); 9851 if (extras != null) { 9852 intent.putExtras(extras); 9853 } 9854 if (targetPkg != null) { 9855 intent.setPackage(targetPkg); 9856 } 9857 // Modify the UID when posting to other users 9858 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 9859 if (uid > 0 && UserHandle.getUserId(uid) != id) { 9860 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 9861 intent.putExtra(Intent.EXTRA_UID, uid); 9862 } 9863 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 9864 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 9865 if (DEBUG_BROADCASTS) { 9866 RuntimeException here = new RuntimeException("here"); 9867 here.fillInStackTrace(); 9868 Slog.d(TAG, "Sending to user " + id + ": " 9869 + intent.toShortString(false, true, false, false) 9870 + " " + intent.getExtras(), here); 9871 } 9872 am.broadcastIntent(null, intent, null, finishedReceiver, 9873 0, null, null, null, android.app.AppOpsManager.OP_NONE, 9874 null, finishedReceiver != null, false, id); 9875 } 9876 } catch (RemoteException ex) { 9877 } 9878 } 9879 }); 9880 } 9881 9882 /** 9883 * Check if the external storage media is available. This is true if there 9884 * is a mounted external storage medium or if the external storage is 9885 * emulated. 9886 */ 9887 private boolean isExternalMediaAvailable() { 9888 return mMediaMounted || Environment.isExternalStorageEmulated(); 9889 } 9890 9891 @Override 9892 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 9893 // writer 9894 synchronized (mPackages) { 9895 if (!isExternalMediaAvailable()) { 9896 // If the external storage is no longer mounted at this point, 9897 // the caller may not have been able to delete all of this 9898 // packages files and can not delete any more. Bail. 9899 return null; 9900 } 9901 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 9902 if (lastPackage != null) { 9903 pkgs.remove(lastPackage); 9904 } 9905 if (pkgs.size() > 0) { 9906 return pkgs.get(0); 9907 } 9908 } 9909 return null; 9910 } 9911 9912 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 9913 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 9914 userId, andCode ? 1 : 0, packageName); 9915 if (mSystemReady) { 9916 msg.sendToTarget(); 9917 } else { 9918 if (mPostSystemReadyMessages == null) { 9919 mPostSystemReadyMessages = new ArrayList<>(); 9920 } 9921 mPostSystemReadyMessages.add(msg); 9922 } 9923 } 9924 9925 void startCleaningPackages() { 9926 // reader 9927 synchronized (mPackages) { 9928 if (!isExternalMediaAvailable()) { 9929 return; 9930 } 9931 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 9932 return; 9933 } 9934 } 9935 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 9936 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 9937 IActivityManager am = ActivityManagerNative.getDefault(); 9938 if (am != null) { 9939 try { 9940 am.startService(null, intent, null, mContext.getOpPackageName(), 9941 UserHandle.USER_SYSTEM); 9942 } catch (RemoteException e) { 9943 } 9944 } 9945 } 9946 9947 @Override 9948 public void installPackage(String originPath, IPackageInstallObserver2 observer, 9949 int installFlags, String installerPackageName, VerificationParams verificationParams, 9950 String packageAbiOverride) { 9951 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 9952 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 9953 } 9954 9955 @Override 9956 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 9957 int installFlags, String installerPackageName, VerificationParams verificationParams, 9958 String packageAbiOverride, int userId) { 9959 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 9960 9961 final int callingUid = Binder.getCallingUid(); 9962 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 9963 9964 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9965 try { 9966 if (observer != null) { 9967 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 9968 } 9969 } catch (RemoteException re) { 9970 } 9971 return; 9972 } 9973 9974 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 9975 installFlags |= PackageManager.INSTALL_FROM_ADB; 9976 9977 } else { 9978 // Caller holds INSTALL_PACKAGES permission, so we're less strict 9979 // about installerPackageName. 9980 9981 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 9982 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 9983 } 9984 9985 UserHandle user; 9986 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 9987 user = UserHandle.ALL; 9988 } else { 9989 user = new UserHandle(userId); 9990 } 9991 9992 // Only system components can circumvent runtime permissions when installing. 9993 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 9994 && mContext.checkCallingOrSelfPermission(Manifest.permission 9995 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 9996 throw new SecurityException("You need the " 9997 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 9998 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 9999 } 10000 10001 verificationParams.setInstallerUid(callingUid); 10002 10003 final File originFile = new File(originPath); 10004 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 10005 10006 final Message msg = mHandler.obtainMessage(INIT_COPY); 10007 final InstallParams params = new InstallParams(origin, null, observer, installFlags, 10008 installerPackageName, null, verificationParams, user, packageAbiOverride, null); 10009 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 10010 msg.obj = params; 10011 10012 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 10013 System.identityHashCode(msg.obj)); 10014 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 10015 System.identityHashCode(msg.obj)); 10016 10017 mHandler.sendMessage(msg); 10018 } 10019 10020 void installStage(String packageName, File stagedDir, String stagedCid, 10021 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 10022 String installerPackageName, int installerUid, UserHandle user) { 10023 if (DEBUG_EPHEMERAL) { 10024 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 10025 Slog.d(TAG, "Ephemeral install of " + packageName); 10026 } 10027 } 10028 final VerificationParams verifParams = new VerificationParams( 10029 null, sessionParams.originatingUri, sessionParams.referrerUri, 10030 sessionParams.originatingUid, null); 10031 verifParams.setInstallerUid(installerUid); 10032 10033 final OriginInfo origin; 10034 if (stagedDir != null) { 10035 origin = OriginInfo.fromStagedFile(stagedDir); 10036 } else { 10037 origin = OriginInfo.fromStagedContainer(stagedCid); 10038 } 10039 10040 final Message msg = mHandler.obtainMessage(INIT_COPY); 10041 final InstallParams params = new InstallParams(origin, null, observer, 10042 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 10043 verifParams, user, sessionParams.abiOverride, 10044 sessionParams.grantedRuntimePermissions); 10045 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 10046 msg.obj = params; 10047 10048 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 10049 System.identityHashCode(msg.obj)); 10050 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 10051 System.identityHashCode(msg.obj)); 10052 10053 mHandler.sendMessage(msg); 10054 } 10055 10056 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 10057 Bundle extras = new Bundle(1); 10058 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 10059 10060 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 10061 packageName, extras, 0, null, null, new int[] {userId}); 10062 try { 10063 IActivityManager am = ActivityManagerNative.getDefault(); 10064 final boolean isSystem = 10065 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 10066 if (isSystem && am.isUserRunning(userId, 0)) { 10067 // The just-installed/enabled app is bundled on the system, so presumed 10068 // to be able to run automatically without needing an explicit launch. 10069 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 10070 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 10071 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 10072 .setPackage(packageName); 10073 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 10074 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 10075 } 10076 } catch (RemoteException e) { 10077 // shouldn't happen 10078 Slog.w(TAG, "Unable to bootstrap installed package", e); 10079 } 10080 } 10081 10082 @Override 10083 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 10084 int userId) { 10085 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10086 PackageSetting pkgSetting; 10087 final int uid = Binder.getCallingUid(); 10088 enforceCrossUserPermission(uid, userId, true, true, 10089 "setApplicationHiddenSetting for user " + userId); 10090 10091 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 10092 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 10093 return false; 10094 } 10095 10096 long callingId = Binder.clearCallingIdentity(); 10097 try { 10098 boolean sendAdded = false; 10099 boolean sendRemoved = false; 10100 // writer 10101 synchronized (mPackages) { 10102 pkgSetting = mSettings.mPackages.get(packageName); 10103 if (pkgSetting == null) { 10104 return false; 10105 } 10106 if (pkgSetting.getHidden(userId) != hidden) { 10107 pkgSetting.setHidden(hidden, userId); 10108 mSettings.writePackageRestrictionsLPr(userId); 10109 if (hidden) { 10110 sendRemoved = true; 10111 } else { 10112 sendAdded = true; 10113 } 10114 } 10115 } 10116 if (sendAdded) { 10117 sendPackageAddedForUser(packageName, pkgSetting, userId); 10118 return true; 10119 } 10120 if (sendRemoved) { 10121 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 10122 "hiding pkg"); 10123 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 10124 return true; 10125 } 10126 } finally { 10127 Binder.restoreCallingIdentity(callingId); 10128 } 10129 return false; 10130 } 10131 10132 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 10133 int userId) { 10134 final PackageRemovedInfo info = new PackageRemovedInfo(); 10135 info.removedPackage = packageName; 10136 info.removedUsers = new int[] {userId}; 10137 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 10138 info.sendBroadcast(false, false, false); 10139 } 10140 10141 /** 10142 * Returns true if application is not found or there was an error. Otherwise it returns 10143 * the hidden state of the package for the given user. 10144 */ 10145 @Override 10146 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 10147 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10148 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 10149 false, "getApplicationHidden for user " + userId); 10150 PackageSetting pkgSetting; 10151 long callingId = Binder.clearCallingIdentity(); 10152 try { 10153 // writer 10154 synchronized (mPackages) { 10155 pkgSetting = mSettings.mPackages.get(packageName); 10156 if (pkgSetting == null) { 10157 return true; 10158 } 10159 return pkgSetting.getHidden(userId); 10160 } 10161 } finally { 10162 Binder.restoreCallingIdentity(callingId); 10163 } 10164 } 10165 10166 /** 10167 * @hide 10168 */ 10169 @Override 10170 public int installExistingPackageAsUser(String packageName, int userId) { 10171 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 10172 null); 10173 PackageSetting pkgSetting; 10174 final int uid = Binder.getCallingUid(); 10175 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 10176 + userId); 10177 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 10178 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 10179 } 10180 10181 long callingId = Binder.clearCallingIdentity(); 10182 try { 10183 boolean sendAdded = false; 10184 10185 // writer 10186 synchronized (mPackages) { 10187 pkgSetting = mSettings.mPackages.get(packageName); 10188 if (pkgSetting == null) { 10189 return PackageManager.INSTALL_FAILED_INVALID_URI; 10190 } 10191 if (!pkgSetting.getInstalled(userId)) { 10192 pkgSetting.setInstalled(true, userId); 10193 pkgSetting.setHidden(false, userId); 10194 mSettings.writePackageRestrictionsLPr(userId); 10195 sendAdded = true; 10196 } 10197 } 10198 10199 if (sendAdded) { 10200 sendPackageAddedForUser(packageName, pkgSetting, userId); 10201 } 10202 } finally { 10203 Binder.restoreCallingIdentity(callingId); 10204 } 10205 10206 return PackageManager.INSTALL_SUCCEEDED; 10207 } 10208 10209 boolean isUserRestricted(int userId, String restrictionKey) { 10210 Bundle restrictions = sUserManager.getUserRestrictions(userId); 10211 if (restrictions.getBoolean(restrictionKey, false)) { 10212 Log.w(TAG, "User is restricted: " + restrictionKey); 10213 return true; 10214 } 10215 return false; 10216 } 10217 10218 @Override 10219 public boolean setPackageSuspendedAsUser(String packageName, boolean suspended, int userId) { 10220 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10221 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, true, 10222 "setPackageSuspended for user " + userId); 10223 10224 long callingId = Binder.clearCallingIdentity(); 10225 try { 10226 synchronized (mPackages) { 10227 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 10228 if (pkgSetting != null) { 10229 if (pkgSetting.getSuspended(userId) != suspended) { 10230 pkgSetting.setSuspended(suspended, userId); 10231 mSettings.writePackageRestrictionsLPr(userId); 10232 } 10233 10234 // TODO: 10235 // * broadcast a PACKAGE_(UN)SUSPENDED intent for launchers to pick up 10236 // * remove app from recents (kill app it if it is running) 10237 // * erase existing notifications for this app 10238 return true; 10239 } 10240 10241 return false; 10242 } 10243 } finally { 10244 Binder.restoreCallingIdentity(callingId); 10245 } 10246 } 10247 10248 @Override 10249 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 10250 mContext.enforceCallingOrSelfPermission( 10251 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10252 "Only package verification agents can verify applications"); 10253 10254 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 10255 final PackageVerificationResponse response = new PackageVerificationResponse( 10256 verificationCode, Binder.getCallingUid()); 10257 msg.arg1 = id; 10258 msg.obj = response; 10259 mHandler.sendMessage(msg); 10260 } 10261 10262 @Override 10263 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 10264 long millisecondsToDelay) { 10265 mContext.enforceCallingOrSelfPermission( 10266 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10267 "Only package verification agents can extend verification timeouts"); 10268 10269 final PackageVerificationState state = mPendingVerification.get(id); 10270 final PackageVerificationResponse response = new PackageVerificationResponse( 10271 verificationCodeAtTimeout, Binder.getCallingUid()); 10272 10273 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 10274 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 10275 } 10276 if (millisecondsToDelay < 0) { 10277 millisecondsToDelay = 0; 10278 } 10279 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 10280 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 10281 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 10282 } 10283 10284 if ((state != null) && !state.timeoutExtended()) { 10285 state.extendTimeout(); 10286 10287 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 10288 msg.arg1 = id; 10289 msg.obj = response; 10290 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 10291 } 10292 } 10293 10294 private void broadcastPackageVerified(int verificationId, Uri packageUri, 10295 int verificationCode, UserHandle user) { 10296 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 10297 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 10298 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10299 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10300 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 10301 10302 mContext.sendBroadcastAsUser(intent, user, 10303 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 10304 } 10305 10306 private ComponentName matchComponentForVerifier(String packageName, 10307 List<ResolveInfo> receivers) { 10308 ActivityInfo targetReceiver = null; 10309 10310 final int NR = receivers.size(); 10311 for (int i = 0; i < NR; i++) { 10312 final ResolveInfo info = receivers.get(i); 10313 if (info.activityInfo == null) { 10314 continue; 10315 } 10316 10317 if (packageName.equals(info.activityInfo.packageName)) { 10318 targetReceiver = info.activityInfo; 10319 break; 10320 } 10321 } 10322 10323 if (targetReceiver == null) { 10324 return null; 10325 } 10326 10327 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 10328 } 10329 10330 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 10331 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 10332 if (pkgInfo.verifiers.length == 0) { 10333 return null; 10334 } 10335 10336 final int N = pkgInfo.verifiers.length; 10337 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 10338 for (int i = 0; i < N; i++) { 10339 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 10340 10341 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 10342 receivers); 10343 if (comp == null) { 10344 continue; 10345 } 10346 10347 final int verifierUid = getUidForVerifier(verifierInfo); 10348 if (verifierUid == -1) { 10349 continue; 10350 } 10351 10352 if (DEBUG_VERIFY) { 10353 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 10354 + " with the correct signature"); 10355 } 10356 sufficientVerifiers.add(comp); 10357 verificationState.addSufficientVerifier(verifierUid); 10358 } 10359 10360 return sufficientVerifiers; 10361 } 10362 10363 private int getUidForVerifier(VerifierInfo verifierInfo) { 10364 synchronized (mPackages) { 10365 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 10366 if (pkg == null) { 10367 return -1; 10368 } else if (pkg.mSignatures.length != 1) { 10369 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10370 + " has more than one signature; ignoring"); 10371 return -1; 10372 } 10373 10374 /* 10375 * If the public key of the package's signature does not match 10376 * our expected public key, then this is a different package and 10377 * we should skip. 10378 */ 10379 10380 final byte[] expectedPublicKey; 10381 try { 10382 final Signature verifierSig = pkg.mSignatures[0]; 10383 final PublicKey publicKey = verifierSig.getPublicKey(); 10384 expectedPublicKey = publicKey.getEncoded(); 10385 } catch (CertificateException e) { 10386 return -1; 10387 } 10388 10389 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 10390 10391 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 10392 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10393 + " does not have the expected public key; ignoring"); 10394 return -1; 10395 } 10396 10397 return pkg.applicationInfo.uid; 10398 } 10399 } 10400 10401 @Override 10402 public void finishPackageInstall(int token) { 10403 enforceSystemOrRoot("Only the system is allowed to finish installs"); 10404 10405 if (DEBUG_INSTALL) { 10406 Slog.v(TAG, "BM finishing package install for " + token); 10407 } 10408 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10409 10410 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10411 mHandler.sendMessage(msg); 10412 } 10413 10414 /** 10415 * Get the verification agent timeout. 10416 * 10417 * @return verification timeout in milliseconds 10418 */ 10419 private long getVerificationTimeout() { 10420 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 10421 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 10422 DEFAULT_VERIFICATION_TIMEOUT); 10423 } 10424 10425 /** 10426 * Get the default verification agent response code. 10427 * 10428 * @return default verification response code 10429 */ 10430 private int getDefaultVerificationResponse() { 10431 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10432 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 10433 DEFAULT_VERIFICATION_RESPONSE); 10434 } 10435 10436 /** 10437 * Check whether or not package verification has been enabled. 10438 * 10439 * @return true if verification should be performed 10440 */ 10441 private boolean isVerificationEnabled(int userId, int installFlags) { 10442 if (!DEFAULT_VERIFY_ENABLE) { 10443 return false; 10444 } 10445 // TODO: fix b/25118622; don't bypass verification 10446 if (Build.IS_DEBUGGABLE && (installFlags & PackageManager.INSTALL_QUICK) != 0) { 10447 return false; 10448 } 10449 // Ephemeral apps don't get the full verification treatment 10450 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 10451 if (DEBUG_EPHEMERAL) { 10452 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 10453 } 10454 return false; 10455 } 10456 10457 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 10458 10459 // Check if installing from ADB 10460 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 10461 // Do not run verification in a test harness environment 10462 if (ActivityManager.isRunningInTestHarness()) { 10463 return false; 10464 } 10465 if (ensureVerifyAppsEnabled) { 10466 return true; 10467 } 10468 // Check if the developer does not want package verification for ADB installs 10469 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10470 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 10471 return false; 10472 } 10473 } 10474 10475 if (ensureVerifyAppsEnabled) { 10476 return true; 10477 } 10478 10479 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10480 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 10481 } 10482 10483 @Override 10484 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 10485 throws RemoteException { 10486 mContext.enforceCallingOrSelfPermission( 10487 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 10488 "Only intentfilter verification agents can verify applications"); 10489 10490 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 10491 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 10492 Binder.getCallingUid(), verificationCode, failedDomains); 10493 msg.arg1 = id; 10494 msg.obj = response; 10495 mHandler.sendMessage(msg); 10496 } 10497 10498 @Override 10499 public int getIntentVerificationStatus(String packageName, int userId) { 10500 synchronized (mPackages) { 10501 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 10502 } 10503 } 10504 10505 @Override 10506 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 10507 mContext.enforceCallingOrSelfPermission( 10508 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10509 10510 boolean result = false; 10511 synchronized (mPackages) { 10512 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 10513 } 10514 if (result) { 10515 scheduleWritePackageRestrictionsLocked(userId); 10516 } 10517 return result; 10518 } 10519 10520 @Override 10521 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 10522 synchronized (mPackages) { 10523 return mSettings.getIntentFilterVerificationsLPr(packageName); 10524 } 10525 } 10526 10527 @Override 10528 public List<IntentFilter> getAllIntentFilters(String packageName) { 10529 if (TextUtils.isEmpty(packageName)) { 10530 return Collections.<IntentFilter>emptyList(); 10531 } 10532 synchronized (mPackages) { 10533 PackageParser.Package pkg = mPackages.get(packageName); 10534 if (pkg == null || pkg.activities == null) { 10535 return Collections.<IntentFilter>emptyList(); 10536 } 10537 final int count = pkg.activities.size(); 10538 ArrayList<IntentFilter> result = new ArrayList<>(); 10539 for (int n=0; n<count; n++) { 10540 PackageParser.Activity activity = pkg.activities.get(n); 10541 if (activity.intents != null && activity.intents.size() > 0) { 10542 result.addAll(activity.intents); 10543 } 10544 } 10545 return result; 10546 } 10547 } 10548 10549 @Override 10550 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 10551 mContext.enforceCallingOrSelfPermission( 10552 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10553 10554 synchronized (mPackages) { 10555 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 10556 if (packageName != null) { 10557 result |= updateIntentVerificationStatus(packageName, 10558 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 10559 userId); 10560 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 10561 packageName, userId); 10562 } 10563 return result; 10564 } 10565 } 10566 10567 @Override 10568 public String getDefaultBrowserPackageName(int userId) { 10569 synchronized (mPackages) { 10570 return mSettings.getDefaultBrowserPackageNameLPw(userId); 10571 } 10572 } 10573 10574 /** 10575 * Get the "allow unknown sources" setting. 10576 * 10577 * @return the current "allow unknown sources" setting 10578 */ 10579 private int getUnknownSourcesSettings() { 10580 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10581 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 10582 -1); 10583 } 10584 10585 @Override 10586 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 10587 final int uid = Binder.getCallingUid(); 10588 // writer 10589 synchronized (mPackages) { 10590 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 10591 if (targetPackageSetting == null) { 10592 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 10593 } 10594 10595 PackageSetting installerPackageSetting; 10596 if (installerPackageName != null) { 10597 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 10598 if (installerPackageSetting == null) { 10599 throw new IllegalArgumentException("Unknown installer package: " 10600 + installerPackageName); 10601 } 10602 } else { 10603 installerPackageSetting = null; 10604 } 10605 10606 Signature[] callerSignature; 10607 Object obj = mSettings.getUserIdLPr(uid); 10608 if (obj != null) { 10609 if (obj instanceof SharedUserSetting) { 10610 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 10611 } else if (obj instanceof PackageSetting) { 10612 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 10613 } else { 10614 throw new SecurityException("Bad object " + obj + " for uid " + uid); 10615 } 10616 } else { 10617 throw new SecurityException("Unknown calling uid " + uid); 10618 } 10619 10620 // Verify: can't set installerPackageName to a package that is 10621 // not signed with the same cert as the caller. 10622 if (installerPackageSetting != null) { 10623 if (compareSignatures(callerSignature, 10624 installerPackageSetting.signatures.mSignatures) 10625 != PackageManager.SIGNATURE_MATCH) { 10626 throw new SecurityException( 10627 "Caller does not have same cert as new installer package " 10628 + installerPackageName); 10629 } 10630 } 10631 10632 // Verify: if target already has an installer package, it must 10633 // be signed with the same cert as the caller. 10634 if (targetPackageSetting.installerPackageName != null) { 10635 PackageSetting setting = mSettings.mPackages.get( 10636 targetPackageSetting.installerPackageName); 10637 // If the currently set package isn't valid, then it's always 10638 // okay to change it. 10639 if (setting != null) { 10640 if (compareSignatures(callerSignature, 10641 setting.signatures.mSignatures) 10642 != PackageManager.SIGNATURE_MATCH) { 10643 throw new SecurityException( 10644 "Caller does not have same cert as old installer package " 10645 + targetPackageSetting.installerPackageName); 10646 } 10647 } 10648 } 10649 10650 // Okay! 10651 targetPackageSetting.installerPackageName = installerPackageName; 10652 scheduleWriteSettingsLocked(); 10653 } 10654 } 10655 10656 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 10657 // Queue up an async operation since the package installation may take a little while. 10658 mHandler.post(new Runnable() { 10659 public void run() { 10660 mHandler.removeCallbacks(this); 10661 // Result object to be returned 10662 PackageInstalledInfo res = new PackageInstalledInfo(); 10663 res.returnCode = currentStatus; 10664 res.uid = -1; 10665 res.pkg = null; 10666 res.removedInfo = new PackageRemovedInfo(); 10667 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10668 args.doPreInstall(res.returnCode); 10669 synchronized (mInstallLock) { 10670 installPackageTracedLI(args, res); 10671 } 10672 args.doPostInstall(res.returnCode, res.uid); 10673 } 10674 10675 // A restore should be performed at this point if (a) the install 10676 // succeeded, (b) the operation is not an update, and (c) the new 10677 // package has not opted out of backup participation. 10678 final boolean update = res.removedInfo.removedPackage != null; 10679 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 10680 boolean doRestore = !update 10681 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 10682 10683 // Set up the post-install work request bookkeeping. This will be used 10684 // and cleaned up by the post-install event handling regardless of whether 10685 // there's a restore pass performed. Token values are >= 1. 10686 int token; 10687 if (mNextInstallToken < 0) mNextInstallToken = 1; 10688 token = mNextInstallToken++; 10689 10690 PostInstallData data = new PostInstallData(args, res); 10691 mRunningInstalls.put(token, data); 10692 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 10693 10694 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 10695 // Pass responsibility to the Backup Manager. It will perform a 10696 // restore if appropriate, then pass responsibility back to the 10697 // Package Manager to run the post-install observer callbacks 10698 // and broadcasts. 10699 IBackupManager bm = IBackupManager.Stub.asInterface( 10700 ServiceManager.getService(Context.BACKUP_SERVICE)); 10701 if (bm != null) { 10702 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 10703 + " to BM for possible restore"); 10704 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10705 try { 10706 // TODO: http://b/22388012 10707 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 10708 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 10709 } else { 10710 doRestore = false; 10711 } 10712 } catch (RemoteException e) { 10713 // can't happen; the backup manager is local 10714 } catch (Exception e) { 10715 Slog.e(TAG, "Exception trying to enqueue restore", e); 10716 doRestore = false; 10717 } 10718 } else { 10719 Slog.e(TAG, "Backup Manager not found!"); 10720 doRestore = false; 10721 } 10722 } 10723 10724 if (!doRestore) { 10725 // No restore possible, or the Backup Manager was mysteriously not 10726 // available -- just fire the post-install work request directly. 10727 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 10728 10729 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 10730 10731 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10732 mHandler.sendMessage(msg); 10733 } 10734 } 10735 }); 10736 } 10737 10738 private abstract class HandlerParams { 10739 private static final int MAX_RETRIES = 4; 10740 10741 /** 10742 * Number of times startCopy() has been attempted and had a non-fatal 10743 * error. 10744 */ 10745 private int mRetries = 0; 10746 10747 /** User handle for the user requesting the information or installation. */ 10748 private final UserHandle mUser; 10749 String traceMethod; 10750 int traceCookie; 10751 10752 HandlerParams(UserHandle user) { 10753 mUser = user; 10754 } 10755 10756 UserHandle getUser() { 10757 return mUser; 10758 } 10759 10760 HandlerParams setTraceMethod(String traceMethod) { 10761 this.traceMethod = traceMethod; 10762 return this; 10763 } 10764 10765 HandlerParams setTraceCookie(int traceCookie) { 10766 this.traceCookie = traceCookie; 10767 return this; 10768 } 10769 10770 final boolean startCopy() { 10771 boolean res; 10772 try { 10773 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 10774 10775 if (++mRetries > MAX_RETRIES) { 10776 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 10777 mHandler.sendEmptyMessage(MCS_GIVE_UP); 10778 handleServiceError(); 10779 return false; 10780 } else { 10781 handleStartCopy(); 10782 res = true; 10783 } 10784 } catch (RemoteException e) { 10785 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 10786 mHandler.sendEmptyMessage(MCS_RECONNECT); 10787 res = false; 10788 } 10789 handleReturnCode(); 10790 return res; 10791 } 10792 10793 final void serviceError() { 10794 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 10795 handleServiceError(); 10796 handleReturnCode(); 10797 } 10798 10799 abstract void handleStartCopy() throws RemoteException; 10800 abstract void handleServiceError(); 10801 abstract void handleReturnCode(); 10802 } 10803 10804 class MeasureParams extends HandlerParams { 10805 private final PackageStats mStats; 10806 private boolean mSuccess; 10807 10808 private final IPackageStatsObserver mObserver; 10809 10810 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 10811 super(new UserHandle(stats.userHandle)); 10812 mObserver = observer; 10813 mStats = stats; 10814 } 10815 10816 @Override 10817 public String toString() { 10818 return "MeasureParams{" 10819 + Integer.toHexString(System.identityHashCode(this)) 10820 + " " + mStats.packageName + "}"; 10821 } 10822 10823 @Override 10824 void handleStartCopy() throws RemoteException { 10825 synchronized (mInstallLock) { 10826 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 10827 } 10828 10829 if (mSuccess) { 10830 final boolean mounted; 10831 if (Environment.isExternalStorageEmulated()) { 10832 mounted = true; 10833 } else { 10834 final String status = Environment.getExternalStorageState(); 10835 mounted = (Environment.MEDIA_MOUNTED.equals(status) 10836 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 10837 } 10838 10839 if (mounted) { 10840 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 10841 10842 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 10843 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 10844 10845 mStats.externalDataSize = calculateDirectorySize(mContainerService, 10846 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 10847 10848 // Always subtract cache size, since it's a subdirectory 10849 mStats.externalDataSize -= mStats.externalCacheSize; 10850 10851 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 10852 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 10853 10854 mStats.externalObbSize = calculateDirectorySize(mContainerService, 10855 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 10856 } 10857 } 10858 } 10859 10860 @Override 10861 void handleReturnCode() { 10862 if (mObserver != null) { 10863 try { 10864 mObserver.onGetStatsCompleted(mStats, mSuccess); 10865 } catch (RemoteException e) { 10866 Slog.i(TAG, "Observer no longer exists."); 10867 } 10868 } 10869 } 10870 10871 @Override 10872 void handleServiceError() { 10873 Slog.e(TAG, "Could not measure application " + mStats.packageName 10874 + " external storage"); 10875 } 10876 } 10877 10878 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 10879 throws RemoteException { 10880 long result = 0; 10881 for (File path : paths) { 10882 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 10883 } 10884 return result; 10885 } 10886 10887 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 10888 for (File path : paths) { 10889 try { 10890 mcs.clearDirectory(path.getAbsolutePath()); 10891 } catch (RemoteException e) { 10892 } 10893 } 10894 } 10895 10896 static class OriginInfo { 10897 /** 10898 * Location where install is coming from, before it has been 10899 * copied/renamed into place. This could be a single monolithic APK 10900 * file, or a cluster directory. This location may be untrusted. 10901 */ 10902 final File file; 10903 final String cid; 10904 10905 /** 10906 * Flag indicating that {@link #file} or {@link #cid} has already been 10907 * staged, meaning downstream users don't need to defensively copy the 10908 * contents. 10909 */ 10910 final boolean staged; 10911 10912 /** 10913 * Flag indicating that {@link #file} or {@link #cid} is an already 10914 * installed app that is being moved. 10915 */ 10916 final boolean existing; 10917 10918 final String resolvedPath; 10919 final File resolvedFile; 10920 10921 static OriginInfo fromNothing() { 10922 return new OriginInfo(null, null, false, false); 10923 } 10924 10925 static OriginInfo fromUntrustedFile(File file) { 10926 return new OriginInfo(file, null, false, false); 10927 } 10928 10929 static OriginInfo fromExistingFile(File file) { 10930 return new OriginInfo(file, null, false, true); 10931 } 10932 10933 static OriginInfo fromStagedFile(File file) { 10934 return new OriginInfo(file, null, true, false); 10935 } 10936 10937 static OriginInfo fromStagedContainer(String cid) { 10938 return new OriginInfo(null, cid, true, false); 10939 } 10940 10941 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 10942 this.file = file; 10943 this.cid = cid; 10944 this.staged = staged; 10945 this.existing = existing; 10946 10947 if (cid != null) { 10948 resolvedPath = PackageHelper.getSdDir(cid); 10949 resolvedFile = new File(resolvedPath); 10950 } else if (file != null) { 10951 resolvedPath = file.getAbsolutePath(); 10952 resolvedFile = file; 10953 } else { 10954 resolvedPath = null; 10955 resolvedFile = null; 10956 } 10957 } 10958 } 10959 10960 static class MoveInfo { 10961 final int moveId; 10962 final String fromUuid; 10963 final String toUuid; 10964 final String packageName; 10965 final String dataAppName; 10966 final int appId; 10967 final String seinfo; 10968 10969 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 10970 String dataAppName, int appId, String seinfo) { 10971 this.moveId = moveId; 10972 this.fromUuid = fromUuid; 10973 this.toUuid = toUuid; 10974 this.packageName = packageName; 10975 this.dataAppName = dataAppName; 10976 this.appId = appId; 10977 this.seinfo = seinfo; 10978 } 10979 } 10980 10981 class InstallParams extends HandlerParams { 10982 final OriginInfo origin; 10983 final MoveInfo move; 10984 final IPackageInstallObserver2 observer; 10985 int installFlags; 10986 final String installerPackageName; 10987 final String volumeUuid; 10988 final VerificationParams verificationParams; 10989 private InstallArgs mArgs; 10990 private int mRet; 10991 final String packageAbiOverride; 10992 final String[] grantedRuntimePermissions; 10993 10994 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10995 int installFlags, String installerPackageName, String volumeUuid, 10996 VerificationParams verificationParams, UserHandle user, String packageAbiOverride, 10997 String[] grantedPermissions) { 10998 super(user); 10999 this.origin = origin; 11000 this.move = move; 11001 this.observer = observer; 11002 this.installFlags = installFlags; 11003 this.installerPackageName = installerPackageName; 11004 this.volumeUuid = volumeUuid; 11005 this.verificationParams = verificationParams; 11006 this.packageAbiOverride = packageAbiOverride; 11007 this.grantedRuntimePermissions = grantedPermissions; 11008 } 11009 11010 @Override 11011 public String toString() { 11012 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 11013 + " file=" + origin.file + " cid=" + origin.cid + "}"; 11014 } 11015 11016 public ManifestDigest getManifestDigest() { 11017 if (verificationParams == null) { 11018 return null; 11019 } 11020 return verificationParams.getManifestDigest(); 11021 } 11022 11023 private int installLocationPolicy(PackageInfoLite pkgLite) { 11024 String packageName = pkgLite.packageName; 11025 int installLocation = pkgLite.installLocation; 11026 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11027 // reader 11028 synchronized (mPackages) { 11029 PackageParser.Package pkg = mPackages.get(packageName); 11030 if (pkg != null) { 11031 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 11032 // Check for downgrading. 11033 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 11034 try { 11035 checkDowngrade(pkg, pkgLite); 11036 } catch (PackageManagerException e) { 11037 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 11038 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 11039 } 11040 } 11041 // Check for updated system application. 11042 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 11043 if (onSd) { 11044 Slog.w(TAG, "Cannot install update to system app on sdcard"); 11045 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 11046 } 11047 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11048 } else { 11049 if (onSd) { 11050 // Install flag overrides everything. 11051 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11052 } 11053 // If current upgrade specifies particular preference 11054 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 11055 // Application explicitly specified internal. 11056 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11057 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 11058 // App explictly prefers external. Let policy decide 11059 } else { 11060 // Prefer previous location 11061 if (isExternal(pkg)) { 11062 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11063 } 11064 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11065 } 11066 } 11067 } else { 11068 // Invalid install. Return error code 11069 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 11070 } 11071 } 11072 } 11073 // All the special cases have been taken care of. 11074 // Return result based on recommended install location. 11075 if (onSd) { 11076 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11077 } 11078 return pkgLite.recommendedInstallLocation; 11079 } 11080 11081 /* 11082 * Invoke remote method to get package information and install 11083 * location values. Override install location based on default 11084 * policy if needed and then create install arguments based 11085 * on the install location. 11086 */ 11087 public void handleStartCopy() throws RemoteException { 11088 int ret = PackageManager.INSTALL_SUCCEEDED; 11089 11090 // If we're already staged, we've firmly committed to an install location 11091 if (origin.staged) { 11092 if (origin.file != null) { 11093 installFlags |= PackageManager.INSTALL_INTERNAL; 11094 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 11095 } else if (origin.cid != null) { 11096 installFlags |= PackageManager.INSTALL_EXTERNAL; 11097 installFlags &= ~PackageManager.INSTALL_INTERNAL; 11098 } else { 11099 throw new IllegalStateException("Invalid stage location"); 11100 } 11101 } 11102 11103 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11104 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 11105 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 11106 PackageInfoLite pkgLite = null; 11107 11108 if (onInt && onSd) { 11109 // Check if both bits are set. 11110 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 11111 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11112 } else if (onSd && ephemeral) { 11113 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 11114 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11115 } else { 11116 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 11117 packageAbiOverride); 11118 11119 if (DEBUG_EPHEMERAL && ephemeral) { 11120 Slog.v(TAG, "pkgLite for install: " + pkgLite); 11121 } 11122 11123 /* 11124 * If we have too little free space, try to free cache 11125 * before giving up. 11126 */ 11127 if (!origin.staged && pkgLite.recommendedInstallLocation 11128 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 11129 // TODO: focus freeing disk space on the target device 11130 final StorageManager storage = StorageManager.from(mContext); 11131 final long lowThreshold = storage.getStorageLowBytes( 11132 Environment.getDataDirectory()); 11133 11134 final long sizeBytes = mContainerService.calculateInstalledSize( 11135 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 11136 11137 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 11138 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 11139 installFlags, packageAbiOverride); 11140 } 11141 11142 /* 11143 * The cache free must have deleted the file we 11144 * downloaded to install. 11145 * 11146 * TODO: fix the "freeCache" call to not delete 11147 * the file we care about. 11148 */ 11149 if (pkgLite.recommendedInstallLocation 11150 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 11151 pkgLite.recommendedInstallLocation 11152 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 11153 } 11154 } 11155 } 11156 11157 if (ret == PackageManager.INSTALL_SUCCEEDED) { 11158 int loc = pkgLite.recommendedInstallLocation; 11159 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 11160 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11161 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 11162 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 11163 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 11164 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11165 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 11166 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 11167 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 11168 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 11169 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 11170 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 11171 } else { 11172 // Override with defaults if needed. 11173 loc = installLocationPolicy(pkgLite); 11174 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 11175 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 11176 } else if (!onSd && !onInt) { 11177 // Override install location with flags 11178 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 11179 // Set the flag to install on external media. 11180 installFlags |= PackageManager.INSTALL_EXTERNAL; 11181 installFlags &= ~PackageManager.INSTALL_INTERNAL; 11182 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 11183 if (DEBUG_EPHEMERAL) { 11184 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 11185 } 11186 installFlags |= PackageManager.INSTALL_EPHEMERAL; 11187 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 11188 |PackageManager.INSTALL_INTERNAL); 11189 } else { 11190 // Make sure the flag for installing on external 11191 // media is unset 11192 installFlags |= PackageManager.INSTALL_INTERNAL; 11193 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 11194 } 11195 } 11196 } 11197 } 11198 11199 final InstallArgs args = createInstallArgs(this); 11200 mArgs = args; 11201 11202 if (ret == PackageManager.INSTALL_SUCCEEDED) { 11203 // TODO: http://b/22976637 11204 // Apps installed for "all" users use the device owner to verify the app 11205 UserHandle verifierUser = getUser(); 11206 if (verifierUser == UserHandle.ALL) { 11207 verifierUser = UserHandle.SYSTEM; 11208 } 11209 11210 /* 11211 * Determine if we have any installed package verifiers. If we 11212 * do, then we'll defer to them to verify the packages. 11213 */ 11214 final int requiredUid = mRequiredVerifierPackage == null ? -1 11215 : getPackageUid(mRequiredVerifierPackage, verifierUser.getIdentifier()); 11216 if (!origin.existing && requiredUid != -1 11217 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 11218 final Intent verification = new Intent( 11219 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 11220 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 11221 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 11222 PACKAGE_MIME_TYPE); 11223 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11224 11225 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 11226 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 11227 verifierUser.getIdentifier()); 11228 11229 if (DEBUG_VERIFY) { 11230 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 11231 + verification.toString() + " with " + pkgLite.verifiers.length 11232 + " optional verifiers"); 11233 } 11234 11235 final int verificationId = mPendingVerificationToken++; 11236 11237 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11238 11239 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 11240 installerPackageName); 11241 11242 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 11243 installFlags); 11244 11245 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 11246 pkgLite.packageName); 11247 11248 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 11249 pkgLite.versionCode); 11250 11251 if (verificationParams != null) { 11252 if (verificationParams.getVerificationURI() != null) { 11253 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 11254 verificationParams.getVerificationURI()); 11255 } 11256 if (verificationParams.getOriginatingURI() != null) { 11257 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 11258 verificationParams.getOriginatingURI()); 11259 } 11260 if (verificationParams.getReferrer() != null) { 11261 verification.putExtra(Intent.EXTRA_REFERRER, 11262 verificationParams.getReferrer()); 11263 } 11264 if (verificationParams.getOriginatingUid() >= 0) { 11265 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 11266 verificationParams.getOriginatingUid()); 11267 } 11268 if (verificationParams.getInstallerUid() >= 0) { 11269 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 11270 verificationParams.getInstallerUid()); 11271 } 11272 } 11273 11274 final PackageVerificationState verificationState = new PackageVerificationState( 11275 requiredUid, args); 11276 11277 mPendingVerification.append(verificationId, verificationState); 11278 11279 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 11280 receivers, verificationState); 11281 11282 /* 11283 * If any sufficient verifiers were listed in the package 11284 * manifest, attempt to ask them. 11285 */ 11286 if (sufficientVerifiers != null) { 11287 final int N = sufficientVerifiers.size(); 11288 if (N == 0) { 11289 Slog.i(TAG, "Additional verifiers required, but none installed."); 11290 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 11291 } else { 11292 for (int i = 0; i < N; i++) { 11293 final ComponentName verifierComponent = sufficientVerifiers.get(i); 11294 11295 final Intent sufficientIntent = new Intent(verification); 11296 sufficientIntent.setComponent(verifierComponent); 11297 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 11298 } 11299 } 11300 } 11301 11302 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 11303 mRequiredVerifierPackage, receivers); 11304 if (ret == PackageManager.INSTALL_SUCCEEDED 11305 && mRequiredVerifierPackage != null) { 11306 Trace.asyncTraceBegin( 11307 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 11308 /* 11309 * Send the intent to the required verification agent, 11310 * but only start the verification timeout after the 11311 * target BroadcastReceivers have run. 11312 */ 11313 verification.setComponent(requiredVerifierComponent); 11314 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 11315 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11316 new BroadcastReceiver() { 11317 @Override 11318 public void onReceive(Context context, Intent intent) { 11319 final Message msg = mHandler 11320 .obtainMessage(CHECK_PENDING_VERIFICATION); 11321 msg.arg1 = verificationId; 11322 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 11323 } 11324 }, null, 0, null, null); 11325 11326 /* 11327 * We don't want the copy to proceed until verification 11328 * succeeds, so null out this field. 11329 */ 11330 mArgs = null; 11331 } 11332 } else { 11333 /* 11334 * No package verification is enabled, so immediately start 11335 * the remote call to initiate copy using temporary file. 11336 */ 11337 ret = args.copyApk(mContainerService, true); 11338 } 11339 } 11340 11341 mRet = ret; 11342 } 11343 11344 @Override 11345 void handleReturnCode() { 11346 // If mArgs is null, then MCS couldn't be reached. When it 11347 // reconnects, it will try again to install. At that point, this 11348 // will succeed. 11349 if (mArgs != null) { 11350 processPendingInstall(mArgs, mRet); 11351 } 11352 } 11353 11354 @Override 11355 void handleServiceError() { 11356 mArgs = createInstallArgs(this); 11357 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11358 } 11359 11360 public boolean isForwardLocked() { 11361 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11362 } 11363 } 11364 11365 /** 11366 * Used during creation of InstallArgs 11367 * 11368 * @param installFlags package installation flags 11369 * @return true if should be installed on external storage 11370 */ 11371 private static boolean installOnExternalAsec(int installFlags) { 11372 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 11373 return false; 11374 } 11375 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 11376 return true; 11377 } 11378 return false; 11379 } 11380 11381 /** 11382 * Used during creation of InstallArgs 11383 * 11384 * @param installFlags package installation flags 11385 * @return true if should be installed as forward locked 11386 */ 11387 private static boolean installForwardLocked(int installFlags) { 11388 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11389 } 11390 11391 private InstallArgs createInstallArgs(InstallParams params) { 11392 if (params.move != null) { 11393 return new MoveInstallArgs(params); 11394 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 11395 return new AsecInstallArgs(params); 11396 } else { 11397 return new FileInstallArgs(params); 11398 } 11399 } 11400 11401 /** 11402 * Create args that describe an existing installed package. Typically used 11403 * when cleaning up old installs, or used as a move source. 11404 */ 11405 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 11406 String resourcePath, String[] instructionSets) { 11407 final boolean isInAsec; 11408 if (installOnExternalAsec(installFlags)) { 11409 /* Apps on SD card are always in ASEC containers. */ 11410 isInAsec = true; 11411 } else if (installForwardLocked(installFlags) 11412 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 11413 /* 11414 * Forward-locked apps are only in ASEC containers if they're the 11415 * new style 11416 */ 11417 isInAsec = true; 11418 } else { 11419 isInAsec = false; 11420 } 11421 11422 if (isInAsec) { 11423 return new AsecInstallArgs(codePath, instructionSets, 11424 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 11425 } else { 11426 return new FileInstallArgs(codePath, resourcePath, instructionSets); 11427 } 11428 } 11429 11430 static abstract class InstallArgs { 11431 /** @see InstallParams#origin */ 11432 final OriginInfo origin; 11433 /** @see InstallParams#move */ 11434 final MoveInfo move; 11435 11436 final IPackageInstallObserver2 observer; 11437 // Always refers to PackageManager flags only 11438 final int installFlags; 11439 final String installerPackageName; 11440 final String volumeUuid; 11441 final ManifestDigest manifestDigest; 11442 final UserHandle user; 11443 final String abiOverride; 11444 final String[] installGrantPermissions; 11445 /** If non-null, drop an async trace when the install completes */ 11446 final String traceMethod; 11447 final int traceCookie; 11448 11449 // The list of instruction sets supported by this app. This is currently 11450 // only used during the rmdex() phase to clean up resources. We can get rid of this 11451 // if we move dex files under the common app path. 11452 /* nullable */ String[] instructionSets; 11453 11454 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 11455 int installFlags, String installerPackageName, String volumeUuid, 11456 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 11457 String abiOverride, String[] installGrantPermissions, 11458 String traceMethod, int traceCookie) { 11459 this.origin = origin; 11460 this.move = move; 11461 this.installFlags = installFlags; 11462 this.observer = observer; 11463 this.installerPackageName = installerPackageName; 11464 this.volumeUuid = volumeUuid; 11465 this.manifestDigest = manifestDigest; 11466 this.user = user; 11467 this.instructionSets = instructionSets; 11468 this.abiOverride = abiOverride; 11469 this.installGrantPermissions = installGrantPermissions; 11470 this.traceMethod = traceMethod; 11471 this.traceCookie = traceCookie; 11472 } 11473 11474 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 11475 abstract int doPreInstall(int status); 11476 11477 /** 11478 * Rename package into final resting place. All paths on the given 11479 * scanned package should be updated to reflect the rename. 11480 */ 11481 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 11482 abstract int doPostInstall(int status, int uid); 11483 11484 /** @see PackageSettingBase#codePathString */ 11485 abstract String getCodePath(); 11486 /** @see PackageSettingBase#resourcePathString */ 11487 abstract String getResourcePath(); 11488 11489 // Need installer lock especially for dex file removal. 11490 abstract void cleanUpResourcesLI(); 11491 abstract boolean doPostDeleteLI(boolean delete); 11492 11493 /** 11494 * Called before the source arguments are copied. This is used mostly 11495 * for MoveParams when it needs to read the source file to put it in the 11496 * destination. 11497 */ 11498 int doPreCopy() { 11499 return PackageManager.INSTALL_SUCCEEDED; 11500 } 11501 11502 /** 11503 * Called after the source arguments are copied. This is used mostly for 11504 * MoveParams when it needs to read the source file to put it in the 11505 * destination. 11506 * 11507 * @return 11508 */ 11509 int doPostCopy(int uid) { 11510 return PackageManager.INSTALL_SUCCEEDED; 11511 } 11512 11513 protected boolean isFwdLocked() { 11514 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11515 } 11516 11517 protected boolean isExternalAsec() { 11518 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11519 } 11520 11521 protected boolean isEphemeral() { 11522 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 11523 } 11524 11525 UserHandle getUser() { 11526 return user; 11527 } 11528 } 11529 11530 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 11531 if (!allCodePaths.isEmpty()) { 11532 if (instructionSets == null) { 11533 throw new IllegalStateException("instructionSet == null"); 11534 } 11535 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 11536 for (String codePath : allCodePaths) { 11537 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 11538 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 11539 if (retCode < 0) { 11540 Slog.w(TAG, "Couldn't remove dex file for package: " 11541 + " at location " + codePath + ", retcode=" + retCode); 11542 // we don't consider this to be a failure of the core package deletion 11543 } 11544 } 11545 } 11546 } 11547 } 11548 11549 /** 11550 * Logic to handle installation of non-ASEC applications, including copying 11551 * and renaming logic. 11552 */ 11553 class FileInstallArgs extends InstallArgs { 11554 private File codeFile; 11555 private File resourceFile; 11556 11557 // Example topology: 11558 // /data/app/com.example/base.apk 11559 // /data/app/com.example/split_foo.apk 11560 // /data/app/com.example/lib/arm/libfoo.so 11561 // /data/app/com.example/lib/arm64/libfoo.so 11562 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 11563 11564 /** New install */ 11565 FileInstallArgs(InstallParams params) { 11566 super(params.origin, params.move, params.observer, params.installFlags, 11567 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11568 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11569 params.grantedRuntimePermissions, 11570 params.traceMethod, params.traceCookie); 11571 if (isFwdLocked()) { 11572 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 11573 } 11574 } 11575 11576 /** Existing install */ 11577 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 11578 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 11579 null, null, null, 0); 11580 this.codeFile = (codePath != null) ? new File(codePath) : null; 11581 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 11582 } 11583 11584 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11585 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 11586 try { 11587 return doCopyApk(imcs, temp); 11588 } finally { 11589 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11590 } 11591 } 11592 11593 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11594 if (origin.staged) { 11595 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 11596 codeFile = origin.file; 11597 resourceFile = origin.file; 11598 return PackageManager.INSTALL_SUCCEEDED; 11599 } 11600 11601 try { 11602 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 11603 final File tempDir = 11604 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 11605 codeFile = tempDir; 11606 resourceFile = tempDir; 11607 } catch (IOException e) { 11608 Slog.w(TAG, "Failed to create copy file: " + e); 11609 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11610 } 11611 11612 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 11613 @Override 11614 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 11615 if (!FileUtils.isValidExtFilename(name)) { 11616 throw new IllegalArgumentException("Invalid filename: " + name); 11617 } 11618 try { 11619 final File file = new File(codeFile, name); 11620 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 11621 O_RDWR | O_CREAT, 0644); 11622 Os.chmod(file.getAbsolutePath(), 0644); 11623 return new ParcelFileDescriptor(fd); 11624 } catch (ErrnoException e) { 11625 throw new RemoteException("Failed to open: " + e.getMessage()); 11626 } 11627 } 11628 }; 11629 11630 int ret = PackageManager.INSTALL_SUCCEEDED; 11631 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 11632 if (ret != PackageManager.INSTALL_SUCCEEDED) { 11633 Slog.e(TAG, "Failed to copy package"); 11634 return ret; 11635 } 11636 11637 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 11638 NativeLibraryHelper.Handle handle = null; 11639 try { 11640 handle = NativeLibraryHelper.Handle.create(codeFile); 11641 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 11642 abiOverride); 11643 } catch (IOException e) { 11644 Slog.e(TAG, "Copying native libraries failed", e); 11645 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11646 } finally { 11647 IoUtils.closeQuietly(handle); 11648 } 11649 11650 return ret; 11651 } 11652 11653 int doPreInstall(int status) { 11654 if (status != PackageManager.INSTALL_SUCCEEDED) { 11655 cleanUp(); 11656 } 11657 return status; 11658 } 11659 11660 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11661 if (status != PackageManager.INSTALL_SUCCEEDED) { 11662 cleanUp(); 11663 return false; 11664 } 11665 11666 final File targetDir = codeFile.getParentFile(); 11667 final File beforeCodeFile = codeFile; 11668 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 11669 11670 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 11671 try { 11672 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 11673 } catch (ErrnoException e) { 11674 Slog.w(TAG, "Failed to rename", e); 11675 return false; 11676 } 11677 11678 if (!SELinux.restoreconRecursive(afterCodeFile)) { 11679 Slog.w(TAG, "Failed to restorecon"); 11680 return false; 11681 } 11682 11683 // Reflect the rename internally 11684 codeFile = afterCodeFile; 11685 resourceFile = afterCodeFile; 11686 11687 // Reflect the rename in scanned details 11688 pkg.codePath = afterCodeFile.getAbsolutePath(); 11689 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11690 pkg.baseCodePath); 11691 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11692 pkg.splitCodePaths); 11693 11694 // Reflect the rename in app info 11695 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11696 pkg.applicationInfo.setCodePath(pkg.codePath); 11697 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11698 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11699 pkg.applicationInfo.setResourcePath(pkg.codePath); 11700 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11701 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11702 11703 return true; 11704 } 11705 11706 int doPostInstall(int status, int uid) { 11707 if (status != PackageManager.INSTALL_SUCCEEDED) { 11708 cleanUp(); 11709 } 11710 return status; 11711 } 11712 11713 @Override 11714 String getCodePath() { 11715 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11716 } 11717 11718 @Override 11719 String getResourcePath() { 11720 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11721 } 11722 11723 private boolean cleanUp() { 11724 if (codeFile == null || !codeFile.exists()) { 11725 return false; 11726 } 11727 11728 if (codeFile.isDirectory()) { 11729 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11730 } else { 11731 codeFile.delete(); 11732 } 11733 11734 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 11735 resourceFile.delete(); 11736 } 11737 11738 return true; 11739 } 11740 11741 void cleanUpResourcesLI() { 11742 // Try enumerating all code paths before deleting 11743 List<String> allCodePaths = Collections.EMPTY_LIST; 11744 if (codeFile != null && codeFile.exists()) { 11745 try { 11746 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11747 allCodePaths = pkg.getAllCodePaths(); 11748 } catch (PackageParserException e) { 11749 // Ignored; we tried our best 11750 } 11751 } 11752 11753 cleanUp(); 11754 removeDexFiles(allCodePaths, instructionSets); 11755 } 11756 11757 boolean doPostDeleteLI(boolean delete) { 11758 // XXX err, shouldn't we respect the delete flag? 11759 cleanUpResourcesLI(); 11760 return true; 11761 } 11762 } 11763 11764 private boolean isAsecExternal(String cid) { 11765 final String asecPath = PackageHelper.getSdFilesystem(cid); 11766 return !asecPath.startsWith(mAsecInternalPath); 11767 } 11768 11769 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 11770 PackageManagerException { 11771 if (copyRet < 0) { 11772 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 11773 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 11774 throw new PackageManagerException(copyRet, message); 11775 } 11776 } 11777 } 11778 11779 /** 11780 * Extract the MountService "container ID" from the full code path of an 11781 * .apk. 11782 */ 11783 static String cidFromCodePath(String fullCodePath) { 11784 int eidx = fullCodePath.lastIndexOf("/"); 11785 String subStr1 = fullCodePath.substring(0, eidx); 11786 int sidx = subStr1.lastIndexOf("/"); 11787 return subStr1.substring(sidx+1, eidx); 11788 } 11789 11790 /** 11791 * Logic to handle installation of ASEC applications, including copying and 11792 * renaming logic. 11793 */ 11794 class AsecInstallArgs extends InstallArgs { 11795 static final String RES_FILE_NAME = "pkg.apk"; 11796 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 11797 11798 String cid; 11799 String packagePath; 11800 String resourcePath; 11801 11802 /** New install */ 11803 AsecInstallArgs(InstallParams params) { 11804 super(params.origin, params.move, params.observer, params.installFlags, 11805 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11806 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11807 params.grantedRuntimePermissions, 11808 params.traceMethod, params.traceCookie); 11809 } 11810 11811 /** Existing install */ 11812 AsecInstallArgs(String fullCodePath, String[] instructionSets, 11813 boolean isExternal, boolean isForwardLocked) { 11814 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 11815 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11816 instructionSets, null, null, null, 0); 11817 // Hackily pretend we're still looking at a full code path 11818 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 11819 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 11820 } 11821 11822 // Extract cid from fullCodePath 11823 int eidx = fullCodePath.lastIndexOf("/"); 11824 String subStr1 = fullCodePath.substring(0, eidx); 11825 int sidx = subStr1.lastIndexOf("/"); 11826 cid = subStr1.substring(sidx+1, eidx); 11827 setMountPath(subStr1); 11828 } 11829 11830 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 11831 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 11832 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11833 instructionSets, null, null, null, 0); 11834 this.cid = cid; 11835 setMountPath(PackageHelper.getSdDir(cid)); 11836 } 11837 11838 void createCopyFile() { 11839 cid = mInstallerService.allocateExternalStageCidLegacy(); 11840 } 11841 11842 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11843 if (origin.staged && origin.cid != null) { 11844 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 11845 cid = origin.cid; 11846 setMountPath(PackageHelper.getSdDir(cid)); 11847 return PackageManager.INSTALL_SUCCEEDED; 11848 } 11849 11850 if (temp) { 11851 createCopyFile(); 11852 } else { 11853 /* 11854 * Pre-emptively destroy the container since it's destroyed if 11855 * copying fails due to it existing anyway. 11856 */ 11857 PackageHelper.destroySdDir(cid); 11858 } 11859 11860 final String newMountPath = imcs.copyPackageToContainer( 11861 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 11862 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 11863 11864 if (newMountPath != null) { 11865 setMountPath(newMountPath); 11866 return PackageManager.INSTALL_SUCCEEDED; 11867 } else { 11868 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11869 } 11870 } 11871 11872 @Override 11873 String getCodePath() { 11874 return packagePath; 11875 } 11876 11877 @Override 11878 String getResourcePath() { 11879 return resourcePath; 11880 } 11881 11882 int doPreInstall(int status) { 11883 if (status != PackageManager.INSTALL_SUCCEEDED) { 11884 // Destroy container 11885 PackageHelper.destroySdDir(cid); 11886 } else { 11887 boolean mounted = PackageHelper.isContainerMounted(cid); 11888 if (!mounted) { 11889 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 11890 Process.SYSTEM_UID); 11891 if (newMountPath != null) { 11892 setMountPath(newMountPath); 11893 } else { 11894 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11895 } 11896 } 11897 } 11898 return status; 11899 } 11900 11901 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11902 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 11903 String newMountPath = null; 11904 if (PackageHelper.isContainerMounted(cid)) { 11905 // Unmount the container 11906 if (!PackageHelper.unMountSdDir(cid)) { 11907 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 11908 return false; 11909 } 11910 } 11911 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11912 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 11913 " which might be stale. Will try to clean up."); 11914 // Clean up the stale container and proceed to recreate. 11915 if (!PackageHelper.destroySdDir(newCacheId)) { 11916 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 11917 return false; 11918 } 11919 // Successfully cleaned up stale container. Try to rename again. 11920 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11921 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 11922 + " inspite of cleaning it up."); 11923 return false; 11924 } 11925 } 11926 if (!PackageHelper.isContainerMounted(newCacheId)) { 11927 Slog.w(TAG, "Mounting container " + newCacheId); 11928 newMountPath = PackageHelper.mountSdDir(newCacheId, 11929 getEncryptKey(), Process.SYSTEM_UID); 11930 } else { 11931 newMountPath = PackageHelper.getSdDir(newCacheId); 11932 } 11933 if (newMountPath == null) { 11934 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 11935 return false; 11936 } 11937 Log.i(TAG, "Succesfully renamed " + cid + 11938 " to " + newCacheId + 11939 " at new path: " + newMountPath); 11940 cid = newCacheId; 11941 11942 final File beforeCodeFile = new File(packagePath); 11943 setMountPath(newMountPath); 11944 final File afterCodeFile = new File(packagePath); 11945 11946 // Reflect the rename in scanned details 11947 pkg.codePath = afterCodeFile.getAbsolutePath(); 11948 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11949 pkg.baseCodePath); 11950 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11951 pkg.splitCodePaths); 11952 11953 // Reflect the rename in app info 11954 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11955 pkg.applicationInfo.setCodePath(pkg.codePath); 11956 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11957 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11958 pkg.applicationInfo.setResourcePath(pkg.codePath); 11959 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11960 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11961 11962 return true; 11963 } 11964 11965 private void setMountPath(String mountPath) { 11966 final File mountFile = new File(mountPath); 11967 11968 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 11969 if (monolithicFile.exists()) { 11970 packagePath = monolithicFile.getAbsolutePath(); 11971 if (isFwdLocked()) { 11972 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 11973 } else { 11974 resourcePath = packagePath; 11975 } 11976 } else { 11977 packagePath = mountFile.getAbsolutePath(); 11978 resourcePath = packagePath; 11979 } 11980 } 11981 11982 int doPostInstall(int status, int uid) { 11983 if (status != PackageManager.INSTALL_SUCCEEDED) { 11984 cleanUp(); 11985 } else { 11986 final int groupOwner; 11987 final String protectedFile; 11988 if (isFwdLocked()) { 11989 groupOwner = UserHandle.getSharedAppGid(uid); 11990 protectedFile = RES_FILE_NAME; 11991 } else { 11992 groupOwner = -1; 11993 protectedFile = null; 11994 } 11995 11996 if (uid < Process.FIRST_APPLICATION_UID 11997 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 11998 Slog.e(TAG, "Failed to finalize " + cid); 11999 PackageHelper.destroySdDir(cid); 12000 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12001 } 12002 12003 boolean mounted = PackageHelper.isContainerMounted(cid); 12004 if (!mounted) { 12005 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 12006 } 12007 } 12008 return status; 12009 } 12010 12011 private void cleanUp() { 12012 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 12013 12014 // Destroy secure container 12015 PackageHelper.destroySdDir(cid); 12016 } 12017 12018 private List<String> getAllCodePaths() { 12019 final File codeFile = new File(getCodePath()); 12020 if (codeFile != null && codeFile.exists()) { 12021 try { 12022 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 12023 return pkg.getAllCodePaths(); 12024 } catch (PackageParserException e) { 12025 // Ignored; we tried our best 12026 } 12027 } 12028 return Collections.EMPTY_LIST; 12029 } 12030 12031 void cleanUpResourcesLI() { 12032 // Enumerate all code paths before deleting 12033 cleanUpResourcesLI(getAllCodePaths()); 12034 } 12035 12036 private void cleanUpResourcesLI(List<String> allCodePaths) { 12037 cleanUp(); 12038 removeDexFiles(allCodePaths, instructionSets); 12039 } 12040 12041 String getPackageName() { 12042 return getAsecPackageName(cid); 12043 } 12044 12045 boolean doPostDeleteLI(boolean delete) { 12046 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 12047 final List<String> allCodePaths = getAllCodePaths(); 12048 boolean mounted = PackageHelper.isContainerMounted(cid); 12049 if (mounted) { 12050 // Unmount first 12051 if (PackageHelper.unMountSdDir(cid)) { 12052 mounted = false; 12053 } 12054 } 12055 if (!mounted && delete) { 12056 cleanUpResourcesLI(allCodePaths); 12057 } 12058 return !mounted; 12059 } 12060 12061 @Override 12062 int doPreCopy() { 12063 if (isFwdLocked()) { 12064 if (!PackageHelper.fixSdPermissions(cid, 12065 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 12066 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12067 } 12068 } 12069 12070 return PackageManager.INSTALL_SUCCEEDED; 12071 } 12072 12073 @Override 12074 int doPostCopy(int uid) { 12075 if (isFwdLocked()) { 12076 if (uid < Process.FIRST_APPLICATION_UID 12077 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 12078 RES_FILE_NAME)) { 12079 Slog.e(TAG, "Failed to finalize " + cid); 12080 PackageHelper.destroySdDir(cid); 12081 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12082 } 12083 } 12084 12085 return PackageManager.INSTALL_SUCCEEDED; 12086 } 12087 } 12088 12089 /** 12090 * Logic to handle movement of existing installed applications. 12091 */ 12092 class MoveInstallArgs extends InstallArgs { 12093 private File codeFile; 12094 private File resourceFile; 12095 12096 /** New install */ 12097 MoveInstallArgs(InstallParams params) { 12098 super(params.origin, params.move, params.observer, params.installFlags, 12099 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 12100 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 12101 params.grantedRuntimePermissions, 12102 params.traceMethod, params.traceCookie); 12103 } 12104 12105 int copyApk(IMediaContainerService imcs, boolean temp) { 12106 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 12107 + move.fromUuid + " to " + move.toUuid); 12108 synchronized (mInstaller) { 12109 if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName, 12110 move.dataAppName, move.appId, move.seinfo) != 0) { 12111 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12112 } 12113 } 12114 12115 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 12116 resourceFile = codeFile; 12117 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 12118 12119 return PackageManager.INSTALL_SUCCEEDED; 12120 } 12121 12122 int doPreInstall(int status) { 12123 if (status != PackageManager.INSTALL_SUCCEEDED) { 12124 cleanUp(move.toUuid); 12125 } 12126 return status; 12127 } 12128 12129 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12130 if (status != PackageManager.INSTALL_SUCCEEDED) { 12131 cleanUp(move.toUuid); 12132 return false; 12133 } 12134 12135 // Reflect the move in app info 12136 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 12137 pkg.applicationInfo.setCodePath(pkg.codePath); 12138 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 12139 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 12140 pkg.applicationInfo.setResourcePath(pkg.codePath); 12141 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 12142 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 12143 12144 return true; 12145 } 12146 12147 int doPostInstall(int status, int uid) { 12148 if (status == PackageManager.INSTALL_SUCCEEDED) { 12149 cleanUp(move.fromUuid); 12150 } else { 12151 cleanUp(move.toUuid); 12152 } 12153 return status; 12154 } 12155 12156 @Override 12157 String getCodePath() { 12158 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 12159 } 12160 12161 @Override 12162 String getResourcePath() { 12163 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 12164 } 12165 12166 private boolean cleanUp(String volumeUuid) { 12167 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 12168 move.dataAppName); 12169 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 12170 synchronized (mInstallLock) { 12171 // Clean up both app data and code 12172 removeDataDirsLI(volumeUuid, move.packageName); 12173 if (codeFile.isDirectory()) { 12174 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 12175 } else { 12176 codeFile.delete(); 12177 } 12178 } 12179 return true; 12180 } 12181 12182 void cleanUpResourcesLI() { 12183 throw new UnsupportedOperationException(); 12184 } 12185 12186 boolean doPostDeleteLI(boolean delete) { 12187 throw new UnsupportedOperationException(); 12188 } 12189 } 12190 12191 static String getAsecPackageName(String packageCid) { 12192 int idx = packageCid.lastIndexOf("-"); 12193 if (idx == -1) { 12194 return packageCid; 12195 } 12196 return packageCid.substring(0, idx); 12197 } 12198 12199 // Utility method used to create code paths based on package name and available index. 12200 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 12201 String idxStr = ""; 12202 int idx = 1; 12203 // Fall back to default value of idx=1 if prefix is not 12204 // part of oldCodePath 12205 if (oldCodePath != null) { 12206 String subStr = oldCodePath; 12207 // Drop the suffix right away 12208 if (suffix != null && subStr.endsWith(suffix)) { 12209 subStr = subStr.substring(0, subStr.length() - suffix.length()); 12210 } 12211 // If oldCodePath already contains prefix find out the 12212 // ending index to either increment or decrement. 12213 int sidx = subStr.lastIndexOf(prefix); 12214 if (sidx != -1) { 12215 subStr = subStr.substring(sidx + prefix.length()); 12216 if (subStr != null) { 12217 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 12218 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 12219 } 12220 try { 12221 idx = Integer.parseInt(subStr); 12222 if (idx <= 1) { 12223 idx++; 12224 } else { 12225 idx--; 12226 } 12227 } catch(NumberFormatException e) { 12228 } 12229 } 12230 } 12231 } 12232 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 12233 return prefix + idxStr; 12234 } 12235 12236 private File getNextCodePath(File targetDir, String packageName) { 12237 int suffix = 1; 12238 File result; 12239 do { 12240 result = new File(targetDir, packageName + "-" + suffix); 12241 suffix++; 12242 } while (result.exists()); 12243 return result; 12244 } 12245 12246 // Utility method that returns the relative package path with respect 12247 // to the installation directory. Like say for /data/data/com.test-1.apk 12248 // string com.test-1 is returned. 12249 static String deriveCodePathName(String codePath) { 12250 if (codePath == null) { 12251 return null; 12252 } 12253 final File codeFile = new File(codePath); 12254 final String name = codeFile.getName(); 12255 if (codeFile.isDirectory()) { 12256 return name; 12257 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 12258 final int lastDot = name.lastIndexOf('.'); 12259 return name.substring(0, lastDot); 12260 } else { 12261 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 12262 return null; 12263 } 12264 } 12265 12266 static class PackageInstalledInfo { 12267 String name; 12268 int uid; 12269 // The set of users that originally had this package installed. 12270 int[] origUsers; 12271 // The set of users that now have this package installed. 12272 int[] newUsers; 12273 PackageParser.Package pkg; 12274 int returnCode; 12275 String returnMsg; 12276 PackageRemovedInfo removedInfo; 12277 12278 public void setError(int code, String msg) { 12279 returnCode = code; 12280 returnMsg = msg; 12281 Slog.w(TAG, msg); 12282 } 12283 12284 public void setError(String msg, PackageParserException e) { 12285 returnCode = e.error; 12286 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 12287 Slog.w(TAG, msg, e); 12288 } 12289 12290 public void setError(String msg, PackageManagerException e) { 12291 returnCode = e.error; 12292 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 12293 Slog.w(TAG, msg, e); 12294 } 12295 12296 // In some error cases we want to convey more info back to the observer 12297 String origPackage; 12298 String origPermission; 12299 } 12300 12301 /* 12302 * Install a non-existing package. 12303 */ 12304 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 12305 UserHandle user, String installerPackageName, String volumeUuid, 12306 PackageInstalledInfo res) { 12307 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 12308 12309 // Remember this for later, in case we need to rollback this install 12310 String pkgName = pkg.packageName; 12311 12312 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 12313 // TODO: b/23350563 12314 final boolean dataDirExists = Environment 12315 .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists(); 12316 12317 synchronized(mPackages) { 12318 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 12319 // A package with the same name is already installed, though 12320 // it has been renamed to an older name. The package we 12321 // are trying to install should be installed as an update to 12322 // the existing one, but that has not been requested, so bail. 12323 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 12324 + " without first uninstalling package running as " 12325 + mSettings.mRenamedPackages.get(pkgName)); 12326 return; 12327 } 12328 if (mPackages.containsKey(pkgName)) { 12329 // Don't allow installation over an existing package with the same name. 12330 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 12331 + " without first uninstalling."); 12332 return; 12333 } 12334 } 12335 12336 try { 12337 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 12338 System.currentTimeMillis(), user); 12339 12340 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 12341 // delete the partially installed application. the data directory will have to be 12342 // restored if it was already existing 12343 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12344 // remove package from internal structures. Note that we want deletePackageX to 12345 // delete the package data and cache directories that it created in 12346 // scanPackageLocked, unless those directories existed before we even tried to 12347 // install. 12348 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 12349 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 12350 res.removedInfo, true); 12351 } 12352 12353 } catch (PackageManagerException e) { 12354 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12355 } 12356 12357 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12358 } 12359 12360 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 12361 // Can't rotate keys during boot or if sharedUser. 12362 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 12363 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 12364 return false; 12365 } 12366 // app is using upgradeKeySets; make sure all are valid 12367 KeySetManagerService ksms = mSettings.mKeySetManagerService; 12368 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 12369 for (int i = 0; i < upgradeKeySets.length; i++) { 12370 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 12371 Slog.wtf(TAG, "Package " 12372 + (oldPs.name != null ? oldPs.name : "<null>") 12373 + " contains upgrade-key-set reference to unknown key-set: " 12374 + upgradeKeySets[i] 12375 + " reverting to signatures check."); 12376 return false; 12377 } 12378 } 12379 return true; 12380 } 12381 12382 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 12383 // Upgrade keysets are being used. Determine if new package has a superset of the 12384 // required keys. 12385 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 12386 KeySetManagerService ksms = mSettings.mKeySetManagerService; 12387 for (int i = 0; i < upgradeKeySets.length; i++) { 12388 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 12389 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 12390 return true; 12391 } 12392 } 12393 return false; 12394 } 12395 12396 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 12397 UserHandle user, String installerPackageName, String volumeUuid, 12398 PackageInstalledInfo res) { 12399 final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 12400 12401 final PackageParser.Package oldPackage; 12402 final String pkgName = pkg.packageName; 12403 final int[] allUsers; 12404 final boolean[] perUserInstalled; 12405 12406 // First find the old package info and check signatures 12407 synchronized(mPackages) { 12408 oldPackage = mPackages.get(pkgName); 12409 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 12410 if (isEphemeral && !oldIsEphemeral) { 12411 // can't downgrade from full to ephemeral 12412 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 12413 res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 12414 return; 12415 } 12416 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 12417 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12418 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12419 if(!checkUpgradeKeySetLP(ps, pkg)) { 12420 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 12421 "New package not signed by keys specified by upgrade-keysets: " 12422 + pkgName); 12423 return; 12424 } 12425 } else { 12426 // default to original signature matching 12427 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 12428 != PackageManager.SIGNATURE_MATCH) { 12429 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 12430 "New package has a different signature: " + pkgName); 12431 return; 12432 } 12433 } 12434 12435 // In case of rollback, remember per-user/profile install state 12436 allUsers = sUserManager.getUserIds(); 12437 perUserInstalled = new boolean[allUsers.length]; 12438 for (int i = 0; i < allUsers.length; i++) { 12439 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12440 } 12441 } 12442 12443 boolean sysPkg = (isSystemApp(oldPackage)); 12444 if (sysPkg) { 12445 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 12446 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 12447 } else { 12448 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 12449 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 12450 } 12451 } 12452 12453 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 12454 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 12455 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 12456 String volumeUuid, PackageInstalledInfo res) { 12457 String pkgName = deletedPackage.packageName; 12458 boolean deletedPkg = true; 12459 boolean updatedSettings = false; 12460 12461 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 12462 + deletedPackage); 12463 long origUpdateTime; 12464 if (pkg.mExtras != null) { 12465 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 12466 } else { 12467 origUpdateTime = 0; 12468 } 12469 12470 // First delete the existing package while retaining the data directory 12471 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 12472 res.removedInfo, true)) { 12473 // If the existing package wasn't successfully deleted 12474 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 12475 deletedPkg = false; 12476 } else { 12477 // Successfully deleted the old package; proceed with replace. 12478 12479 // If deleted package lived in a container, give users a chance to 12480 // relinquish resources before killing. 12481 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 12482 if (DEBUG_INSTALL) { 12483 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 12484 } 12485 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 12486 final ArrayList<String> pkgList = new ArrayList<String>(1); 12487 pkgList.add(deletedPackage.applicationInfo.packageName); 12488 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 12489 } 12490 12491 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 12492 try { 12493 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 12494 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 12495 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12496 perUserInstalled, res, user); 12497 updatedSettings = true; 12498 } catch (PackageManagerException e) { 12499 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12500 } 12501 } 12502 12503 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12504 // remove package from internal structures. Note that we want deletePackageX to 12505 // delete the package data and cache directories that it created in 12506 // scanPackageLocked, unless those directories existed before we even tried to 12507 // install. 12508 if(updatedSettings) { 12509 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 12510 deletePackageLI( 12511 pkgName, null, true, allUsers, perUserInstalled, 12512 PackageManager.DELETE_KEEP_DATA, 12513 res.removedInfo, true); 12514 } 12515 // Since we failed to install the new package we need to restore the old 12516 // package that we deleted. 12517 if (deletedPkg) { 12518 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 12519 File restoreFile = new File(deletedPackage.codePath); 12520 // Parse old package 12521 boolean oldExternal = isExternal(deletedPackage); 12522 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 12523 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 12524 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 12525 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 12526 try { 12527 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 12528 null); 12529 } catch (PackageManagerException e) { 12530 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 12531 + e.getMessage()); 12532 return; 12533 } 12534 // Restore of old package succeeded. Update permissions. 12535 // writer 12536 synchronized (mPackages) { 12537 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 12538 UPDATE_PERMISSIONS_ALL); 12539 // can downgrade to reader 12540 mSettings.writeLPr(); 12541 } 12542 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 12543 } 12544 } 12545 } 12546 12547 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 12548 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 12549 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 12550 String volumeUuid, PackageInstalledInfo res) { 12551 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 12552 + ", old=" + deletedPackage); 12553 boolean disabledSystem = false; 12554 boolean updatedSettings = false; 12555 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 12556 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 12557 != 0) { 12558 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12559 } 12560 String packageName = deletedPackage.packageName; 12561 if (packageName == null) { 12562 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12563 "Attempt to delete null packageName."); 12564 return; 12565 } 12566 PackageParser.Package oldPkg; 12567 PackageSetting oldPkgSetting; 12568 // reader 12569 synchronized (mPackages) { 12570 oldPkg = mPackages.get(packageName); 12571 oldPkgSetting = mSettings.mPackages.get(packageName); 12572 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 12573 (oldPkgSetting == null)) { 12574 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12575 "Couldn't find package:" + packageName + " information"); 12576 return; 12577 } 12578 } 12579 12580 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 12581 12582 res.removedInfo.uid = oldPkg.applicationInfo.uid; 12583 res.removedInfo.removedPackage = packageName; 12584 // Remove existing system package 12585 removePackageLI(oldPkgSetting, true); 12586 // writer 12587 synchronized (mPackages) { 12588 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 12589 if (!disabledSystem && deletedPackage != null) { 12590 // We didn't need to disable the .apk as a current system package, 12591 // which means we are replacing another update that is already 12592 // installed. We need to make sure to delete the older one's .apk. 12593 res.removedInfo.args = createInstallArgsForExisting(0, 12594 deletedPackage.applicationInfo.getCodePath(), 12595 deletedPackage.applicationInfo.getResourcePath(), 12596 getAppDexInstructionSets(deletedPackage.applicationInfo)); 12597 } else { 12598 res.removedInfo.args = null; 12599 } 12600 } 12601 12602 // Successfully disabled the old package. Now proceed with re-installation 12603 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 12604 12605 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12606 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 12607 12608 PackageParser.Package newPackage = null; 12609 try { 12610 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 12611 if (newPackage.mExtras != null) { 12612 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 12613 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 12614 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 12615 12616 // is the update attempting to change shared user? that isn't going to work... 12617 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 12618 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 12619 "Forbidding shared user change from " + oldPkgSetting.sharedUser 12620 + " to " + newPkgSetting.sharedUser); 12621 updatedSettings = true; 12622 } 12623 } 12624 12625 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12626 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12627 perUserInstalled, res, user); 12628 updatedSettings = true; 12629 } 12630 12631 } catch (PackageManagerException e) { 12632 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12633 } 12634 12635 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12636 // Re installation failed. Restore old information 12637 // Remove new pkg information 12638 if (newPackage != null) { 12639 removeInstalledPackageLI(newPackage, true); 12640 } 12641 // Add back the old system package 12642 try { 12643 scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 12644 } catch (PackageManagerException e) { 12645 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 12646 } 12647 // Restore the old system information in Settings 12648 synchronized (mPackages) { 12649 if (disabledSystem) { 12650 mSettings.enableSystemPackageLPw(packageName); 12651 } 12652 if (updatedSettings) { 12653 mSettings.setInstallerPackageName(packageName, 12654 oldPkgSetting.installerPackageName); 12655 } 12656 mSettings.writeLPr(); 12657 } 12658 } 12659 } 12660 12661 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 12662 // Collect all used permissions in the UID 12663 ArraySet<String> usedPermissions = new ArraySet<>(); 12664 final int packageCount = su.packages.size(); 12665 for (int i = 0; i < packageCount; i++) { 12666 PackageSetting ps = su.packages.valueAt(i); 12667 if (ps.pkg == null) { 12668 continue; 12669 } 12670 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 12671 for (int j = 0; j < requestedPermCount; j++) { 12672 String permission = ps.pkg.requestedPermissions.get(j); 12673 BasePermission bp = mSettings.mPermissions.get(permission); 12674 if (bp != null) { 12675 usedPermissions.add(permission); 12676 } 12677 } 12678 } 12679 12680 PermissionsState permissionsState = su.getPermissionsState(); 12681 // Prune install permissions 12682 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 12683 final int installPermCount = installPermStates.size(); 12684 for (int i = installPermCount - 1; i >= 0; i--) { 12685 PermissionState permissionState = installPermStates.get(i); 12686 if (!usedPermissions.contains(permissionState.getName())) { 12687 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 12688 if (bp != null) { 12689 permissionsState.revokeInstallPermission(bp); 12690 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 12691 PackageManager.MASK_PERMISSION_FLAGS, 0); 12692 } 12693 } 12694 } 12695 12696 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 12697 12698 // Prune runtime permissions 12699 for (int userId : allUserIds) { 12700 List<PermissionState> runtimePermStates = permissionsState 12701 .getRuntimePermissionStates(userId); 12702 final int runtimePermCount = runtimePermStates.size(); 12703 for (int i = runtimePermCount - 1; i >= 0; i--) { 12704 PermissionState permissionState = runtimePermStates.get(i); 12705 if (!usedPermissions.contains(permissionState.getName())) { 12706 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 12707 if (bp != null) { 12708 permissionsState.revokeRuntimePermission(bp, userId); 12709 permissionsState.updatePermissionFlags(bp, userId, 12710 PackageManager.MASK_PERMISSION_FLAGS, 0); 12711 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 12712 runtimePermissionChangedUserIds, userId); 12713 } 12714 } 12715 } 12716 } 12717 12718 return runtimePermissionChangedUserIds; 12719 } 12720 12721 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 12722 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 12723 UserHandle user) { 12724 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 12725 12726 String pkgName = newPackage.packageName; 12727 synchronized (mPackages) { 12728 //write settings. the installStatus will be incomplete at this stage. 12729 //note that the new package setting would have already been 12730 //added to mPackages. It hasn't been persisted yet. 12731 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 12732 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 12733 mSettings.writeLPr(); 12734 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12735 } 12736 12737 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 12738 synchronized (mPackages) { 12739 updatePermissionsLPw(newPackage.packageName, newPackage, 12740 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 12741 ? UPDATE_PERMISSIONS_ALL : 0)); 12742 // For system-bundled packages, we assume that installing an upgraded version 12743 // of the package implies that the user actually wants to run that new code, 12744 // so we enable the package. 12745 PackageSetting ps = mSettings.mPackages.get(pkgName); 12746 if (ps != null) { 12747 if (isSystemApp(newPackage)) { 12748 // NB: implicit assumption that system package upgrades apply to all users 12749 if (DEBUG_INSTALL) { 12750 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 12751 } 12752 if (res.origUsers != null) { 12753 for (int userHandle : res.origUsers) { 12754 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 12755 userHandle, installerPackageName); 12756 } 12757 } 12758 // Also convey the prior install/uninstall state 12759 if (allUsers != null && perUserInstalled != null) { 12760 for (int i = 0; i < allUsers.length; i++) { 12761 if (DEBUG_INSTALL) { 12762 Slog.d(TAG, " user " + allUsers[i] 12763 + " => " + perUserInstalled[i]); 12764 } 12765 ps.setInstalled(perUserInstalled[i], allUsers[i]); 12766 } 12767 // these install state changes will be persisted in the 12768 // upcoming call to mSettings.writeLPr(). 12769 } 12770 } 12771 // It's implied that when a user requests installation, they want the app to be 12772 // installed and enabled. 12773 int userId = user.getIdentifier(); 12774 if (userId != UserHandle.USER_ALL) { 12775 ps.setInstalled(true, userId); 12776 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 12777 } 12778 } 12779 res.name = pkgName; 12780 res.uid = newPackage.applicationInfo.uid; 12781 res.pkg = newPackage; 12782 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 12783 mSettings.setInstallerPackageName(pkgName, installerPackageName); 12784 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12785 //to update install status 12786 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 12787 mSettings.writeLPr(); 12788 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12789 } 12790 12791 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12792 } 12793 12794 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 12795 try { 12796 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 12797 installPackageLI(args, res); 12798 } finally { 12799 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12800 } 12801 } 12802 12803 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 12804 final int installFlags = args.installFlags; 12805 final String installerPackageName = args.installerPackageName; 12806 final String volumeUuid = args.volumeUuid; 12807 final File tmpPackageFile = new File(args.getCodePath()); 12808 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 12809 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 12810 || (args.volumeUuid != null)); 12811 final boolean quickInstall = ((installFlags & PackageManager.INSTALL_QUICK) != 0); 12812 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 12813 boolean replace = false; 12814 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 12815 if (args.move != null) { 12816 // moving a complete application; perfom an initial scan on the new install location 12817 scanFlags |= SCAN_INITIAL; 12818 } 12819 // Result object to be returned 12820 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12821 12822 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 12823 12824 // Sanity check 12825 if (ephemeral && (forwardLocked || onExternal)) { 12826 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 12827 + " external=" + onExternal); 12828 res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 12829 return; 12830 } 12831 12832 // Retrieve PackageSettings and parse package 12833 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 12834 | PackageParser.PARSE_ENFORCE_CODE 12835 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 12836 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 12837 | (quickInstall ? PackageParser.PARSE_SKIP_VERIFICATION : 0) 12838 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0); 12839 PackageParser pp = new PackageParser(); 12840 pp.setSeparateProcesses(mSeparateProcesses); 12841 pp.setDisplayMetrics(mMetrics); 12842 12843 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 12844 final PackageParser.Package pkg; 12845 try { 12846 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 12847 } catch (PackageParserException e) { 12848 res.setError("Failed parse during installPackageLI", e); 12849 return; 12850 } finally { 12851 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12852 } 12853 12854 // Mark that we have an install time CPU ABI override. 12855 pkg.cpuAbiOverride = args.abiOverride; 12856 12857 String pkgName = res.name = pkg.packageName; 12858 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 12859 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 12860 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 12861 return; 12862 } 12863 } 12864 12865 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 12866 try { 12867 pp.collectCertificates(pkg, parseFlags); 12868 } catch (PackageParserException e) { 12869 res.setError("Failed collect during installPackageLI", e); 12870 return; 12871 } finally { 12872 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12873 } 12874 12875 /* If the installer passed in a manifest digest, compare it now. */ 12876 if (args.manifestDigest != null) { 12877 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectManifestDigest"); 12878 try { 12879 pp.collectManifestDigest(pkg); 12880 } catch (PackageParserException e) { 12881 res.setError("Failed collect during installPackageLI", e); 12882 return; 12883 } finally { 12884 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12885 } 12886 12887 if (DEBUG_INSTALL) { 12888 final String parsedManifest = pkg.manifestDigest == null ? "null" 12889 : pkg.manifestDigest.toString(); 12890 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 12891 + parsedManifest); 12892 } 12893 12894 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 12895 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 12896 return; 12897 } 12898 } else if (DEBUG_INSTALL) { 12899 final String parsedManifest = pkg.manifestDigest == null 12900 ? "null" : pkg.manifestDigest.toString(); 12901 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 12902 } 12903 12904 // Get rid of all references to package scan path via parser. 12905 pp = null; 12906 String oldCodePath = null; 12907 boolean systemApp = false; 12908 synchronized (mPackages) { 12909 // Check if installing already existing package 12910 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12911 String oldName = mSettings.mRenamedPackages.get(pkgName); 12912 if (pkg.mOriginalPackages != null 12913 && pkg.mOriginalPackages.contains(oldName) 12914 && mPackages.containsKey(oldName)) { 12915 // This package is derived from an original package, 12916 // and this device has been updating from that original 12917 // name. We must continue using the original name, so 12918 // rename the new package here. 12919 pkg.setPackageName(oldName); 12920 pkgName = pkg.packageName; 12921 replace = true; 12922 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 12923 + oldName + " pkgName=" + pkgName); 12924 } else if (mPackages.containsKey(pkgName)) { 12925 // This package, under its official name, already exists 12926 // on the device; we should replace it. 12927 replace = true; 12928 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 12929 } 12930 12931 // Prevent apps opting out from runtime permissions 12932 if (replace) { 12933 PackageParser.Package oldPackage = mPackages.get(pkgName); 12934 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 12935 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 12936 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 12937 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 12938 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 12939 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 12940 + " doesn't support runtime permissions but the old" 12941 + " target SDK " + oldTargetSdk + " does."); 12942 return; 12943 } 12944 } 12945 } 12946 12947 PackageSetting ps = mSettings.mPackages.get(pkgName); 12948 if (ps != null) { 12949 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 12950 12951 // Quick sanity check that we're signed correctly if updating; 12952 // we'll check this again later when scanning, but we want to 12953 // bail early here before tripping over redefined permissions. 12954 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12955 if (!checkUpgradeKeySetLP(ps, pkg)) { 12956 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 12957 + pkg.packageName + " upgrade keys do not match the " 12958 + "previously installed version"); 12959 return; 12960 } 12961 } else { 12962 try { 12963 verifySignaturesLP(ps, pkg); 12964 } catch (PackageManagerException e) { 12965 res.setError(e.error, e.getMessage()); 12966 return; 12967 } 12968 } 12969 12970 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 12971 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 12972 systemApp = (ps.pkg.applicationInfo.flags & 12973 ApplicationInfo.FLAG_SYSTEM) != 0; 12974 } 12975 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12976 } 12977 12978 // Check whether the newly-scanned package wants to define an already-defined perm 12979 int N = pkg.permissions.size(); 12980 for (int i = N-1; i >= 0; i--) { 12981 PackageParser.Permission perm = pkg.permissions.get(i); 12982 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 12983 if (bp != null) { 12984 // If the defining package is signed with our cert, it's okay. This 12985 // also includes the "updating the same package" case, of course. 12986 // "updating same package" could also involve key-rotation. 12987 final boolean sigsOk; 12988 if (bp.sourcePackage.equals(pkg.packageName) 12989 && (bp.packageSetting instanceof PackageSetting) 12990 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 12991 scanFlags))) { 12992 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 12993 } else { 12994 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 12995 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 12996 } 12997 if (!sigsOk) { 12998 // If the owning package is the system itself, we log but allow 12999 // install to proceed; we fail the install on all other permission 13000 // redefinitions. 13001 if (!bp.sourcePackage.equals("android")) { 13002 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 13003 + pkg.packageName + " attempting to redeclare permission " 13004 + perm.info.name + " already owned by " + bp.sourcePackage); 13005 res.origPermission = perm.info.name; 13006 res.origPackage = bp.sourcePackage; 13007 return; 13008 } else { 13009 Slog.w(TAG, "Package " + pkg.packageName 13010 + " attempting to redeclare system permission " 13011 + perm.info.name + "; ignoring new declaration"); 13012 pkg.permissions.remove(i); 13013 } 13014 } 13015 } 13016 } 13017 13018 } 13019 13020 if (systemApp) { 13021 if (onExternal) { 13022 // Abort update; system app can't be replaced with app on sdcard 13023 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 13024 "Cannot install updates to system apps on sdcard"); 13025 return; 13026 } else if (ephemeral) { 13027 // Abort update; system app can't be replaced with an ephemeral app 13028 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 13029 "Cannot update a system app with an ephemeral app"); 13030 return; 13031 } 13032 } 13033 13034 if (args.move != null) { 13035 // We did an in-place move, so dex is ready to roll 13036 scanFlags |= SCAN_NO_DEX; 13037 scanFlags |= SCAN_MOVE; 13038 13039 synchronized (mPackages) { 13040 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13041 if (ps == null) { 13042 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 13043 "Missing settings for moved package " + pkgName); 13044 } 13045 13046 // We moved the entire application as-is, so bring over the 13047 // previously derived ABI information. 13048 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 13049 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 13050 } 13051 13052 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 13053 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 13054 scanFlags |= SCAN_NO_DEX; 13055 13056 try { 13057 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 13058 true /* extract libs */); 13059 } catch (PackageManagerException pme) { 13060 Slog.e(TAG, "Error deriving application ABI", pme); 13061 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 13062 return; 13063 } 13064 } 13065 13066 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 13067 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 13068 return; 13069 } 13070 13071 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 13072 13073 if (replace) { 13074 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 13075 installerPackageName, volumeUuid, res); 13076 } else { 13077 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 13078 args.user, installerPackageName, volumeUuid, res); 13079 } 13080 synchronized (mPackages) { 13081 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13082 if (ps != null) { 13083 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 13084 } 13085 } 13086 } 13087 13088 private void startIntentFilterVerifications(int userId, boolean replacing, 13089 PackageParser.Package pkg) { 13090 if (mIntentFilterVerifierComponent == null) { 13091 Slog.w(TAG, "No IntentFilter verification will not be done as " 13092 + "there is no IntentFilterVerifier available!"); 13093 return; 13094 } 13095 13096 final int verifierUid = getPackageUid( 13097 mIntentFilterVerifierComponent.getPackageName(), 13098 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 13099 13100 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 13101 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 13102 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 13103 mHandler.sendMessage(msg); 13104 } 13105 13106 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 13107 PackageParser.Package pkg) { 13108 int size = pkg.activities.size(); 13109 if (size == 0) { 13110 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 13111 "No activity, so no need to verify any IntentFilter!"); 13112 return; 13113 } 13114 13115 final boolean hasDomainURLs = hasDomainURLs(pkg); 13116 if (!hasDomainURLs) { 13117 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 13118 "No domain URLs, so no need to verify any IntentFilter!"); 13119 return; 13120 } 13121 13122 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 13123 + " if any IntentFilter from the " + size 13124 + " Activities needs verification ..."); 13125 13126 int count = 0; 13127 final String packageName = pkg.packageName; 13128 13129 synchronized (mPackages) { 13130 // If this is a new install and we see that we've already run verification for this 13131 // package, we have nothing to do: it means the state was restored from backup. 13132 if (!replacing) { 13133 IntentFilterVerificationInfo ivi = 13134 mSettings.getIntentFilterVerificationLPr(packageName); 13135 if (ivi != null) { 13136 if (DEBUG_DOMAIN_VERIFICATION) { 13137 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 13138 + ivi.getStatusString()); 13139 } 13140 return; 13141 } 13142 } 13143 13144 // If any filters need to be verified, then all need to be. 13145 boolean needToVerify = false; 13146 for (PackageParser.Activity a : pkg.activities) { 13147 for (ActivityIntentInfo filter : a.intents) { 13148 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 13149 if (DEBUG_DOMAIN_VERIFICATION) { 13150 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 13151 } 13152 needToVerify = true; 13153 break; 13154 } 13155 } 13156 } 13157 13158 if (needToVerify) { 13159 final int verificationId = mIntentFilterVerificationToken++; 13160 for (PackageParser.Activity a : pkg.activities) { 13161 for (ActivityIntentInfo filter : a.intents) { 13162 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 13163 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 13164 "Verification needed for IntentFilter:" + filter.toString()); 13165 mIntentFilterVerifier.addOneIntentFilterVerification( 13166 verifierUid, userId, verificationId, filter, packageName); 13167 count++; 13168 } 13169 } 13170 } 13171 } 13172 } 13173 13174 if (count > 0) { 13175 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 13176 + " IntentFilter verification" + (count > 1 ? "s" : "") 13177 + " for userId:" + userId); 13178 mIntentFilterVerifier.startVerifications(userId); 13179 } else { 13180 if (DEBUG_DOMAIN_VERIFICATION) { 13181 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 13182 } 13183 } 13184 } 13185 13186 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 13187 final ComponentName cn = filter.activity.getComponentName(); 13188 final String packageName = cn.getPackageName(); 13189 13190 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 13191 packageName); 13192 if (ivi == null) { 13193 return true; 13194 } 13195 int status = ivi.getStatus(); 13196 switch (status) { 13197 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 13198 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 13199 return true; 13200 13201 default: 13202 // Nothing to do 13203 return false; 13204 } 13205 } 13206 13207 private static boolean isMultiArch(ApplicationInfo info) { 13208 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 13209 } 13210 13211 private static boolean isExternal(PackageParser.Package pkg) { 13212 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 13213 } 13214 13215 private static boolean isExternal(PackageSetting ps) { 13216 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 13217 } 13218 13219 private static boolean isEphemeral(PackageParser.Package pkg) { 13220 return pkg.applicationInfo.isEphemeralApp(); 13221 } 13222 13223 private static boolean isEphemeral(PackageSetting ps) { 13224 return ps.pkg != null && isEphemeral(ps.pkg); 13225 } 13226 13227 private static boolean isSystemApp(PackageParser.Package pkg) { 13228 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 13229 } 13230 13231 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 13232 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 13233 } 13234 13235 private static boolean hasDomainURLs(PackageParser.Package pkg) { 13236 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 13237 } 13238 13239 private static boolean isSystemApp(PackageSetting ps) { 13240 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 13241 } 13242 13243 private static boolean isUpdatedSystemApp(PackageSetting ps) { 13244 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 13245 } 13246 13247 private int packageFlagsToInstallFlags(PackageSetting ps) { 13248 int installFlags = 0; 13249 if (isEphemeral(ps)) { 13250 installFlags |= PackageManager.INSTALL_EPHEMERAL; 13251 } 13252 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 13253 // This existing package was an external ASEC install when we have 13254 // the external flag without a UUID 13255 installFlags |= PackageManager.INSTALL_EXTERNAL; 13256 } 13257 if (ps.isForwardLocked()) { 13258 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 13259 } 13260 return installFlags; 13261 } 13262 13263 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 13264 if (isExternal(pkg)) { 13265 if (TextUtils.isEmpty(pkg.volumeUuid)) { 13266 return StorageManager.UUID_PRIMARY_PHYSICAL; 13267 } else { 13268 return pkg.volumeUuid; 13269 } 13270 } else { 13271 return StorageManager.UUID_PRIVATE_INTERNAL; 13272 } 13273 } 13274 13275 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 13276 if (isExternal(pkg)) { 13277 if (TextUtils.isEmpty(pkg.volumeUuid)) { 13278 return mSettings.getExternalVersion(); 13279 } else { 13280 return mSettings.findOrCreateVersion(pkg.volumeUuid); 13281 } 13282 } else { 13283 return mSettings.getInternalVersion(); 13284 } 13285 } 13286 13287 private void deleteTempPackageFiles() { 13288 final FilenameFilter filter = new FilenameFilter() { 13289 public boolean accept(File dir, String name) { 13290 return name.startsWith("vmdl") && name.endsWith(".tmp"); 13291 } 13292 }; 13293 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 13294 file.delete(); 13295 } 13296 } 13297 13298 @Override 13299 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 13300 int flags) { 13301 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 13302 flags); 13303 } 13304 13305 @Override 13306 public void deletePackage(final String packageName, 13307 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 13308 mContext.enforceCallingOrSelfPermission( 13309 android.Manifest.permission.DELETE_PACKAGES, null); 13310 Preconditions.checkNotNull(packageName); 13311 Preconditions.checkNotNull(observer); 13312 final int uid = Binder.getCallingUid(); 13313 final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0; 13314 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 13315 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 13316 mContext.enforceCallingOrSelfPermission( 13317 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 13318 "deletePackage for user " + userId); 13319 } 13320 13321 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 13322 try { 13323 observer.onPackageDeleted(packageName, 13324 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 13325 } catch (RemoteException re) { 13326 } 13327 return; 13328 } 13329 13330 for (int currentUserId : users) { 13331 if (getBlockUninstallForUser(packageName, currentUserId)) { 13332 try { 13333 observer.onPackageDeleted(packageName, 13334 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 13335 } catch (RemoteException re) { 13336 } 13337 return; 13338 } 13339 } 13340 13341 if (DEBUG_REMOVE) { 13342 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 13343 } 13344 // Queue up an async operation since the package deletion may take a little while. 13345 mHandler.post(new Runnable() { 13346 public void run() { 13347 mHandler.removeCallbacks(this); 13348 final int returnCode = deletePackageX(packageName, userId, flags); 13349 try { 13350 observer.onPackageDeleted(packageName, returnCode, null); 13351 } catch (RemoteException e) { 13352 Log.i(TAG, "Observer no longer exists."); 13353 } //end catch 13354 } //end run 13355 }); 13356 } 13357 13358 private boolean isPackageDeviceAdmin(String packageName, int userId) { 13359 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 13360 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 13361 try { 13362 if (dpm != null) { 13363 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 13364 /* callingUserOnly =*/ false); 13365 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 13366 : deviceOwnerComponentName.getPackageName(); 13367 // Does the package contains the device owner? 13368 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 13369 // this check is probably not needed, since DO should be registered as a device 13370 // admin on some user too. (Original bug for this: b/17657954) 13371 if (packageName.equals(deviceOwnerPackageName)) { 13372 return true; 13373 } 13374 // Does it contain a device admin for any user? 13375 int[] users; 13376 if (userId == UserHandle.USER_ALL) { 13377 users = sUserManager.getUserIds(); 13378 } else { 13379 users = new int[]{userId}; 13380 } 13381 for (int i = 0; i < users.length; ++i) { 13382 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 13383 return true; 13384 } 13385 } 13386 } 13387 } catch (RemoteException e) { 13388 } 13389 return false; 13390 } 13391 13392 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 13393 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 13394 } 13395 13396 /** 13397 * This method is an internal method that could be get invoked either 13398 * to delete an installed package or to clean up a failed installation. 13399 * After deleting an installed package, a broadcast is sent to notify any 13400 * listeners that the package has been installed. For cleaning up a failed 13401 * installation, the broadcast is not necessary since the package's 13402 * installation wouldn't have sent the initial broadcast either 13403 * The key steps in deleting a package are 13404 * deleting the package information in internal structures like mPackages, 13405 * deleting the packages base directories through installd 13406 * updating mSettings to reflect current status 13407 * persisting settings for later use 13408 * sending a broadcast if necessary 13409 */ 13410 private int deletePackageX(String packageName, int userId, int flags) { 13411 final PackageRemovedInfo info = new PackageRemovedInfo(); 13412 final boolean res; 13413 13414 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 13415 ? UserHandle.ALL : new UserHandle(userId); 13416 13417 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 13418 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 13419 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 13420 } 13421 13422 boolean removedForAllUsers = false; 13423 boolean systemUpdate = false; 13424 13425 PackageParser.Package uninstalledPkg; 13426 13427 // for the uninstall-updates case and restricted profiles, remember the per- 13428 // userhandle installed state 13429 int[] allUsers; 13430 boolean[] perUserInstalled; 13431 synchronized (mPackages) { 13432 uninstalledPkg = mPackages.get(packageName); 13433 PackageSetting ps = mSettings.mPackages.get(packageName); 13434 allUsers = sUserManager.getUserIds(); 13435 perUserInstalled = new boolean[allUsers.length]; 13436 for (int i = 0; i < allUsers.length; i++) { 13437 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 13438 } 13439 } 13440 13441 synchronized (mInstallLock) { 13442 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 13443 res = deletePackageLI(packageName, removeForUser, 13444 true, allUsers, perUserInstalled, 13445 flags | REMOVE_CHATTY, info, true); 13446 systemUpdate = info.isRemovedPackageSystemUpdate; 13447 synchronized (mPackages) { 13448 if (res) { 13449 if (!systemUpdate && mPackages.get(packageName) == null) { 13450 removedForAllUsers = true; 13451 } 13452 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPkg); 13453 } 13454 } 13455 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 13456 + " removedForAllUsers=" + removedForAllUsers); 13457 } 13458 13459 if (res) { 13460 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 13461 13462 // If the removed package was a system update, the old system package 13463 // was re-enabled; we need to broadcast this information 13464 if (systemUpdate) { 13465 Bundle extras = new Bundle(1); 13466 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 13467 ? info.removedAppId : info.uid); 13468 extras.putBoolean(Intent.EXTRA_REPLACING, true); 13469 13470 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 13471 extras, 0, null, null, null); 13472 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 13473 extras, 0, null, null, null); 13474 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 13475 null, 0, packageName, null, null); 13476 } 13477 } 13478 // Force a gc here. 13479 Runtime.getRuntime().gc(); 13480 // Delete the resources here after sending the broadcast to let 13481 // other processes clean up before deleting resources. 13482 if (info.args != null) { 13483 synchronized (mInstallLock) { 13484 info.args.doPostDeleteLI(true); 13485 } 13486 } 13487 13488 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 13489 } 13490 13491 class PackageRemovedInfo { 13492 String removedPackage; 13493 int uid = -1; 13494 int removedAppId = -1; 13495 int[] removedUsers = null; 13496 boolean isRemovedPackageSystemUpdate = false; 13497 // Clean up resources deleted packages. 13498 InstallArgs args = null; 13499 13500 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 13501 Bundle extras = new Bundle(1); 13502 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 13503 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 13504 if (replacing) { 13505 extras.putBoolean(Intent.EXTRA_REPLACING, true); 13506 } 13507 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 13508 if (removedPackage != null) { 13509 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 13510 extras, 0, null, null, removedUsers); 13511 if (fullRemove && !replacing) { 13512 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 13513 extras, 0, null, null, removedUsers); 13514 } 13515 } 13516 if (removedAppId >= 0) { 13517 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 13518 removedUsers); 13519 } 13520 } 13521 } 13522 13523 /* 13524 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 13525 * flag is not set, the data directory is removed as well. 13526 * make sure this flag is set for partially installed apps. If not its meaningless to 13527 * delete a partially installed application. 13528 */ 13529 private void removePackageDataLI(PackageSetting ps, 13530 int[] allUserHandles, boolean[] perUserInstalled, 13531 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 13532 String packageName = ps.name; 13533 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 13534 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 13535 // Retrieve object to delete permissions for shared user later on 13536 final PackageSetting deletedPs; 13537 // reader 13538 synchronized (mPackages) { 13539 deletedPs = mSettings.mPackages.get(packageName); 13540 if (outInfo != null) { 13541 outInfo.removedPackage = packageName; 13542 outInfo.removedUsers = deletedPs != null 13543 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 13544 : null; 13545 } 13546 } 13547 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 13548 removeDataDirsLI(ps.volumeUuid, packageName); 13549 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 13550 } 13551 // writer 13552 synchronized (mPackages) { 13553 if (deletedPs != null) { 13554 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 13555 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 13556 clearDefaultBrowserIfNeeded(packageName); 13557 if (outInfo != null) { 13558 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 13559 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 13560 } 13561 updatePermissionsLPw(deletedPs.name, null, 0); 13562 if (deletedPs.sharedUser != null) { 13563 // Remove permissions associated with package. Since runtime 13564 // permissions are per user we have to kill the removed package 13565 // or packages running under the shared user of the removed 13566 // package if revoking the permissions requested only by the removed 13567 // package is successful and this causes a change in gids. 13568 for (int userId : UserManagerService.getInstance().getUserIds()) { 13569 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 13570 userId); 13571 if (userIdToKill == UserHandle.USER_ALL 13572 || userIdToKill >= UserHandle.USER_SYSTEM) { 13573 // If gids changed for this user, kill all affected packages. 13574 mHandler.post(new Runnable() { 13575 @Override 13576 public void run() { 13577 // This has to happen with no lock held. 13578 killApplication(deletedPs.name, deletedPs.appId, 13579 KILL_APP_REASON_GIDS_CHANGED); 13580 } 13581 }); 13582 break; 13583 } 13584 } 13585 } 13586 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 13587 } 13588 // make sure to preserve per-user disabled state if this removal was just 13589 // a downgrade of a system app to the factory package 13590 if (allUserHandles != null && perUserInstalled != null) { 13591 if (DEBUG_REMOVE) { 13592 Slog.d(TAG, "Propagating install state across downgrade"); 13593 } 13594 for (int i = 0; i < allUserHandles.length; i++) { 13595 if (DEBUG_REMOVE) { 13596 Slog.d(TAG, " user " + allUserHandles[i] 13597 + " => " + perUserInstalled[i]); 13598 } 13599 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13600 } 13601 } 13602 } 13603 // can downgrade to reader 13604 if (writeSettings) { 13605 // Save settings now 13606 mSettings.writeLPr(); 13607 } 13608 } 13609 if (outInfo != null) { 13610 // A user ID was deleted here. Go through all users and remove it 13611 // from KeyStore. 13612 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 13613 } 13614 } 13615 13616 static boolean locationIsPrivileged(File path) { 13617 try { 13618 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 13619 .getCanonicalPath(); 13620 return path.getCanonicalPath().startsWith(privilegedAppDir); 13621 } catch (IOException e) { 13622 Slog.e(TAG, "Unable to access code path " + path); 13623 } 13624 return false; 13625 } 13626 13627 /* 13628 * Tries to delete system package. 13629 */ 13630 private boolean deleteSystemPackageLI(PackageSetting newPs, 13631 int[] allUserHandles, boolean[] perUserInstalled, 13632 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 13633 final boolean applyUserRestrictions 13634 = (allUserHandles != null) && (perUserInstalled != null); 13635 PackageSetting disabledPs = null; 13636 // Confirm if the system package has been updated 13637 // An updated system app can be deleted. This will also have to restore 13638 // the system pkg from system partition 13639 // reader 13640 synchronized (mPackages) { 13641 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 13642 } 13643 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 13644 + " disabledPs=" + disabledPs); 13645 if (disabledPs == null) { 13646 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 13647 return false; 13648 } else if (DEBUG_REMOVE) { 13649 Slog.d(TAG, "Deleting system pkg from data partition"); 13650 } 13651 if (DEBUG_REMOVE) { 13652 if (applyUserRestrictions) { 13653 Slog.d(TAG, "Remembering install states:"); 13654 for (int i = 0; i < allUserHandles.length; i++) { 13655 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 13656 } 13657 } 13658 } 13659 // Delete the updated package 13660 outInfo.isRemovedPackageSystemUpdate = true; 13661 if (disabledPs.versionCode < newPs.versionCode) { 13662 // Delete data for downgrades 13663 flags &= ~PackageManager.DELETE_KEEP_DATA; 13664 } else { 13665 // Preserve data by setting flag 13666 flags |= PackageManager.DELETE_KEEP_DATA; 13667 } 13668 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 13669 allUserHandles, perUserInstalled, outInfo, writeSettings); 13670 if (!ret) { 13671 return false; 13672 } 13673 // writer 13674 synchronized (mPackages) { 13675 // Reinstate the old system package 13676 mSettings.enableSystemPackageLPw(newPs.name); 13677 // Remove any native libraries from the upgraded package. 13678 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 13679 } 13680 // Install the system package 13681 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 13682 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 13683 if (locationIsPrivileged(disabledPs.codePath)) { 13684 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 13685 } 13686 13687 final PackageParser.Package newPkg; 13688 try { 13689 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 13690 } catch (PackageManagerException e) { 13691 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 13692 return false; 13693 } 13694 13695 // writer 13696 synchronized (mPackages) { 13697 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 13698 13699 // Propagate the permissions state as we do not want to drop on the floor 13700 // runtime permissions. The update permissions method below will take 13701 // care of removing obsolete permissions and grant install permissions. 13702 ps.getPermissionsState().copyFrom(newPs.getPermissionsState()); 13703 updatePermissionsLPw(newPkg.packageName, newPkg, 13704 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 13705 13706 if (applyUserRestrictions) { 13707 if (DEBUG_REMOVE) { 13708 Slog.d(TAG, "Propagating install state across reinstall"); 13709 } 13710 for (int i = 0; i < allUserHandles.length; i++) { 13711 if (DEBUG_REMOVE) { 13712 Slog.d(TAG, " user " + allUserHandles[i] 13713 + " => " + perUserInstalled[i]); 13714 } 13715 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13716 13717 mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false); 13718 } 13719 // Regardless of writeSettings we need to ensure that this restriction 13720 // state propagation is persisted 13721 mSettings.writeAllUsersPackageRestrictionsLPr(); 13722 } 13723 // can downgrade to reader here 13724 if (writeSettings) { 13725 mSettings.writeLPr(); 13726 } 13727 } 13728 return true; 13729 } 13730 13731 private boolean deleteInstalledPackageLI(PackageSetting ps, 13732 boolean deleteCodeAndResources, int flags, 13733 int[] allUserHandles, boolean[] perUserInstalled, 13734 PackageRemovedInfo outInfo, boolean writeSettings) { 13735 if (outInfo != null) { 13736 outInfo.uid = ps.appId; 13737 } 13738 13739 // Delete package data from internal structures and also remove data if flag is set 13740 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 13741 13742 // Delete application code and resources 13743 if (deleteCodeAndResources && (outInfo != null)) { 13744 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 13745 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 13746 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 13747 } 13748 return true; 13749 } 13750 13751 @Override 13752 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 13753 int userId) { 13754 mContext.enforceCallingOrSelfPermission( 13755 android.Manifest.permission.DELETE_PACKAGES, null); 13756 synchronized (mPackages) { 13757 PackageSetting ps = mSettings.mPackages.get(packageName); 13758 if (ps == null) { 13759 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 13760 return false; 13761 } 13762 if (!ps.getInstalled(userId)) { 13763 // Can't block uninstall for an app that is not installed or enabled. 13764 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 13765 return false; 13766 } 13767 ps.setBlockUninstall(blockUninstall, userId); 13768 mSettings.writePackageRestrictionsLPr(userId); 13769 } 13770 return true; 13771 } 13772 13773 @Override 13774 public boolean getBlockUninstallForUser(String packageName, int userId) { 13775 synchronized (mPackages) { 13776 PackageSetting ps = mSettings.mPackages.get(packageName); 13777 if (ps == null) { 13778 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 13779 return false; 13780 } 13781 return ps.getBlockUninstall(userId); 13782 } 13783 } 13784 13785 /* 13786 * This method handles package deletion in general 13787 */ 13788 private boolean deletePackageLI(String packageName, UserHandle user, 13789 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 13790 int flags, PackageRemovedInfo outInfo, 13791 boolean writeSettings) { 13792 if (packageName == null) { 13793 Slog.w(TAG, "Attempt to delete null packageName."); 13794 return false; 13795 } 13796 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 13797 PackageSetting ps; 13798 boolean dataOnly = false; 13799 int removeUser = -1; 13800 int appId = -1; 13801 synchronized (mPackages) { 13802 ps = mSettings.mPackages.get(packageName); 13803 if (ps == null) { 13804 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13805 return false; 13806 } 13807 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 13808 && user.getIdentifier() != UserHandle.USER_ALL) { 13809 // The caller is asking that the package only be deleted for a single 13810 // user. To do this, we just mark its uninstalled state and delete 13811 // its data. If this is a system app, we only allow this to happen if 13812 // they have set the special DELETE_SYSTEM_APP which requests different 13813 // semantics than normal for uninstalling system apps. 13814 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 13815 final int userId = user.getIdentifier(); 13816 ps.setUserState(userId, 13817 COMPONENT_ENABLED_STATE_DEFAULT, 13818 false, //installed 13819 true, //stopped 13820 true, //notLaunched 13821 false, //hidden 13822 false, //suspended 13823 null, null, null, 13824 false, // blockUninstall 13825 ps.readUserState(userId).domainVerificationStatus, 0); 13826 if (!isSystemApp(ps)) { 13827 // Do not uninstall the APK if an app should be cached 13828 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 13829 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 13830 // Other user still have this package installed, so all 13831 // we need to do is clear this user's data and save that 13832 // it is uninstalled. 13833 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 13834 removeUser = user.getIdentifier(); 13835 appId = ps.appId; 13836 scheduleWritePackageRestrictionsLocked(removeUser); 13837 } else { 13838 // We need to set it back to 'installed' so the uninstall 13839 // broadcasts will be sent correctly. 13840 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 13841 ps.setInstalled(true, user.getIdentifier()); 13842 } 13843 } else { 13844 // This is a system app, so we assume that the 13845 // other users still have this package installed, so all 13846 // we need to do is clear this user's data and save that 13847 // it is uninstalled. 13848 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 13849 removeUser = user.getIdentifier(); 13850 appId = ps.appId; 13851 scheduleWritePackageRestrictionsLocked(removeUser); 13852 } 13853 } 13854 } 13855 13856 if (removeUser >= 0) { 13857 // From above, we determined that we are deleting this only 13858 // for a single user. Continue the work here. 13859 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 13860 if (outInfo != null) { 13861 outInfo.removedPackage = packageName; 13862 outInfo.removedAppId = appId; 13863 outInfo.removedUsers = new int[] {removeUser}; 13864 } 13865 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 13866 removeKeystoreDataIfNeeded(removeUser, appId); 13867 schedulePackageCleaning(packageName, removeUser, false); 13868 synchronized (mPackages) { 13869 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 13870 scheduleWritePackageRestrictionsLocked(removeUser); 13871 } 13872 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser); 13873 } 13874 return true; 13875 } 13876 13877 if (dataOnly) { 13878 // Delete application data first 13879 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 13880 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 13881 return true; 13882 } 13883 13884 boolean ret = false; 13885 if (isSystemApp(ps)) { 13886 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 13887 // When an updated system application is deleted we delete the existing resources as well and 13888 // fall back to existing code in system partition 13889 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 13890 flags, outInfo, writeSettings); 13891 } else { 13892 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 13893 // Kill application pre-emptively especially for apps on sd. 13894 killApplication(packageName, ps.appId, "uninstall pkg"); 13895 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 13896 allUserHandles, perUserInstalled, 13897 outInfo, writeSettings); 13898 } 13899 13900 return ret; 13901 } 13902 13903 private final static class ClearStorageConnection implements ServiceConnection { 13904 IMediaContainerService mContainerService; 13905 13906 @Override 13907 public void onServiceConnected(ComponentName name, IBinder service) { 13908 synchronized (this) { 13909 mContainerService = IMediaContainerService.Stub.asInterface(service); 13910 notifyAll(); 13911 } 13912 } 13913 13914 @Override 13915 public void onServiceDisconnected(ComponentName name) { 13916 } 13917 } 13918 13919 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 13920 final boolean mounted; 13921 if (Environment.isExternalStorageEmulated()) { 13922 mounted = true; 13923 } else { 13924 final String status = Environment.getExternalStorageState(); 13925 13926 mounted = status.equals(Environment.MEDIA_MOUNTED) 13927 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 13928 } 13929 13930 if (!mounted) { 13931 return; 13932 } 13933 13934 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 13935 int[] users; 13936 if (userId == UserHandle.USER_ALL) { 13937 users = sUserManager.getUserIds(); 13938 } else { 13939 users = new int[] { userId }; 13940 } 13941 final ClearStorageConnection conn = new ClearStorageConnection(); 13942 if (mContext.bindServiceAsUser( 13943 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 13944 try { 13945 for (int curUser : users) { 13946 long timeout = SystemClock.uptimeMillis() + 5000; 13947 synchronized (conn) { 13948 long now = SystemClock.uptimeMillis(); 13949 while (conn.mContainerService == null && now < timeout) { 13950 try { 13951 conn.wait(timeout - now); 13952 } catch (InterruptedException e) { 13953 } 13954 } 13955 } 13956 if (conn.mContainerService == null) { 13957 return; 13958 } 13959 13960 final UserEnvironment userEnv = new UserEnvironment(curUser); 13961 clearDirectory(conn.mContainerService, 13962 userEnv.buildExternalStorageAppCacheDirs(packageName)); 13963 if (allData) { 13964 clearDirectory(conn.mContainerService, 13965 userEnv.buildExternalStorageAppDataDirs(packageName)); 13966 clearDirectory(conn.mContainerService, 13967 userEnv.buildExternalStorageAppMediaDirs(packageName)); 13968 } 13969 } 13970 } finally { 13971 mContext.unbindService(conn); 13972 } 13973 } 13974 } 13975 13976 @Override 13977 public void clearApplicationUserData(final String packageName, 13978 final IPackageDataObserver observer, final int userId) { 13979 mContext.enforceCallingOrSelfPermission( 13980 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 13981 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 13982 // Queue up an async operation since the package deletion may take a little while. 13983 mHandler.post(new Runnable() { 13984 public void run() { 13985 mHandler.removeCallbacks(this); 13986 final boolean succeeded; 13987 synchronized (mInstallLock) { 13988 succeeded = clearApplicationUserDataLI(packageName, userId); 13989 } 13990 clearExternalStorageDataSync(packageName, userId, true); 13991 if (succeeded) { 13992 // invoke DeviceStorageMonitor's update method to clear any notifications 13993 DeviceStorageMonitorInternal 13994 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13995 if (dsm != null) { 13996 dsm.checkMemory(); 13997 } 13998 } 13999 if(observer != null) { 14000 try { 14001 observer.onRemoveCompleted(packageName, succeeded); 14002 } catch (RemoteException e) { 14003 Log.i(TAG, "Observer no longer exists."); 14004 } 14005 } //end if observer 14006 } //end run 14007 }); 14008 } 14009 14010 private boolean clearApplicationUserDataLI(String packageName, int userId) { 14011 if (packageName == null) { 14012 Slog.w(TAG, "Attempt to delete null packageName."); 14013 return false; 14014 } 14015 14016 // Try finding details about the requested package 14017 PackageParser.Package pkg; 14018 synchronized (mPackages) { 14019 pkg = mPackages.get(packageName); 14020 if (pkg == null) { 14021 final PackageSetting ps = mSettings.mPackages.get(packageName); 14022 if (ps != null) { 14023 pkg = ps.pkg; 14024 } 14025 } 14026 14027 if (pkg == null) { 14028 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 14029 return false; 14030 } 14031 14032 PackageSetting ps = (PackageSetting) pkg.mExtras; 14033 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 14034 } 14035 14036 // Always delete data directories for package, even if we found no other 14037 // record of app. This helps users recover from UID mismatches without 14038 // resorting to a full data wipe. 14039 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 14040 if (retCode < 0) { 14041 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 14042 return false; 14043 } 14044 14045 final int appId = pkg.applicationInfo.uid; 14046 removeKeystoreDataIfNeeded(userId, appId); 14047 14048 // Create a native library symlink only if we have native libraries 14049 // and if the native libraries are 32 bit libraries. We do not provide 14050 // this symlink for 64 bit libraries. 14051 if (pkg.applicationInfo.primaryCpuAbi != null && 14052 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 14053 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 14054 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 14055 nativeLibPath, userId) < 0) { 14056 Slog.w(TAG, "Failed linking native library dir"); 14057 return false; 14058 } 14059 } 14060 14061 return true; 14062 } 14063 14064 /** 14065 * Reverts user permission state changes (permissions and flags) in 14066 * all packages for a given user. 14067 * 14068 * @param userId The device user for which to do a reset. 14069 */ 14070 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 14071 final int packageCount = mPackages.size(); 14072 for (int i = 0; i < packageCount; i++) { 14073 PackageParser.Package pkg = mPackages.valueAt(i); 14074 PackageSetting ps = (PackageSetting) pkg.mExtras; 14075 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 14076 } 14077 } 14078 14079 /** 14080 * Reverts user permission state changes (permissions and flags). 14081 * 14082 * @param ps The package for which to reset. 14083 * @param userId The device user for which to do a reset. 14084 */ 14085 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 14086 final PackageSetting ps, final int userId) { 14087 if (ps.pkg == null) { 14088 return; 14089 } 14090 14091 // These are flags that can change base on user actions. 14092 final int userSettableMask = FLAG_PERMISSION_USER_SET 14093 | FLAG_PERMISSION_USER_FIXED 14094 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 14095 | FLAG_PERMISSION_REVIEW_REQUIRED; 14096 14097 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 14098 | FLAG_PERMISSION_POLICY_FIXED; 14099 14100 boolean writeInstallPermissions = false; 14101 boolean writeRuntimePermissions = false; 14102 14103 final int permissionCount = ps.pkg.requestedPermissions.size(); 14104 for (int i = 0; i < permissionCount; i++) { 14105 String permission = ps.pkg.requestedPermissions.get(i); 14106 14107 BasePermission bp = mSettings.mPermissions.get(permission); 14108 if (bp == null) { 14109 continue; 14110 } 14111 14112 // If shared user we just reset the state to which only this app contributed. 14113 if (ps.sharedUser != null) { 14114 boolean used = false; 14115 final int packageCount = ps.sharedUser.packages.size(); 14116 for (int j = 0; j < packageCount; j++) { 14117 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 14118 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 14119 && pkg.pkg.requestedPermissions.contains(permission)) { 14120 used = true; 14121 break; 14122 } 14123 } 14124 if (used) { 14125 continue; 14126 } 14127 } 14128 14129 PermissionsState permissionsState = ps.getPermissionsState(); 14130 14131 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 14132 14133 // Always clear the user settable flags. 14134 final boolean hasInstallState = permissionsState.getInstallPermissionState( 14135 bp.name) != null; 14136 // If permission review is enabled and this is a legacy app, mark the 14137 // permission as requiring a review as this is the initial state. 14138 int flags = 0; 14139 if (Build.PERMISSIONS_REVIEW_REQUIRED 14140 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 14141 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 14142 } 14143 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 14144 if (hasInstallState) { 14145 writeInstallPermissions = true; 14146 } else { 14147 writeRuntimePermissions = true; 14148 } 14149 } 14150 14151 // Below is only runtime permission handling. 14152 if (!bp.isRuntime()) { 14153 continue; 14154 } 14155 14156 // Never clobber system or policy. 14157 if ((oldFlags & policyOrSystemFlags) != 0) { 14158 continue; 14159 } 14160 14161 // If this permission was granted by default, make sure it is. 14162 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 14163 if (permissionsState.grantRuntimePermission(bp, userId) 14164 != PERMISSION_OPERATION_FAILURE) { 14165 writeRuntimePermissions = true; 14166 } 14167 // If permission review is enabled the permissions for a legacy apps 14168 // are represented as constantly granted runtime ones, so don't revoke. 14169 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 14170 // Otherwise, reset the permission. 14171 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 14172 switch (revokeResult) { 14173 case PERMISSION_OPERATION_SUCCESS: { 14174 writeRuntimePermissions = true; 14175 } break; 14176 14177 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 14178 writeRuntimePermissions = true; 14179 final int appId = ps.appId; 14180 mHandler.post(new Runnable() { 14181 @Override 14182 public void run() { 14183 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 14184 } 14185 }); 14186 } break; 14187 } 14188 } 14189 } 14190 14191 // Synchronously write as we are taking permissions away. 14192 if (writeRuntimePermissions) { 14193 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 14194 } 14195 14196 // Synchronously write as we are taking permissions away. 14197 if (writeInstallPermissions) { 14198 mSettings.writeLPr(); 14199 } 14200 } 14201 14202 /** 14203 * Remove entries from the keystore daemon. Will only remove it if the 14204 * {@code appId} is valid. 14205 */ 14206 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 14207 if (appId < 0) { 14208 return; 14209 } 14210 14211 final KeyStore keyStore = KeyStore.getInstance(); 14212 if (keyStore != null) { 14213 if (userId == UserHandle.USER_ALL) { 14214 for (final int individual : sUserManager.getUserIds()) { 14215 keyStore.clearUid(UserHandle.getUid(individual, appId)); 14216 } 14217 } else { 14218 keyStore.clearUid(UserHandle.getUid(userId, appId)); 14219 } 14220 } else { 14221 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 14222 } 14223 } 14224 14225 @Override 14226 public void deleteApplicationCacheFiles(final String packageName, 14227 final IPackageDataObserver observer) { 14228 mContext.enforceCallingOrSelfPermission( 14229 android.Manifest.permission.DELETE_CACHE_FILES, null); 14230 // Queue up an async operation since the package deletion may take a little while. 14231 final int userId = UserHandle.getCallingUserId(); 14232 mHandler.post(new Runnable() { 14233 public void run() { 14234 mHandler.removeCallbacks(this); 14235 final boolean succeded; 14236 synchronized (mInstallLock) { 14237 succeded = deleteApplicationCacheFilesLI(packageName, userId); 14238 } 14239 clearExternalStorageDataSync(packageName, userId, false); 14240 if (observer != null) { 14241 try { 14242 observer.onRemoveCompleted(packageName, succeded); 14243 } catch (RemoteException e) { 14244 Log.i(TAG, "Observer no longer exists."); 14245 } 14246 } //end if observer 14247 } //end run 14248 }); 14249 } 14250 14251 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 14252 if (packageName == null) { 14253 Slog.w(TAG, "Attempt to delete null packageName."); 14254 return false; 14255 } 14256 PackageParser.Package p; 14257 synchronized (mPackages) { 14258 p = mPackages.get(packageName); 14259 } 14260 if (p == null) { 14261 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 14262 return false; 14263 } 14264 final ApplicationInfo applicationInfo = p.applicationInfo; 14265 if (applicationInfo == null) { 14266 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 14267 return false; 14268 } 14269 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 14270 if (retCode < 0) { 14271 Slog.w(TAG, "Couldn't remove cache files for package: " 14272 + packageName + " u" + userId); 14273 return false; 14274 } 14275 return true; 14276 } 14277 14278 @Override 14279 public void getPackageSizeInfo(final String packageName, int userHandle, 14280 final IPackageStatsObserver observer) { 14281 mContext.enforceCallingOrSelfPermission( 14282 android.Manifest.permission.GET_PACKAGE_SIZE, null); 14283 if (packageName == null) { 14284 throw new IllegalArgumentException("Attempt to get size of null packageName"); 14285 } 14286 14287 PackageStats stats = new PackageStats(packageName, userHandle); 14288 14289 /* 14290 * Queue up an async operation since the package measurement may take a 14291 * little while. 14292 */ 14293 Message msg = mHandler.obtainMessage(INIT_COPY); 14294 msg.obj = new MeasureParams(stats, observer); 14295 mHandler.sendMessage(msg); 14296 } 14297 14298 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 14299 PackageStats pStats) { 14300 if (packageName == null) { 14301 Slog.w(TAG, "Attempt to get size of null packageName."); 14302 return false; 14303 } 14304 PackageParser.Package p; 14305 boolean dataOnly = false; 14306 String libDirRoot = null; 14307 String asecPath = null; 14308 PackageSetting ps = null; 14309 synchronized (mPackages) { 14310 p = mPackages.get(packageName); 14311 ps = mSettings.mPackages.get(packageName); 14312 if(p == null) { 14313 dataOnly = true; 14314 if((ps == null) || (ps.pkg == null)) { 14315 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 14316 return false; 14317 } 14318 p = ps.pkg; 14319 } 14320 if (ps != null) { 14321 libDirRoot = ps.legacyNativeLibraryPathString; 14322 } 14323 if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) { 14324 final long token = Binder.clearCallingIdentity(); 14325 try { 14326 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 14327 if (secureContainerId != null) { 14328 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 14329 } 14330 } finally { 14331 Binder.restoreCallingIdentity(token); 14332 } 14333 } 14334 } 14335 String publicSrcDir = null; 14336 if(!dataOnly) { 14337 final ApplicationInfo applicationInfo = p.applicationInfo; 14338 if (applicationInfo == null) { 14339 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 14340 return false; 14341 } 14342 if (p.isForwardLocked()) { 14343 publicSrcDir = applicationInfo.getBaseResourcePath(); 14344 } 14345 } 14346 // TODO: extend to measure size of split APKs 14347 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 14348 // not just the first level. 14349 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 14350 // just the primary. 14351 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 14352 14353 String apkPath; 14354 File packageDir = new File(p.codePath); 14355 14356 if (packageDir.isDirectory() && p.canHaveOatDir()) { 14357 apkPath = packageDir.getAbsolutePath(); 14358 // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice 14359 if (libDirRoot != null && libDirRoot.startsWith(apkPath)) { 14360 libDirRoot = null; 14361 } 14362 } else { 14363 apkPath = p.baseCodePath; 14364 } 14365 14366 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, apkPath, 14367 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 14368 if (res < 0) { 14369 return false; 14370 } 14371 14372 // Fix-up for forward-locked applications in ASEC containers. 14373 if (!isExternal(p)) { 14374 pStats.codeSize += pStats.externalCodeSize; 14375 pStats.externalCodeSize = 0L; 14376 } 14377 14378 return true; 14379 } 14380 14381 14382 @Override 14383 public void addPackageToPreferred(String packageName) { 14384 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 14385 } 14386 14387 @Override 14388 public void removePackageFromPreferred(String packageName) { 14389 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 14390 } 14391 14392 @Override 14393 public List<PackageInfo> getPreferredPackages(int flags) { 14394 return new ArrayList<PackageInfo>(); 14395 } 14396 14397 private int getUidTargetSdkVersionLockedLPr(int uid) { 14398 Object obj = mSettings.getUserIdLPr(uid); 14399 if (obj instanceof SharedUserSetting) { 14400 final SharedUserSetting sus = (SharedUserSetting) obj; 14401 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 14402 final Iterator<PackageSetting> it = sus.packages.iterator(); 14403 while (it.hasNext()) { 14404 final PackageSetting ps = it.next(); 14405 if (ps.pkg != null) { 14406 int v = ps.pkg.applicationInfo.targetSdkVersion; 14407 if (v < vers) vers = v; 14408 } 14409 } 14410 return vers; 14411 } else if (obj instanceof PackageSetting) { 14412 final PackageSetting ps = (PackageSetting) obj; 14413 if (ps.pkg != null) { 14414 return ps.pkg.applicationInfo.targetSdkVersion; 14415 } 14416 } 14417 return Build.VERSION_CODES.CUR_DEVELOPMENT; 14418 } 14419 14420 @Override 14421 public void addPreferredActivity(IntentFilter filter, int match, 14422 ComponentName[] set, ComponentName activity, int userId) { 14423 addPreferredActivityInternal(filter, match, set, activity, true, userId, 14424 "Adding preferred"); 14425 } 14426 14427 private void addPreferredActivityInternal(IntentFilter filter, int match, 14428 ComponentName[] set, ComponentName activity, boolean always, int userId, 14429 String opname) { 14430 // writer 14431 int callingUid = Binder.getCallingUid(); 14432 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 14433 if (filter.countActions() == 0) { 14434 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 14435 return; 14436 } 14437 synchronized (mPackages) { 14438 if (mContext.checkCallingOrSelfPermission( 14439 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14440 != PackageManager.PERMISSION_GRANTED) { 14441 if (getUidTargetSdkVersionLockedLPr(callingUid) 14442 < Build.VERSION_CODES.FROYO) { 14443 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 14444 + callingUid); 14445 return; 14446 } 14447 mContext.enforceCallingOrSelfPermission( 14448 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14449 } 14450 14451 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 14452 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 14453 + userId + ":"); 14454 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14455 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 14456 scheduleWritePackageRestrictionsLocked(userId); 14457 } 14458 } 14459 14460 @Override 14461 public void replacePreferredActivity(IntentFilter filter, int match, 14462 ComponentName[] set, ComponentName activity, int userId) { 14463 if (filter.countActions() != 1) { 14464 throw new IllegalArgumentException( 14465 "replacePreferredActivity expects filter to have only 1 action."); 14466 } 14467 if (filter.countDataAuthorities() != 0 14468 || filter.countDataPaths() != 0 14469 || filter.countDataSchemes() > 1 14470 || filter.countDataTypes() != 0) { 14471 throw new IllegalArgumentException( 14472 "replacePreferredActivity expects filter to have no data authorities, " + 14473 "paths, or types; and at most one scheme."); 14474 } 14475 14476 final int callingUid = Binder.getCallingUid(); 14477 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 14478 synchronized (mPackages) { 14479 if (mContext.checkCallingOrSelfPermission( 14480 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14481 != PackageManager.PERMISSION_GRANTED) { 14482 if (getUidTargetSdkVersionLockedLPr(callingUid) 14483 < Build.VERSION_CODES.FROYO) { 14484 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 14485 + Binder.getCallingUid()); 14486 return; 14487 } 14488 mContext.enforceCallingOrSelfPermission( 14489 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14490 } 14491 14492 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 14493 if (pir != null) { 14494 // Get all of the existing entries that exactly match this filter. 14495 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 14496 if (existing != null && existing.size() == 1) { 14497 PreferredActivity cur = existing.get(0); 14498 if (DEBUG_PREFERRED) { 14499 Slog.i(TAG, "Checking replace of preferred:"); 14500 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14501 if (!cur.mPref.mAlways) { 14502 Slog.i(TAG, " -- CUR; not mAlways!"); 14503 } else { 14504 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 14505 Slog.i(TAG, " -- CUR: mSet=" 14506 + Arrays.toString(cur.mPref.mSetComponents)); 14507 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 14508 Slog.i(TAG, " -- NEW: mMatch=" 14509 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 14510 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 14511 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 14512 } 14513 } 14514 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 14515 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 14516 && cur.mPref.sameSet(set)) { 14517 // Setting the preferred activity to what it happens to be already 14518 if (DEBUG_PREFERRED) { 14519 Slog.i(TAG, "Replacing with same preferred activity " 14520 + cur.mPref.mShortComponent + " for user " 14521 + userId + ":"); 14522 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14523 } 14524 return; 14525 } 14526 } 14527 14528 if (existing != null) { 14529 if (DEBUG_PREFERRED) { 14530 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 14531 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14532 } 14533 for (int i = 0; i < existing.size(); i++) { 14534 PreferredActivity pa = existing.get(i); 14535 if (DEBUG_PREFERRED) { 14536 Slog.i(TAG, "Removing existing preferred activity " 14537 + pa.mPref.mComponent + ":"); 14538 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 14539 } 14540 pir.removeFilter(pa); 14541 } 14542 } 14543 } 14544 addPreferredActivityInternal(filter, match, set, activity, true, userId, 14545 "Replacing preferred"); 14546 } 14547 } 14548 14549 @Override 14550 public void clearPackagePreferredActivities(String packageName) { 14551 final int uid = Binder.getCallingUid(); 14552 // writer 14553 synchronized (mPackages) { 14554 PackageParser.Package pkg = mPackages.get(packageName); 14555 if (pkg == null || pkg.applicationInfo.uid != uid) { 14556 if (mContext.checkCallingOrSelfPermission( 14557 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14558 != PackageManager.PERMISSION_GRANTED) { 14559 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 14560 < Build.VERSION_CODES.FROYO) { 14561 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 14562 + Binder.getCallingUid()); 14563 return; 14564 } 14565 mContext.enforceCallingOrSelfPermission( 14566 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14567 } 14568 } 14569 14570 int user = UserHandle.getCallingUserId(); 14571 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 14572 scheduleWritePackageRestrictionsLocked(user); 14573 } 14574 } 14575 } 14576 14577 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14578 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 14579 ArrayList<PreferredActivity> removed = null; 14580 boolean changed = false; 14581 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14582 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 14583 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14584 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 14585 continue; 14586 } 14587 Iterator<PreferredActivity> it = pir.filterIterator(); 14588 while (it.hasNext()) { 14589 PreferredActivity pa = it.next(); 14590 // Mark entry for removal only if it matches the package name 14591 // and the entry is of type "always". 14592 if (packageName == null || 14593 (pa.mPref.mComponent.getPackageName().equals(packageName) 14594 && pa.mPref.mAlways)) { 14595 if (removed == null) { 14596 removed = new ArrayList<PreferredActivity>(); 14597 } 14598 removed.add(pa); 14599 } 14600 } 14601 if (removed != null) { 14602 for (int j=0; j<removed.size(); j++) { 14603 PreferredActivity pa = removed.get(j); 14604 pir.removeFilter(pa); 14605 } 14606 changed = true; 14607 } 14608 } 14609 return changed; 14610 } 14611 14612 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14613 private void clearIntentFilterVerificationsLPw(int userId) { 14614 final int packageCount = mPackages.size(); 14615 for (int i = 0; i < packageCount; i++) { 14616 PackageParser.Package pkg = mPackages.valueAt(i); 14617 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 14618 } 14619 } 14620 14621 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14622 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 14623 if (userId == UserHandle.USER_ALL) { 14624 if (mSettings.removeIntentFilterVerificationLPw(packageName, 14625 sUserManager.getUserIds())) { 14626 for (int oneUserId : sUserManager.getUserIds()) { 14627 scheduleWritePackageRestrictionsLocked(oneUserId); 14628 } 14629 } 14630 } else { 14631 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 14632 scheduleWritePackageRestrictionsLocked(userId); 14633 } 14634 } 14635 } 14636 14637 void clearDefaultBrowserIfNeeded(String packageName) { 14638 for (int oneUserId : sUserManager.getUserIds()) { 14639 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 14640 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 14641 if (packageName.equals(defaultBrowserPackageName)) { 14642 setDefaultBrowserPackageName(null, oneUserId); 14643 } 14644 } 14645 } 14646 14647 @Override 14648 public void resetApplicationPreferences(int userId) { 14649 mContext.enforceCallingOrSelfPermission( 14650 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14651 // writer 14652 synchronized (mPackages) { 14653 final long identity = Binder.clearCallingIdentity(); 14654 try { 14655 clearPackagePreferredActivitiesLPw(null, userId); 14656 mSettings.applyDefaultPreferredAppsLPw(this, userId); 14657 // TODO: We have to reset the default SMS and Phone. This requires 14658 // significant refactoring to keep all default apps in the package 14659 // manager (cleaner but more work) or have the services provide 14660 // callbacks to the package manager to request a default app reset. 14661 applyFactoryDefaultBrowserLPw(userId); 14662 clearIntentFilterVerificationsLPw(userId); 14663 primeDomainVerificationsLPw(userId); 14664 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 14665 scheduleWritePackageRestrictionsLocked(userId); 14666 } finally { 14667 Binder.restoreCallingIdentity(identity); 14668 } 14669 } 14670 } 14671 14672 @Override 14673 public int getPreferredActivities(List<IntentFilter> outFilters, 14674 List<ComponentName> outActivities, String packageName) { 14675 14676 int num = 0; 14677 final int userId = UserHandle.getCallingUserId(); 14678 // reader 14679 synchronized (mPackages) { 14680 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 14681 if (pir != null) { 14682 final Iterator<PreferredActivity> it = pir.filterIterator(); 14683 while (it.hasNext()) { 14684 final PreferredActivity pa = it.next(); 14685 if (packageName == null 14686 || (pa.mPref.mComponent.getPackageName().equals(packageName) 14687 && pa.mPref.mAlways)) { 14688 if (outFilters != null) { 14689 outFilters.add(new IntentFilter(pa)); 14690 } 14691 if (outActivities != null) { 14692 outActivities.add(pa.mPref.mComponent); 14693 } 14694 } 14695 } 14696 } 14697 } 14698 14699 return num; 14700 } 14701 14702 @Override 14703 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 14704 int userId) { 14705 int callingUid = Binder.getCallingUid(); 14706 if (callingUid != Process.SYSTEM_UID) { 14707 throw new SecurityException( 14708 "addPersistentPreferredActivity can only be run by the system"); 14709 } 14710 if (filter.countActions() == 0) { 14711 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 14712 return; 14713 } 14714 synchronized (mPackages) { 14715 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 14716 " :"); 14717 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14718 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 14719 new PersistentPreferredActivity(filter, activity)); 14720 scheduleWritePackageRestrictionsLocked(userId); 14721 } 14722 } 14723 14724 @Override 14725 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 14726 int callingUid = Binder.getCallingUid(); 14727 if (callingUid != Process.SYSTEM_UID) { 14728 throw new SecurityException( 14729 "clearPackagePersistentPreferredActivities can only be run by the system"); 14730 } 14731 ArrayList<PersistentPreferredActivity> removed = null; 14732 boolean changed = false; 14733 synchronized (mPackages) { 14734 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 14735 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 14736 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 14737 .valueAt(i); 14738 if (userId != thisUserId) { 14739 continue; 14740 } 14741 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 14742 while (it.hasNext()) { 14743 PersistentPreferredActivity ppa = it.next(); 14744 // Mark entry for removal only if it matches the package name. 14745 if (ppa.mComponent.getPackageName().equals(packageName)) { 14746 if (removed == null) { 14747 removed = new ArrayList<PersistentPreferredActivity>(); 14748 } 14749 removed.add(ppa); 14750 } 14751 } 14752 if (removed != null) { 14753 for (int j=0; j<removed.size(); j++) { 14754 PersistentPreferredActivity ppa = removed.get(j); 14755 ppir.removeFilter(ppa); 14756 } 14757 changed = true; 14758 } 14759 } 14760 14761 if (changed) { 14762 scheduleWritePackageRestrictionsLocked(userId); 14763 } 14764 } 14765 } 14766 14767 /** 14768 * Common machinery for picking apart a restored XML blob and passing 14769 * it to a caller-supplied functor to be applied to the running system. 14770 */ 14771 private void restoreFromXml(XmlPullParser parser, int userId, 14772 String expectedStartTag, BlobXmlRestorer functor) 14773 throws IOException, XmlPullParserException { 14774 int type; 14775 while ((type = parser.next()) != XmlPullParser.START_TAG 14776 && type != XmlPullParser.END_DOCUMENT) { 14777 } 14778 if (type != XmlPullParser.START_TAG) { 14779 // oops didn't find a start tag?! 14780 if (DEBUG_BACKUP) { 14781 Slog.e(TAG, "Didn't find start tag during restore"); 14782 } 14783 return; 14784 } 14785 14786 // this is supposed to be TAG_PREFERRED_BACKUP 14787 if (!expectedStartTag.equals(parser.getName())) { 14788 if (DEBUG_BACKUP) { 14789 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 14790 } 14791 return; 14792 } 14793 14794 // skip interfering stuff, then we're aligned with the backing implementation 14795 while ((type = parser.next()) == XmlPullParser.TEXT) { } 14796 functor.apply(parser, userId); 14797 } 14798 14799 private interface BlobXmlRestorer { 14800 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 14801 } 14802 14803 /** 14804 * Non-Binder method, support for the backup/restore mechanism: write the 14805 * full set of preferred activities in its canonical XML format. Returns the 14806 * XML output as a byte array, or null if there is none. 14807 */ 14808 @Override 14809 public byte[] getPreferredActivityBackup(int userId) { 14810 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14811 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 14812 } 14813 14814 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14815 try { 14816 final XmlSerializer serializer = new FastXmlSerializer(); 14817 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14818 serializer.startDocument(null, true); 14819 serializer.startTag(null, TAG_PREFERRED_BACKUP); 14820 14821 synchronized (mPackages) { 14822 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 14823 } 14824 14825 serializer.endTag(null, TAG_PREFERRED_BACKUP); 14826 serializer.endDocument(); 14827 serializer.flush(); 14828 } catch (Exception e) { 14829 if (DEBUG_BACKUP) { 14830 Slog.e(TAG, "Unable to write preferred activities for backup", e); 14831 } 14832 return null; 14833 } 14834 14835 return dataStream.toByteArray(); 14836 } 14837 14838 @Override 14839 public void restorePreferredActivities(byte[] backup, int userId) { 14840 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14841 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14842 } 14843 14844 try { 14845 final XmlPullParser parser = Xml.newPullParser(); 14846 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14847 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 14848 new BlobXmlRestorer() { 14849 @Override 14850 public void apply(XmlPullParser parser, int userId) 14851 throws XmlPullParserException, IOException { 14852 synchronized (mPackages) { 14853 mSettings.readPreferredActivitiesLPw(parser, userId); 14854 } 14855 } 14856 } ); 14857 } catch (Exception e) { 14858 if (DEBUG_BACKUP) { 14859 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14860 } 14861 } 14862 } 14863 14864 /** 14865 * Non-Binder method, support for the backup/restore mechanism: write the 14866 * default browser (etc) settings in its canonical XML format. Returns the default 14867 * browser XML representation as a byte array, or null if there is none. 14868 */ 14869 @Override 14870 public byte[] getDefaultAppsBackup(int userId) { 14871 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14872 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 14873 } 14874 14875 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14876 try { 14877 final XmlSerializer serializer = new FastXmlSerializer(); 14878 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14879 serializer.startDocument(null, true); 14880 serializer.startTag(null, TAG_DEFAULT_APPS); 14881 14882 synchronized (mPackages) { 14883 mSettings.writeDefaultAppsLPr(serializer, userId); 14884 } 14885 14886 serializer.endTag(null, TAG_DEFAULT_APPS); 14887 serializer.endDocument(); 14888 serializer.flush(); 14889 } catch (Exception e) { 14890 if (DEBUG_BACKUP) { 14891 Slog.e(TAG, "Unable to write default apps for backup", e); 14892 } 14893 return null; 14894 } 14895 14896 return dataStream.toByteArray(); 14897 } 14898 14899 @Override 14900 public void restoreDefaultApps(byte[] backup, int userId) { 14901 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14902 throw new SecurityException("Only the system may call restoreDefaultApps()"); 14903 } 14904 14905 try { 14906 final XmlPullParser parser = Xml.newPullParser(); 14907 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14908 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 14909 new BlobXmlRestorer() { 14910 @Override 14911 public void apply(XmlPullParser parser, int userId) 14912 throws XmlPullParserException, IOException { 14913 synchronized (mPackages) { 14914 mSettings.readDefaultAppsLPw(parser, userId); 14915 } 14916 } 14917 } ); 14918 } catch (Exception e) { 14919 if (DEBUG_BACKUP) { 14920 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 14921 } 14922 } 14923 } 14924 14925 @Override 14926 public byte[] getIntentFilterVerificationBackup(int userId) { 14927 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14928 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 14929 } 14930 14931 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14932 try { 14933 final XmlSerializer serializer = new FastXmlSerializer(); 14934 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14935 serializer.startDocument(null, true); 14936 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 14937 14938 synchronized (mPackages) { 14939 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 14940 } 14941 14942 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 14943 serializer.endDocument(); 14944 serializer.flush(); 14945 } catch (Exception e) { 14946 if (DEBUG_BACKUP) { 14947 Slog.e(TAG, "Unable to write default apps for backup", e); 14948 } 14949 return null; 14950 } 14951 14952 return dataStream.toByteArray(); 14953 } 14954 14955 @Override 14956 public void restoreIntentFilterVerification(byte[] backup, int userId) { 14957 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14958 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14959 } 14960 14961 try { 14962 final XmlPullParser parser = Xml.newPullParser(); 14963 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14964 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 14965 new BlobXmlRestorer() { 14966 @Override 14967 public void apply(XmlPullParser parser, int userId) 14968 throws XmlPullParserException, IOException { 14969 synchronized (mPackages) { 14970 mSettings.readAllDomainVerificationsLPr(parser, userId); 14971 mSettings.writeLPr(); 14972 } 14973 } 14974 } ); 14975 } catch (Exception e) { 14976 if (DEBUG_BACKUP) { 14977 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14978 } 14979 } 14980 } 14981 14982 @Override 14983 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 14984 int sourceUserId, int targetUserId, int flags) { 14985 mContext.enforceCallingOrSelfPermission( 14986 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14987 int callingUid = Binder.getCallingUid(); 14988 enforceOwnerRights(ownerPackage, callingUid); 14989 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14990 if (intentFilter.countActions() == 0) { 14991 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 14992 return; 14993 } 14994 synchronized (mPackages) { 14995 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 14996 ownerPackage, targetUserId, flags); 14997 CrossProfileIntentResolver resolver = 14998 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14999 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 15000 // We have all those whose filter is equal. Now checking if the rest is equal as well. 15001 if (existing != null) { 15002 int size = existing.size(); 15003 for (int i = 0; i < size; i++) { 15004 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 15005 return; 15006 } 15007 } 15008 } 15009 resolver.addFilter(newFilter); 15010 scheduleWritePackageRestrictionsLocked(sourceUserId); 15011 } 15012 } 15013 15014 @Override 15015 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 15016 mContext.enforceCallingOrSelfPermission( 15017 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 15018 int callingUid = Binder.getCallingUid(); 15019 enforceOwnerRights(ownerPackage, callingUid); 15020 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 15021 synchronized (mPackages) { 15022 CrossProfileIntentResolver resolver = 15023 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 15024 ArraySet<CrossProfileIntentFilter> set = 15025 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 15026 for (CrossProfileIntentFilter filter : set) { 15027 if (filter.getOwnerPackage().equals(ownerPackage)) { 15028 resolver.removeFilter(filter); 15029 } 15030 } 15031 scheduleWritePackageRestrictionsLocked(sourceUserId); 15032 } 15033 } 15034 15035 // Enforcing that callingUid is owning pkg on userId 15036 private void enforceOwnerRights(String pkg, int callingUid) { 15037 // The system owns everything. 15038 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 15039 return; 15040 } 15041 int callingUserId = UserHandle.getUserId(callingUid); 15042 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 15043 if (pi == null) { 15044 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 15045 + callingUserId); 15046 } 15047 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 15048 throw new SecurityException("Calling uid " + callingUid 15049 + " does not own package " + pkg); 15050 } 15051 } 15052 15053 @Override 15054 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 15055 Intent intent = new Intent(Intent.ACTION_MAIN); 15056 intent.addCategory(Intent.CATEGORY_HOME); 15057 15058 final int callingUserId = UserHandle.getCallingUserId(); 15059 List<ResolveInfo> list = queryIntentActivities(intent, null, 15060 PackageManager.GET_META_DATA, callingUserId); 15061 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 15062 true, false, false, callingUserId); 15063 15064 allHomeCandidates.clear(); 15065 if (list != null) { 15066 for (ResolveInfo ri : list) { 15067 allHomeCandidates.add(ri); 15068 } 15069 } 15070 return (preferred == null || preferred.activityInfo == null) 15071 ? null 15072 : new ComponentName(preferred.activityInfo.packageName, 15073 preferred.activityInfo.name); 15074 } 15075 15076 @Override 15077 public void setApplicationEnabledSetting(String appPackageName, 15078 int newState, int flags, int userId, String callingPackage) { 15079 if (!sUserManager.exists(userId)) return; 15080 if (callingPackage == null) { 15081 callingPackage = Integer.toString(Binder.getCallingUid()); 15082 } 15083 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 15084 } 15085 15086 @Override 15087 public void setComponentEnabledSetting(ComponentName componentName, 15088 int newState, int flags, int userId) { 15089 if (!sUserManager.exists(userId)) return; 15090 setEnabledSetting(componentName.getPackageName(), 15091 componentName.getClassName(), newState, flags, userId, null); 15092 } 15093 15094 private void setEnabledSetting(final String packageName, String className, int newState, 15095 final int flags, int userId, String callingPackage) { 15096 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 15097 || newState == COMPONENT_ENABLED_STATE_ENABLED 15098 || newState == COMPONENT_ENABLED_STATE_DISABLED 15099 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 15100 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 15101 throw new IllegalArgumentException("Invalid new component state: " 15102 + newState); 15103 } 15104 PackageSetting pkgSetting; 15105 final int uid = Binder.getCallingUid(); 15106 final int permission = mContext.checkCallingOrSelfPermission( 15107 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 15108 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 15109 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 15110 boolean sendNow = false; 15111 boolean isApp = (className == null); 15112 String componentName = isApp ? packageName : className; 15113 int packageUid = -1; 15114 ArrayList<String> components; 15115 15116 // writer 15117 synchronized (mPackages) { 15118 pkgSetting = mSettings.mPackages.get(packageName); 15119 if (pkgSetting == null) { 15120 if (className == null) { 15121 throw new IllegalArgumentException( 15122 "Unknown package: " + packageName); 15123 } 15124 throw new IllegalArgumentException( 15125 "Unknown component: " + packageName 15126 + "/" + className); 15127 } 15128 // Allow root and verify that userId is not being specified by a different user 15129 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 15130 throw new SecurityException( 15131 "Permission Denial: attempt to change component state from pid=" 15132 + Binder.getCallingPid() 15133 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 15134 } 15135 if (className == null) { 15136 // We're dealing with an application/package level state change 15137 if (pkgSetting.getEnabled(userId) == newState) { 15138 // Nothing to do 15139 return; 15140 } 15141 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 15142 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 15143 // Don't care about who enables an app. 15144 callingPackage = null; 15145 } 15146 pkgSetting.setEnabled(newState, userId, callingPackage); 15147 // pkgSetting.pkg.mSetEnabled = newState; 15148 } else { 15149 // We're dealing with a component level state change 15150 // First, verify that this is a valid class name. 15151 PackageParser.Package pkg = pkgSetting.pkg; 15152 if (pkg == null || !pkg.hasComponentClassName(className)) { 15153 if (pkg != null && 15154 pkg.applicationInfo.targetSdkVersion >= 15155 Build.VERSION_CODES.JELLY_BEAN) { 15156 throw new IllegalArgumentException("Component class " + className 15157 + " does not exist in " + packageName); 15158 } else { 15159 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 15160 + className + " does not exist in " + packageName); 15161 } 15162 } 15163 switch (newState) { 15164 case COMPONENT_ENABLED_STATE_ENABLED: 15165 if (!pkgSetting.enableComponentLPw(className, userId)) { 15166 return; 15167 } 15168 break; 15169 case COMPONENT_ENABLED_STATE_DISABLED: 15170 if (!pkgSetting.disableComponentLPw(className, userId)) { 15171 return; 15172 } 15173 break; 15174 case COMPONENT_ENABLED_STATE_DEFAULT: 15175 if (!pkgSetting.restoreComponentLPw(className, userId)) { 15176 return; 15177 } 15178 break; 15179 default: 15180 Slog.e(TAG, "Invalid new component state: " + newState); 15181 return; 15182 } 15183 } 15184 scheduleWritePackageRestrictionsLocked(userId); 15185 components = mPendingBroadcasts.get(userId, packageName); 15186 final boolean newPackage = components == null; 15187 if (newPackage) { 15188 components = new ArrayList<String>(); 15189 } 15190 if (!components.contains(componentName)) { 15191 components.add(componentName); 15192 } 15193 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 15194 sendNow = true; 15195 // Purge entry from pending broadcast list if another one exists already 15196 // since we are sending one right away. 15197 mPendingBroadcasts.remove(userId, packageName); 15198 } else { 15199 if (newPackage) { 15200 mPendingBroadcasts.put(userId, packageName, components); 15201 } 15202 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 15203 // Schedule a message 15204 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 15205 } 15206 } 15207 } 15208 15209 long callingId = Binder.clearCallingIdentity(); 15210 try { 15211 if (sendNow) { 15212 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 15213 sendPackageChangedBroadcast(packageName, 15214 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 15215 } 15216 } finally { 15217 Binder.restoreCallingIdentity(callingId); 15218 } 15219 } 15220 15221 private void sendPackageChangedBroadcast(String packageName, 15222 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 15223 if (DEBUG_INSTALL) 15224 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 15225 + componentNames); 15226 Bundle extras = new Bundle(4); 15227 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 15228 String nameList[] = new String[componentNames.size()]; 15229 componentNames.toArray(nameList); 15230 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 15231 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 15232 extras.putInt(Intent.EXTRA_UID, packageUid); 15233 // If this is not reporting a change of the overall package, then only send it 15234 // to registered receivers. We don't want to launch a swath of apps for every 15235 // little component state change. 15236 final int flags = !componentNames.contains(packageName) 15237 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 15238 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 15239 new int[] {UserHandle.getUserId(packageUid)}); 15240 } 15241 15242 @Override 15243 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 15244 if (!sUserManager.exists(userId)) return; 15245 final int uid = Binder.getCallingUid(); 15246 final int permission = mContext.checkCallingOrSelfPermission( 15247 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 15248 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 15249 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 15250 // writer 15251 synchronized (mPackages) { 15252 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 15253 allowedByPermission, uid, userId)) { 15254 scheduleWritePackageRestrictionsLocked(userId); 15255 } 15256 } 15257 } 15258 15259 @Override 15260 public String getInstallerPackageName(String packageName) { 15261 // reader 15262 synchronized (mPackages) { 15263 return mSettings.getInstallerPackageNameLPr(packageName); 15264 } 15265 } 15266 15267 @Override 15268 public int getApplicationEnabledSetting(String packageName, int userId) { 15269 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 15270 int uid = Binder.getCallingUid(); 15271 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 15272 // reader 15273 synchronized (mPackages) { 15274 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 15275 } 15276 } 15277 15278 @Override 15279 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 15280 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 15281 int uid = Binder.getCallingUid(); 15282 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 15283 // reader 15284 synchronized (mPackages) { 15285 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 15286 } 15287 } 15288 15289 @Override 15290 public void enterSafeMode() { 15291 enforceSystemOrRoot("Only the system can request entering safe mode"); 15292 15293 if (!mSystemReady) { 15294 mSafeMode = true; 15295 } 15296 } 15297 15298 @Override 15299 public void systemReady() { 15300 mSystemReady = true; 15301 15302 // Read the compatibilty setting when the system is ready. 15303 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 15304 mContext.getContentResolver(), 15305 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 15306 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 15307 if (DEBUG_SETTINGS) { 15308 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 15309 } 15310 15311 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 15312 15313 synchronized (mPackages) { 15314 // Verify that all of the preferred activity components actually 15315 // exist. It is possible for applications to be updated and at 15316 // that point remove a previously declared activity component that 15317 // had been set as a preferred activity. We try to clean this up 15318 // the next time we encounter that preferred activity, but it is 15319 // possible for the user flow to never be able to return to that 15320 // situation so here we do a sanity check to make sure we haven't 15321 // left any junk around. 15322 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 15323 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 15324 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 15325 removed.clear(); 15326 for (PreferredActivity pa : pir.filterSet()) { 15327 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 15328 removed.add(pa); 15329 } 15330 } 15331 if (removed.size() > 0) { 15332 for (int r=0; r<removed.size(); r++) { 15333 PreferredActivity pa = removed.get(r); 15334 Slog.w(TAG, "Removing dangling preferred activity: " 15335 + pa.mPref.mComponent); 15336 pir.removeFilter(pa); 15337 } 15338 mSettings.writePackageRestrictionsLPr( 15339 mSettings.mPreferredActivities.keyAt(i)); 15340 } 15341 } 15342 15343 for (int userId : UserManagerService.getInstance().getUserIds()) { 15344 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 15345 grantPermissionsUserIds = ArrayUtils.appendInt( 15346 grantPermissionsUserIds, userId); 15347 } 15348 } 15349 } 15350 sUserManager.systemReady(); 15351 15352 // If we upgraded grant all default permissions before kicking off. 15353 for (int userId : grantPermissionsUserIds) { 15354 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 15355 } 15356 15357 // Kick off any messages waiting for system ready 15358 if (mPostSystemReadyMessages != null) { 15359 for (Message msg : mPostSystemReadyMessages) { 15360 msg.sendToTarget(); 15361 } 15362 mPostSystemReadyMessages = null; 15363 } 15364 15365 // Watch for external volumes that come and go over time 15366 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15367 storage.registerListener(mStorageListener); 15368 15369 mInstallerService.systemReady(); 15370 mPackageDexOptimizer.systemReady(); 15371 15372 MountServiceInternal mountServiceInternal = LocalServices.getService( 15373 MountServiceInternal.class); 15374 mountServiceInternal.addExternalStoragePolicy( 15375 new MountServiceInternal.ExternalStorageMountPolicy() { 15376 @Override 15377 public int getMountMode(int uid, String packageName) { 15378 if (Process.isIsolated(uid)) { 15379 return Zygote.MOUNT_EXTERNAL_NONE; 15380 } 15381 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 15382 return Zygote.MOUNT_EXTERNAL_DEFAULT; 15383 } 15384 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 15385 return Zygote.MOUNT_EXTERNAL_DEFAULT; 15386 } 15387 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 15388 return Zygote.MOUNT_EXTERNAL_READ; 15389 } 15390 return Zygote.MOUNT_EXTERNAL_WRITE; 15391 } 15392 15393 @Override 15394 public boolean hasExternalStorage(int uid, String packageName) { 15395 return true; 15396 } 15397 }); 15398 } 15399 15400 @Override 15401 public boolean isSafeMode() { 15402 return mSafeMode; 15403 } 15404 15405 @Override 15406 public boolean hasSystemUidErrors() { 15407 return mHasSystemUidErrors; 15408 } 15409 15410 static String arrayToString(int[] array) { 15411 StringBuffer buf = new StringBuffer(128); 15412 buf.append('['); 15413 if (array != null) { 15414 for (int i=0; i<array.length; i++) { 15415 if (i > 0) buf.append(", "); 15416 buf.append(array[i]); 15417 } 15418 } 15419 buf.append(']'); 15420 return buf.toString(); 15421 } 15422 15423 static class DumpState { 15424 public static final int DUMP_LIBS = 1 << 0; 15425 public static final int DUMP_FEATURES = 1 << 1; 15426 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 15427 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 15428 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 15429 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 15430 public static final int DUMP_PERMISSIONS = 1 << 6; 15431 public static final int DUMP_PACKAGES = 1 << 7; 15432 public static final int DUMP_SHARED_USERS = 1 << 8; 15433 public static final int DUMP_MESSAGES = 1 << 9; 15434 public static final int DUMP_PROVIDERS = 1 << 10; 15435 public static final int DUMP_VERIFIERS = 1 << 11; 15436 public static final int DUMP_PREFERRED = 1 << 12; 15437 public static final int DUMP_PREFERRED_XML = 1 << 13; 15438 public static final int DUMP_KEYSETS = 1 << 14; 15439 public static final int DUMP_VERSION = 1 << 15; 15440 public static final int DUMP_INSTALLS = 1 << 16; 15441 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 15442 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 15443 15444 public static final int OPTION_SHOW_FILTERS = 1 << 0; 15445 15446 private int mTypes; 15447 15448 private int mOptions; 15449 15450 private boolean mTitlePrinted; 15451 15452 private SharedUserSetting mSharedUser; 15453 15454 public boolean isDumping(int type) { 15455 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 15456 return true; 15457 } 15458 15459 return (mTypes & type) != 0; 15460 } 15461 15462 public void setDump(int type) { 15463 mTypes |= type; 15464 } 15465 15466 public boolean isOptionEnabled(int option) { 15467 return (mOptions & option) != 0; 15468 } 15469 15470 public void setOptionEnabled(int option) { 15471 mOptions |= option; 15472 } 15473 15474 public boolean onTitlePrinted() { 15475 final boolean printed = mTitlePrinted; 15476 mTitlePrinted = true; 15477 return printed; 15478 } 15479 15480 public boolean getTitlePrinted() { 15481 return mTitlePrinted; 15482 } 15483 15484 public void setTitlePrinted(boolean enabled) { 15485 mTitlePrinted = enabled; 15486 } 15487 15488 public SharedUserSetting getSharedUser() { 15489 return mSharedUser; 15490 } 15491 15492 public void setSharedUser(SharedUserSetting user) { 15493 mSharedUser = user; 15494 } 15495 } 15496 15497 @Override 15498 public void onShellCommand(FileDescriptor in, FileDescriptor out, 15499 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 15500 (new PackageManagerShellCommand(this)).exec( 15501 this, in, out, err, args, resultReceiver); 15502 } 15503 15504 @Override 15505 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 15506 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 15507 != PackageManager.PERMISSION_GRANTED) { 15508 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 15509 + Binder.getCallingPid() 15510 + ", uid=" + Binder.getCallingUid() 15511 + " without permission " 15512 + android.Manifest.permission.DUMP); 15513 return; 15514 } 15515 15516 DumpState dumpState = new DumpState(); 15517 boolean fullPreferred = false; 15518 boolean checkin = false; 15519 15520 String packageName = null; 15521 ArraySet<String> permissionNames = null; 15522 15523 int opti = 0; 15524 while (opti < args.length) { 15525 String opt = args[opti]; 15526 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 15527 break; 15528 } 15529 opti++; 15530 15531 if ("-a".equals(opt)) { 15532 // Right now we only know how to print all. 15533 } else if ("-h".equals(opt)) { 15534 pw.println("Package manager dump options:"); 15535 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 15536 pw.println(" --checkin: dump for a checkin"); 15537 pw.println(" -f: print details of intent filters"); 15538 pw.println(" -h: print this help"); 15539 pw.println(" cmd may be one of:"); 15540 pw.println(" l[ibraries]: list known shared libraries"); 15541 pw.println(" f[eatures]: list device features"); 15542 pw.println(" k[eysets]: print known keysets"); 15543 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 15544 pw.println(" perm[issions]: dump permissions"); 15545 pw.println(" permission [name ...]: dump declaration and use of given permission"); 15546 pw.println(" pref[erred]: print preferred package settings"); 15547 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 15548 pw.println(" prov[iders]: dump content providers"); 15549 pw.println(" p[ackages]: dump installed packages"); 15550 pw.println(" s[hared-users]: dump shared user IDs"); 15551 pw.println(" m[essages]: print collected runtime messages"); 15552 pw.println(" v[erifiers]: print package verifier info"); 15553 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 15554 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 15555 pw.println(" version: print database version info"); 15556 pw.println(" write: write current settings now"); 15557 pw.println(" installs: details about install sessions"); 15558 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 15559 pw.println(" <package.name>: info about given package"); 15560 return; 15561 } else if ("--checkin".equals(opt)) { 15562 checkin = true; 15563 } else if ("-f".equals(opt)) { 15564 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 15565 } else { 15566 pw.println("Unknown argument: " + opt + "; use -h for help"); 15567 } 15568 } 15569 15570 // Is the caller requesting to dump a particular piece of data? 15571 if (opti < args.length) { 15572 String cmd = args[opti]; 15573 opti++; 15574 // Is this a package name? 15575 if ("android".equals(cmd) || cmd.contains(".")) { 15576 packageName = cmd; 15577 // When dumping a single package, we always dump all of its 15578 // filter information since the amount of data will be reasonable. 15579 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 15580 } else if ("check-permission".equals(cmd)) { 15581 if (opti >= args.length) { 15582 pw.println("Error: check-permission missing permission argument"); 15583 return; 15584 } 15585 String perm = args[opti]; 15586 opti++; 15587 if (opti >= args.length) { 15588 pw.println("Error: check-permission missing package argument"); 15589 return; 15590 } 15591 String pkg = args[opti]; 15592 opti++; 15593 int user = UserHandle.getUserId(Binder.getCallingUid()); 15594 if (opti < args.length) { 15595 try { 15596 user = Integer.parseInt(args[opti]); 15597 } catch (NumberFormatException e) { 15598 pw.println("Error: check-permission user argument is not a number: " 15599 + args[opti]); 15600 return; 15601 } 15602 } 15603 pw.println(checkPermission(perm, pkg, user)); 15604 return; 15605 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 15606 dumpState.setDump(DumpState.DUMP_LIBS); 15607 } else if ("f".equals(cmd) || "features".equals(cmd)) { 15608 dumpState.setDump(DumpState.DUMP_FEATURES); 15609 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 15610 if (opti >= args.length) { 15611 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 15612 | DumpState.DUMP_SERVICE_RESOLVERS 15613 | DumpState.DUMP_RECEIVER_RESOLVERS 15614 | DumpState.DUMP_CONTENT_RESOLVERS); 15615 } else { 15616 while (opti < args.length) { 15617 String name = args[opti]; 15618 if ("a".equals(name) || "activity".equals(name)) { 15619 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 15620 } else if ("s".equals(name) || "service".equals(name)) { 15621 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 15622 } else if ("r".equals(name) || "receiver".equals(name)) { 15623 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 15624 } else if ("c".equals(name) || "content".equals(name)) { 15625 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 15626 } else { 15627 pw.println("Error: unknown resolver table type: " + name); 15628 return; 15629 } 15630 opti++; 15631 } 15632 } 15633 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 15634 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 15635 } else if ("permission".equals(cmd)) { 15636 if (opti >= args.length) { 15637 pw.println("Error: permission requires permission name"); 15638 return; 15639 } 15640 permissionNames = new ArraySet<>(); 15641 while (opti < args.length) { 15642 permissionNames.add(args[opti]); 15643 opti++; 15644 } 15645 dumpState.setDump(DumpState.DUMP_PERMISSIONS 15646 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 15647 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 15648 dumpState.setDump(DumpState.DUMP_PREFERRED); 15649 } else if ("preferred-xml".equals(cmd)) { 15650 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 15651 if (opti < args.length && "--full".equals(args[opti])) { 15652 fullPreferred = true; 15653 opti++; 15654 } 15655 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 15656 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 15657 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 15658 dumpState.setDump(DumpState.DUMP_PACKAGES); 15659 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 15660 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 15661 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 15662 dumpState.setDump(DumpState.DUMP_PROVIDERS); 15663 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 15664 dumpState.setDump(DumpState.DUMP_MESSAGES); 15665 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 15666 dumpState.setDump(DumpState.DUMP_VERIFIERS); 15667 } else if ("i".equals(cmd) || "ifv".equals(cmd) 15668 || "intent-filter-verifiers".equals(cmd)) { 15669 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 15670 } else if ("version".equals(cmd)) { 15671 dumpState.setDump(DumpState.DUMP_VERSION); 15672 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 15673 dumpState.setDump(DumpState.DUMP_KEYSETS); 15674 } else if ("installs".equals(cmd)) { 15675 dumpState.setDump(DumpState.DUMP_INSTALLS); 15676 } else if ("write".equals(cmd)) { 15677 synchronized (mPackages) { 15678 mSettings.writeLPr(); 15679 pw.println("Settings written."); 15680 return; 15681 } 15682 } 15683 } 15684 15685 if (checkin) { 15686 pw.println("vers,1"); 15687 } 15688 15689 // reader 15690 synchronized (mPackages) { 15691 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 15692 if (!checkin) { 15693 if (dumpState.onTitlePrinted()) 15694 pw.println(); 15695 pw.println("Database versions:"); 15696 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 15697 } 15698 } 15699 15700 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 15701 if (!checkin) { 15702 if (dumpState.onTitlePrinted()) 15703 pw.println(); 15704 pw.println("Verifiers:"); 15705 pw.print(" Required: "); 15706 pw.print(mRequiredVerifierPackage); 15707 pw.print(" (uid="); 15708 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 15709 pw.println(")"); 15710 } else if (mRequiredVerifierPackage != null) { 15711 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 15712 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 15713 } 15714 } 15715 15716 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 15717 packageName == null) { 15718 if (mIntentFilterVerifierComponent != null) { 15719 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 15720 if (!checkin) { 15721 if (dumpState.onTitlePrinted()) 15722 pw.println(); 15723 pw.println("Intent Filter Verifier:"); 15724 pw.print(" Using: "); 15725 pw.print(verifierPackageName); 15726 pw.print(" (uid="); 15727 pw.print(getPackageUid(verifierPackageName, 0)); 15728 pw.println(")"); 15729 } else if (verifierPackageName != null) { 15730 pw.print("ifv,"); pw.print(verifierPackageName); 15731 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 15732 } 15733 } else { 15734 pw.println(); 15735 pw.println("No Intent Filter Verifier available!"); 15736 } 15737 } 15738 15739 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 15740 boolean printedHeader = false; 15741 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 15742 while (it.hasNext()) { 15743 String name = it.next(); 15744 SharedLibraryEntry ent = mSharedLibraries.get(name); 15745 if (!checkin) { 15746 if (!printedHeader) { 15747 if (dumpState.onTitlePrinted()) 15748 pw.println(); 15749 pw.println("Libraries:"); 15750 printedHeader = true; 15751 } 15752 pw.print(" "); 15753 } else { 15754 pw.print("lib,"); 15755 } 15756 pw.print(name); 15757 if (!checkin) { 15758 pw.print(" -> "); 15759 } 15760 if (ent.path != null) { 15761 if (!checkin) { 15762 pw.print("(jar) "); 15763 pw.print(ent.path); 15764 } else { 15765 pw.print(",jar,"); 15766 pw.print(ent.path); 15767 } 15768 } else { 15769 if (!checkin) { 15770 pw.print("(apk) "); 15771 pw.print(ent.apk); 15772 } else { 15773 pw.print(",apk,"); 15774 pw.print(ent.apk); 15775 } 15776 } 15777 pw.println(); 15778 } 15779 } 15780 15781 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 15782 if (dumpState.onTitlePrinted()) 15783 pw.println(); 15784 if (!checkin) { 15785 pw.println("Features:"); 15786 } 15787 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 15788 while (it.hasNext()) { 15789 String name = it.next(); 15790 if (!checkin) { 15791 pw.print(" "); 15792 } else { 15793 pw.print("feat,"); 15794 } 15795 pw.println(name); 15796 } 15797 } 15798 15799 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 15800 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 15801 : "Activity Resolver Table:", " ", packageName, 15802 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15803 dumpState.setTitlePrinted(true); 15804 } 15805 } 15806 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 15807 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 15808 : "Receiver Resolver Table:", " ", packageName, 15809 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15810 dumpState.setTitlePrinted(true); 15811 } 15812 } 15813 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 15814 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 15815 : "Service Resolver Table:", " ", packageName, 15816 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15817 dumpState.setTitlePrinted(true); 15818 } 15819 } 15820 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 15821 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 15822 : "Provider Resolver Table:", " ", packageName, 15823 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15824 dumpState.setTitlePrinted(true); 15825 } 15826 } 15827 15828 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 15829 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 15830 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 15831 int user = mSettings.mPreferredActivities.keyAt(i); 15832 if (pir.dump(pw, 15833 dumpState.getTitlePrinted() 15834 ? "\nPreferred Activities User " + user + ":" 15835 : "Preferred Activities User " + user + ":", " ", 15836 packageName, true, false)) { 15837 dumpState.setTitlePrinted(true); 15838 } 15839 } 15840 } 15841 15842 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 15843 pw.flush(); 15844 FileOutputStream fout = new FileOutputStream(fd); 15845 BufferedOutputStream str = new BufferedOutputStream(fout); 15846 XmlSerializer serializer = new FastXmlSerializer(); 15847 try { 15848 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 15849 serializer.startDocument(null, true); 15850 serializer.setFeature( 15851 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 15852 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 15853 serializer.endDocument(); 15854 serializer.flush(); 15855 } catch (IllegalArgumentException e) { 15856 pw.println("Failed writing: " + e); 15857 } catch (IllegalStateException e) { 15858 pw.println("Failed writing: " + e); 15859 } catch (IOException e) { 15860 pw.println("Failed writing: " + e); 15861 } 15862 } 15863 15864 if (!checkin 15865 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 15866 && packageName == null) { 15867 pw.println(); 15868 int count = mSettings.mPackages.size(); 15869 if (count == 0) { 15870 pw.println("No applications!"); 15871 pw.println(); 15872 } else { 15873 final String prefix = " "; 15874 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 15875 if (allPackageSettings.size() == 0) { 15876 pw.println("No domain preferred apps!"); 15877 pw.println(); 15878 } else { 15879 pw.println("App verification status:"); 15880 pw.println(); 15881 count = 0; 15882 for (PackageSetting ps : allPackageSettings) { 15883 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 15884 if (ivi == null || ivi.getPackageName() == null) continue; 15885 pw.println(prefix + "Package: " + ivi.getPackageName()); 15886 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 15887 pw.println(prefix + "Status: " + ivi.getStatusString()); 15888 pw.println(); 15889 count++; 15890 } 15891 if (count == 0) { 15892 pw.println(prefix + "No app verification established."); 15893 pw.println(); 15894 } 15895 for (int userId : sUserManager.getUserIds()) { 15896 pw.println("App linkages for user " + userId + ":"); 15897 pw.println(); 15898 count = 0; 15899 for (PackageSetting ps : allPackageSettings) { 15900 final long status = ps.getDomainVerificationStatusForUser(userId); 15901 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 15902 continue; 15903 } 15904 pw.println(prefix + "Package: " + ps.name); 15905 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 15906 String statusStr = IntentFilterVerificationInfo. 15907 getStatusStringFromValue(status); 15908 pw.println(prefix + "Status: " + statusStr); 15909 pw.println(); 15910 count++; 15911 } 15912 if (count == 0) { 15913 pw.println(prefix + "No configured app linkages."); 15914 pw.println(); 15915 } 15916 } 15917 } 15918 } 15919 } 15920 15921 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 15922 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 15923 if (packageName == null && permissionNames == null) { 15924 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 15925 if (iperm == 0) { 15926 if (dumpState.onTitlePrinted()) 15927 pw.println(); 15928 pw.println("AppOp Permissions:"); 15929 } 15930 pw.print(" AppOp Permission "); 15931 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 15932 pw.println(":"); 15933 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 15934 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 15935 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 15936 } 15937 } 15938 } 15939 } 15940 15941 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 15942 boolean printedSomething = false; 15943 for (PackageParser.Provider p : mProviders.mProviders.values()) { 15944 if (packageName != null && !packageName.equals(p.info.packageName)) { 15945 continue; 15946 } 15947 if (!printedSomething) { 15948 if (dumpState.onTitlePrinted()) 15949 pw.println(); 15950 pw.println("Registered ContentProviders:"); 15951 printedSomething = true; 15952 } 15953 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 15954 pw.print(" "); pw.println(p.toString()); 15955 } 15956 printedSomething = false; 15957 for (Map.Entry<String, PackageParser.Provider> entry : 15958 mProvidersByAuthority.entrySet()) { 15959 PackageParser.Provider p = entry.getValue(); 15960 if (packageName != null && !packageName.equals(p.info.packageName)) { 15961 continue; 15962 } 15963 if (!printedSomething) { 15964 if (dumpState.onTitlePrinted()) 15965 pw.println(); 15966 pw.println("ContentProvider Authorities:"); 15967 printedSomething = true; 15968 } 15969 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 15970 pw.print(" "); pw.println(p.toString()); 15971 if (p.info != null && p.info.applicationInfo != null) { 15972 final String appInfo = p.info.applicationInfo.toString(); 15973 pw.print(" applicationInfo="); pw.println(appInfo); 15974 } 15975 } 15976 } 15977 15978 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 15979 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 15980 } 15981 15982 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 15983 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 15984 } 15985 15986 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 15987 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 15988 } 15989 15990 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 15991 // XXX should handle packageName != null by dumping only install data that 15992 // the given package is involved with. 15993 if (dumpState.onTitlePrinted()) pw.println(); 15994 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 15995 } 15996 15997 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 15998 if (dumpState.onTitlePrinted()) pw.println(); 15999 mSettings.dumpReadMessagesLPr(pw, dumpState); 16000 16001 pw.println(); 16002 pw.println("Package warning messages:"); 16003 BufferedReader in = null; 16004 String line = null; 16005 try { 16006 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 16007 while ((line = in.readLine()) != null) { 16008 if (line.contains("ignored: updated version")) continue; 16009 pw.println(line); 16010 } 16011 } catch (IOException ignored) { 16012 } finally { 16013 IoUtils.closeQuietly(in); 16014 } 16015 } 16016 16017 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 16018 BufferedReader in = null; 16019 String line = null; 16020 try { 16021 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 16022 while ((line = in.readLine()) != null) { 16023 if (line.contains("ignored: updated version")) continue; 16024 pw.print("msg,"); 16025 pw.println(line); 16026 } 16027 } catch (IOException ignored) { 16028 } finally { 16029 IoUtils.closeQuietly(in); 16030 } 16031 } 16032 } 16033 } 16034 16035 private String dumpDomainString(String packageName) { 16036 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName); 16037 List<IntentFilter> filters = getAllIntentFilters(packageName); 16038 16039 ArraySet<String> result = new ArraySet<>(); 16040 if (iviList.size() > 0) { 16041 for (IntentFilterVerificationInfo ivi : iviList) { 16042 for (String host : ivi.getDomains()) { 16043 result.add(host); 16044 } 16045 } 16046 } 16047 if (filters != null && filters.size() > 0) { 16048 for (IntentFilter filter : filters) { 16049 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 16050 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 16051 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 16052 result.addAll(filter.getHostsList()); 16053 } 16054 } 16055 } 16056 16057 StringBuilder sb = new StringBuilder(result.size() * 16); 16058 for (String domain : result) { 16059 if (sb.length() > 0) sb.append(" "); 16060 sb.append(domain); 16061 } 16062 return sb.toString(); 16063 } 16064 16065 // ------- apps on sdcard specific code ------- 16066 static final boolean DEBUG_SD_INSTALL = false; 16067 16068 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 16069 16070 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 16071 16072 private boolean mMediaMounted = false; 16073 16074 static String getEncryptKey() { 16075 try { 16076 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 16077 SD_ENCRYPTION_KEYSTORE_NAME); 16078 if (sdEncKey == null) { 16079 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 16080 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 16081 if (sdEncKey == null) { 16082 Slog.e(TAG, "Failed to create encryption keys"); 16083 return null; 16084 } 16085 } 16086 return sdEncKey; 16087 } catch (NoSuchAlgorithmException nsae) { 16088 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 16089 return null; 16090 } catch (IOException ioe) { 16091 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 16092 return null; 16093 } 16094 } 16095 16096 /* 16097 * Update media status on PackageManager. 16098 */ 16099 @Override 16100 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 16101 int callingUid = Binder.getCallingUid(); 16102 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 16103 throw new SecurityException("Media status can only be updated by the system"); 16104 } 16105 // reader; this apparently protects mMediaMounted, but should probably 16106 // be a different lock in that case. 16107 synchronized (mPackages) { 16108 Log.i(TAG, "Updating external media status from " 16109 + (mMediaMounted ? "mounted" : "unmounted") + " to " 16110 + (mediaStatus ? "mounted" : "unmounted")); 16111 if (DEBUG_SD_INSTALL) 16112 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 16113 + ", mMediaMounted=" + mMediaMounted); 16114 if (mediaStatus == mMediaMounted) { 16115 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 16116 : 0, -1); 16117 mHandler.sendMessage(msg); 16118 return; 16119 } 16120 mMediaMounted = mediaStatus; 16121 } 16122 // Queue up an async operation since the package installation may take a 16123 // little while. 16124 mHandler.post(new Runnable() { 16125 public void run() { 16126 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 16127 } 16128 }); 16129 } 16130 16131 /** 16132 * Called by MountService when the initial ASECs to scan are available. 16133 * Should block until all the ASEC containers are finished being scanned. 16134 */ 16135 public void scanAvailableAsecs() { 16136 updateExternalMediaStatusInner(true, false, false); 16137 if (mShouldRestoreconData) { 16138 SELinuxMMAC.setRestoreconDone(); 16139 mShouldRestoreconData = false; 16140 } 16141 } 16142 16143 /* 16144 * Collect information of applications on external media, map them against 16145 * existing containers and update information based on current mount status. 16146 * Please note that we always have to report status if reportStatus has been 16147 * set to true especially when unloading packages. 16148 */ 16149 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 16150 boolean externalStorage) { 16151 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 16152 int[] uidArr = EmptyArray.INT; 16153 16154 final String[] list = PackageHelper.getSecureContainerList(); 16155 if (ArrayUtils.isEmpty(list)) { 16156 Log.i(TAG, "No secure containers found"); 16157 } else { 16158 // Process list of secure containers and categorize them 16159 // as active or stale based on their package internal state. 16160 16161 // reader 16162 synchronized (mPackages) { 16163 for (String cid : list) { 16164 // Leave stages untouched for now; installer service owns them 16165 if (PackageInstallerService.isStageName(cid)) continue; 16166 16167 if (DEBUG_SD_INSTALL) 16168 Log.i(TAG, "Processing container " + cid); 16169 String pkgName = getAsecPackageName(cid); 16170 if (pkgName == null) { 16171 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 16172 continue; 16173 } 16174 if (DEBUG_SD_INSTALL) 16175 Log.i(TAG, "Looking for pkg : " + pkgName); 16176 16177 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16178 if (ps == null) { 16179 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 16180 continue; 16181 } 16182 16183 /* 16184 * Skip packages that are not external if we're unmounting 16185 * external storage. 16186 */ 16187 if (externalStorage && !isMounted && !isExternal(ps)) { 16188 continue; 16189 } 16190 16191 final AsecInstallArgs args = new AsecInstallArgs(cid, 16192 getAppDexInstructionSets(ps), ps.isForwardLocked()); 16193 // The package status is changed only if the code path 16194 // matches between settings and the container id. 16195 if (ps.codePathString != null 16196 && ps.codePathString.startsWith(args.getCodePath())) { 16197 if (DEBUG_SD_INSTALL) { 16198 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 16199 + " at code path: " + ps.codePathString); 16200 } 16201 16202 // We do have a valid package installed on sdcard 16203 processCids.put(args, ps.codePathString); 16204 final int uid = ps.appId; 16205 if (uid != -1) { 16206 uidArr = ArrayUtils.appendInt(uidArr, uid); 16207 } 16208 } else { 16209 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 16210 + ps.codePathString); 16211 } 16212 } 16213 } 16214 16215 Arrays.sort(uidArr); 16216 } 16217 16218 // Process packages with valid entries. 16219 if (isMounted) { 16220 if (DEBUG_SD_INSTALL) 16221 Log.i(TAG, "Loading packages"); 16222 loadMediaPackages(processCids, uidArr, externalStorage); 16223 startCleaningPackages(); 16224 mInstallerService.onSecureContainersAvailable(); 16225 } else { 16226 if (DEBUG_SD_INSTALL) 16227 Log.i(TAG, "Unloading packages"); 16228 unloadMediaPackages(processCids, uidArr, reportStatus); 16229 } 16230 } 16231 16232 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 16233 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 16234 final int size = infos.size(); 16235 final String[] packageNames = new String[size]; 16236 final int[] packageUids = new int[size]; 16237 for (int i = 0; i < size; i++) { 16238 final ApplicationInfo info = infos.get(i); 16239 packageNames[i] = info.packageName; 16240 packageUids[i] = info.uid; 16241 } 16242 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 16243 finishedReceiver); 16244 } 16245 16246 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 16247 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 16248 sendResourcesChangedBroadcast(mediaStatus, replacing, 16249 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 16250 } 16251 16252 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 16253 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 16254 int size = pkgList.length; 16255 if (size > 0) { 16256 // Send broadcasts here 16257 Bundle extras = new Bundle(); 16258 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 16259 if (uidArr != null) { 16260 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 16261 } 16262 if (replacing) { 16263 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 16264 } 16265 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 16266 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 16267 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 16268 } 16269 } 16270 16271 /* 16272 * Look at potentially valid container ids from processCids If package 16273 * information doesn't match the one on record or package scanning fails, 16274 * the cid is added to list of removeCids. We currently don't delete stale 16275 * containers. 16276 */ 16277 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 16278 boolean externalStorage) { 16279 ArrayList<String> pkgList = new ArrayList<String>(); 16280 Set<AsecInstallArgs> keys = processCids.keySet(); 16281 16282 for (AsecInstallArgs args : keys) { 16283 String codePath = processCids.get(args); 16284 if (DEBUG_SD_INSTALL) 16285 Log.i(TAG, "Loading container : " + args.cid); 16286 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 16287 try { 16288 // Make sure there are no container errors first. 16289 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 16290 Slog.e(TAG, "Failed to mount cid : " + args.cid 16291 + " when installing from sdcard"); 16292 continue; 16293 } 16294 // Check code path here. 16295 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 16296 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 16297 + " does not match one in settings " + codePath); 16298 continue; 16299 } 16300 // Parse package 16301 int parseFlags = mDefParseFlags; 16302 if (args.isExternalAsec()) { 16303 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 16304 } 16305 if (args.isFwdLocked()) { 16306 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 16307 } 16308 16309 synchronized (mInstallLock) { 16310 PackageParser.Package pkg = null; 16311 try { 16312 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null); 16313 } catch (PackageManagerException e) { 16314 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 16315 } 16316 // Scan the package 16317 if (pkg != null) { 16318 /* 16319 * TODO why is the lock being held? doPostInstall is 16320 * called in other places without the lock. This needs 16321 * to be straightened out. 16322 */ 16323 // writer 16324 synchronized (mPackages) { 16325 retCode = PackageManager.INSTALL_SUCCEEDED; 16326 pkgList.add(pkg.packageName); 16327 // Post process args 16328 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 16329 pkg.applicationInfo.uid); 16330 } 16331 } else { 16332 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 16333 } 16334 } 16335 16336 } finally { 16337 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 16338 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 16339 } 16340 } 16341 } 16342 // writer 16343 synchronized (mPackages) { 16344 // If the platform SDK has changed since the last time we booted, 16345 // we need to re-grant app permission to catch any new ones that 16346 // appear. This is really a hack, and means that apps can in some 16347 // cases get permissions that the user didn't initially explicitly 16348 // allow... it would be nice to have some better way to handle 16349 // this situation. 16350 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 16351 : mSettings.getInternalVersion(); 16352 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 16353 : StorageManager.UUID_PRIVATE_INTERNAL; 16354 16355 int updateFlags = UPDATE_PERMISSIONS_ALL; 16356 if (ver.sdkVersion != mSdkVersion) { 16357 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 16358 + mSdkVersion + "; regranting permissions for external"); 16359 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 16360 } 16361 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 16362 16363 // Yay, everything is now upgraded 16364 ver.forceCurrent(); 16365 16366 // can downgrade to reader 16367 // Persist settings 16368 mSettings.writeLPr(); 16369 } 16370 // Send a broadcast to let everyone know we are done processing 16371 if (pkgList.size() > 0) { 16372 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 16373 } 16374 } 16375 16376 /* 16377 * Utility method to unload a list of specified containers 16378 */ 16379 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 16380 // Just unmount all valid containers. 16381 for (AsecInstallArgs arg : cidArgs) { 16382 synchronized (mInstallLock) { 16383 arg.doPostDeleteLI(false); 16384 } 16385 } 16386 } 16387 16388 /* 16389 * Unload packages mounted on external media. This involves deleting package 16390 * data from internal structures, sending broadcasts about diabled packages, 16391 * gc'ing to free up references, unmounting all secure containers 16392 * corresponding to packages on external media, and posting a 16393 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 16394 * that we always have to post this message if status has been requested no 16395 * matter what. 16396 */ 16397 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 16398 final boolean reportStatus) { 16399 if (DEBUG_SD_INSTALL) 16400 Log.i(TAG, "unloading media packages"); 16401 ArrayList<String> pkgList = new ArrayList<String>(); 16402 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 16403 final Set<AsecInstallArgs> keys = processCids.keySet(); 16404 for (AsecInstallArgs args : keys) { 16405 String pkgName = args.getPackageName(); 16406 if (DEBUG_SD_INSTALL) 16407 Log.i(TAG, "Trying to unload pkg : " + pkgName); 16408 // Delete package internally 16409 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 16410 synchronized (mInstallLock) { 16411 boolean res = deletePackageLI(pkgName, null, false, null, null, 16412 PackageManager.DELETE_KEEP_DATA, outInfo, false); 16413 if (res) { 16414 pkgList.add(pkgName); 16415 } else { 16416 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 16417 failedList.add(args); 16418 } 16419 } 16420 } 16421 16422 // reader 16423 synchronized (mPackages) { 16424 // We didn't update the settings after removing each package; 16425 // write them now for all packages. 16426 mSettings.writeLPr(); 16427 } 16428 16429 // We have to absolutely send UPDATED_MEDIA_STATUS only 16430 // after confirming that all the receivers processed the ordered 16431 // broadcast when packages get disabled, force a gc to clean things up. 16432 // and unload all the containers. 16433 if (pkgList.size() > 0) { 16434 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 16435 new IIntentReceiver.Stub() { 16436 public void performReceive(Intent intent, int resultCode, String data, 16437 Bundle extras, boolean ordered, boolean sticky, 16438 int sendingUser) throws RemoteException { 16439 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 16440 reportStatus ? 1 : 0, 1, keys); 16441 mHandler.sendMessage(msg); 16442 } 16443 }); 16444 } else { 16445 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 16446 keys); 16447 mHandler.sendMessage(msg); 16448 } 16449 } 16450 16451 private void loadPrivatePackages(final VolumeInfo vol) { 16452 mHandler.post(new Runnable() { 16453 @Override 16454 public void run() { 16455 loadPrivatePackagesInner(vol); 16456 } 16457 }); 16458 } 16459 16460 private void loadPrivatePackagesInner(VolumeInfo vol) { 16461 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 16462 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 16463 16464 final VersionInfo ver; 16465 final List<PackageSetting> packages; 16466 synchronized (mPackages) { 16467 ver = mSettings.findOrCreateVersion(vol.fsUuid); 16468 packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 16469 } 16470 16471 for (PackageSetting ps : packages) { 16472 synchronized (mInstallLock) { 16473 final PackageParser.Package pkg; 16474 try { 16475 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 16476 loaded.add(pkg.applicationInfo); 16477 } catch (PackageManagerException e) { 16478 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 16479 } 16480 16481 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 16482 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 16483 } 16484 } 16485 } 16486 16487 synchronized (mPackages) { 16488 int updateFlags = UPDATE_PERMISSIONS_ALL; 16489 if (ver.sdkVersion != mSdkVersion) { 16490 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 16491 + mSdkVersion + "; regranting permissions for " + vol.fsUuid); 16492 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 16493 } 16494 updatePermissionsLPw(null, null, vol.fsUuid, updateFlags); 16495 16496 // Yay, everything is now upgraded 16497 ver.forceCurrent(); 16498 16499 mSettings.writeLPr(); 16500 } 16501 16502 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 16503 sendResourcesChangedBroadcast(true, false, loaded, null); 16504 } 16505 16506 private void unloadPrivatePackages(final VolumeInfo vol) { 16507 mHandler.post(new Runnable() { 16508 @Override 16509 public void run() { 16510 unloadPrivatePackagesInner(vol); 16511 } 16512 }); 16513 } 16514 16515 private void unloadPrivatePackagesInner(VolumeInfo vol) { 16516 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 16517 synchronized (mInstallLock) { 16518 synchronized (mPackages) { 16519 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 16520 for (PackageSetting ps : packages) { 16521 if (ps.pkg == null) continue; 16522 16523 final ApplicationInfo info = ps.pkg.applicationInfo; 16524 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 16525 if (deletePackageLI(ps.name, null, false, null, null, 16526 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 16527 unloaded.add(info); 16528 } else { 16529 Slog.w(TAG, "Failed to unload " + ps.codePath); 16530 } 16531 } 16532 16533 mSettings.writeLPr(); 16534 } 16535 } 16536 16537 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 16538 sendResourcesChangedBroadcast(false, false, unloaded, null); 16539 } 16540 16541 /** 16542 * Examine all users present on given mounted volume, and destroy data 16543 * belonging to users that are no longer valid, or whose user ID has been 16544 * recycled. 16545 */ 16546 private void reconcileUsers(String volumeUuid) { 16547 final File[] files = FileUtils 16548 .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid)); 16549 for (File file : files) { 16550 if (!file.isDirectory()) continue; 16551 16552 final int userId; 16553 final UserInfo info; 16554 try { 16555 userId = Integer.parseInt(file.getName()); 16556 info = sUserManager.getUserInfo(userId); 16557 } catch (NumberFormatException e) { 16558 Slog.w(TAG, "Invalid user directory " + file); 16559 continue; 16560 } 16561 16562 boolean destroyUser = false; 16563 if (info == null) { 16564 logCriticalInfo(Log.WARN, "Destroying user directory " + file 16565 + " because no matching user was found"); 16566 destroyUser = true; 16567 } else { 16568 try { 16569 UserManagerService.enforceSerialNumber(file, info.serialNumber); 16570 } catch (IOException e) { 16571 logCriticalInfo(Log.WARN, "Destroying user directory " + file 16572 + " because we failed to enforce serial number: " + e); 16573 destroyUser = true; 16574 } 16575 } 16576 16577 if (destroyUser) { 16578 synchronized (mInstallLock) { 16579 mInstaller.removeUserDataDirs(volumeUuid, userId); 16580 } 16581 } 16582 } 16583 16584 final StorageManager sm = mContext.getSystemService(StorageManager.class); 16585 final UserManager um = mContext.getSystemService(UserManager.class); 16586 for (UserInfo user : um.getUsers()) { 16587 final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id); 16588 if (userDir.exists()) continue; 16589 16590 try { 16591 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, user.isEphemeral()); 16592 UserManagerService.enforceSerialNumber(userDir, user.serialNumber); 16593 } catch (IOException e) { 16594 Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e); 16595 } 16596 } 16597 } 16598 16599 /** 16600 * Examine all apps present on given mounted volume, and destroy apps that 16601 * aren't expected, either due to uninstallation or reinstallation on 16602 * another volume. 16603 */ 16604 private void reconcileApps(String volumeUuid) { 16605 final File[] files = FileUtils 16606 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 16607 for (File file : files) { 16608 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 16609 && !PackageInstallerService.isStageName(file.getName()); 16610 if (!isPackage) { 16611 // Ignore entries which are not packages 16612 continue; 16613 } 16614 16615 boolean destroyApp = false; 16616 String packageName = null; 16617 try { 16618 final PackageLite pkg = PackageParser.parsePackageLite(file, 16619 PackageParser.PARSE_MUST_BE_APK); 16620 packageName = pkg.packageName; 16621 16622 synchronized (mPackages) { 16623 final PackageSetting ps = mSettings.mPackages.get(packageName); 16624 if (ps == null) { 16625 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + " 16626 + volumeUuid + " because we found no install record"); 16627 destroyApp = true; 16628 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 16629 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on " 16630 + volumeUuid + " because we expected it on " + ps.volumeUuid); 16631 destroyApp = true; 16632 } 16633 } 16634 16635 } catch (PackageParserException e) { 16636 logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e); 16637 destroyApp = true; 16638 } 16639 16640 if (destroyApp) { 16641 synchronized (mInstallLock) { 16642 if (packageName != null) { 16643 removeDataDirsLI(volumeUuid, packageName); 16644 } 16645 if (file.isDirectory()) { 16646 mInstaller.rmPackageDir(file.getAbsolutePath()); 16647 } else { 16648 file.delete(); 16649 } 16650 } 16651 } 16652 } 16653 } 16654 16655 private void unfreezePackage(String packageName) { 16656 synchronized (mPackages) { 16657 final PackageSetting ps = mSettings.mPackages.get(packageName); 16658 if (ps != null) { 16659 ps.frozen = false; 16660 } 16661 } 16662 } 16663 16664 @Override 16665 public int movePackage(final String packageName, final String volumeUuid) { 16666 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 16667 16668 final int moveId = mNextMoveId.getAndIncrement(); 16669 mHandler.post(new Runnable() { 16670 @Override 16671 public void run() { 16672 try { 16673 movePackageInternal(packageName, volumeUuid, moveId); 16674 } catch (PackageManagerException e) { 16675 Slog.w(TAG, "Failed to move " + packageName, e); 16676 mMoveCallbacks.notifyStatusChanged(moveId, 16677 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 16678 } 16679 } 16680 }); 16681 return moveId; 16682 } 16683 16684 private void movePackageInternal(final String packageName, final String volumeUuid, 16685 final int moveId) throws PackageManagerException { 16686 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 16687 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16688 final PackageManager pm = mContext.getPackageManager(); 16689 16690 final boolean currentAsec; 16691 final String currentVolumeUuid; 16692 final File codeFile; 16693 final String installerPackageName; 16694 final String packageAbiOverride; 16695 final int appId; 16696 final String seinfo; 16697 final String label; 16698 16699 // reader 16700 synchronized (mPackages) { 16701 final PackageParser.Package pkg = mPackages.get(packageName); 16702 final PackageSetting ps = mSettings.mPackages.get(packageName); 16703 if (pkg == null || ps == null) { 16704 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 16705 } 16706 16707 if (pkg.applicationInfo.isSystemApp()) { 16708 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 16709 "Cannot move system application"); 16710 } 16711 16712 if (pkg.applicationInfo.isExternalAsec()) { 16713 currentAsec = true; 16714 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 16715 } else if (pkg.applicationInfo.isForwardLocked()) { 16716 currentAsec = true; 16717 currentVolumeUuid = "forward_locked"; 16718 } else { 16719 currentAsec = false; 16720 currentVolumeUuid = ps.volumeUuid; 16721 16722 final File probe = new File(pkg.codePath); 16723 final File probeOat = new File(probe, "oat"); 16724 if (!probe.isDirectory() || !probeOat.isDirectory()) { 16725 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16726 "Move only supported for modern cluster style installs"); 16727 } 16728 } 16729 16730 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 16731 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16732 "Package already moved to " + volumeUuid); 16733 } 16734 16735 if (ps.frozen) { 16736 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 16737 "Failed to move already frozen package"); 16738 } 16739 ps.frozen = true; 16740 16741 codeFile = new File(pkg.codePath); 16742 installerPackageName = ps.installerPackageName; 16743 packageAbiOverride = ps.cpuAbiOverrideString; 16744 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16745 seinfo = pkg.applicationInfo.seinfo; 16746 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 16747 } 16748 16749 // Now that we're guarded by frozen state, kill app during move 16750 final long token = Binder.clearCallingIdentity(); 16751 try { 16752 killApplication(packageName, appId, "move pkg"); 16753 } finally { 16754 Binder.restoreCallingIdentity(token); 16755 } 16756 16757 final Bundle extras = new Bundle(); 16758 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 16759 extras.putString(Intent.EXTRA_TITLE, label); 16760 mMoveCallbacks.notifyCreated(moveId, extras); 16761 16762 int installFlags; 16763 final boolean moveCompleteApp; 16764 final File measurePath; 16765 16766 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 16767 installFlags = INSTALL_INTERNAL; 16768 moveCompleteApp = !currentAsec; 16769 measurePath = Environment.getDataAppDirectory(volumeUuid); 16770 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 16771 installFlags = INSTALL_EXTERNAL; 16772 moveCompleteApp = false; 16773 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 16774 } else { 16775 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 16776 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 16777 || !volume.isMountedWritable()) { 16778 unfreezePackage(packageName); 16779 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16780 "Move location not mounted private volume"); 16781 } 16782 16783 Preconditions.checkState(!currentAsec); 16784 16785 installFlags = INSTALL_INTERNAL; 16786 moveCompleteApp = true; 16787 measurePath = Environment.getDataAppDirectory(volumeUuid); 16788 } 16789 16790 final PackageStats stats = new PackageStats(null, -1); 16791 synchronized (mInstaller) { 16792 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 16793 unfreezePackage(packageName); 16794 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16795 "Failed to measure package size"); 16796 } 16797 } 16798 16799 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 16800 + stats.dataSize); 16801 16802 final long startFreeBytes = measurePath.getFreeSpace(); 16803 final long sizeBytes; 16804 if (moveCompleteApp) { 16805 sizeBytes = stats.codeSize + stats.dataSize; 16806 } else { 16807 sizeBytes = stats.codeSize; 16808 } 16809 16810 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 16811 unfreezePackage(packageName); 16812 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16813 "Not enough free space to move"); 16814 } 16815 16816 mMoveCallbacks.notifyStatusChanged(moveId, 10); 16817 16818 final CountDownLatch installedLatch = new CountDownLatch(1); 16819 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 16820 @Override 16821 public void onUserActionRequired(Intent intent) throws RemoteException { 16822 throw new IllegalStateException(); 16823 } 16824 16825 @Override 16826 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 16827 Bundle extras) throws RemoteException { 16828 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 16829 + PackageManager.installStatusToString(returnCode, msg)); 16830 16831 installedLatch.countDown(); 16832 16833 // Regardless of success or failure of the move operation, 16834 // always unfreeze the package 16835 unfreezePackage(packageName); 16836 16837 final int status = PackageManager.installStatusToPublicStatus(returnCode); 16838 switch (status) { 16839 case PackageInstaller.STATUS_SUCCESS: 16840 mMoveCallbacks.notifyStatusChanged(moveId, 16841 PackageManager.MOVE_SUCCEEDED); 16842 break; 16843 case PackageInstaller.STATUS_FAILURE_STORAGE: 16844 mMoveCallbacks.notifyStatusChanged(moveId, 16845 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 16846 break; 16847 default: 16848 mMoveCallbacks.notifyStatusChanged(moveId, 16849 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 16850 break; 16851 } 16852 } 16853 }; 16854 16855 final MoveInfo move; 16856 if (moveCompleteApp) { 16857 // Kick off a thread to report progress estimates 16858 new Thread() { 16859 @Override 16860 public void run() { 16861 while (true) { 16862 try { 16863 if (installedLatch.await(1, TimeUnit.SECONDS)) { 16864 break; 16865 } 16866 } catch (InterruptedException ignored) { 16867 } 16868 16869 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 16870 final int progress = 10 + (int) MathUtils.constrain( 16871 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 16872 mMoveCallbacks.notifyStatusChanged(moveId, progress); 16873 } 16874 } 16875 }.start(); 16876 16877 final String dataAppName = codeFile.getName(); 16878 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 16879 dataAppName, appId, seinfo); 16880 } else { 16881 move = null; 16882 } 16883 16884 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 16885 16886 final Message msg = mHandler.obtainMessage(INIT_COPY); 16887 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 16888 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 16889 installerPackageName, volumeUuid, null, user, packageAbiOverride, null); 16890 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 16891 msg.obj = params; 16892 16893 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 16894 System.identityHashCode(msg.obj)); 16895 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 16896 System.identityHashCode(msg.obj)); 16897 16898 mHandler.sendMessage(msg); 16899 } 16900 16901 @Override 16902 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 16903 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 16904 16905 final int realMoveId = mNextMoveId.getAndIncrement(); 16906 final Bundle extras = new Bundle(); 16907 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 16908 mMoveCallbacks.notifyCreated(realMoveId, extras); 16909 16910 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 16911 @Override 16912 public void onCreated(int moveId, Bundle extras) { 16913 // Ignored 16914 } 16915 16916 @Override 16917 public void onStatusChanged(int moveId, int status, long estMillis) { 16918 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 16919 } 16920 }; 16921 16922 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16923 storage.setPrimaryStorageUuid(volumeUuid, callback); 16924 return realMoveId; 16925 } 16926 16927 @Override 16928 public int getMoveStatus(int moveId) { 16929 mContext.enforceCallingOrSelfPermission( 16930 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16931 return mMoveCallbacks.mLastStatus.get(moveId); 16932 } 16933 16934 @Override 16935 public void registerMoveCallback(IPackageMoveObserver callback) { 16936 mContext.enforceCallingOrSelfPermission( 16937 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16938 mMoveCallbacks.register(callback); 16939 } 16940 16941 @Override 16942 public void unregisterMoveCallback(IPackageMoveObserver callback) { 16943 mContext.enforceCallingOrSelfPermission( 16944 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16945 mMoveCallbacks.unregister(callback); 16946 } 16947 16948 @Override 16949 public boolean setInstallLocation(int loc) { 16950 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 16951 null); 16952 if (getInstallLocation() == loc) { 16953 return true; 16954 } 16955 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 16956 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 16957 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 16958 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 16959 return true; 16960 } 16961 return false; 16962 } 16963 16964 @Override 16965 public int getInstallLocation() { 16966 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 16967 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 16968 PackageHelper.APP_INSTALL_AUTO); 16969 } 16970 16971 /** Called by UserManagerService */ 16972 void cleanUpUser(UserManagerService userManager, int userHandle) { 16973 synchronized (mPackages) { 16974 mDirtyUsers.remove(userHandle); 16975 mUserNeedsBadging.delete(userHandle); 16976 mSettings.removeUserLPw(userHandle); 16977 mPendingBroadcasts.remove(userHandle); 16978 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 16979 } 16980 synchronized (mInstallLock) { 16981 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16982 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 16983 final String volumeUuid = vol.getFsUuid(); 16984 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 16985 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 16986 } 16987 synchronized (mPackages) { 16988 removeUnusedPackagesLILPw(userManager, userHandle); 16989 } 16990 } 16991 } 16992 16993 /** 16994 * We're removing userHandle and would like to remove any downloaded packages 16995 * that are no longer in use by any other user. 16996 * @param userHandle the user being removed 16997 */ 16998 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 16999 final boolean DEBUG_CLEAN_APKS = false; 17000 int [] users = userManager.getUserIds(); 17001 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 17002 while (psit.hasNext()) { 17003 PackageSetting ps = psit.next(); 17004 if (ps.pkg == null) { 17005 continue; 17006 } 17007 final String packageName = ps.pkg.packageName; 17008 // Skip over if system app 17009 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 17010 continue; 17011 } 17012 if (DEBUG_CLEAN_APKS) { 17013 Slog.i(TAG, "Checking package " + packageName); 17014 } 17015 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 17016 if (keep) { 17017 if (DEBUG_CLEAN_APKS) { 17018 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 17019 } 17020 } else { 17021 for (int i = 0; i < users.length; i++) { 17022 if (users[i] != userHandle && ps.getInstalled(users[i])) { 17023 keep = true; 17024 if (DEBUG_CLEAN_APKS) { 17025 Slog.i(TAG, " Keeping package " + packageName + " for user " 17026 + users[i]); 17027 } 17028 break; 17029 } 17030 } 17031 } 17032 if (!keep) { 17033 if (DEBUG_CLEAN_APKS) { 17034 Slog.i(TAG, " Removing package " + packageName); 17035 } 17036 mHandler.post(new Runnable() { 17037 public void run() { 17038 deletePackageX(packageName, userHandle, 0); 17039 } //end run 17040 }); 17041 } 17042 } 17043 } 17044 17045 /** Called by UserManagerService */ 17046 void createNewUser(int userHandle) { 17047 synchronized (mInstallLock) { 17048 mInstaller.createUserConfig(userHandle); 17049 mSettings.createNewUserLI(this, mInstaller, userHandle); 17050 } 17051 synchronized (mPackages) { 17052 applyFactoryDefaultBrowserLPw(userHandle); 17053 primeDomainVerificationsLPw(userHandle); 17054 } 17055 } 17056 17057 void newUserCreated(final int userHandle) { 17058 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 17059 // If permission review for legacy apps is required, we represent 17060 // dagerous permissions for such apps as always granted runtime 17061 // permissions to keep per user flag state whether review is needed. 17062 // Hence, if a new user is added we have to propagate dangerous 17063 // permission grants for these legacy apps. 17064 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 17065 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 17066 | UPDATE_PERMISSIONS_REPLACE_ALL); 17067 } 17068 } 17069 17070 @Override 17071 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 17072 mContext.enforceCallingOrSelfPermission( 17073 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 17074 "Only package verification agents can read the verifier device identity"); 17075 17076 synchronized (mPackages) { 17077 return mSettings.getVerifierDeviceIdentityLPw(); 17078 } 17079 } 17080 17081 @Override 17082 public void setPermissionEnforced(String permission, boolean enforced) { 17083 // TODO: Now that we no longer change GID for storage, this should to away. 17084 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 17085 "setPermissionEnforced"); 17086 if (READ_EXTERNAL_STORAGE.equals(permission)) { 17087 synchronized (mPackages) { 17088 if (mSettings.mReadExternalStorageEnforced == null 17089 || mSettings.mReadExternalStorageEnforced != enforced) { 17090 mSettings.mReadExternalStorageEnforced = enforced; 17091 mSettings.writeLPr(); 17092 } 17093 } 17094 // kill any non-foreground processes so we restart them and 17095 // grant/revoke the GID. 17096 final IActivityManager am = ActivityManagerNative.getDefault(); 17097 if (am != null) { 17098 final long token = Binder.clearCallingIdentity(); 17099 try { 17100 am.killProcessesBelowForeground("setPermissionEnforcement"); 17101 } catch (RemoteException e) { 17102 } finally { 17103 Binder.restoreCallingIdentity(token); 17104 } 17105 } 17106 } else { 17107 throw new IllegalArgumentException("No selective enforcement for " + permission); 17108 } 17109 } 17110 17111 @Override 17112 @Deprecated 17113 public boolean isPermissionEnforced(String permission) { 17114 return true; 17115 } 17116 17117 @Override 17118 public boolean isStorageLow() { 17119 final long token = Binder.clearCallingIdentity(); 17120 try { 17121 final DeviceStorageMonitorInternal 17122 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 17123 if (dsm != null) { 17124 return dsm.isMemoryLow(); 17125 } else { 17126 return false; 17127 } 17128 } finally { 17129 Binder.restoreCallingIdentity(token); 17130 } 17131 } 17132 17133 @Override 17134 public IPackageInstaller getPackageInstaller() { 17135 return mInstallerService; 17136 } 17137 17138 private boolean userNeedsBadging(int userId) { 17139 int index = mUserNeedsBadging.indexOfKey(userId); 17140 if (index < 0) { 17141 final UserInfo userInfo; 17142 final long token = Binder.clearCallingIdentity(); 17143 try { 17144 userInfo = sUserManager.getUserInfo(userId); 17145 } finally { 17146 Binder.restoreCallingIdentity(token); 17147 } 17148 final boolean b; 17149 if (userInfo != null && userInfo.isManagedProfile()) { 17150 b = true; 17151 } else { 17152 b = false; 17153 } 17154 mUserNeedsBadging.put(userId, b); 17155 return b; 17156 } 17157 return mUserNeedsBadging.valueAt(index); 17158 } 17159 17160 @Override 17161 public KeySet getKeySetByAlias(String packageName, String alias) { 17162 if (packageName == null || alias == null) { 17163 return null; 17164 } 17165 synchronized(mPackages) { 17166 final PackageParser.Package pkg = mPackages.get(packageName); 17167 if (pkg == null) { 17168 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 17169 throw new IllegalArgumentException("Unknown package: " + packageName); 17170 } 17171 KeySetManagerService ksms = mSettings.mKeySetManagerService; 17172 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 17173 } 17174 } 17175 17176 @Override 17177 public KeySet getSigningKeySet(String packageName) { 17178 if (packageName == null) { 17179 return null; 17180 } 17181 synchronized(mPackages) { 17182 final PackageParser.Package pkg = mPackages.get(packageName); 17183 if (pkg == null) { 17184 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 17185 throw new IllegalArgumentException("Unknown package: " + packageName); 17186 } 17187 if (pkg.applicationInfo.uid != Binder.getCallingUid() 17188 && Process.SYSTEM_UID != Binder.getCallingUid()) { 17189 throw new SecurityException("May not access signing KeySet of other apps."); 17190 } 17191 KeySetManagerService ksms = mSettings.mKeySetManagerService; 17192 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 17193 } 17194 } 17195 17196 @Override 17197 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 17198 if (packageName == null || ks == null) { 17199 return false; 17200 } 17201 synchronized(mPackages) { 17202 final PackageParser.Package pkg = mPackages.get(packageName); 17203 if (pkg == null) { 17204 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 17205 throw new IllegalArgumentException("Unknown package: " + packageName); 17206 } 17207 IBinder ksh = ks.getToken(); 17208 if (ksh instanceof KeySetHandle) { 17209 KeySetManagerService ksms = mSettings.mKeySetManagerService; 17210 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 17211 } 17212 return false; 17213 } 17214 } 17215 17216 @Override 17217 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 17218 if (packageName == null || ks == null) { 17219 return false; 17220 } 17221 synchronized(mPackages) { 17222 final PackageParser.Package pkg = mPackages.get(packageName); 17223 if (pkg == null) { 17224 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 17225 throw new IllegalArgumentException("Unknown package: " + packageName); 17226 } 17227 IBinder ksh = ks.getToken(); 17228 if (ksh instanceof KeySetHandle) { 17229 KeySetManagerService ksms = mSettings.mKeySetManagerService; 17230 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 17231 } 17232 return false; 17233 } 17234 } 17235 17236 private void deletePackageIfUnusedLPr(final String packageName) { 17237 PackageSetting ps = mSettings.mPackages.get(packageName); 17238 if (ps == null) { 17239 return; 17240 } 17241 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 17242 // TODO Implement atomic delete if package is unused 17243 // It is currently possible that the package will be deleted even if it is installed 17244 // after this method returns. 17245 mHandler.post(new Runnable() { 17246 public void run() { 17247 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 17248 } 17249 }); 17250 } 17251 } 17252 17253 /** 17254 * Check and throw if the given before/after packages would be considered a 17255 * downgrade. 17256 */ 17257 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 17258 throws PackageManagerException { 17259 if (after.versionCode < before.mVersionCode) { 17260 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 17261 "Update version code " + after.versionCode + " is older than current " 17262 + before.mVersionCode); 17263 } else if (after.versionCode == before.mVersionCode) { 17264 if (after.baseRevisionCode < before.baseRevisionCode) { 17265 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 17266 "Update base revision code " + after.baseRevisionCode 17267 + " is older than current " + before.baseRevisionCode); 17268 } 17269 17270 if (!ArrayUtils.isEmpty(after.splitNames)) { 17271 for (int i = 0; i < after.splitNames.length; i++) { 17272 final String splitName = after.splitNames[i]; 17273 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 17274 if (j != -1) { 17275 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 17276 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 17277 "Update split " + splitName + " revision code " 17278 + after.splitRevisionCodes[i] + " is older than current " 17279 + before.splitRevisionCodes[j]); 17280 } 17281 } 17282 } 17283 } 17284 } 17285 } 17286 17287 private static class MoveCallbacks extends Handler { 17288 private static final int MSG_CREATED = 1; 17289 private static final int MSG_STATUS_CHANGED = 2; 17290 17291 private final RemoteCallbackList<IPackageMoveObserver> 17292 mCallbacks = new RemoteCallbackList<>(); 17293 17294 private final SparseIntArray mLastStatus = new SparseIntArray(); 17295 17296 public MoveCallbacks(Looper looper) { 17297 super(looper); 17298 } 17299 17300 public void register(IPackageMoveObserver callback) { 17301 mCallbacks.register(callback); 17302 } 17303 17304 public void unregister(IPackageMoveObserver callback) { 17305 mCallbacks.unregister(callback); 17306 } 17307 17308 @Override 17309 public void handleMessage(Message msg) { 17310 final SomeArgs args = (SomeArgs) msg.obj; 17311 final int n = mCallbacks.beginBroadcast(); 17312 for (int i = 0; i < n; i++) { 17313 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 17314 try { 17315 invokeCallback(callback, msg.what, args); 17316 } catch (RemoteException ignored) { 17317 } 17318 } 17319 mCallbacks.finishBroadcast(); 17320 args.recycle(); 17321 } 17322 17323 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 17324 throws RemoteException { 17325 switch (what) { 17326 case MSG_CREATED: { 17327 callback.onCreated(args.argi1, (Bundle) args.arg2); 17328 break; 17329 } 17330 case MSG_STATUS_CHANGED: { 17331 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 17332 break; 17333 } 17334 } 17335 } 17336 17337 private void notifyCreated(int moveId, Bundle extras) { 17338 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 17339 17340 final SomeArgs args = SomeArgs.obtain(); 17341 args.argi1 = moveId; 17342 args.arg2 = extras; 17343 obtainMessage(MSG_CREATED, args).sendToTarget(); 17344 } 17345 17346 private void notifyStatusChanged(int moveId, int status) { 17347 notifyStatusChanged(moveId, status, -1); 17348 } 17349 17350 private void notifyStatusChanged(int moveId, int status, long estMillis) { 17351 Slog.v(TAG, "Move " + moveId + " status " + status); 17352 17353 final SomeArgs args = SomeArgs.obtain(); 17354 args.argi1 = moveId; 17355 args.argi2 = status; 17356 args.arg3 = estMillis; 17357 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 17358 17359 synchronized (mLastStatus) { 17360 mLastStatus.put(moveId, status); 17361 } 17362 } 17363 } 17364 17365 private final static class OnPermissionChangeListeners extends Handler { 17366 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 17367 17368 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 17369 new RemoteCallbackList<>(); 17370 17371 public OnPermissionChangeListeners(Looper looper) { 17372 super(looper); 17373 } 17374 17375 @Override 17376 public void handleMessage(Message msg) { 17377 switch (msg.what) { 17378 case MSG_ON_PERMISSIONS_CHANGED: { 17379 final int uid = msg.arg1; 17380 handleOnPermissionsChanged(uid); 17381 } break; 17382 } 17383 } 17384 17385 public void addListenerLocked(IOnPermissionsChangeListener listener) { 17386 mPermissionListeners.register(listener); 17387 17388 } 17389 17390 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 17391 mPermissionListeners.unregister(listener); 17392 } 17393 17394 public void onPermissionsChanged(int uid) { 17395 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 17396 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 17397 } 17398 } 17399 17400 private void handleOnPermissionsChanged(int uid) { 17401 final int count = mPermissionListeners.beginBroadcast(); 17402 try { 17403 for (int i = 0; i < count; i++) { 17404 IOnPermissionsChangeListener callback = mPermissionListeners 17405 .getBroadcastItem(i); 17406 try { 17407 callback.onPermissionsChanged(uid); 17408 } catch (RemoteException e) { 17409 Log.e(TAG, "Permission listener is dead", e); 17410 } 17411 } 17412 } finally { 17413 mPermissionListeners.finishBroadcast(); 17414 } 17415 } 17416 } 17417 17418 private class PackageManagerInternalImpl extends PackageManagerInternal { 17419 @Override 17420 public void setLocationPackagesProvider(PackagesProvider provider) { 17421 synchronized (mPackages) { 17422 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 17423 } 17424 } 17425 17426 @Override 17427 public void setImePackagesProvider(PackagesProvider provider) { 17428 synchronized (mPackages) { 17429 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 17430 } 17431 } 17432 17433 @Override 17434 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 17435 synchronized (mPackages) { 17436 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 17437 } 17438 } 17439 17440 @Override 17441 public void setSmsAppPackagesProvider(PackagesProvider provider) { 17442 synchronized (mPackages) { 17443 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 17444 } 17445 } 17446 17447 @Override 17448 public void setDialerAppPackagesProvider(PackagesProvider provider) { 17449 synchronized (mPackages) { 17450 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 17451 } 17452 } 17453 17454 @Override 17455 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 17456 synchronized (mPackages) { 17457 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 17458 } 17459 } 17460 17461 @Override 17462 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 17463 synchronized (mPackages) { 17464 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 17465 } 17466 } 17467 17468 @Override 17469 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 17470 synchronized (mPackages) { 17471 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 17472 packageName, userId); 17473 } 17474 } 17475 17476 @Override 17477 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 17478 synchronized (mPackages) { 17479 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 17480 packageName, userId); 17481 } 17482 } 17483 17484 @Override 17485 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 17486 synchronized (mPackages) { 17487 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 17488 packageName, userId); 17489 } 17490 } 17491 17492 @Override 17493 public void setKeepUninstalledPackages(final List<String> packageList) { 17494 Preconditions.checkNotNull(packageList); 17495 List<String> removedFromList = null; 17496 synchronized (mPackages) { 17497 if (mKeepUninstalledPackages != null) { 17498 final int packagesCount = mKeepUninstalledPackages.size(); 17499 for (int i = 0; i < packagesCount; i++) { 17500 String oldPackage = mKeepUninstalledPackages.get(i); 17501 if (packageList != null && packageList.contains(oldPackage)) { 17502 continue; 17503 } 17504 if (removedFromList == null) { 17505 removedFromList = new ArrayList<>(); 17506 } 17507 removedFromList.add(oldPackage); 17508 } 17509 } 17510 mKeepUninstalledPackages = new ArrayList<>(packageList); 17511 if (removedFromList != null) { 17512 final int removedCount = removedFromList.size(); 17513 for (int i = 0; i < removedCount; i++) { 17514 deletePackageIfUnusedLPr(removedFromList.get(i)); 17515 } 17516 } 17517 } 17518 } 17519 17520 @Override 17521 public boolean isPermissionsReviewRequired(String packageName, int userId) { 17522 synchronized (mPackages) { 17523 // If we do not support permission review, done. 17524 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 17525 return false; 17526 } 17527 17528 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 17529 if (packageSetting == null) { 17530 return false; 17531 } 17532 17533 // Permission review applies only to apps not supporting the new permission model. 17534 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 17535 return false; 17536 } 17537 17538 // Legacy apps have the permission and get user consent on launch. 17539 PermissionsState permissionsState = packageSetting.getPermissionsState(); 17540 return permissionsState.isPermissionReviewRequired(userId); 17541 } 17542 } 17543 } 17544 17545 @Override 17546 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 17547 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 17548 synchronized (mPackages) { 17549 final long identity = Binder.clearCallingIdentity(); 17550 try { 17551 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 17552 packageNames, userId); 17553 } finally { 17554 Binder.restoreCallingIdentity(identity); 17555 } 17556 } 17557 } 17558 17559 private static void enforceSystemOrPhoneCaller(String tag) { 17560 int callingUid = Binder.getCallingUid(); 17561 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 17562 throw new SecurityException( 17563 "Cannot call " + tag + " from UID " + callingUid); 17564 } 17565 } 17566} 17567