PackageManagerService.java revision 373f0b4313d3a2444aebf6b89a71c4ba64566110
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 // Ephemeral apps don't get the full verification treatment 10446 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 10447 if (DEBUG_EPHEMERAL) { 10448 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 10449 } 10450 return false; 10451 } 10452 10453 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 10454 10455 // Check if installing from ADB 10456 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 10457 // Do not run verification in a test harness environment 10458 if (ActivityManager.isRunningInTestHarness()) { 10459 return false; 10460 } 10461 if (ensureVerifyAppsEnabled) { 10462 return true; 10463 } 10464 // Check if the developer does not want package verification for ADB installs 10465 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10466 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 10467 return false; 10468 } 10469 } 10470 10471 if (ensureVerifyAppsEnabled) { 10472 return true; 10473 } 10474 10475 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10476 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 10477 } 10478 10479 @Override 10480 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 10481 throws RemoteException { 10482 mContext.enforceCallingOrSelfPermission( 10483 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 10484 "Only intentfilter verification agents can verify applications"); 10485 10486 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 10487 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 10488 Binder.getCallingUid(), verificationCode, failedDomains); 10489 msg.arg1 = id; 10490 msg.obj = response; 10491 mHandler.sendMessage(msg); 10492 } 10493 10494 @Override 10495 public int getIntentVerificationStatus(String packageName, int userId) { 10496 synchronized (mPackages) { 10497 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 10498 } 10499 } 10500 10501 @Override 10502 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 10503 mContext.enforceCallingOrSelfPermission( 10504 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10505 10506 boolean result = false; 10507 synchronized (mPackages) { 10508 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 10509 } 10510 if (result) { 10511 scheduleWritePackageRestrictionsLocked(userId); 10512 } 10513 return result; 10514 } 10515 10516 @Override 10517 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 10518 synchronized (mPackages) { 10519 return mSettings.getIntentFilterVerificationsLPr(packageName); 10520 } 10521 } 10522 10523 @Override 10524 public List<IntentFilter> getAllIntentFilters(String packageName) { 10525 if (TextUtils.isEmpty(packageName)) { 10526 return Collections.<IntentFilter>emptyList(); 10527 } 10528 synchronized (mPackages) { 10529 PackageParser.Package pkg = mPackages.get(packageName); 10530 if (pkg == null || pkg.activities == null) { 10531 return Collections.<IntentFilter>emptyList(); 10532 } 10533 final int count = pkg.activities.size(); 10534 ArrayList<IntentFilter> result = new ArrayList<>(); 10535 for (int n=0; n<count; n++) { 10536 PackageParser.Activity activity = pkg.activities.get(n); 10537 if (activity.intents != null && activity.intents.size() > 0) { 10538 result.addAll(activity.intents); 10539 } 10540 } 10541 return result; 10542 } 10543 } 10544 10545 @Override 10546 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 10547 mContext.enforceCallingOrSelfPermission( 10548 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10549 10550 synchronized (mPackages) { 10551 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 10552 if (packageName != null) { 10553 result |= updateIntentVerificationStatus(packageName, 10554 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 10555 userId); 10556 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 10557 packageName, userId); 10558 } 10559 return result; 10560 } 10561 } 10562 10563 @Override 10564 public String getDefaultBrowserPackageName(int userId) { 10565 synchronized (mPackages) { 10566 return mSettings.getDefaultBrowserPackageNameLPw(userId); 10567 } 10568 } 10569 10570 /** 10571 * Get the "allow unknown sources" setting. 10572 * 10573 * @return the current "allow unknown sources" setting 10574 */ 10575 private int getUnknownSourcesSettings() { 10576 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10577 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 10578 -1); 10579 } 10580 10581 @Override 10582 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 10583 final int uid = Binder.getCallingUid(); 10584 // writer 10585 synchronized (mPackages) { 10586 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 10587 if (targetPackageSetting == null) { 10588 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 10589 } 10590 10591 PackageSetting installerPackageSetting; 10592 if (installerPackageName != null) { 10593 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 10594 if (installerPackageSetting == null) { 10595 throw new IllegalArgumentException("Unknown installer package: " 10596 + installerPackageName); 10597 } 10598 } else { 10599 installerPackageSetting = null; 10600 } 10601 10602 Signature[] callerSignature; 10603 Object obj = mSettings.getUserIdLPr(uid); 10604 if (obj != null) { 10605 if (obj instanceof SharedUserSetting) { 10606 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 10607 } else if (obj instanceof PackageSetting) { 10608 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 10609 } else { 10610 throw new SecurityException("Bad object " + obj + " for uid " + uid); 10611 } 10612 } else { 10613 throw new SecurityException("Unknown calling uid " + uid); 10614 } 10615 10616 // Verify: can't set installerPackageName to a package that is 10617 // not signed with the same cert as the caller. 10618 if (installerPackageSetting != null) { 10619 if (compareSignatures(callerSignature, 10620 installerPackageSetting.signatures.mSignatures) 10621 != PackageManager.SIGNATURE_MATCH) { 10622 throw new SecurityException( 10623 "Caller does not have same cert as new installer package " 10624 + installerPackageName); 10625 } 10626 } 10627 10628 // Verify: if target already has an installer package, it must 10629 // be signed with the same cert as the caller. 10630 if (targetPackageSetting.installerPackageName != null) { 10631 PackageSetting setting = mSettings.mPackages.get( 10632 targetPackageSetting.installerPackageName); 10633 // If the currently set package isn't valid, then it's always 10634 // okay to change it. 10635 if (setting != null) { 10636 if (compareSignatures(callerSignature, 10637 setting.signatures.mSignatures) 10638 != PackageManager.SIGNATURE_MATCH) { 10639 throw new SecurityException( 10640 "Caller does not have same cert as old installer package " 10641 + targetPackageSetting.installerPackageName); 10642 } 10643 } 10644 } 10645 10646 // Okay! 10647 targetPackageSetting.installerPackageName = installerPackageName; 10648 scheduleWriteSettingsLocked(); 10649 } 10650 } 10651 10652 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 10653 // Queue up an async operation since the package installation may take a little while. 10654 mHandler.post(new Runnable() { 10655 public void run() { 10656 mHandler.removeCallbacks(this); 10657 // Result object to be returned 10658 PackageInstalledInfo res = new PackageInstalledInfo(); 10659 res.returnCode = currentStatus; 10660 res.uid = -1; 10661 res.pkg = null; 10662 res.removedInfo = new PackageRemovedInfo(); 10663 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10664 args.doPreInstall(res.returnCode); 10665 synchronized (mInstallLock) { 10666 installPackageTracedLI(args, res); 10667 } 10668 args.doPostInstall(res.returnCode, res.uid); 10669 } 10670 10671 // A restore should be performed at this point if (a) the install 10672 // succeeded, (b) the operation is not an update, and (c) the new 10673 // package has not opted out of backup participation. 10674 final boolean update = res.removedInfo.removedPackage != null; 10675 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 10676 boolean doRestore = !update 10677 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 10678 10679 // Set up the post-install work request bookkeeping. This will be used 10680 // and cleaned up by the post-install event handling regardless of whether 10681 // there's a restore pass performed. Token values are >= 1. 10682 int token; 10683 if (mNextInstallToken < 0) mNextInstallToken = 1; 10684 token = mNextInstallToken++; 10685 10686 PostInstallData data = new PostInstallData(args, res); 10687 mRunningInstalls.put(token, data); 10688 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 10689 10690 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 10691 // Pass responsibility to the Backup Manager. It will perform a 10692 // restore if appropriate, then pass responsibility back to the 10693 // Package Manager to run the post-install observer callbacks 10694 // and broadcasts. 10695 IBackupManager bm = IBackupManager.Stub.asInterface( 10696 ServiceManager.getService(Context.BACKUP_SERVICE)); 10697 if (bm != null) { 10698 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 10699 + " to BM for possible restore"); 10700 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10701 try { 10702 // TODO: http://b/22388012 10703 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 10704 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 10705 } else { 10706 doRestore = false; 10707 } 10708 } catch (RemoteException e) { 10709 // can't happen; the backup manager is local 10710 } catch (Exception e) { 10711 Slog.e(TAG, "Exception trying to enqueue restore", e); 10712 doRestore = false; 10713 } 10714 } else { 10715 Slog.e(TAG, "Backup Manager not found!"); 10716 doRestore = false; 10717 } 10718 } 10719 10720 if (!doRestore) { 10721 // No restore possible, or the Backup Manager was mysteriously not 10722 // available -- just fire the post-install work request directly. 10723 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 10724 10725 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 10726 10727 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10728 mHandler.sendMessage(msg); 10729 } 10730 } 10731 }); 10732 } 10733 10734 private abstract class HandlerParams { 10735 private static final int MAX_RETRIES = 4; 10736 10737 /** 10738 * Number of times startCopy() has been attempted and had a non-fatal 10739 * error. 10740 */ 10741 private int mRetries = 0; 10742 10743 /** User handle for the user requesting the information or installation. */ 10744 private final UserHandle mUser; 10745 String traceMethod; 10746 int traceCookie; 10747 10748 HandlerParams(UserHandle user) { 10749 mUser = user; 10750 } 10751 10752 UserHandle getUser() { 10753 return mUser; 10754 } 10755 10756 HandlerParams setTraceMethod(String traceMethod) { 10757 this.traceMethod = traceMethod; 10758 return this; 10759 } 10760 10761 HandlerParams setTraceCookie(int traceCookie) { 10762 this.traceCookie = traceCookie; 10763 return this; 10764 } 10765 10766 final boolean startCopy() { 10767 boolean res; 10768 try { 10769 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 10770 10771 if (++mRetries > MAX_RETRIES) { 10772 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 10773 mHandler.sendEmptyMessage(MCS_GIVE_UP); 10774 handleServiceError(); 10775 return false; 10776 } else { 10777 handleStartCopy(); 10778 res = true; 10779 } 10780 } catch (RemoteException e) { 10781 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 10782 mHandler.sendEmptyMessage(MCS_RECONNECT); 10783 res = false; 10784 } 10785 handleReturnCode(); 10786 return res; 10787 } 10788 10789 final void serviceError() { 10790 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 10791 handleServiceError(); 10792 handleReturnCode(); 10793 } 10794 10795 abstract void handleStartCopy() throws RemoteException; 10796 abstract void handleServiceError(); 10797 abstract void handleReturnCode(); 10798 } 10799 10800 class MeasureParams extends HandlerParams { 10801 private final PackageStats mStats; 10802 private boolean mSuccess; 10803 10804 private final IPackageStatsObserver mObserver; 10805 10806 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 10807 super(new UserHandle(stats.userHandle)); 10808 mObserver = observer; 10809 mStats = stats; 10810 } 10811 10812 @Override 10813 public String toString() { 10814 return "MeasureParams{" 10815 + Integer.toHexString(System.identityHashCode(this)) 10816 + " " + mStats.packageName + "}"; 10817 } 10818 10819 @Override 10820 void handleStartCopy() throws RemoteException { 10821 synchronized (mInstallLock) { 10822 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 10823 } 10824 10825 if (mSuccess) { 10826 final boolean mounted; 10827 if (Environment.isExternalStorageEmulated()) { 10828 mounted = true; 10829 } else { 10830 final String status = Environment.getExternalStorageState(); 10831 mounted = (Environment.MEDIA_MOUNTED.equals(status) 10832 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 10833 } 10834 10835 if (mounted) { 10836 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 10837 10838 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 10839 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 10840 10841 mStats.externalDataSize = calculateDirectorySize(mContainerService, 10842 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 10843 10844 // Always subtract cache size, since it's a subdirectory 10845 mStats.externalDataSize -= mStats.externalCacheSize; 10846 10847 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 10848 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 10849 10850 mStats.externalObbSize = calculateDirectorySize(mContainerService, 10851 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 10852 } 10853 } 10854 } 10855 10856 @Override 10857 void handleReturnCode() { 10858 if (mObserver != null) { 10859 try { 10860 mObserver.onGetStatsCompleted(mStats, mSuccess); 10861 } catch (RemoteException e) { 10862 Slog.i(TAG, "Observer no longer exists."); 10863 } 10864 } 10865 } 10866 10867 @Override 10868 void handleServiceError() { 10869 Slog.e(TAG, "Could not measure application " + mStats.packageName 10870 + " external storage"); 10871 } 10872 } 10873 10874 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 10875 throws RemoteException { 10876 long result = 0; 10877 for (File path : paths) { 10878 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 10879 } 10880 return result; 10881 } 10882 10883 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 10884 for (File path : paths) { 10885 try { 10886 mcs.clearDirectory(path.getAbsolutePath()); 10887 } catch (RemoteException e) { 10888 } 10889 } 10890 } 10891 10892 static class OriginInfo { 10893 /** 10894 * Location where install is coming from, before it has been 10895 * copied/renamed into place. This could be a single monolithic APK 10896 * file, or a cluster directory. This location may be untrusted. 10897 */ 10898 final File file; 10899 final String cid; 10900 10901 /** 10902 * Flag indicating that {@link #file} or {@link #cid} has already been 10903 * staged, meaning downstream users don't need to defensively copy the 10904 * contents. 10905 */ 10906 final boolean staged; 10907 10908 /** 10909 * Flag indicating that {@link #file} or {@link #cid} is an already 10910 * installed app that is being moved. 10911 */ 10912 final boolean existing; 10913 10914 final String resolvedPath; 10915 final File resolvedFile; 10916 10917 static OriginInfo fromNothing() { 10918 return new OriginInfo(null, null, false, false); 10919 } 10920 10921 static OriginInfo fromUntrustedFile(File file) { 10922 return new OriginInfo(file, null, false, false); 10923 } 10924 10925 static OriginInfo fromExistingFile(File file) { 10926 return new OriginInfo(file, null, false, true); 10927 } 10928 10929 static OriginInfo fromStagedFile(File file) { 10930 return new OriginInfo(file, null, true, false); 10931 } 10932 10933 static OriginInfo fromStagedContainer(String cid) { 10934 return new OriginInfo(null, cid, true, false); 10935 } 10936 10937 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 10938 this.file = file; 10939 this.cid = cid; 10940 this.staged = staged; 10941 this.existing = existing; 10942 10943 if (cid != null) { 10944 resolvedPath = PackageHelper.getSdDir(cid); 10945 resolvedFile = new File(resolvedPath); 10946 } else if (file != null) { 10947 resolvedPath = file.getAbsolutePath(); 10948 resolvedFile = file; 10949 } else { 10950 resolvedPath = null; 10951 resolvedFile = null; 10952 } 10953 } 10954 } 10955 10956 static class MoveInfo { 10957 final int moveId; 10958 final String fromUuid; 10959 final String toUuid; 10960 final String packageName; 10961 final String dataAppName; 10962 final int appId; 10963 final String seinfo; 10964 10965 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 10966 String dataAppName, int appId, String seinfo) { 10967 this.moveId = moveId; 10968 this.fromUuid = fromUuid; 10969 this.toUuid = toUuid; 10970 this.packageName = packageName; 10971 this.dataAppName = dataAppName; 10972 this.appId = appId; 10973 this.seinfo = seinfo; 10974 } 10975 } 10976 10977 class InstallParams extends HandlerParams { 10978 final OriginInfo origin; 10979 final MoveInfo move; 10980 final IPackageInstallObserver2 observer; 10981 int installFlags; 10982 final String installerPackageName; 10983 final String volumeUuid; 10984 final VerificationParams verificationParams; 10985 private InstallArgs mArgs; 10986 private int mRet; 10987 final String packageAbiOverride; 10988 final String[] grantedRuntimePermissions; 10989 10990 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10991 int installFlags, String installerPackageName, String volumeUuid, 10992 VerificationParams verificationParams, UserHandle user, String packageAbiOverride, 10993 String[] grantedPermissions) { 10994 super(user); 10995 this.origin = origin; 10996 this.move = move; 10997 this.observer = observer; 10998 this.installFlags = installFlags; 10999 this.installerPackageName = installerPackageName; 11000 this.volumeUuid = volumeUuid; 11001 this.verificationParams = verificationParams; 11002 this.packageAbiOverride = packageAbiOverride; 11003 this.grantedRuntimePermissions = grantedPermissions; 11004 } 11005 11006 @Override 11007 public String toString() { 11008 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 11009 + " file=" + origin.file + " cid=" + origin.cid + "}"; 11010 } 11011 11012 public ManifestDigest getManifestDigest() { 11013 if (verificationParams == null) { 11014 return null; 11015 } 11016 return verificationParams.getManifestDigest(); 11017 } 11018 11019 private int installLocationPolicy(PackageInfoLite pkgLite) { 11020 String packageName = pkgLite.packageName; 11021 int installLocation = pkgLite.installLocation; 11022 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11023 // reader 11024 synchronized (mPackages) { 11025 PackageParser.Package pkg = mPackages.get(packageName); 11026 if (pkg != null) { 11027 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 11028 // Check for downgrading. 11029 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 11030 try { 11031 checkDowngrade(pkg, pkgLite); 11032 } catch (PackageManagerException e) { 11033 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 11034 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 11035 } 11036 } 11037 // Check for updated system application. 11038 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 11039 if (onSd) { 11040 Slog.w(TAG, "Cannot install update to system app on sdcard"); 11041 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 11042 } 11043 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11044 } else { 11045 if (onSd) { 11046 // Install flag overrides everything. 11047 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11048 } 11049 // If current upgrade specifies particular preference 11050 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 11051 // Application explicitly specified internal. 11052 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11053 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 11054 // App explictly prefers external. Let policy decide 11055 } else { 11056 // Prefer previous location 11057 if (isExternal(pkg)) { 11058 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11059 } 11060 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11061 } 11062 } 11063 } else { 11064 // Invalid install. Return error code 11065 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 11066 } 11067 } 11068 } 11069 // All the special cases have been taken care of. 11070 // Return result based on recommended install location. 11071 if (onSd) { 11072 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11073 } 11074 return pkgLite.recommendedInstallLocation; 11075 } 11076 11077 /* 11078 * Invoke remote method to get package information and install 11079 * location values. Override install location based on default 11080 * policy if needed and then create install arguments based 11081 * on the install location. 11082 */ 11083 public void handleStartCopy() throws RemoteException { 11084 int ret = PackageManager.INSTALL_SUCCEEDED; 11085 11086 // If we're already staged, we've firmly committed to an install location 11087 if (origin.staged) { 11088 if (origin.file != null) { 11089 installFlags |= PackageManager.INSTALL_INTERNAL; 11090 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 11091 } else if (origin.cid != null) { 11092 installFlags |= PackageManager.INSTALL_EXTERNAL; 11093 installFlags &= ~PackageManager.INSTALL_INTERNAL; 11094 } else { 11095 throw new IllegalStateException("Invalid stage location"); 11096 } 11097 } 11098 11099 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11100 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 11101 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 11102 PackageInfoLite pkgLite = null; 11103 11104 if (onInt && onSd) { 11105 // Check if both bits are set. 11106 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 11107 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11108 } else if (onSd && ephemeral) { 11109 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 11110 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11111 } else { 11112 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 11113 packageAbiOverride); 11114 11115 if (DEBUG_EPHEMERAL && ephemeral) { 11116 Slog.v(TAG, "pkgLite for install: " + pkgLite); 11117 } 11118 11119 /* 11120 * If we have too little free space, try to free cache 11121 * before giving up. 11122 */ 11123 if (!origin.staged && pkgLite.recommendedInstallLocation 11124 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 11125 // TODO: focus freeing disk space on the target device 11126 final StorageManager storage = StorageManager.from(mContext); 11127 final long lowThreshold = storage.getStorageLowBytes( 11128 Environment.getDataDirectory()); 11129 11130 final long sizeBytes = mContainerService.calculateInstalledSize( 11131 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 11132 11133 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 11134 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 11135 installFlags, packageAbiOverride); 11136 } 11137 11138 /* 11139 * The cache free must have deleted the file we 11140 * downloaded to install. 11141 * 11142 * TODO: fix the "freeCache" call to not delete 11143 * the file we care about. 11144 */ 11145 if (pkgLite.recommendedInstallLocation 11146 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 11147 pkgLite.recommendedInstallLocation 11148 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 11149 } 11150 } 11151 } 11152 11153 if (ret == PackageManager.INSTALL_SUCCEEDED) { 11154 int loc = pkgLite.recommendedInstallLocation; 11155 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 11156 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11157 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 11158 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 11159 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 11160 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11161 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 11162 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 11163 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 11164 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 11165 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 11166 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 11167 } else { 11168 // Override with defaults if needed. 11169 loc = installLocationPolicy(pkgLite); 11170 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 11171 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 11172 } else if (!onSd && !onInt) { 11173 // Override install location with flags 11174 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 11175 // Set the flag to install on external media. 11176 installFlags |= PackageManager.INSTALL_EXTERNAL; 11177 installFlags &= ~PackageManager.INSTALL_INTERNAL; 11178 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 11179 if (DEBUG_EPHEMERAL) { 11180 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 11181 } 11182 installFlags |= PackageManager.INSTALL_EPHEMERAL; 11183 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 11184 |PackageManager.INSTALL_INTERNAL); 11185 } else { 11186 // Make sure the flag for installing on external 11187 // media is unset 11188 installFlags |= PackageManager.INSTALL_INTERNAL; 11189 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 11190 } 11191 } 11192 } 11193 } 11194 11195 final InstallArgs args = createInstallArgs(this); 11196 mArgs = args; 11197 11198 if (ret == PackageManager.INSTALL_SUCCEEDED) { 11199 // TODO: http://b/22976637 11200 // Apps installed for "all" users use the device owner to verify the app 11201 UserHandle verifierUser = getUser(); 11202 if (verifierUser == UserHandle.ALL) { 11203 verifierUser = UserHandle.SYSTEM; 11204 } 11205 11206 /* 11207 * Determine if we have any installed package verifiers. If we 11208 * do, then we'll defer to them to verify the packages. 11209 */ 11210 final int requiredUid = mRequiredVerifierPackage == null ? -1 11211 : getPackageUid(mRequiredVerifierPackage, verifierUser.getIdentifier()); 11212 if (!origin.existing && requiredUid != -1 11213 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 11214 final Intent verification = new Intent( 11215 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 11216 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 11217 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 11218 PACKAGE_MIME_TYPE); 11219 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11220 11221 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 11222 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 11223 verifierUser.getIdentifier()); 11224 11225 if (DEBUG_VERIFY) { 11226 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 11227 + verification.toString() + " with " + pkgLite.verifiers.length 11228 + " optional verifiers"); 11229 } 11230 11231 final int verificationId = mPendingVerificationToken++; 11232 11233 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11234 11235 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 11236 installerPackageName); 11237 11238 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 11239 installFlags); 11240 11241 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 11242 pkgLite.packageName); 11243 11244 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 11245 pkgLite.versionCode); 11246 11247 if (verificationParams != null) { 11248 if (verificationParams.getVerificationURI() != null) { 11249 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 11250 verificationParams.getVerificationURI()); 11251 } 11252 if (verificationParams.getOriginatingURI() != null) { 11253 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 11254 verificationParams.getOriginatingURI()); 11255 } 11256 if (verificationParams.getReferrer() != null) { 11257 verification.putExtra(Intent.EXTRA_REFERRER, 11258 verificationParams.getReferrer()); 11259 } 11260 if (verificationParams.getOriginatingUid() >= 0) { 11261 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 11262 verificationParams.getOriginatingUid()); 11263 } 11264 if (verificationParams.getInstallerUid() >= 0) { 11265 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 11266 verificationParams.getInstallerUid()); 11267 } 11268 } 11269 11270 final PackageVerificationState verificationState = new PackageVerificationState( 11271 requiredUid, args); 11272 11273 mPendingVerification.append(verificationId, verificationState); 11274 11275 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 11276 receivers, verificationState); 11277 11278 /* 11279 * If any sufficient verifiers were listed in the package 11280 * manifest, attempt to ask them. 11281 */ 11282 if (sufficientVerifiers != null) { 11283 final int N = sufficientVerifiers.size(); 11284 if (N == 0) { 11285 Slog.i(TAG, "Additional verifiers required, but none installed."); 11286 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 11287 } else { 11288 for (int i = 0; i < N; i++) { 11289 final ComponentName verifierComponent = sufficientVerifiers.get(i); 11290 11291 final Intent sufficientIntent = new Intent(verification); 11292 sufficientIntent.setComponent(verifierComponent); 11293 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 11294 } 11295 } 11296 } 11297 11298 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 11299 mRequiredVerifierPackage, receivers); 11300 if (ret == PackageManager.INSTALL_SUCCEEDED 11301 && mRequiredVerifierPackage != null) { 11302 Trace.asyncTraceBegin( 11303 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 11304 /* 11305 * Send the intent to the required verification agent, 11306 * but only start the verification timeout after the 11307 * target BroadcastReceivers have run. 11308 */ 11309 verification.setComponent(requiredVerifierComponent); 11310 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 11311 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11312 new BroadcastReceiver() { 11313 @Override 11314 public void onReceive(Context context, Intent intent) { 11315 final Message msg = mHandler 11316 .obtainMessage(CHECK_PENDING_VERIFICATION); 11317 msg.arg1 = verificationId; 11318 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 11319 } 11320 }, null, 0, null, null); 11321 11322 /* 11323 * We don't want the copy to proceed until verification 11324 * succeeds, so null out this field. 11325 */ 11326 mArgs = null; 11327 } 11328 } else { 11329 /* 11330 * No package verification is enabled, so immediately start 11331 * the remote call to initiate copy using temporary file. 11332 */ 11333 ret = args.copyApk(mContainerService, true); 11334 } 11335 } 11336 11337 mRet = ret; 11338 } 11339 11340 @Override 11341 void handleReturnCode() { 11342 // If mArgs is null, then MCS couldn't be reached. When it 11343 // reconnects, it will try again to install. At that point, this 11344 // will succeed. 11345 if (mArgs != null) { 11346 processPendingInstall(mArgs, mRet); 11347 } 11348 } 11349 11350 @Override 11351 void handleServiceError() { 11352 mArgs = createInstallArgs(this); 11353 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11354 } 11355 11356 public boolean isForwardLocked() { 11357 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11358 } 11359 } 11360 11361 /** 11362 * Used during creation of InstallArgs 11363 * 11364 * @param installFlags package installation flags 11365 * @return true if should be installed on external storage 11366 */ 11367 private static boolean installOnExternalAsec(int installFlags) { 11368 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 11369 return false; 11370 } 11371 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 11372 return true; 11373 } 11374 return false; 11375 } 11376 11377 /** 11378 * Used during creation of InstallArgs 11379 * 11380 * @param installFlags package installation flags 11381 * @return true if should be installed as forward locked 11382 */ 11383 private static boolean installForwardLocked(int installFlags) { 11384 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11385 } 11386 11387 private InstallArgs createInstallArgs(InstallParams params) { 11388 if (params.move != null) { 11389 return new MoveInstallArgs(params); 11390 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 11391 return new AsecInstallArgs(params); 11392 } else { 11393 return new FileInstallArgs(params); 11394 } 11395 } 11396 11397 /** 11398 * Create args that describe an existing installed package. Typically used 11399 * when cleaning up old installs, or used as a move source. 11400 */ 11401 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 11402 String resourcePath, String[] instructionSets) { 11403 final boolean isInAsec; 11404 if (installOnExternalAsec(installFlags)) { 11405 /* Apps on SD card are always in ASEC containers. */ 11406 isInAsec = true; 11407 } else if (installForwardLocked(installFlags) 11408 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 11409 /* 11410 * Forward-locked apps are only in ASEC containers if they're the 11411 * new style 11412 */ 11413 isInAsec = true; 11414 } else { 11415 isInAsec = false; 11416 } 11417 11418 if (isInAsec) { 11419 return new AsecInstallArgs(codePath, instructionSets, 11420 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 11421 } else { 11422 return new FileInstallArgs(codePath, resourcePath, instructionSets); 11423 } 11424 } 11425 11426 static abstract class InstallArgs { 11427 /** @see InstallParams#origin */ 11428 final OriginInfo origin; 11429 /** @see InstallParams#move */ 11430 final MoveInfo move; 11431 11432 final IPackageInstallObserver2 observer; 11433 // Always refers to PackageManager flags only 11434 final int installFlags; 11435 final String installerPackageName; 11436 final String volumeUuid; 11437 final ManifestDigest manifestDigest; 11438 final UserHandle user; 11439 final String abiOverride; 11440 final String[] installGrantPermissions; 11441 /** If non-null, drop an async trace when the install completes */ 11442 final String traceMethod; 11443 final int traceCookie; 11444 11445 // The list of instruction sets supported by this app. This is currently 11446 // only used during the rmdex() phase to clean up resources. We can get rid of this 11447 // if we move dex files under the common app path. 11448 /* nullable */ String[] instructionSets; 11449 11450 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 11451 int installFlags, String installerPackageName, String volumeUuid, 11452 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 11453 String abiOverride, String[] installGrantPermissions, 11454 String traceMethod, int traceCookie) { 11455 this.origin = origin; 11456 this.move = move; 11457 this.installFlags = installFlags; 11458 this.observer = observer; 11459 this.installerPackageName = installerPackageName; 11460 this.volumeUuid = volumeUuid; 11461 this.manifestDigest = manifestDigest; 11462 this.user = user; 11463 this.instructionSets = instructionSets; 11464 this.abiOverride = abiOverride; 11465 this.installGrantPermissions = installGrantPermissions; 11466 this.traceMethod = traceMethod; 11467 this.traceCookie = traceCookie; 11468 } 11469 11470 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 11471 abstract int doPreInstall(int status); 11472 11473 /** 11474 * Rename package into final resting place. All paths on the given 11475 * scanned package should be updated to reflect the rename. 11476 */ 11477 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 11478 abstract int doPostInstall(int status, int uid); 11479 11480 /** @see PackageSettingBase#codePathString */ 11481 abstract String getCodePath(); 11482 /** @see PackageSettingBase#resourcePathString */ 11483 abstract String getResourcePath(); 11484 11485 // Need installer lock especially for dex file removal. 11486 abstract void cleanUpResourcesLI(); 11487 abstract boolean doPostDeleteLI(boolean delete); 11488 11489 /** 11490 * Called before the source arguments are copied. This is used mostly 11491 * for MoveParams when it needs to read the source file to put it in the 11492 * destination. 11493 */ 11494 int doPreCopy() { 11495 return PackageManager.INSTALL_SUCCEEDED; 11496 } 11497 11498 /** 11499 * Called after the source arguments are copied. This is used mostly for 11500 * MoveParams when it needs to read the source file to put it in the 11501 * destination. 11502 * 11503 * @return 11504 */ 11505 int doPostCopy(int uid) { 11506 return PackageManager.INSTALL_SUCCEEDED; 11507 } 11508 11509 protected boolean isFwdLocked() { 11510 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11511 } 11512 11513 protected boolean isExternalAsec() { 11514 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11515 } 11516 11517 protected boolean isEphemeral() { 11518 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 11519 } 11520 11521 UserHandle getUser() { 11522 return user; 11523 } 11524 } 11525 11526 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 11527 if (!allCodePaths.isEmpty()) { 11528 if (instructionSets == null) { 11529 throw new IllegalStateException("instructionSet == null"); 11530 } 11531 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 11532 for (String codePath : allCodePaths) { 11533 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 11534 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 11535 if (retCode < 0) { 11536 Slog.w(TAG, "Couldn't remove dex file for package: " 11537 + " at location " + codePath + ", retcode=" + retCode); 11538 // we don't consider this to be a failure of the core package deletion 11539 } 11540 } 11541 } 11542 } 11543 } 11544 11545 /** 11546 * Logic to handle installation of non-ASEC applications, including copying 11547 * and renaming logic. 11548 */ 11549 class FileInstallArgs extends InstallArgs { 11550 private File codeFile; 11551 private File resourceFile; 11552 11553 // Example topology: 11554 // /data/app/com.example/base.apk 11555 // /data/app/com.example/split_foo.apk 11556 // /data/app/com.example/lib/arm/libfoo.so 11557 // /data/app/com.example/lib/arm64/libfoo.so 11558 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 11559 11560 /** New install */ 11561 FileInstallArgs(InstallParams params) { 11562 super(params.origin, params.move, params.observer, params.installFlags, 11563 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11564 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11565 params.grantedRuntimePermissions, 11566 params.traceMethod, params.traceCookie); 11567 if (isFwdLocked()) { 11568 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 11569 } 11570 } 11571 11572 /** Existing install */ 11573 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 11574 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 11575 null, null, null, 0); 11576 this.codeFile = (codePath != null) ? new File(codePath) : null; 11577 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 11578 } 11579 11580 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11581 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 11582 try { 11583 return doCopyApk(imcs, temp); 11584 } finally { 11585 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11586 } 11587 } 11588 11589 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11590 if (origin.staged) { 11591 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 11592 codeFile = origin.file; 11593 resourceFile = origin.file; 11594 return PackageManager.INSTALL_SUCCEEDED; 11595 } 11596 11597 try { 11598 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 11599 final File tempDir = 11600 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 11601 codeFile = tempDir; 11602 resourceFile = tempDir; 11603 } catch (IOException e) { 11604 Slog.w(TAG, "Failed to create copy file: " + e); 11605 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11606 } 11607 11608 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 11609 @Override 11610 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 11611 if (!FileUtils.isValidExtFilename(name)) { 11612 throw new IllegalArgumentException("Invalid filename: " + name); 11613 } 11614 try { 11615 final File file = new File(codeFile, name); 11616 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 11617 O_RDWR | O_CREAT, 0644); 11618 Os.chmod(file.getAbsolutePath(), 0644); 11619 return new ParcelFileDescriptor(fd); 11620 } catch (ErrnoException e) { 11621 throw new RemoteException("Failed to open: " + e.getMessage()); 11622 } 11623 } 11624 }; 11625 11626 int ret = PackageManager.INSTALL_SUCCEEDED; 11627 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 11628 if (ret != PackageManager.INSTALL_SUCCEEDED) { 11629 Slog.e(TAG, "Failed to copy package"); 11630 return ret; 11631 } 11632 11633 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 11634 NativeLibraryHelper.Handle handle = null; 11635 try { 11636 handle = NativeLibraryHelper.Handle.create(codeFile); 11637 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 11638 abiOverride); 11639 } catch (IOException e) { 11640 Slog.e(TAG, "Copying native libraries failed", e); 11641 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11642 } finally { 11643 IoUtils.closeQuietly(handle); 11644 } 11645 11646 return ret; 11647 } 11648 11649 int doPreInstall(int status) { 11650 if (status != PackageManager.INSTALL_SUCCEEDED) { 11651 cleanUp(); 11652 } 11653 return status; 11654 } 11655 11656 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11657 if (status != PackageManager.INSTALL_SUCCEEDED) { 11658 cleanUp(); 11659 return false; 11660 } 11661 11662 final File targetDir = codeFile.getParentFile(); 11663 final File beforeCodeFile = codeFile; 11664 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 11665 11666 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 11667 try { 11668 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 11669 } catch (ErrnoException e) { 11670 Slog.w(TAG, "Failed to rename", e); 11671 return false; 11672 } 11673 11674 if (!SELinux.restoreconRecursive(afterCodeFile)) { 11675 Slog.w(TAG, "Failed to restorecon"); 11676 return false; 11677 } 11678 11679 // Reflect the rename internally 11680 codeFile = afterCodeFile; 11681 resourceFile = afterCodeFile; 11682 11683 // Reflect the rename in scanned details 11684 pkg.codePath = afterCodeFile.getAbsolutePath(); 11685 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11686 pkg.baseCodePath); 11687 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11688 pkg.splitCodePaths); 11689 11690 // Reflect the rename in app info 11691 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11692 pkg.applicationInfo.setCodePath(pkg.codePath); 11693 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11694 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11695 pkg.applicationInfo.setResourcePath(pkg.codePath); 11696 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11697 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11698 11699 return true; 11700 } 11701 11702 int doPostInstall(int status, int uid) { 11703 if (status != PackageManager.INSTALL_SUCCEEDED) { 11704 cleanUp(); 11705 } 11706 return status; 11707 } 11708 11709 @Override 11710 String getCodePath() { 11711 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11712 } 11713 11714 @Override 11715 String getResourcePath() { 11716 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11717 } 11718 11719 private boolean cleanUp() { 11720 if (codeFile == null || !codeFile.exists()) { 11721 return false; 11722 } 11723 11724 if (codeFile.isDirectory()) { 11725 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11726 } else { 11727 codeFile.delete(); 11728 } 11729 11730 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 11731 resourceFile.delete(); 11732 } 11733 11734 return true; 11735 } 11736 11737 void cleanUpResourcesLI() { 11738 // Try enumerating all code paths before deleting 11739 List<String> allCodePaths = Collections.EMPTY_LIST; 11740 if (codeFile != null && codeFile.exists()) { 11741 try { 11742 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11743 allCodePaths = pkg.getAllCodePaths(); 11744 } catch (PackageParserException e) { 11745 // Ignored; we tried our best 11746 } 11747 } 11748 11749 cleanUp(); 11750 removeDexFiles(allCodePaths, instructionSets); 11751 } 11752 11753 boolean doPostDeleteLI(boolean delete) { 11754 // XXX err, shouldn't we respect the delete flag? 11755 cleanUpResourcesLI(); 11756 return true; 11757 } 11758 } 11759 11760 private boolean isAsecExternal(String cid) { 11761 final String asecPath = PackageHelper.getSdFilesystem(cid); 11762 return !asecPath.startsWith(mAsecInternalPath); 11763 } 11764 11765 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 11766 PackageManagerException { 11767 if (copyRet < 0) { 11768 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 11769 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 11770 throw new PackageManagerException(copyRet, message); 11771 } 11772 } 11773 } 11774 11775 /** 11776 * Extract the MountService "container ID" from the full code path of an 11777 * .apk. 11778 */ 11779 static String cidFromCodePath(String fullCodePath) { 11780 int eidx = fullCodePath.lastIndexOf("/"); 11781 String subStr1 = fullCodePath.substring(0, eidx); 11782 int sidx = subStr1.lastIndexOf("/"); 11783 return subStr1.substring(sidx+1, eidx); 11784 } 11785 11786 /** 11787 * Logic to handle installation of ASEC applications, including copying and 11788 * renaming logic. 11789 */ 11790 class AsecInstallArgs extends InstallArgs { 11791 static final String RES_FILE_NAME = "pkg.apk"; 11792 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 11793 11794 String cid; 11795 String packagePath; 11796 String resourcePath; 11797 11798 /** New install */ 11799 AsecInstallArgs(InstallParams params) { 11800 super(params.origin, params.move, params.observer, params.installFlags, 11801 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11802 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11803 params.grantedRuntimePermissions, 11804 params.traceMethod, params.traceCookie); 11805 } 11806 11807 /** Existing install */ 11808 AsecInstallArgs(String fullCodePath, String[] instructionSets, 11809 boolean isExternal, boolean isForwardLocked) { 11810 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 11811 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11812 instructionSets, null, null, null, 0); 11813 // Hackily pretend we're still looking at a full code path 11814 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 11815 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 11816 } 11817 11818 // Extract cid from fullCodePath 11819 int eidx = fullCodePath.lastIndexOf("/"); 11820 String subStr1 = fullCodePath.substring(0, eidx); 11821 int sidx = subStr1.lastIndexOf("/"); 11822 cid = subStr1.substring(sidx+1, eidx); 11823 setMountPath(subStr1); 11824 } 11825 11826 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 11827 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 11828 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11829 instructionSets, null, null, null, 0); 11830 this.cid = cid; 11831 setMountPath(PackageHelper.getSdDir(cid)); 11832 } 11833 11834 void createCopyFile() { 11835 cid = mInstallerService.allocateExternalStageCidLegacy(); 11836 } 11837 11838 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11839 if (origin.staged && origin.cid != null) { 11840 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 11841 cid = origin.cid; 11842 setMountPath(PackageHelper.getSdDir(cid)); 11843 return PackageManager.INSTALL_SUCCEEDED; 11844 } 11845 11846 if (temp) { 11847 createCopyFile(); 11848 } else { 11849 /* 11850 * Pre-emptively destroy the container since it's destroyed if 11851 * copying fails due to it existing anyway. 11852 */ 11853 PackageHelper.destroySdDir(cid); 11854 } 11855 11856 final String newMountPath = imcs.copyPackageToContainer( 11857 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 11858 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 11859 11860 if (newMountPath != null) { 11861 setMountPath(newMountPath); 11862 return PackageManager.INSTALL_SUCCEEDED; 11863 } else { 11864 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11865 } 11866 } 11867 11868 @Override 11869 String getCodePath() { 11870 return packagePath; 11871 } 11872 11873 @Override 11874 String getResourcePath() { 11875 return resourcePath; 11876 } 11877 11878 int doPreInstall(int status) { 11879 if (status != PackageManager.INSTALL_SUCCEEDED) { 11880 // Destroy container 11881 PackageHelper.destroySdDir(cid); 11882 } else { 11883 boolean mounted = PackageHelper.isContainerMounted(cid); 11884 if (!mounted) { 11885 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 11886 Process.SYSTEM_UID); 11887 if (newMountPath != null) { 11888 setMountPath(newMountPath); 11889 } else { 11890 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11891 } 11892 } 11893 } 11894 return status; 11895 } 11896 11897 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11898 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 11899 String newMountPath = null; 11900 if (PackageHelper.isContainerMounted(cid)) { 11901 // Unmount the container 11902 if (!PackageHelper.unMountSdDir(cid)) { 11903 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 11904 return false; 11905 } 11906 } 11907 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11908 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 11909 " which might be stale. Will try to clean up."); 11910 // Clean up the stale container and proceed to recreate. 11911 if (!PackageHelper.destroySdDir(newCacheId)) { 11912 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 11913 return false; 11914 } 11915 // Successfully cleaned up stale container. Try to rename again. 11916 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11917 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 11918 + " inspite of cleaning it up."); 11919 return false; 11920 } 11921 } 11922 if (!PackageHelper.isContainerMounted(newCacheId)) { 11923 Slog.w(TAG, "Mounting container " + newCacheId); 11924 newMountPath = PackageHelper.mountSdDir(newCacheId, 11925 getEncryptKey(), Process.SYSTEM_UID); 11926 } else { 11927 newMountPath = PackageHelper.getSdDir(newCacheId); 11928 } 11929 if (newMountPath == null) { 11930 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 11931 return false; 11932 } 11933 Log.i(TAG, "Succesfully renamed " + cid + 11934 " to " + newCacheId + 11935 " at new path: " + newMountPath); 11936 cid = newCacheId; 11937 11938 final File beforeCodeFile = new File(packagePath); 11939 setMountPath(newMountPath); 11940 final File afterCodeFile = new File(packagePath); 11941 11942 // Reflect the rename in scanned details 11943 pkg.codePath = afterCodeFile.getAbsolutePath(); 11944 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11945 pkg.baseCodePath); 11946 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11947 pkg.splitCodePaths); 11948 11949 // Reflect the rename in app info 11950 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11951 pkg.applicationInfo.setCodePath(pkg.codePath); 11952 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11953 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11954 pkg.applicationInfo.setResourcePath(pkg.codePath); 11955 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11956 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11957 11958 return true; 11959 } 11960 11961 private void setMountPath(String mountPath) { 11962 final File mountFile = new File(mountPath); 11963 11964 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 11965 if (monolithicFile.exists()) { 11966 packagePath = monolithicFile.getAbsolutePath(); 11967 if (isFwdLocked()) { 11968 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 11969 } else { 11970 resourcePath = packagePath; 11971 } 11972 } else { 11973 packagePath = mountFile.getAbsolutePath(); 11974 resourcePath = packagePath; 11975 } 11976 } 11977 11978 int doPostInstall(int status, int uid) { 11979 if (status != PackageManager.INSTALL_SUCCEEDED) { 11980 cleanUp(); 11981 } else { 11982 final int groupOwner; 11983 final String protectedFile; 11984 if (isFwdLocked()) { 11985 groupOwner = UserHandle.getSharedAppGid(uid); 11986 protectedFile = RES_FILE_NAME; 11987 } else { 11988 groupOwner = -1; 11989 protectedFile = null; 11990 } 11991 11992 if (uid < Process.FIRST_APPLICATION_UID 11993 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 11994 Slog.e(TAG, "Failed to finalize " + cid); 11995 PackageHelper.destroySdDir(cid); 11996 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11997 } 11998 11999 boolean mounted = PackageHelper.isContainerMounted(cid); 12000 if (!mounted) { 12001 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 12002 } 12003 } 12004 return status; 12005 } 12006 12007 private void cleanUp() { 12008 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 12009 12010 // Destroy secure container 12011 PackageHelper.destroySdDir(cid); 12012 } 12013 12014 private List<String> getAllCodePaths() { 12015 final File codeFile = new File(getCodePath()); 12016 if (codeFile != null && codeFile.exists()) { 12017 try { 12018 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 12019 return pkg.getAllCodePaths(); 12020 } catch (PackageParserException e) { 12021 // Ignored; we tried our best 12022 } 12023 } 12024 return Collections.EMPTY_LIST; 12025 } 12026 12027 void cleanUpResourcesLI() { 12028 // Enumerate all code paths before deleting 12029 cleanUpResourcesLI(getAllCodePaths()); 12030 } 12031 12032 private void cleanUpResourcesLI(List<String> allCodePaths) { 12033 cleanUp(); 12034 removeDexFiles(allCodePaths, instructionSets); 12035 } 12036 12037 String getPackageName() { 12038 return getAsecPackageName(cid); 12039 } 12040 12041 boolean doPostDeleteLI(boolean delete) { 12042 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 12043 final List<String> allCodePaths = getAllCodePaths(); 12044 boolean mounted = PackageHelper.isContainerMounted(cid); 12045 if (mounted) { 12046 // Unmount first 12047 if (PackageHelper.unMountSdDir(cid)) { 12048 mounted = false; 12049 } 12050 } 12051 if (!mounted && delete) { 12052 cleanUpResourcesLI(allCodePaths); 12053 } 12054 return !mounted; 12055 } 12056 12057 @Override 12058 int doPreCopy() { 12059 if (isFwdLocked()) { 12060 if (!PackageHelper.fixSdPermissions(cid, 12061 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 12062 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12063 } 12064 } 12065 12066 return PackageManager.INSTALL_SUCCEEDED; 12067 } 12068 12069 @Override 12070 int doPostCopy(int uid) { 12071 if (isFwdLocked()) { 12072 if (uid < Process.FIRST_APPLICATION_UID 12073 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 12074 RES_FILE_NAME)) { 12075 Slog.e(TAG, "Failed to finalize " + cid); 12076 PackageHelper.destroySdDir(cid); 12077 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12078 } 12079 } 12080 12081 return PackageManager.INSTALL_SUCCEEDED; 12082 } 12083 } 12084 12085 /** 12086 * Logic to handle movement of existing installed applications. 12087 */ 12088 class MoveInstallArgs extends InstallArgs { 12089 private File codeFile; 12090 private File resourceFile; 12091 12092 /** New install */ 12093 MoveInstallArgs(InstallParams params) { 12094 super(params.origin, params.move, params.observer, params.installFlags, 12095 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 12096 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 12097 params.grantedRuntimePermissions, 12098 params.traceMethod, params.traceCookie); 12099 } 12100 12101 int copyApk(IMediaContainerService imcs, boolean temp) { 12102 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 12103 + move.fromUuid + " to " + move.toUuid); 12104 synchronized (mInstaller) { 12105 if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName, 12106 move.dataAppName, move.appId, move.seinfo) != 0) { 12107 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12108 } 12109 } 12110 12111 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 12112 resourceFile = codeFile; 12113 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 12114 12115 return PackageManager.INSTALL_SUCCEEDED; 12116 } 12117 12118 int doPreInstall(int status) { 12119 if (status != PackageManager.INSTALL_SUCCEEDED) { 12120 cleanUp(move.toUuid); 12121 } 12122 return status; 12123 } 12124 12125 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12126 if (status != PackageManager.INSTALL_SUCCEEDED) { 12127 cleanUp(move.toUuid); 12128 return false; 12129 } 12130 12131 // Reflect the move in app info 12132 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 12133 pkg.applicationInfo.setCodePath(pkg.codePath); 12134 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 12135 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 12136 pkg.applicationInfo.setResourcePath(pkg.codePath); 12137 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 12138 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 12139 12140 return true; 12141 } 12142 12143 int doPostInstall(int status, int uid) { 12144 if (status == PackageManager.INSTALL_SUCCEEDED) { 12145 cleanUp(move.fromUuid); 12146 } else { 12147 cleanUp(move.toUuid); 12148 } 12149 return status; 12150 } 12151 12152 @Override 12153 String getCodePath() { 12154 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 12155 } 12156 12157 @Override 12158 String getResourcePath() { 12159 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 12160 } 12161 12162 private boolean cleanUp(String volumeUuid) { 12163 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 12164 move.dataAppName); 12165 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 12166 synchronized (mInstallLock) { 12167 // Clean up both app data and code 12168 removeDataDirsLI(volumeUuid, move.packageName); 12169 if (codeFile.isDirectory()) { 12170 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 12171 } else { 12172 codeFile.delete(); 12173 } 12174 } 12175 return true; 12176 } 12177 12178 void cleanUpResourcesLI() { 12179 throw new UnsupportedOperationException(); 12180 } 12181 12182 boolean doPostDeleteLI(boolean delete) { 12183 throw new UnsupportedOperationException(); 12184 } 12185 } 12186 12187 static String getAsecPackageName(String packageCid) { 12188 int idx = packageCid.lastIndexOf("-"); 12189 if (idx == -1) { 12190 return packageCid; 12191 } 12192 return packageCid.substring(0, idx); 12193 } 12194 12195 // Utility method used to create code paths based on package name and available index. 12196 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 12197 String idxStr = ""; 12198 int idx = 1; 12199 // Fall back to default value of idx=1 if prefix is not 12200 // part of oldCodePath 12201 if (oldCodePath != null) { 12202 String subStr = oldCodePath; 12203 // Drop the suffix right away 12204 if (suffix != null && subStr.endsWith(suffix)) { 12205 subStr = subStr.substring(0, subStr.length() - suffix.length()); 12206 } 12207 // If oldCodePath already contains prefix find out the 12208 // ending index to either increment or decrement. 12209 int sidx = subStr.lastIndexOf(prefix); 12210 if (sidx != -1) { 12211 subStr = subStr.substring(sidx + prefix.length()); 12212 if (subStr != null) { 12213 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 12214 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 12215 } 12216 try { 12217 idx = Integer.parseInt(subStr); 12218 if (idx <= 1) { 12219 idx++; 12220 } else { 12221 idx--; 12222 } 12223 } catch(NumberFormatException e) { 12224 } 12225 } 12226 } 12227 } 12228 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 12229 return prefix + idxStr; 12230 } 12231 12232 private File getNextCodePath(File targetDir, String packageName) { 12233 int suffix = 1; 12234 File result; 12235 do { 12236 result = new File(targetDir, packageName + "-" + suffix); 12237 suffix++; 12238 } while (result.exists()); 12239 return result; 12240 } 12241 12242 // Utility method that returns the relative package path with respect 12243 // to the installation directory. Like say for /data/data/com.test-1.apk 12244 // string com.test-1 is returned. 12245 static String deriveCodePathName(String codePath) { 12246 if (codePath == null) { 12247 return null; 12248 } 12249 final File codeFile = new File(codePath); 12250 final String name = codeFile.getName(); 12251 if (codeFile.isDirectory()) { 12252 return name; 12253 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 12254 final int lastDot = name.lastIndexOf('.'); 12255 return name.substring(0, lastDot); 12256 } else { 12257 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 12258 return null; 12259 } 12260 } 12261 12262 static class PackageInstalledInfo { 12263 String name; 12264 int uid; 12265 // The set of users that originally had this package installed. 12266 int[] origUsers; 12267 // The set of users that now have this package installed. 12268 int[] newUsers; 12269 PackageParser.Package pkg; 12270 int returnCode; 12271 String returnMsg; 12272 PackageRemovedInfo removedInfo; 12273 12274 public void setError(int code, String msg) { 12275 returnCode = code; 12276 returnMsg = msg; 12277 Slog.w(TAG, msg); 12278 } 12279 12280 public void setError(String msg, PackageParserException e) { 12281 returnCode = e.error; 12282 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 12283 Slog.w(TAG, msg, e); 12284 } 12285 12286 public void setError(String msg, PackageManagerException e) { 12287 returnCode = e.error; 12288 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 12289 Slog.w(TAG, msg, e); 12290 } 12291 12292 // In some error cases we want to convey more info back to the observer 12293 String origPackage; 12294 String origPermission; 12295 } 12296 12297 /* 12298 * Install a non-existing package. 12299 */ 12300 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 12301 UserHandle user, String installerPackageName, String volumeUuid, 12302 PackageInstalledInfo res) { 12303 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 12304 12305 // Remember this for later, in case we need to rollback this install 12306 String pkgName = pkg.packageName; 12307 12308 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 12309 // TODO: b/23350563 12310 final boolean dataDirExists = Environment 12311 .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists(); 12312 12313 synchronized(mPackages) { 12314 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 12315 // A package with the same name is already installed, though 12316 // it has been renamed to an older name. The package we 12317 // are trying to install should be installed as an update to 12318 // the existing one, but that has not been requested, so bail. 12319 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 12320 + " without first uninstalling package running as " 12321 + mSettings.mRenamedPackages.get(pkgName)); 12322 return; 12323 } 12324 if (mPackages.containsKey(pkgName)) { 12325 // Don't allow installation over an existing package with the same name. 12326 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 12327 + " without first uninstalling."); 12328 return; 12329 } 12330 } 12331 12332 try { 12333 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 12334 System.currentTimeMillis(), user); 12335 12336 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 12337 // delete the partially installed application. the data directory will have to be 12338 // restored if it was already existing 12339 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12340 // remove package from internal structures. Note that we want deletePackageX to 12341 // delete the package data and cache directories that it created in 12342 // scanPackageLocked, unless those directories existed before we even tried to 12343 // install. 12344 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 12345 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 12346 res.removedInfo, true); 12347 } 12348 12349 } catch (PackageManagerException e) { 12350 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12351 } 12352 12353 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12354 } 12355 12356 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 12357 // Can't rotate keys during boot or if sharedUser. 12358 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 12359 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 12360 return false; 12361 } 12362 // app is using upgradeKeySets; make sure all are valid 12363 KeySetManagerService ksms = mSettings.mKeySetManagerService; 12364 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 12365 for (int i = 0; i < upgradeKeySets.length; i++) { 12366 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 12367 Slog.wtf(TAG, "Package " 12368 + (oldPs.name != null ? oldPs.name : "<null>") 12369 + " contains upgrade-key-set reference to unknown key-set: " 12370 + upgradeKeySets[i] 12371 + " reverting to signatures check."); 12372 return false; 12373 } 12374 } 12375 return true; 12376 } 12377 12378 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 12379 // Upgrade keysets are being used. Determine if new package has a superset of the 12380 // required keys. 12381 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 12382 KeySetManagerService ksms = mSettings.mKeySetManagerService; 12383 for (int i = 0; i < upgradeKeySets.length; i++) { 12384 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 12385 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 12386 return true; 12387 } 12388 } 12389 return false; 12390 } 12391 12392 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 12393 UserHandle user, String installerPackageName, String volumeUuid, 12394 PackageInstalledInfo res) { 12395 final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 12396 12397 final PackageParser.Package oldPackage; 12398 final String pkgName = pkg.packageName; 12399 final int[] allUsers; 12400 final boolean[] perUserInstalled; 12401 12402 // First find the old package info and check signatures 12403 synchronized(mPackages) { 12404 oldPackage = mPackages.get(pkgName); 12405 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 12406 if (isEphemeral && !oldIsEphemeral) { 12407 // can't downgrade from full to ephemeral 12408 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 12409 res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 12410 return; 12411 } 12412 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 12413 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12414 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12415 if(!checkUpgradeKeySetLP(ps, pkg)) { 12416 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 12417 "New package not signed by keys specified by upgrade-keysets: " 12418 + pkgName); 12419 return; 12420 } 12421 } else { 12422 // default to original signature matching 12423 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 12424 != PackageManager.SIGNATURE_MATCH) { 12425 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 12426 "New package has a different signature: " + pkgName); 12427 return; 12428 } 12429 } 12430 12431 // In case of rollback, remember per-user/profile install state 12432 allUsers = sUserManager.getUserIds(); 12433 perUserInstalled = new boolean[allUsers.length]; 12434 for (int i = 0; i < allUsers.length; i++) { 12435 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12436 } 12437 } 12438 12439 boolean sysPkg = (isSystemApp(oldPackage)); 12440 if (sysPkg) { 12441 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 12442 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 12443 } else { 12444 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 12445 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 12446 } 12447 } 12448 12449 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 12450 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 12451 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 12452 String volumeUuid, PackageInstalledInfo res) { 12453 String pkgName = deletedPackage.packageName; 12454 boolean deletedPkg = true; 12455 boolean updatedSettings = false; 12456 12457 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 12458 + deletedPackage); 12459 long origUpdateTime; 12460 if (pkg.mExtras != null) { 12461 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 12462 } else { 12463 origUpdateTime = 0; 12464 } 12465 12466 // First delete the existing package while retaining the data directory 12467 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 12468 res.removedInfo, true)) { 12469 // If the existing package wasn't successfully deleted 12470 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 12471 deletedPkg = false; 12472 } else { 12473 // Successfully deleted the old package; proceed with replace. 12474 12475 // If deleted package lived in a container, give users a chance to 12476 // relinquish resources before killing. 12477 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 12478 if (DEBUG_INSTALL) { 12479 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 12480 } 12481 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 12482 final ArrayList<String> pkgList = new ArrayList<String>(1); 12483 pkgList.add(deletedPackage.applicationInfo.packageName); 12484 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 12485 } 12486 12487 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 12488 try { 12489 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 12490 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 12491 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12492 perUserInstalled, res, user); 12493 updatedSettings = true; 12494 } catch (PackageManagerException e) { 12495 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12496 } 12497 } 12498 12499 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12500 // remove package from internal structures. Note that we want deletePackageX to 12501 // delete the package data and cache directories that it created in 12502 // scanPackageLocked, unless those directories existed before we even tried to 12503 // install. 12504 if(updatedSettings) { 12505 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 12506 deletePackageLI( 12507 pkgName, null, true, allUsers, perUserInstalled, 12508 PackageManager.DELETE_KEEP_DATA, 12509 res.removedInfo, true); 12510 } 12511 // Since we failed to install the new package we need to restore the old 12512 // package that we deleted. 12513 if (deletedPkg) { 12514 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 12515 File restoreFile = new File(deletedPackage.codePath); 12516 // Parse old package 12517 boolean oldExternal = isExternal(deletedPackage); 12518 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 12519 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 12520 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 12521 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 12522 try { 12523 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 12524 null); 12525 } catch (PackageManagerException e) { 12526 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 12527 + e.getMessage()); 12528 return; 12529 } 12530 // Restore of old package succeeded. Update permissions. 12531 // writer 12532 synchronized (mPackages) { 12533 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 12534 UPDATE_PERMISSIONS_ALL); 12535 // can downgrade to reader 12536 mSettings.writeLPr(); 12537 } 12538 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 12539 } 12540 } 12541 } 12542 12543 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 12544 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 12545 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 12546 String volumeUuid, PackageInstalledInfo res) { 12547 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 12548 + ", old=" + deletedPackage); 12549 boolean disabledSystem = false; 12550 boolean updatedSettings = false; 12551 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 12552 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 12553 != 0) { 12554 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12555 } 12556 String packageName = deletedPackage.packageName; 12557 if (packageName == null) { 12558 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12559 "Attempt to delete null packageName."); 12560 return; 12561 } 12562 PackageParser.Package oldPkg; 12563 PackageSetting oldPkgSetting; 12564 // reader 12565 synchronized (mPackages) { 12566 oldPkg = mPackages.get(packageName); 12567 oldPkgSetting = mSettings.mPackages.get(packageName); 12568 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 12569 (oldPkgSetting == null)) { 12570 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12571 "Couldn't find package:" + packageName + " information"); 12572 return; 12573 } 12574 } 12575 12576 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 12577 12578 res.removedInfo.uid = oldPkg.applicationInfo.uid; 12579 res.removedInfo.removedPackage = packageName; 12580 // Remove existing system package 12581 removePackageLI(oldPkgSetting, true); 12582 // writer 12583 synchronized (mPackages) { 12584 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 12585 if (!disabledSystem && deletedPackage != null) { 12586 // We didn't need to disable the .apk as a current system package, 12587 // which means we are replacing another update that is already 12588 // installed. We need to make sure to delete the older one's .apk. 12589 res.removedInfo.args = createInstallArgsForExisting(0, 12590 deletedPackage.applicationInfo.getCodePath(), 12591 deletedPackage.applicationInfo.getResourcePath(), 12592 getAppDexInstructionSets(deletedPackage.applicationInfo)); 12593 } else { 12594 res.removedInfo.args = null; 12595 } 12596 } 12597 12598 // Successfully disabled the old package. Now proceed with re-installation 12599 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 12600 12601 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12602 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 12603 12604 PackageParser.Package newPackage = null; 12605 try { 12606 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 12607 if (newPackage.mExtras != null) { 12608 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 12609 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 12610 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 12611 12612 // is the update attempting to change shared user? that isn't going to work... 12613 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 12614 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 12615 "Forbidding shared user change from " + oldPkgSetting.sharedUser 12616 + " to " + newPkgSetting.sharedUser); 12617 updatedSettings = true; 12618 } 12619 } 12620 12621 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12622 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12623 perUserInstalled, res, user); 12624 updatedSettings = true; 12625 } 12626 12627 } catch (PackageManagerException e) { 12628 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12629 } 12630 12631 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12632 // Re installation failed. Restore old information 12633 // Remove new pkg information 12634 if (newPackage != null) { 12635 removeInstalledPackageLI(newPackage, true); 12636 } 12637 // Add back the old system package 12638 try { 12639 scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 12640 } catch (PackageManagerException e) { 12641 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 12642 } 12643 // Restore the old system information in Settings 12644 synchronized (mPackages) { 12645 if (disabledSystem) { 12646 mSettings.enableSystemPackageLPw(packageName); 12647 } 12648 if (updatedSettings) { 12649 mSettings.setInstallerPackageName(packageName, 12650 oldPkgSetting.installerPackageName); 12651 } 12652 mSettings.writeLPr(); 12653 } 12654 } 12655 } 12656 12657 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 12658 // Collect all used permissions in the UID 12659 ArraySet<String> usedPermissions = new ArraySet<>(); 12660 final int packageCount = su.packages.size(); 12661 for (int i = 0; i < packageCount; i++) { 12662 PackageSetting ps = su.packages.valueAt(i); 12663 if (ps.pkg == null) { 12664 continue; 12665 } 12666 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 12667 for (int j = 0; j < requestedPermCount; j++) { 12668 String permission = ps.pkg.requestedPermissions.get(j); 12669 BasePermission bp = mSettings.mPermissions.get(permission); 12670 if (bp != null) { 12671 usedPermissions.add(permission); 12672 } 12673 } 12674 } 12675 12676 PermissionsState permissionsState = su.getPermissionsState(); 12677 // Prune install permissions 12678 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 12679 final int installPermCount = installPermStates.size(); 12680 for (int i = installPermCount - 1; i >= 0; i--) { 12681 PermissionState permissionState = installPermStates.get(i); 12682 if (!usedPermissions.contains(permissionState.getName())) { 12683 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 12684 if (bp != null) { 12685 permissionsState.revokeInstallPermission(bp); 12686 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 12687 PackageManager.MASK_PERMISSION_FLAGS, 0); 12688 } 12689 } 12690 } 12691 12692 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 12693 12694 // Prune runtime permissions 12695 for (int userId : allUserIds) { 12696 List<PermissionState> runtimePermStates = permissionsState 12697 .getRuntimePermissionStates(userId); 12698 final int runtimePermCount = runtimePermStates.size(); 12699 for (int i = runtimePermCount - 1; i >= 0; i--) { 12700 PermissionState permissionState = runtimePermStates.get(i); 12701 if (!usedPermissions.contains(permissionState.getName())) { 12702 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 12703 if (bp != null) { 12704 permissionsState.revokeRuntimePermission(bp, userId); 12705 permissionsState.updatePermissionFlags(bp, userId, 12706 PackageManager.MASK_PERMISSION_FLAGS, 0); 12707 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 12708 runtimePermissionChangedUserIds, userId); 12709 } 12710 } 12711 } 12712 } 12713 12714 return runtimePermissionChangedUserIds; 12715 } 12716 12717 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 12718 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 12719 UserHandle user) { 12720 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 12721 12722 String pkgName = newPackage.packageName; 12723 synchronized (mPackages) { 12724 //write settings. the installStatus will be incomplete at this stage. 12725 //note that the new package setting would have already been 12726 //added to mPackages. It hasn't been persisted yet. 12727 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 12728 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 12729 mSettings.writeLPr(); 12730 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12731 } 12732 12733 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 12734 synchronized (mPackages) { 12735 updatePermissionsLPw(newPackage.packageName, newPackage, 12736 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 12737 ? UPDATE_PERMISSIONS_ALL : 0)); 12738 // For system-bundled packages, we assume that installing an upgraded version 12739 // of the package implies that the user actually wants to run that new code, 12740 // so we enable the package. 12741 PackageSetting ps = mSettings.mPackages.get(pkgName); 12742 if (ps != null) { 12743 if (isSystemApp(newPackage)) { 12744 // NB: implicit assumption that system package upgrades apply to all users 12745 if (DEBUG_INSTALL) { 12746 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 12747 } 12748 if (res.origUsers != null) { 12749 for (int userHandle : res.origUsers) { 12750 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 12751 userHandle, installerPackageName); 12752 } 12753 } 12754 // Also convey the prior install/uninstall state 12755 if (allUsers != null && perUserInstalled != null) { 12756 for (int i = 0; i < allUsers.length; i++) { 12757 if (DEBUG_INSTALL) { 12758 Slog.d(TAG, " user " + allUsers[i] 12759 + " => " + perUserInstalled[i]); 12760 } 12761 ps.setInstalled(perUserInstalled[i], allUsers[i]); 12762 } 12763 // these install state changes will be persisted in the 12764 // upcoming call to mSettings.writeLPr(). 12765 } 12766 } 12767 // It's implied that when a user requests installation, they want the app to be 12768 // installed and enabled. 12769 int userId = user.getIdentifier(); 12770 if (userId != UserHandle.USER_ALL) { 12771 ps.setInstalled(true, userId); 12772 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 12773 } 12774 } 12775 res.name = pkgName; 12776 res.uid = newPackage.applicationInfo.uid; 12777 res.pkg = newPackage; 12778 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 12779 mSettings.setInstallerPackageName(pkgName, installerPackageName); 12780 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12781 //to update install status 12782 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 12783 mSettings.writeLPr(); 12784 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12785 } 12786 12787 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12788 } 12789 12790 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 12791 try { 12792 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 12793 installPackageLI(args, res); 12794 } finally { 12795 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12796 } 12797 } 12798 12799 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 12800 final int installFlags = args.installFlags; 12801 final String installerPackageName = args.installerPackageName; 12802 final String volumeUuid = args.volumeUuid; 12803 final File tmpPackageFile = new File(args.getCodePath()); 12804 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 12805 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 12806 || (args.volumeUuid != null)); 12807 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 12808 boolean replace = false; 12809 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 12810 if (args.move != null) { 12811 // moving a complete application; perfom an initial scan on the new install location 12812 scanFlags |= SCAN_INITIAL; 12813 } 12814 // Result object to be returned 12815 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12816 12817 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 12818 12819 // Sanity check 12820 if (ephemeral && (forwardLocked || onExternal)) { 12821 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 12822 + " external=" + onExternal); 12823 res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 12824 return; 12825 } 12826 12827 // Retrieve PackageSettings and parse package 12828 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 12829 | PackageParser.PARSE_ENFORCE_CODE 12830 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 12831 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 12832 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0); 12833 PackageParser pp = new PackageParser(); 12834 pp.setSeparateProcesses(mSeparateProcesses); 12835 pp.setDisplayMetrics(mMetrics); 12836 12837 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 12838 final PackageParser.Package pkg; 12839 try { 12840 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 12841 } catch (PackageParserException e) { 12842 res.setError("Failed parse during installPackageLI", e); 12843 return; 12844 } finally { 12845 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12846 } 12847 12848 // Mark that we have an install time CPU ABI override. 12849 pkg.cpuAbiOverride = args.abiOverride; 12850 12851 String pkgName = res.name = pkg.packageName; 12852 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 12853 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 12854 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 12855 return; 12856 } 12857 } 12858 12859 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 12860 try { 12861 pp.collectCertificates(pkg, parseFlags); 12862 } catch (PackageParserException e) { 12863 res.setError("Failed collect during installPackageLI", e); 12864 return; 12865 } finally { 12866 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12867 } 12868 12869 /* If the installer passed in a manifest digest, compare it now. */ 12870 if (args.manifestDigest != null) { 12871 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectManifestDigest"); 12872 try { 12873 pp.collectManifestDigest(pkg); 12874 } catch (PackageParserException e) { 12875 res.setError("Failed collect during installPackageLI", e); 12876 return; 12877 } finally { 12878 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12879 } 12880 12881 if (DEBUG_INSTALL) { 12882 final String parsedManifest = pkg.manifestDigest == null ? "null" 12883 : pkg.manifestDigest.toString(); 12884 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 12885 + parsedManifest); 12886 } 12887 12888 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 12889 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 12890 return; 12891 } 12892 } else if (DEBUG_INSTALL) { 12893 final String parsedManifest = pkg.manifestDigest == null 12894 ? "null" : pkg.manifestDigest.toString(); 12895 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 12896 } 12897 12898 // Get rid of all references to package scan path via parser. 12899 pp = null; 12900 String oldCodePath = null; 12901 boolean systemApp = false; 12902 synchronized (mPackages) { 12903 // Check if installing already existing package 12904 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12905 String oldName = mSettings.mRenamedPackages.get(pkgName); 12906 if (pkg.mOriginalPackages != null 12907 && pkg.mOriginalPackages.contains(oldName) 12908 && mPackages.containsKey(oldName)) { 12909 // This package is derived from an original package, 12910 // and this device has been updating from that original 12911 // name. We must continue using the original name, so 12912 // rename the new package here. 12913 pkg.setPackageName(oldName); 12914 pkgName = pkg.packageName; 12915 replace = true; 12916 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 12917 + oldName + " pkgName=" + pkgName); 12918 } else if (mPackages.containsKey(pkgName)) { 12919 // This package, under its official name, already exists 12920 // on the device; we should replace it. 12921 replace = true; 12922 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 12923 } 12924 12925 // Prevent apps opting out from runtime permissions 12926 if (replace) { 12927 PackageParser.Package oldPackage = mPackages.get(pkgName); 12928 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 12929 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 12930 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 12931 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 12932 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 12933 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 12934 + " doesn't support runtime permissions but the old" 12935 + " target SDK " + oldTargetSdk + " does."); 12936 return; 12937 } 12938 } 12939 } 12940 12941 PackageSetting ps = mSettings.mPackages.get(pkgName); 12942 if (ps != null) { 12943 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 12944 12945 // Quick sanity check that we're signed correctly if updating; 12946 // we'll check this again later when scanning, but we want to 12947 // bail early here before tripping over redefined permissions. 12948 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12949 if (!checkUpgradeKeySetLP(ps, pkg)) { 12950 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 12951 + pkg.packageName + " upgrade keys do not match the " 12952 + "previously installed version"); 12953 return; 12954 } 12955 } else { 12956 try { 12957 verifySignaturesLP(ps, pkg); 12958 } catch (PackageManagerException e) { 12959 res.setError(e.error, e.getMessage()); 12960 return; 12961 } 12962 } 12963 12964 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 12965 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 12966 systemApp = (ps.pkg.applicationInfo.flags & 12967 ApplicationInfo.FLAG_SYSTEM) != 0; 12968 } 12969 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12970 } 12971 12972 // Check whether the newly-scanned package wants to define an already-defined perm 12973 int N = pkg.permissions.size(); 12974 for (int i = N-1; i >= 0; i--) { 12975 PackageParser.Permission perm = pkg.permissions.get(i); 12976 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 12977 if (bp != null) { 12978 // If the defining package is signed with our cert, it's okay. This 12979 // also includes the "updating the same package" case, of course. 12980 // "updating same package" could also involve key-rotation. 12981 final boolean sigsOk; 12982 if (bp.sourcePackage.equals(pkg.packageName) 12983 && (bp.packageSetting instanceof PackageSetting) 12984 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 12985 scanFlags))) { 12986 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 12987 } else { 12988 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 12989 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 12990 } 12991 if (!sigsOk) { 12992 // If the owning package is the system itself, we log but allow 12993 // install to proceed; we fail the install on all other permission 12994 // redefinitions. 12995 if (!bp.sourcePackage.equals("android")) { 12996 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 12997 + pkg.packageName + " attempting to redeclare permission " 12998 + perm.info.name + " already owned by " + bp.sourcePackage); 12999 res.origPermission = perm.info.name; 13000 res.origPackage = bp.sourcePackage; 13001 return; 13002 } else { 13003 Slog.w(TAG, "Package " + pkg.packageName 13004 + " attempting to redeclare system permission " 13005 + perm.info.name + "; ignoring new declaration"); 13006 pkg.permissions.remove(i); 13007 } 13008 } 13009 } 13010 } 13011 13012 } 13013 13014 if (systemApp) { 13015 if (onExternal) { 13016 // Abort update; system app can't be replaced with app on sdcard 13017 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 13018 "Cannot install updates to system apps on sdcard"); 13019 return; 13020 } else if (ephemeral) { 13021 // Abort update; system app can't be replaced with an ephemeral app 13022 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 13023 "Cannot update a system app with an ephemeral app"); 13024 return; 13025 } 13026 } 13027 13028 if (args.move != null) { 13029 // We did an in-place move, so dex is ready to roll 13030 scanFlags |= SCAN_NO_DEX; 13031 scanFlags |= SCAN_MOVE; 13032 13033 synchronized (mPackages) { 13034 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13035 if (ps == null) { 13036 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 13037 "Missing settings for moved package " + pkgName); 13038 } 13039 13040 // We moved the entire application as-is, so bring over the 13041 // previously derived ABI information. 13042 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 13043 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 13044 } 13045 13046 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 13047 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 13048 scanFlags |= SCAN_NO_DEX; 13049 13050 try { 13051 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 13052 true /* extract libs */); 13053 } catch (PackageManagerException pme) { 13054 Slog.e(TAG, "Error deriving application ABI", pme); 13055 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 13056 return; 13057 } 13058 } 13059 13060 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 13061 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 13062 return; 13063 } 13064 13065 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 13066 13067 if (replace) { 13068 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 13069 installerPackageName, volumeUuid, res); 13070 } else { 13071 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 13072 args.user, installerPackageName, volumeUuid, res); 13073 } 13074 synchronized (mPackages) { 13075 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13076 if (ps != null) { 13077 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 13078 } 13079 } 13080 } 13081 13082 private void startIntentFilterVerifications(int userId, boolean replacing, 13083 PackageParser.Package pkg) { 13084 if (mIntentFilterVerifierComponent == null) { 13085 Slog.w(TAG, "No IntentFilter verification will not be done as " 13086 + "there is no IntentFilterVerifier available!"); 13087 return; 13088 } 13089 13090 final int verifierUid = getPackageUid( 13091 mIntentFilterVerifierComponent.getPackageName(), 13092 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 13093 13094 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 13095 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 13096 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 13097 mHandler.sendMessage(msg); 13098 } 13099 13100 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 13101 PackageParser.Package pkg) { 13102 int size = pkg.activities.size(); 13103 if (size == 0) { 13104 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 13105 "No activity, so no need to verify any IntentFilter!"); 13106 return; 13107 } 13108 13109 final boolean hasDomainURLs = hasDomainURLs(pkg); 13110 if (!hasDomainURLs) { 13111 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 13112 "No domain URLs, so no need to verify any IntentFilter!"); 13113 return; 13114 } 13115 13116 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 13117 + " if any IntentFilter from the " + size 13118 + " Activities needs verification ..."); 13119 13120 int count = 0; 13121 final String packageName = pkg.packageName; 13122 13123 synchronized (mPackages) { 13124 // If this is a new install and we see that we've already run verification for this 13125 // package, we have nothing to do: it means the state was restored from backup. 13126 if (!replacing) { 13127 IntentFilterVerificationInfo ivi = 13128 mSettings.getIntentFilterVerificationLPr(packageName); 13129 if (ivi != null) { 13130 if (DEBUG_DOMAIN_VERIFICATION) { 13131 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 13132 + ivi.getStatusString()); 13133 } 13134 return; 13135 } 13136 } 13137 13138 // If any filters need to be verified, then all need to be. 13139 boolean needToVerify = false; 13140 for (PackageParser.Activity a : pkg.activities) { 13141 for (ActivityIntentInfo filter : a.intents) { 13142 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 13143 if (DEBUG_DOMAIN_VERIFICATION) { 13144 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 13145 } 13146 needToVerify = true; 13147 break; 13148 } 13149 } 13150 } 13151 13152 if (needToVerify) { 13153 final int verificationId = mIntentFilterVerificationToken++; 13154 for (PackageParser.Activity a : pkg.activities) { 13155 for (ActivityIntentInfo filter : a.intents) { 13156 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 13157 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 13158 "Verification needed for IntentFilter:" + filter.toString()); 13159 mIntentFilterVerifier.addOneIntentFilterVerification( 13160 verifierUid, userId, verificationId, filter, packageName); 13161 count++; 13162 } 13163 } 13164 } 13165 } 13166 } 13167 13168 if (count > 0) { 13169 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 13170 + " IntentFilter verification" + (count > 1 ? "s" : "") 13171 + " for userId:" + userId); 13172 mIntentFilterVerifier.startVerifications(userId); 13173 } else { 13174 if (DEBUG_DOMAIN_VERIFICATION) { 13175 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 13176 } 13177 } 13178 } 13179 13180 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 13181 final ComponentName cn = filter.activity.getComponentName(); 13182 final String packageName = cn.getPackageName(); 13183 13184 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 13185 packageName); 13186 if (ivi == null) { 13187 return true; 13188 } 13189 int status = ivi.getStatus(); 13190 switch (status) { 13191 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 13192 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 13193 return true; 13194 13195 default: 13196 // Nothing to do 13197 return false; 13198 } 13199 } 13200 13201 private static boolean isMultiArch(ApplicationInfo info) { 13202 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 13203 } 13204 13205 private static boolean isExternal(PackageParser.Package pkg) { 13206 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 13207 } 13208 13209 private static boolean isExternal(PackageSetting ps) { 13210 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 13211 } 13212 13213 private static boolean isEphemeral(PackageParser.Package pkg) { 13214 return pkg.applicationInfo.isEphemeralApp(); 13215 } 13216 13217 private static boolean isEphemeral(PackageSetting ps) { 13218 return ps.pkg != null && isEphemeral(ps.pkg); 13219 } 13220 13221 private static boolean isSystemApp(PackageParser.Package pkg) { 13222 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 13223 } 13224 13225 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 13226 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 13227 } 13228 13229 private static boolean hasDomainURLs(PackageParser.Package pkg) { 13230 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 13231 } 13232 13233 private static boolean isSystemApp(PackageSetting ps) { 13234 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 13235 } 13236 13237 private static boolean isUpdatedSystemApp(PackageSetting ps) { 13238 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 13239 } 13240 13241 private int packageFlagsToInstallFlags(PackageSetting ps) { 13242 int installFlags = 0; 13243 if (isEphemeral(ps)) { 13244 installFlags |= PackageManager.INSTALL_EPHEMERAL; 13245 } 13246 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 13247 // This existing package was an external ASEC install when we have 13248 // the external flag without a UUID 13249 installFlags |= PackageManager.INSTALL_EXTERNAL; 13250 } 13251 if (ps.isForwardLocked()) { 13252 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 13253 } 13254 return installFlags; 13255 } 13256 13257 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 13258 if (isExternal(pkg)) { 13259 if (TextUtils.isEmpty(pkg.volumeUuid)) { 13260 return StorageManager.UUID_PRIMARY_PHYSICAL; 13261 } else { 13262 return pkg.volumeUuid; 13263 } 13264 } else { 13265 return StorageManager.UUID_PRIVATE_INTERNAL; 13266 } 13267 } 13268 13269 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 13270 if (isExternal(pkg)) { 13271 if (TextUtils.isEmpty(pkg.volumeUuid)) { 13272 return mSettings.getExternalVersion(); 13273 } else { 13274 return mSettings.findOrCreateVersion(pkg.volumeUuid); 13275 } 13276 } else { 13277 return mSettings.getInternalVersion(); 13278 } 13279 } 13280 13281 private void deleteTempPackageFiles() { 13282 final FilenameFilter filter = new FilenameFilter() { 13283 public boolean accept(File dir, String name) { 13284 return name.startsWith("vmdl") && name.endsWith(".tmp"); 13285 } 13286 }; 13287 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 13288 file.delete(); 13289 } 13290 } 13291 13292 @Override 13293 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 13294 int flags) { 13295 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 13296 flags); 13297 } 13298 13299 @Override 13300 public void deletePackage(final String packageName, 13301 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 13302 mContext.enforceCallingOrSelfPermission( 13303 android.Manifest.permission.DELETE_PACKAGES, null); 13304 Preconditions.checkNotNull(packageName); 13305 Preconditions.checkNotNull(observer); 13306 final int uid = Binder.getCallingUid(); 13307 final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0; 13308 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 13309 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 13310 mContext.enforceCallingOrSelfPermission( 13311 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 13312 "deletePackage for user " + userId); 13313 } 13314 13315 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 13316 try { 13317 observer.onPackageDeleted(packageName, 13318 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 13319 } catch (RemoteException re) { 13320 } 13321 return; 13322 } 13323 13324 for (int currentUserId : users) { 13325 if (getBlockUninstallForUser(packageName, currentUserId)) { 13326 try { 13327 observer.onPackageDeleted(packageName, 13328 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 13329 } catch (RemoteException re) { 13330 } 13331 return; 13332 } 13333 } 13334 13335 if (DEBUG_REMOVE) { 13336 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 13337 } 13338 // Queue up an async operation since the package deletion may take a little while. 13339 mHandler.post(new Runnable() { 13340 public void run() { 13341 mHandler.removeCallbacks(this); 13342 final int returnCode = deletePackageX(packageName, userId, flags); 13343 try { 13344 observer.onPackageDeleted(packageName, returnCode, null); 13345 } catch (RemoteException e) { 13346 Log.i(TAG, "Observer no longer exists."); 13347 } //end catch 13348 } //end run 13349 }); 13350 } 13351 13352 private boolean isPackageDeviceAdmin(String packageName, int userId) { 13353 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 13354 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 13355 try { 13356 if (dpm != null) { 13357 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 13358 /* callingUserOnly =*/ false); 13359 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 13360 : deviceOwnerComponentName.getPackageName(); 13361 // Does the package contains the device owner? 13362 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 13363 // this check is probably not needed, since DO should be registered as a device 13364 // admin on some user too. (Original bug for this: b/17657954) 13365 if (packageName.equals(deviceOwnerPackageName)) { 13366 return true; 13367 } 13368 // Does it contain a device admin for any user? 13369 int[] users; 13370 if (userId == UserHandle.USER_ALL) { 13371 users = sUserManager.getUserIds(); 13372 } else { 13373 users = new int[]{userId}; 13374 } 13375 for (int i = 0; i < users.length; ++i) { 13376 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 13377 return true; 13378 } 13379 } 13380 } 13381 } catch (RemoteException e) { 13382 } 13383 return false; 13384 } 13385 13386 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 13387 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 13388 } 13389 13390 /** 13391 * This method is an internal method that could be get invoked either 13392 * to delete an installed package or to clean up a failed installation. 13393 * After deleting an installed package, a broadcast is sent to notify any 13394 * listeners that the package has been installed. For cleaning up a failed 13395 * installation, the broadcast is not necessary since the package's 13396 * installation wouldn't have sent the initial broadcast either 13397 * The key steps in deleting a package are 13398 * deleting the package information in internal structures like mPackages, 13399 * deleting the packages base directories through installd 13400 * updating mSettings to reflect current status 13401 * persisting settings for later use 13402 * sending a broadcast if necessary 13403 */ 13404 private int deletePackageX(String packageName, int userId, int flags) { 13405 final PackageRemovedInfo info = new PackageRemovedInfo(); 13406 final boolean res; 13407 13408 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 13409 ? UserHandle.ALL : new UserHandle(userId); 13410 13411 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 13412 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 13413 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 13414 } 13415 13416 boolean removedForAllUsers = false; 13417 boolean systemUpdate = false; 13418 13419 PackageParser.Package uninstalledPkg; 13420 13421 // for the uninstall-updates case and restricted profiles, remember the per- 13422 // userhandle installed state 13423 int[] allUsers; 13424 boolean[] perUserInstalled; 13425 synchronized (mPackages) { 13426 uninstalledPkg = mPackages.get(packageName); 13427 PackageSetting ps = mSettings.mPackages.get(packageName); 13428 allUsers = sUserManager.getUserIds(); 13429 perUserInstalled = new boolean[allUsers.length]; 13430 for (int i = 0; i < allUsers.length; i++) { 13431 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 13432 } 13433 } 13434 13435 synchronized (mInstallLock) { 13436 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 13437 res = deletePackageLI(packageName, removeForUser, 13438 true, allUsers, perUserInstalled, 13439 flags | REMOVE_CHATTY, info, true); 13440 systemUpdate = info.isRemovedPackageSystemUpdate; 13441 synchronized (mPackages) { 13442 if (res) { 13443 if (!systemUpdate && mPackages.get(packageName) == null) { 13444 removedForAllUsers = true; 13445 } 13446 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPkg); 13447 } 13448 } 13449 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 13450 + " removedForAllUsers=" + removedForAllUsers); 13451 } 13452 13453 if (res) { 13454 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 13455 13456 // If the removed package was a system update, the old system package 13457 // was re-enabled; we need to broadcast this information 13458 if (systemUpdate) { 13459 Bundle extras = new Bundle(1); 13460 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 13461 ? info.removedAppId : info.uid); 13462 extras.putBoolean(Intent.EXTRA_REPLACING, true); 13463 13464 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 13465 extras, 0, null, null, null); 13466 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 13467 extras, 0, null, null, null); 13468 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 13469 null, 0, packageName, null, null); 13470 } 13471 } 13472 // Force a gc here. 13473 Runtime.getRuntime().gc(); 13474 // Delete the resources here after sending the broadcast to let 13475 // other processes clean up before deleting resources. 13476 if (info.args != null) { 13477 synchronized (mInstallLock) { 13478 info.args.doPostDeleteLI(true); 13479 } 13480 } 13481 13482 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 13483 } 13484 13485 class PackageRemovedInfo { 13486 String removedPackage; 13487 int uid = -1; 13488 int removedAppId = -1; 13489 int[] removedUsers = null; 13490 boolean isRemovedPackageSystemUpdate = false; 13491 // Clean up resources deleted packages. 13492 InstallArgs args = null; 13493 13494 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 13495 Bundle extras = new Bundle(1); 13496 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 13497 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 13498 if (replacing) { 13499 extras.putBoolean(Intent.EXTRA_REPLACING, true); 13500 } 13501 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 13502 if (removedPackage != null) { 13503 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 13504 extras, 0, null, null, removedUsers); 13505 if (fullRemove && !replacing) { 13506 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 13507 extras, 0, null, null, removedUsers); 13508 } 13509 } 13510 if (removedAppId >= 0) { 13511 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 13512 removedUsers); 13513 } 13514 } 13515 } 13516 13517 /* 13518 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 13519 * flag is not set, the data directory is removed as well. 13520 * make sure this flag is set for partially installed apps. If not its meaningless to 13521 * delete a partially installed application. 13522 */ 13523 private void removePackageDataLI(PackageSetting ps, 13524 int[] allUserHandles, boolean[] perUserInstalled, 13525 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 13526 String packageName = ps.name; 13527 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 13528 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 13529 // Retrieve object to delete permissions for shared user later on 13530 final PackageSetting deletedPs; 13531 // reader 13532 synchronized (mPackages) { 13533 deletedPs = mSettings.mPackages.get(packageName); 13534 if (outInfo != null) { 13535 outInfo.removedPackage = packageName; 13536 outInfo.removedUsers = deletedPs != null 13537 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 13538 : null; 13539 } 13540 } 13541 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 13542 removeDataDirsLI(ps.volumeUuid, packageName); 13543 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 13544 } 13545 // writer 13546 synchronized (mPackages) { 13547 if (deletedPs != null) { 13548 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 13549 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 13550 clearDefaultBrowserIfNeeded(packageName); 13551 if (outInfo != null) { 13552 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 13553 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 13554 } 13555 updatePermissionsLPw(deletedPs.name, null, 0); 13556 if (deletedPs.sharedUser != null) { 13557 // Remove permissions associated with package. Since runtime 13558 // permissions are per user we have to kill the removed package 13559 // or packages running under the shared user of the removed 13560 // package if revoking the permissions requested only by the removed 13561 // package is successful and this causes a change in gids. 13562 for (int userId : UserManagerService.getInstance().getUserIds()) { 13563 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 13564 userId); 13565 if (userIdToKill == UserHandle.USER_ALL 13566 || userIdToKill >= UserHandle.USER_SYSTEM) { 13567 // If gids changed for this user, kill all affected packages. 13568 mHandler.post(new Runnable() { 13569 @Override 13570 public void run() { 13571 // This has to happen with no lock held. 13572 killApplication(deletedPs.name, deletedPs.appId, 13573 KILL_APP_REASON_GIDS_CHANGED); 13574 } 13575 }); 13576 break; 13577 } 13578 } 13579 } 13580 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 13581 } 13582 // make sure to preserve per-user disabled state if this removal was just 13583 // a downgrade of a system app to the factory package 13584 if (allUserHandles != null && perUserInstalled != null) { 13585 if (DEBUG_REMOVE) { 13586 Slog.d(TAG, "Propagating install state across downgrade"); 13587 } 13588 for (int i = 0; i < allUserHandles.length; i++) { 13589 if (DEBUG_REMOVE) { 13590 Slog.d(TAG, " user " + allUserHandles[i] 13591 + " => " + perUserInstalled[i]); 13592 } 13593 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13594 } 13595 } 13596 } 13597 // can downgrade to reader 13598 if (writeSettings) { 13599 // Save settings now 13600 mSettings.writeLPr(); 13601 } 13602 } 13603 if (outInfo != null) { 13604 // A user ID was deleted here. Go through all users and remove it 13605 // from KeyStore. 13606 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 13607 } 13608 } 13609 13610 static boolean locationIsPrivileged(File path) { 13611 try { 13612 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 13613 .getCanonicalPath(); 13614 return path.getCanonicalPath().startsWith(privilegedAppDir); 13615 } catch (IOException e) { 13616 Slog.e(TAG, "Unable to access code path " + path); 13617 } 13618 return false; 13619 } 13620 13621 /* 13622 * Tries to delete system package. 13623 */ 13624 private boolean deleteSystemPackageLI(PackageSetting newPs, 13625 int[] allUserHandles, boolean[] perUserInstalled, 13626 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 13627 final boolean applyUserRestrictions 13628 = (allUserHandles != null) && (perUserInstalled != null); 13629 PackageSetting disabledPs = null; 13630 // Confirm if the system package has been updated 13631 // An updated system app can be deleted. This will also have to restore 13632 // the system pkg from system partition 13633 // reader 13634 synchronized (mPackages) { 13635 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 13636 } 13637 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 13638 + " disabledPs=" + disabledPs); 13639 if (disabledPs == null) { 13640 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 13641 return false; 13642 } else if (DEBUG_REMOVE) { 13643 Slog.d(TAG, "Deleting system pkg from data partition"); 13644 } 13645 if (DEBUG_REMOVE) { 13646 if (applyUserRestrictions) { 13647 Slog.d(TAG, "Remembering install states:"); 13648 for (int i = 0; i < allUserHandles.length; i++) { 13649 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 13650 } 13651 } 13652 } 13653 // Delete the updated package 13654 outInfo.isRemovedPackageSystemUpdate = true; 13655 if (disabledPs.versionCode < newPs.versionCode) { 13656 // Delete data for downgrades 13657 flags &= ~PackageManager.DELETE_KEEP_DATA; 13658 } else { 13659 // Preserve data by setting flag 13660 flags |= PackageManager.DELETE_KEEP_DATA; 13661 } 13662 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 13663 allUserHandles, perUserInstalled, outInfo, writeSettings); 13664 if (!ret) { 13665 return false; 13666 } 13667 // writer 13668 synchronized (mPackages) { 13669 // Reinstate the old system package 13670 mSettings.enableSystemPackageLPw(newPs.name); 13671 // Remove any native libraries from the upgraded package. 13672 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 13673 } 13674 // Install the system package 13675 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 13676 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 13677 if (locationIsPrivileged(disabledPs.codePath)) { 13678 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 13679 } 13680 13681 final PackageParser.Package newPkg; 13682 try { 13683 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 13684 } catch (PackageManagerException e) { 13685 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 13686 return false; 13687 } 13688 13689 // writer 13690 synchronized (mPackages) { 13691 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 13692 13693 // Propagate the permissions state as we do not want to drop on the floor 13694 // runtime permissions. The update permissions method below will take 13695 // care of removing obsolete permissions and grant install permissions. 13696 ps.getPermissionsState().copyFrom(newPs.getPermissionsState()); 13697 updatePermissionsLPw(newPkg.packageName, newPkg, 13698 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 13699 13700 if (applyUserRestrictions) { 13701 if (DEBUG_REMOVE) { 13702 Slog.d(TAG, "Propagating install state across reinstall"); 13703 } 13704 for (int i = 0; i < allUserHandles.length; i++) { 13705 if (DEBUG_REMOVE) { 13706 Slog.d(TAG, " user " + allUserHandles[i] 13707 + " => " + perUserInstalled[i]); 13708 } 13709 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13710 13711 mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false); 13712 } 13713 // Regardless of writeSettings we need to ensure that this restriction 13714 // state propagation is persisted 13715 mSettings.writeAllUsersPackageRestrictionsLPr(); 13716 } 13717 // can downgrade to reader here 13718 if (writeSettings) { 13719 mSettings.writeLPr(); 13720 } 13721 } 13722 return true; 13723 } 13724 13725 private boolean deleteInstalledPackageLI(PackageSetting ps, 13726 boolean deleteCodeAndResources, int flags, 13727 int[] allUserHandles, boolean[] perUserInstalled, 13728 PackageRemovedInfo outInfo, boolean writeSettings) { 13729 if (outInfo != null) { 13730 outInfo.uid = ps.appId; 13731 } 13732 13733 // Delete package data from internal structures and also remove data if flag is set 13734 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 13735 13736 // Delete application code and resources 13737 if (deleteCodeAndResources && (outInfo != null)) { 13738 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 13739 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 13740 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 13741 } 13742 return true; 13743 } 13744 13745 @Override 13746 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 13747 int userId) { 13748 mContext.enforceCallingOrSelfPermission( 13749 android.Manifest.permission.DELETE_PACKAGES, null); 13750 synchronized (mPackages) { 13751 PackageSetting ps = mSettings.mPackages.get(packageName); 13752 if (ps == null) { 13753 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 13754 return false; 13755 } 13756 if (!ps.getInstalled(userId)) { 13757 // Can't block uninstall for an app that is not installed or enabled. 13758 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 13759 return false; 13760 } 13761 ps.setBlockUninstall(blockUninstall, userId); 13762 mSettings.writePackageRestrictionsLPr(userId); 13763 } 13764 return true; 13765 } 13766 13767 @Override 13768 public boolean getBlockUninstallForUser(String packageName, int userId) { 13769 synchronized (mPackages) { 13770 PackageSetting ps = mSettings.mPackages.get(packageName); 13771 if (ps == null) { 13772 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 13773 return false; 13774 } 13775 return ps.getBlockUninstall(userId); 13776 } 13777 } 13778 13779 /* 13780 * This method handles package deletion in general 13781 */ 13782 private boolean deletePackageLI(String packageName, UserHandle user, 13783 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 13784 int flags, PackageRemovedInfo outInfo, 13785 boolean writeSettings) { 13786 if (packageName == null) { 13787 Slog.w(TAG, "Attempt to delete null packageName."); 13788 return false; 13789 } 13790 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 13791 PackageSetting ps; 13792 boolean dataOnly = false; 13793 int removeUser = -1; 13794 int appId = -1; 13795 synchronized (mPackages) { 13796 ps = mSettings.mPackages.get(packageName); 13797 if (ps == null) { 13798 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13799 return false; 13800 } 13801 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 13802 && user.getIdentifier() != UserHandle.USER_ALL) { 13803 // The caller is asking that the package only be deleted for a single 13804 // user. To do this, we just mark its uninstalled state and delete 13805 // its data. If this is a system app, we only allow this to happen if 13806 // they have set the special DELETE_SYSTEM_APP which requests different 13807 // semantics than normal for uninstalling system apps. 13808 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 13809 final int userId = user.getIdentifier(); 13810 ps.setUserState(userId, 13811 COMPONENT_ENABLED_STATE_DEFAULT, 13812 false, //installed 13813 true, //stopped 13814 true, //notLaunched 13815 false, //hidden 13816 false, //suspended 13817 null, null, null, 13818 false, // blockUninstall 13819 ps.readUserState(userId).domainVerificationStatus, 0); 13820 if (!isSystemApp(ps)) { 13821 // Do not uninstall the APK if an app should be cached 13822 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 13823 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 13824 // Other user still have this package installed, so all 13825 // we need to do is clear this user's data and save that 13826 // it is uninstalled. 13827 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 13828 removeUser = user.getIdentifier(); 13829 appId = ps.appId; 13830 scheduleWritePackageRestrictionsLocked(removeUser); 13831 } else { 13832 // We need to set it back to 'installed' so the uninstall 13833 // broadcasts will be sent correctly. 13834 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 13835 ps.setInstalled(true, user.getIdentifier()); 13836 } 13837 } else { 13838 // This is a system app, so we assume that the 13839 // other users still have this package installed, so all 13840 // we need to do is clear this user's data and save that 13841 // it is uninstalled. 13842 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 13843 removeUser = user.getIdentifier(); 13844 appId = ps.appId; 13845 scheduleWritePackageRestrictionsLocked(removeUser); 13846 } 13847 } 13848 } 13849 13850 if (removeUser >= 0) { 13851 // From above, we determined that we are deleting this only 13852 // for a single user. Continue the work here. 13853 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 13854 if (outInfo != null) { 13855 outInfo.removedPackage = packageName; 13856 outInfo.removedAppId = appId; 13857 outInfo.removedUsers = new int[] {removeUser}; 13858 } 13859 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 13860 removeKeystoreDataIfNeeded(removeUser, appId); 13861 schedulePackageCleaning(packageName, removeUser, false); 13862 synchronized (mPackages) { 13863 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 13864 scheduleWritePackageRestrictionsLocked(removeUser); 13865 } 13866 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser); 13867 } 13868 return true; 13869 } 13870 13871 if (dataOnly) { 13872 // Delete application data first 13873 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 13874 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 13875 return true; 13876 } 13877 13878 boolean ret = false; 13879 if (isSystemApp(ps)) { 13880 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 13881 // When an updated system application is deleted we delete the existing resources as well and 13882 // fall back to existing code in system partition 13883 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 13884 flags, outInfo, writeSettings); 13885 } else { 13886 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 13887 // Kill application pre-emptively especially for apps on sd. 13888 killApplication(packageName, ps.appId, "uninstall pkg"); 13889 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 13890 allUserHandles, perUserInstalled, 13891 outInfo, writeSettings); 13892 } 13893 13894 return ret; 13895 } 13896 13897 private final static class ClearStorageConnection implements ServiceConnection { 13898 IMediaContainerService mContainerService; 13899 13900 @Override 13901 public void onServiceConnected(ComponentName name, IBinder service) { 13902 synchronized (this) { 13903 mContainerService = IMediaContainerService.Stub.asInterface(service); 13904 notifyAll(); 13905 } 13906 } 13907 13908 @Override 13909 public void onServiceDisconnected(ComponentName name) { 13910 } 13911 } 13912 13913 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 13914 final boolean mounted; 13915 if (Environment.isExternalStorageEmulated()) { 13916 mounted = true; 13917 } else { 13918 final String status = Environment.getExternalStorageState(); 13919 13920 mounted = status.equals(Environment.MEDIA_MOUNTED) 13921 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 13922 } 13923 13924 if (!mounted) { 13925 return; 13926 } 13927 13928 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 13929 int[] users; 13930 if (userId == UserHandle.USER_ALL) { 13931 users = sUserManager.getUserIds(); 13932 } else { 13933 users = new int[] { userId }; 13934 } 13935 final ClearStorageConnection conn = new ClearStorageConnection(); 13936 if (mContext.bindServiceAsUser( 13937 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 13938 try { 13939 for (int curUser : users) { 13940 long timeout = SystemClock.uptimeMillis() + 5000; 13941 synchronized (conn) { 13942 long now = SystemClock.uptimeMillis(); 13943 while (conn.mContainerService == null && now < timeout) { 13944 try { 13945 conn.wait(timeout - now); 13946 } catch (InterruptedException e) { 13947 } 13948 } 13949 } 13950 if (conn.mContainerService == null) { 13951 return; 13952 } 13953 13954 final UserEnvironment userEnv = new UserEnvironment(curUser); 13955 clearDirectory(conn.mContainerService, 13956 userEnv.buildExternalStorageAppCacheDirs(packageName)); 13957 if (allData) { 13958 clearDirectory(conn.mContainerService, 13959 userEnv.buildExternalStorageAppDataDirs(packageName)); 13960 clearDirectory(conn.mContainerService, 13961 userEnv.buildExternalStorageAppMediaDirs(packageName)); 13962 } 13963 } 13964 } finally { 13965 mContext.unbindService(conn); 13966 } 13967 } 13968 } 13969 13970 @Override 13971 public void clearApplicationUserData(final String packageName, 13972 final IPackageDataObserver observer, final int userId) { 13973 mContext.enforceCallingOrSelfPermission( 13974 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 13975 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 13976 // Queue up an async operation since the package deletion may take a little while. 13977 mHandler.post(new Runnable() { 13978 public void run() { 13979 mHandler.removeCallbacks(this); 13980 final boolean succeeded; 13981 synchronized (mInstallLock) { 13982 succeeded = clearApplicationUserDataLI(packageName, userId); 13983 } 13984 clearExternalStorageDataSync(packageName, userId, true); 13985 if (succeeded) { 13986 // invoke DeviceStorageMonitor's update method to clear any notifications 13987 DeviceStorageMonitorInternal 13988 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13989 if (dsm != null) { 13990 dsm.checkMemory(); 13991 } 13992 } 13993 if(observer != null) { 13994 try { 13995 observer.onRemoveCompleted(packageName, succeeded); 13996 } catch (RemoteException e) { 13997 Log.i(TAG, "Observer no longer exists."); 13998 } 13999 } //end if observer 14000 } //end run 14001 }); 14002 } 14003 14004 private boolean clearApplicationUserDataLI(String packageName, int userId) { 14005 if (packageName == null) { 14006 Slog.w(TAG, "Attempt to delete null packageName."); 14007 return false; 14008 } 14009 14010 // Try finding details about the requested package 14011 PackageParser.Package pkg; 14012 synchronized (mPackages) { 14013 pkg = mPackages.get(packageName); 14014 if (pkg == null) { 14015 final PackageSetting ps = mSettings.mPackages.get(packageName); 14016 if (ps != null) { 14017 pkg = ps.pkg; 14018 } 14019 } 14020 14021 if (pkg == null) { 14022 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 14023 return false; 14024 } 14025 14026 PackageSetting ps = (PackageSetting) pkg.mExtras; 14027 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 14028 } 14029 14030 // Always delete data directories for package, even if we found no other 14031 // record of app. This helps users recover from UID mismatches without 14032 // resorting to a full data wipe. 14033 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 14034 if (retCode < 0) { 14035 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 14036 return false; 14037 } 14038 14039 final int appId = pkg.applicationInfo.uid; 14040 removeKeystoreDataIfNeeded(userId, appId); 14041 14042 // Create a native library symlink only if we have native libraries 14043 // and if the native libraries are 32 bit libraries. We do not provide 14044 // this symlink for 64 bit libraries. 14045 if (pkg.applicationInfo.primaryCpuAbi != null && 14046 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 14047 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 14048 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 14049 nativeLibPath, userId) < 0) { 14050 Slog.w(TAG, "Failed linking native library dir"); 14051 return false; 14052 } 14053 } 14054 14055 return true; 14056 } 14057 14058 /** 14059 * Reverts user permission state changes (permissions and flags) in 14060 * all packages for a given user. 14061 * 14062 * @param userId The device user for which to do a reset. 14063 */ 14064 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 14065 final int packageCount = mPackages.size(); 14066 for (int i = 0; i < packageCount; i++) { 14067 PackageParser.Package pkg = mPackages.valueAt(i); 14068 PackageSetting ps = (PackageSetting) pkg.mExtras; 14069 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 14070 } 14071 } 14072 14073 /** 14074 * Reverts user permission state changes (permissions and flags). 14075 * 14076 * @param ps The package for which to reset. 14077 * @param userId The device user for which to do a reset. 14078 */ 14079 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 14080 final PackageSetting ps, final int userId) { 14081 if (ps.pkg == null) { 14082 return; 14083 } 14084 14085 // These are flags that can change base on user actions. 14086 final int userSettableMask = FLAG_PERMISSION_USER_SET 14087 | FLAG_PERMISSION_USER_FIXED 14088 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 14089 | FLAG_PERMISSION_REVIEW_REQUIRED; 14090 14091 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 14092 | FLAG_PERMISSION_POLICY_FIXED; 14093 14094 boolean writeInstallPermissions = false; 14095 boolean writeRuntimePermissions = false; 14096 14097 final int permissionCount = ps.pkg.requestedPermissions.size(); 14098 for (int i = 0; i < permissionCount; i++) { 14099 String permission = ps.pkg.requestedPermissions.get(i); 14100 14101 BasePermission bp = mSettings.mPermissions.get(permission); 14102 if (bp == null) { 14103 continue; 14104 } 14105 14106 // If shared user we just reset the state to which only this app contributed. 14107 if (ps.sharedUser != null) { 14108 boolean used = false; 14109 final int packageCount = ps.sharedUser.packages.size(); 14110 for (int j = 0; j < packageCount; j++) { 14111 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 14112 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 14113 && pkg.pkg.requestedPermissions.contains(permission)) { 14114 used = true; 14115 break; 14116 } 14117 } 14118 if (used) { 14119 continue; 14120 } 14121 } 14122 14123 PermissionsState permissionsState = ps.getPermissionsState(); 14124 14125 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 14126 14127 // Always clear the user settable flags. 14128 final boolean hasInstallState = permissionsState.getInstallPermissionState( 14129 bp.name) != null; 14130 // If permission review is enabled and this is a legacy app, mark the 14131 // permission as requiring a review as this is the initial state. 14132 int flags = 0; 14133 if (Build.PERMISSIONS_REVIEW_REQUIRED 14134 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 14135 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 14136 } 14137 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 14138 if (hasInstallState) { 14139 writeInstallPermissions = true; 14140 } else { 14141 writeRuntimePermissions = true; 14142 } 14143 } 14144 14145 // Below is only runtime permission handling. 14146 if (!bp.isRuntime()) { 14147 continue; 14148 } 14149 14150 // Never clobber system or policy. 14151 if ((oldFlags & policyOrSystemFlags) != 0) { 14152 continue; 14153 } 14154 14155 // If this permission was granted by default, make sure it is. 14156 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 14157 if (permissionsState.grantRuntimePermission(bp, userId) 14158 != PERMISSION_OPERATION_FAILURE) { 14159 writeRuntimePermissions = true; 14160 } 14161 // If permission review is enabled the permissions for a legacy apps 14162 // are represented as constantly granted runtime ones, so don't revoke. 14163 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 14164 // Otherwise, reset the permission. 14165 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 14166 switch (revokeResult) { 14167 case PERMISSION_OPERATION_SUCCESS: { 14168 writeRuntimePermissions = true; 14169 } break; 14170 14171 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 14172 writeRuntimePermissions = true; 14173 final int appId = ps.appId; 14174 mHandler.post(new Runnable() { 14175 @Override 14176 public void run() { 14177 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 14178 } 14179 }); 14180 } break; 14181 } 14182 } 14183 } 14184 14185 // Synchronously write as we are taking permissions away. 14186 if (writeRuntimePermissions) { 14187 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 14188 } 14189 14190 // Synchronously write as we are taking permissions away. 14191 if (writeInstallPermissions) { 14192 mSettings.writeLPr(); 14193 } 14194 } 14195 14196 /** 14197 * Remove entries from the keystore daemon. Will only remove it if the 14198 * {@code appId} is valid. 14199 */ 14200 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 14201 if (appId < 0) { 14202 return; 14203 } 14204 14205 final KeyStore keyStore = KeyStore.getInstance(); 14206 if (keyStore != null) { 14207 if (userId == UserHandle.USER_ALL) { 14208 for (final int individual : sUserManager.getUserIds()) { 14209 keyStore.clearUid(UserHandle.getUid(individual, appId)); 14210 } 14211 } else { 14212 keyStore.clearUid(UserHandle.getUid(userId, appId)); 14213 } 14214 } else { 14215 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 14216 } 14217 } 14218 14219 @Override 14220 public void deleteApplicationCacheFiles(final String packageName, 14221 final IPackageDataObserver observer) { 14222 mContext.enforceCallingOrSelfPermission( 14223 android.Manifest.permission.DELETE_CACHE_FILES, null); 14224 // Queue up an async operation since the package deletion may take a little while. 14225 final int userId = UserHandle.getCallingUserId(); 14226 mHandler.post(new Runnable() { 14227 public void run() { 14228 mHandler.removeCallbacks(this); 14229 final boolean succeded; 14230 synchronized (mInstallLock) { 14231 succeded = deleteApplicationCacheFilesLI(packageName, userId); 14232 } 14233 clearExternalStorageDataSync(packageName, userId, false); 14234 if (observer != null) { 14235 try { 14236 observer.onRemoveCompleted(packageName, succeded); 14237 } catch (RemoteException e) { 14238 Log.i(TAG, "Observer no longer exists."); 14239 } 14240 } //end if observer 14241 } //end run 14242 }); 14243 } 14244 14245 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 14246 if (packageName == null) { 14247 Slog.w(TAG, "Attempt to delete null packageName."); 14248 return false; 14249 } 14250 PackageParser.Package p; 14251 synchronized (mPackages) { 14252 p = mPackages.get(packageName); 14253 } 14254 if (p == null) { 14255 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 14256 return false; 14257 } 14258 final ApplicationInfo applicationInfo = p.applicationInfo; 14259 if (applicationInfo == null) { 14260 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 14261 return false; 14262 } 14263 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 14264 if (retCode < 0) { 14265 Slog.w(TAG, "Couldn't remove cache files for package: " 14266 + packageName + " u" + userId); 14267 return false; 14268 } 14269 return true; 14270 } 14271 14272 @Override 14273 public void getPackageSizeInfo(final String packageName, int userHandle, 14274 final IPackageStatsObserver observer) { 14275 mContext.enforceCallingOrSelfPermission( 14276 android.Manifest.permission.GET_PACKAGE_SIZE, null); 14277 if (packageName == null) { 14278 throw new IllegalArgumentException("Attempt to get size of null packageName"); 14279 } 14280 14281 PackageStats stats = new PackageStats(packageName, userHandle); 14282 14283 /* 14284 * Queue up an async operation since the package measurement may take a 14285 * little while. 14286 */ 14287 Message msg = mHandler.obtainMessage(INIT_COPY); 14288 msg.obj = new MeasureParams(stats, observer); 14289 mHandler.sendMessage(msg); 14290 } 14291 14292 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 14293 PackageStats pStats) { 14294 if (packageName == null) { 14295 Slog.w(TAG, "Attempt to get size of null packageName."); 14296 return false; 14297 } 14298 PackageParser.Package p; 14299 boolean dataOnly = false; 14300 String libDirRoot = null; 14301 String asecPath = null; 14302 PackageSetting ps = null; 14303 synchronized (mPackages) { 14304 p = mPackages.get(packageName); 14305 ps = mSettings.mPackages.get(packageName); 14306 if(p == null) { 14307 dataOnly = true; 14308 if((ps == null) || (ps.pkg == null)) { 14309 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 14310 return false; 14311 } 14312 p = ps.pkg; 14313 } 14314 if (ps != null) { 14315 libDirRoot = ps.legacyNativeLibraryPathString; 14316 } 14317 if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) { 14318 final long token = Binder.clearCallingIdentity(); 14319 try { 14320 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 14321 if (secureContainerId != null) { 14322 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 14323 } 14324 } finally { 14325 Binder.restoreCallingIdentity(token); 14326 } 14327 } 14328 } 14329 String publicSrcDir = null; 14330 if(!dataOnly) { 14331 final ApplicationInfo applicationInfo = p.applicationInfo; 14332 if (applicationInfo == null) { 14333 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 14334 return false; 14335 } 14336 if (p.isForwardLocked()) { 14337 publicSrcDir = applicationInfo.getBaseResourcePath(); 14338 } 14339 } 14340 // TODO: extend to measure size of split APKs 14341 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 14342 // not just the first level. 14343 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 14344 // just the primary. 14345 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 14346 14347 String apkPath; 14348 File packageDir = new File(p.codePath); 14349 14350 if (packageDir.isDirectory() && p.canHaveOatDir()) { 14351 apkPath = packageDir.getAbsolutePath(); 14352 // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice 14353 if (libDirRoot != null && libDirRoot.startsWith(apkPath)) { 14354 libDirRoot = null; 14355 } 14356 } else { 14357 apkPath = p.baseCodePath; 14358 } 14359 14360 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, apkPath, 14361 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 14362 if (res < 0) { 14363 return false; 14364 } 14365 14366 // Fix-up for forward-locked applications in ASEC containers. 14367 if (!isExternal(p)) { 14368 pStats.codeSize += pStats.externalCodeSize; 14369 pStats.externalCodeSize = 0L; 14370 } 14371 14372 return true; 14373 } 14374 14375 14376 @Override 14377 public void addPackageToPreferred(String packageName) { 14378 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 14379 } 14380 14381 @Override 14382 public void removePackageFromPreferred(String packageName) { 14383 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 14384 } 14385 14386 @Override 14387 public List<PackageInfo> getPreferredPackages(int flags) { 14388 return new ArrayList<PackageInfo>(); 14389 } 14390 14391 private int getUidTargetSdkVersionLockedLPr(int uid) { 14392 Object obj = mSettings.getUserIdLPr(uid); 14393 if (obj instanceof SharedUserSetting) { 14394 final SharedUserSetting sus = (SharedUserSetting) obj; 14395 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 14396 final Iterator<PackageSetting> it = sus.packages.iterator(); 14397 while (it.hasNext()) { 14398 final PackageSetting ps = it.next(); 14399 if (ps.pkg != null) { 14400 int v = ps.pkg.applicationInfo.targetSdkVersion; 14401 if (v < vers) vers = v; 14402 } 14403 } 14404 return vers; 14405 } else if (obj instanceof PackageSetting) { 14406 final PackageSetting ps = (PackageSetting) obj; 14407 if (ps.pkg != null) { 14408 return ps.pkg.applicationInfo.targetSdkVersion; 14409 } 14410 } 14411 return Build.VERSION_CODES.CUR_DEVELOPMENT; 14412 } 14413 14414 @Override 14415 public void addPreferredActivity(IntentFilter filter, int match, 14416 ComponentName[] set, ComponentName activity, int userId) { 14417 addPreferredActivityInternal(filter, match, set, activity, true, userId, 14418 "Adding preferred"); 14419 } 14420 14421 private void addPreferredActivityInternal(IntentFilter filter, int match, 14422 ComponentName[] set, ComponentName activity, boolean always, int userId, 14423 String opname) { 14424 // writer 14425 int callingUid = Binder.getCallingUid(); 14426 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 14427 if (filter.countActions() == 0) { 14428 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 14429 return; 14430 } 14431 synchronized (mPackages) { 14432 if (mContext.checkCallingOrSelfPermission( 14433 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14434 != PackageManager.PERMISSION_GRANTED) { 14435 if (getUidTargetSdkVersionLockedLPr(callingUid) 14436 < Build.VERSION_CODES.FROYO) { 14437 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 14438 + callingUid); 14439 return; 14440 } 14441 mContext.enforceCallingOrSelfPermission( 14442 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14443 } 14444 14445 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 14446 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 14447 + userId + ":"); 14448 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14449 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 14450 scheduleWritePackageRestrictionsLocked(userId); 14451 } 14452 } 14453 14454 @Override 14455 public void replacePreferredActivity(IntentFilter filter, int match, 14456 ComponentName[] set, ComponentName activity, int userId) { 14457 if (filter.countActions() != 1) { 14458 throw new IllegalArgumentException( 14459 "replacePreferredActivity expects filter to have only 1 action."); 14460 } 14461 if (filter.countDataAuthorities() != 0 14462 || filter.countDataPaths() != 0 14463 || filter.countDataSchemes() > 1 14464 || filter.countDataTypes() != 0) { 14465 throw new IllegalArgumentException( 14466 "replacePreferredActivity expects filter to have no data authorities, " + 14467 "paths, or types; and at most one scheme."); 14468 } 14469 14470 final int callingUid = Binder.getCallingUid(); 14471 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 14472 synchronized (mPackages) { 14473 if (mContext.checkCallingOrSelfPermission( 14474 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14475 != PackageManager.PERMISSION_GRANTED) { 14476 if (getUidTargetSdkVersionLockedLPr(callingUid) 14477 < Build.VERSION_CODES.FROYO) { 14478 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 14479 + Binder.getCallingUid()); 14480 return; 14481 } 14482 mContext.enforceCallingOrSelfPermission( 14483 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14484 } 14485 14486 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 14487 if (pir != null) { 14488 // Get all of the existing entries that exactly match this filter. 14489 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 14490 if (existing != null && existing.size() == 1) { 14491 PreferredActivity cur = existing.get(0); 14492 if (DEBUG_PREFERRED) { 14493 Slog.i(TAG, "Checking replace of preferred:"); 14494 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14495 if (!cur.mPref.mAlways) { 14496 Slog.i(TAG, " -- CUR; not mAlways!"); 14497 } else { 14498 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 14499 Slog.i(TAG, " -- CUR: mSet=" 14500 + Arrays.toString(cur.mPref.mSetComponents)); 14501 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 14502 Slog.i(TAG, " -- NEW: mMatch=" 14503 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 14504 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 14505 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 14506 } 14507 } 14508 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 14509 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 14510 && cur.mPref.sameSet(set)) { 14511 // Setting the preferred activity to what it happens to be already 14512 if (DEBUG_PREFERRED) { 14513 Slog.i(TAG, "Replacing with same preferred activity " 14514 + cur.mPref.mShortComponent + " for user " 14515 + userId + ":"); 14516 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14517 } 14518 return; 14519 } 14520 } 14521 14522 if (existing != null) { 14523 if (DEBUG_PREFERRED) { 14524 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 14525 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14526 } 14527 for (int i = 0; i < existing.size(); i++) { 14528 PreferredActivity pa = existing.get(i); 14529 if (DEBUG_PREFERRED) { 14530 Slog.i(TAG, "Removing existing preferred activity " 14531 + pa.mPref.mComponent + ":"); 14532 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 14533 } 14534 pir.removeFilter(pa); 14535 } 14536 } 14537 } 14538 addPreferredActivityInternal(filter, match, set, activity, true, userId, 14539 "Replacing preferred"); 14540 } 14541 } 14542 14543 @Override 14544 public void clearPackagePreferredActivities(String packageName) { 14545 final int uid = Binder.getCallingUid(); 14546 // writer 14547 synchronized (mPackages) { 14548 PackageParser.Package pkg = mPackages.get(packageName); 14549 if (pkg == null || pkg.applicationInfo.uid != uid) { 14550 if (mContext.checkCallingOrSelfPermission( 14551 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14552 != PackageManager.PERMISSION_GRANTED) { 14553 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 14554 < Build.VERSION_CODES.FROYO) { 14555 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 14556 + Binder.getCallingUid()); 14557 return; 14558 } 14559 mContext.enforceCallingOrSelfPermission( 14560 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14561 } 14562 } 14563 14564 int user = UserHandle.getCallingUserId(); 14565 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 14566 scheduleWritePackageRestrictionsLocked(user); 14567 } 14568 } 14569 } 14570 14571 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14572 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 14573 ArrayList<PreferredActivity> removed = null; 14574 boolean changed = false; 14575 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14576 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 14577 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14578 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 14579 continue; 14580 } 14581 Iterator<PreferredActivity> it = pir.filterIterator(); 14582 while (it.hasNext()) { 14583 PreferredActivity pa = it.next(); 14584 // Mark entry for removal only if it matches the package name 14585 // and the entry is of type "always". 14586 if (packageName == null || 14587 (pa.mPref.mComponent.getPackageName().equals(packageName) 14588 && pa.mPref.mAlways)) { 14589 if (removed == null) { 14590 removed = new ArrayList<PreferredActivity>(); 14591 } 14592 removed.add(pa); 14593 } 14594 } 14595 if (removed != null) { 14596 for (int j=0; j<removed.size(); j++) { 14597 PreferredActivity pa = removed.get(j); 14598 pir.removeFilter(pa); 14599 } 14600 changed = true; 14601 } 14602 } 14603 return changed; 14604 } 14605 14606 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14607 private void clearIntentFilterVerificationsLPw(int userId) { 14608 final int packageCount = mPackages.size(); 14609 for (int i = 0; i < packageCount; i++) { 14610 PackageParser.Package pkg = mPackages.valueAt(i); 14611 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 14612 } 14613 } 14614 14615 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14616 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 14617 if (userId == UserHandle.USER_ALL) { 14618 if (mSettings.removeIntentFilterVerificationLPw(packageName, 14619 sUserManager.getUserIds())) { 14620 for (int oneUserId : sUserManager.getUserIds()) { 14621 scheduleWritePackageRestrictionsLocked(oneUserId); 14622 } 14623 } 14624 } else { 14625 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 14626 scheduleWritePackageRestrictionsLocked(userId); 14627 } 14628 } 14629 } 14630 14631 void clearDefaultBrowserIfNeeded(String packageName) { 14632 for (int oneUserId : sUserManager.getUserIds()) { 14633 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 14634 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 14635 if (packageName.equals(defaultBrowserPackageName)) { 14636 setDefaultBrowserPackageName(null, oneUserId); 14637 } 14638 } 14639 } 14640 14641 @Override 14642 public void resetApplicationPreferences(int userId) { 14643 mContext.enforceCallingOrSelfPermission( 14644 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14645 // writer 14646 synchronized (mPackages) { 14647 final long identity = Binder.clearCallingIdentity(); 14648 try { 14649 clearPackagePreferredActivitiesLPw(null, userId); 14650 mSettings.applyDefaultPreferredAppsLPw(this, userId); 14651 // TODO: We have to reset the default SMS and Phone. This requires 14652 // significant refactoring to keep all default apps in the package 14653 // manager (cleaner but more work) or have the services provide 14654 // callbacks to the package manager to request a default app reset. 14655 applyFactoryDefaultBrowserLPw(userId); 14656 clearIntentFilterVerificationsLPw(userId); 14657 primeDomainVerificationsLPw(userId); 14658 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 14659 scheduleWritePackageRestrictionsLocked(userId); 14660 } finally { 14661 Binder.restoreCallingIdentity(identity); 14662 } 14663 } 14664 } 14665 14666 @Override 14667 public int getPreferredActivities(List<IntentFilter> outFilters, 14668 List<ComponentName> outActivities, String packageName) { 14669 14670 int num = 0; 14671 final int userId = UserHandle.getCallingUserId(); 14672 // reader 14673 synchronized (mPackages) { 14674 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 14675 if (pir != null) { 14676 final Iterator<PreferredActivity> it = pir.filterIterator(); 14677 while (it.hasNext()) { 14678 final PreferredActivity pa = it.next(); 14679 if (packageName == null 14680 || (pa.mPref.mComponent.getPackageName().equals(packageName) 14681 && pa.mPref.mAlways)) { 14682 if (outFilters != null) { 14683 outFilters.add(new IntentFilter(pa)); 14684 } 14685 if (outActivities != null) { 14686 outActivities.add(pa.mPref.mComponent); 14687 } 14688 } 14689 } 14690 } 14691 } 14692 14693 return num; 14694 } 14695 14696 @Override 14697 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 14698 int userId) { 14699 int callingUid = Binder.getCallingUid(); 14700 if (callingUid != Process.SYSTEM_UID) { 14701 throw new SecurityException( 14702 "addPersistentPreferredActivity can only be run by the system"); 14703 } 14704 if (filter.countActions() == 0) { 14705 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 14706 return; 14707 } 14708 synchronized (mPackages) { 14709 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 14710 " :"); 14711 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14712 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 14713 new PersistentPreferredActivity(filter, activity)); 14714 scheduleWritePackageRestrictionsLocked(userId); 14715 } 14716 } 14717 14718 @Override 14719 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 14720 int callingUid = Binder.getCallingUid(); 14721 if (callingUid != Process.SYSTEM_UID) { 14722 throw new SecurityException( 14723 "clearPackagePersistentPreferredActivities can only be run by the system"); 14724 } 14725 ArrayList<PersistentPreferredActivity> removed = null; 14726 boolean changed = false; 14727 synchronized (mPackages) { 14728 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 14729 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 14730 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 14731 .valueAt(i); 14732 if (userId != thisUserId) { 14733 continue; 14734 } 14735 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 14736 while (it.hasNext()) { 14737 PersistentPreferredActivity ppa = it.next(); 14738 // Mark entry for removal only if it matches the package name. 14739 if (ppa.mComponent.getPackageName().equals(packageName)) { 14740 if (removed == null) { 14741 removed = new ArrayList<PersistentPreferredActivity>(); 14742 } 14743 removed.add(ppa); 14744 } 14745 } 14746 if (removed != null) { 14747 for (int j=0; j<removed.size(); j++) { 14748 PersistentPreferredActivity ppa = removed.get(j); 14749 ppir.removeFilter(ppa); 14750 } 14751 changed = true; 14752 } 14753 } 14754 14755 if (changed) { 14756 scheduleWritePackageRestrictionsLocked(userId); 14757 } 14758 } 14759 } 14760 14761 /** 14762 * Common machinery for picking apart a restored XML blob and passing 14763 * it to a caller-supplied functor to be applied to the running system. 14764 */ 14765 private void restoreFromXml(XmlPullParser parser, int userId, 14766 String expectedStartTag, BlobXmlRestorer functor) 14767 throws IOException, XmlPullParserException { 14768 int type; 14769 while ((type = parser.next()) != XmlPullParser.START_TAG 14770 && type != XmlPullParser.END_DOCUMENT) { 14771 } 14772 if (type != XmlPullParser.START_TAG) { 14773 // oops didn't find a start tag?! 14774 if (DEBUG_BACKUP) { 14775 Slog.e(TAG, "Didn't find start tag during restore"); 14776 } 14777 return; 14778 } 14779 14780 // this is supposed to be TAG_PREFERRED_BACKUP 14781 if (!expectedStartTag.equals(parser.getName())) { 14782 if (DEBUG_BACKUP) { 14783 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 14784 } 14785 return; 14786 } 14787 14788 // skip interfering stuff, then we're aligned with the backing implementation 14789 while ((type = parser.next()) == XmlPullParser.TEXT) { } 14790 functor.apply(parser, userId); 14791 } 14792 14793 private interface BlobXmlRestorer { 14794 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 14795 } 14796 14797 /** 14798 * Non-Binder method, support for the backup/restore mechanism: write the 14799 * full set of preferred activities in its canonical XML format. Returns the 14800 * XML output as a byte array, or null if there is none. 14801 */ 14802 @Override 14803 public byte[] getPreferredActivityBackup(int userId) { 14804 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14805 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 14806 } 14807 14808 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14809 try { 14810 final XmlSerializer serializer = new FastXmlSerializer(); 14811 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14812 serializer.startDocument(null, true); 14813 serializer.startTag(null, TAG_PREFERRED_BACKUP); 14814 14815 synchronized (mPackages) { 14816 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 14817 } 14818 14819 serializer.endTag(null, TAG_PREFERRED_BACKUP); 14820 serializer.endDocument(); 14821 serializer.flush(); 14822 } catch (Exception e) { 14823 if (DEBUG_BACKUP) { 14824 Slog.e(TAG, "Unable to write preferred activities for backup", e); 14825 } 14826 return null; 14827 } 14828 14829 return dataStream.toByteArray(); 14830 } 14831 14832 @Override 14833 public void restorePreferredActivities(byte[] backup, int userId) { 14834 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14835 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14836 } 14837 14838 try { 14839 final XmlPullParser parser = Xml.newPullParser(); 14840 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14841 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 14842 new BlobXmlRestorer() { 14843 @Override 14844 public void apply(XmlPullParser parser, int userId) 14845 throws XmlPullParserException, IOException { 14846 synchronized (mPackages) { 14847 mSettings.readPreferredActivitiesLPw(parser, userId); 14848 } 14849 } 14850 } ); 14851 } catch (Exception e) { 14852 if (DEBUG_BACKUP) { 14853 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14854 } 14855 } 14856 } 14857 14858 /** 14859 * Non-Binder method, support for the backup/restore mechanism: write the 14860 * default browser (etc) settings in its canonical XML format. Returns the default 14861 * browser XML representation as a byte array, or null if there is none. 14862 */ 14863 @Override 14864 public byte[] getDefaultAppsBackup(int userId) { 14865 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14866 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 14867 } 14868 14869 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14870 try { 14871 final XmlSerializer serializer = new FastXmlSerializer(); 14872 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14873 serializer.startDocument(null, true); 14874 serializer.startTag(null, TAG_DEFAULT_APPS); 14875 14876 synchronized (mPackages) { 14877 mSettings.writeDefaultAppsLPr(serializer, userId); 14878 } 14879 14880 serializer.endTag(null, TAG_DEFAULT_APPS); 14881 serializer.endDocument(); 14882 serializer.flush(); 14883 } catch (Exception e) { 14884 if (DEBUG_BACKUP) { 14885 Slog.e(TAG, "Unable to write default apps for backup", e); 14886 } 14887 return null; 14888 } 14889 14890 return dataStream.toByteArray(); 14891 } 14892 14893 @Override 14894 public void restoreDefaultApps(byte[] backup, int userId) { 14895 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14896 throw new SecurityException("Only the system may call restoreDefaultApps()"); 14897 } 14898 14899 try { 14900 final XmlPullParser parser = Xml.newPullParser(); 14901 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14902 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 14903 new BlobXmlRestorer() { 14904 @Override 14905 public void apply(XmlPullParser parser, int userId) 14906 throws XmlPullParserException, IOException { 14907 synchronized (mPackages) { 14908 mSettings.readDefaultAppsLPw(parser, userId); 14909 } 14910 } 14911 } ); 14912 } catch (Exception e) { 14913 if (DEBUG_BACKUP) { 14914 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 14915 } 14916 } 14917 } 14918 14919 @Override 14920 public byte[] getIntentFilterVerificationBackup(int userId) { 14921 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14922 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 14923 } 14924 14925 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14926 try { 14927 final XmlSerializer serializer = new FastXmlSerializer(); 14928 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14929 serializer.startDocument(null, true); 14930 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 14931 14932 synchronized (mPackages) { 14933 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 14934 } 14935 14936 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 14937 serializer.endDocument(); 14938 serializer.flush(); 14939 } catch (Exception e) { 14940 if (DEBUG_BACKUP) { 14941 Slog.e(TAG, "Unable to write default apps for backup", e); 14942 } 14943 return null; 14944 } 14945 14946 return dataStream.toByteArray(); 14947 } 14948 14949 @Override 14950 public void restoreIntentFilterVerification(byte[] backup, int userId) { 14951 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14952 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14953 } 14954 14955 try { 14956 final XmlPullParser parser = Xml.newPullParser(); 14957 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14958 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 14959 new BlobXmlRestorer() { 14960 @Override 14961 public void apply(XmlPullParser parser, int userId) 14962 throws XmlPullParserException, IOException { 14963 synchronized (mPackages) { 14964 mSettings.readAllDomainVerificationsLPr(parser, userId); 14965 mSettings.writeLPr(); 14966 } 14967 } 14968 } ); 14969 } catch (Exception e) { 14970 if (DEBUG_BACKUP) { 14971 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14972 } 14973 } 14974 } 14975 14976 @Override 14977 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 14978 int sourceUserId, int targetUserId, int flags) { 14979 mContext.enforceCallingOrSelfPermission( 14980 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14981 int callingUid = Binder.getCallingUid(); 14982 enforceOwnerRights(ownerPackage, callingUid); 14983 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14984 if (intentFilter.countActions() == 0) { 14985 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 14986 return; 14987 } 14988 synchronized (mPackages) { 14989 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 14990 ownerPackage, targetUserId, flags); 14991 CrossProfileIntentResolver resolver = 14992 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14993 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 14994 // We have all those whose filter is equal. Now checking if the rest is equal as well. 14995 if (existing != null) { 14996 int size = existing.size(); 14997 for (int i = 0; i < size; i++) { 14998 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 14999 return; 15000 } 15001 } 15002 } 15003 resolver.addFilter(newFilter); 15004 scheduleWritePackageRestrictionsLocked(sourceUserId); 15005 } 15006 } 15007 15008 @Override 15009 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 15010 mContext.enforceCallingOrSelfPermission( 15011 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 15012 int callingUid = Binder.getCallingUid(); 15013 enforceOwnerRights(ownerPackage, callingUid); 15014 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 15015 synchronized (mPackages) { 15016 CrossProfileIntentResolver resolver = 15017 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 15018 ArraySet<CrossProfileIntentFilter> set = 15019 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 15020 for (CrossProfileIntentFilter filter : set) { 15021 if (filter.getOwnerPackage().equals(ownerPackage)) { 15022 resolver.removeFilter(filter); 15023 } 15024 } 15025 scheduleWritePackageRestrictionsLocked(sourceUserId); 15026 } 15027 } 15028 15029 // Enforcing that callingUid is owning pkg on userId 15030 private void enforceOwnerRights(String pkg, int callingUid) { 15031 // The system owns everything. 15032 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 15033 return; 15034 } 15035 int callingUserId = UserHandle.getUserId(callingUid); 15036 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 15037 if (pi == null) { 15038 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 15039 + callingUserId); 15040 } 15041 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 15042 throw new SecurityException("Calling uid " + callingUid 15043 + " does not own package " + pkg); 15044 } 15045 } 15046 15047 @Override 15048 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 15049 Intent intent = new Intent(Intent.ACTION_MAIN); 15050 intent.addCategory(Intent.CATEGORY_HOME); 15051 15052 final int callingUserId = UserHandle.getCallingUserId(); 15053 List<ResolveInfo> list = queryIntentActivities(intent, null, 15054 PackageManager.GET_META_DATA, callingUserId); 15055 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 15056 true, false, false, callingUserId); 15057 15058 allHomeCandidates.clear(); 15059 if (list != null) { 15060 for (ResolveInfo ri : list) { 15061 allHomeCandidates.add(ri); 15062 } 15063 } 15064 return (preferred == null || preferred.activityInfo == null) 15065 ? null 15066 : new ComponentName(preferred.activityInfo.packageName, 15067 preferred.activityInfo.name); 15068 } 15069 15070 @Override 15071 public void setApplicationEnabledSetting(String appPackageName, 15072 int newState, int flags, int userId, String callingPackage) { 15073 if (!sUserManager.exists(userId)) return; 15074 if (callingPackage == null) { 15075 callingPackage = Integer.toString(Binder.getCallingUid()); 15076 } 15077 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 15078 } 15079 15080 @Override 15081 public void setComponentEnabledSetting(ComponentName componentName, 15082 int newState, int flags, int userId) { 15083 if (!sUserManager.exists(userId)) return; 15084 setEnabledSetting(componentName.getPackageName(), 15085 componentName.getClassName(), newState, flags, userId, null); 15086 } 15087 15088 private void setEnabledSetting(final String packageName, String className, int newState, 15089 final int flags, int userId, String callingPackage) { 15090 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 15091 || newState == COMPONENT_ENABLED_STATE_ENABLED 15092 || newState == COMPONENT_ENABLED_STATE_DISABLED 15093 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 15094 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 15095 throw new IllegalArgumentException("Invalid new component state: " 15096 + newState); 15097 } 15098 PackageSetting pkgSetting; 15099 final int uid = Binder.getCallingUid(); 15100 final int permission = mContext.checkCallingOrSelfPermission( 15101 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 15102 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 15103 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 15104 boolean sendNow = false; 15105 boolean isApp = (className == null); 15106 String componentName = isApp ? packageName : className; 15107 int packageUid = -1; 15108 ArrayList<String> components; 15109 15110 // writer 15111 synchronized (mPackages) { 15112 pkgSetting = mSettings.mPackages.get(packageName); 15113 if (pkgSetting == null) { 15114 if (className == null) { 15115 throw new IllegalArgumentException( 15116 "Unknown package: " + packageName); 15117 } 15118 throw new IllegalArgumentException( 15119 "Unknown component: " + packageName 15120 + "/" + className); 15121 } 15122 // Allow root and verify that userId is not being specified by a different user 15123 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 15124 throw new SecurityException( 15125 "Permission Denial: attempt to change component state from pid=" 15126 + Binder.getCallingPid() 15127 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 15128 } 15129 if (className == null) { 15130 // We're dealing with an application/package level state change 15131 if (pkgSetting.getEnabled(userId) == newState) { 15132 // Nothing to do 15133 return; 15134 } 15135 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 15136 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 15137 // Don't care about who enables an app. 15138 callingPackage = null; 15139 } 15140 pkgSetting.setEnabled(newState, userId, callingPackage); 15141 // pkgSetting.pkg.mSetEnabled = newState; 15142 } else { 15143 // We're dealing with a component level state change 15144 // First, verify that this is a valid class name. 15145 PackageParser.Package pkg = pkgSetting.pkg; 15146 if (pkg == null || !pkg.hasComponentClassName(className)) { 15147 if (pkg != null && 15148 pkg.applicationInfo.targetSdkVersion >= 15149 Build.VERSION_CODES.JELLY_BEAN) { 15150 throw new IllegalArgumentException("Component class " + className 15151 + " does not exist in " + packageName); 15152 } else { 15153 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 15154 + className + " does not exist in " + packageName); 15155 } 15156 } 15157 switch (newState) { 15158 case COMPONENT_ENABLED_STATE_ENABLED: 15159 if (!pkgSetting.enableComponentLPw(className, userId)) { 15160 return; 15161 } 15162 break; 15163 case COMPONENT_ENABLED_STATE_DISABLED: 15164 if (!pkgSetting.disableComponentLPw(className, userId)) { 15165 return; 15166 } 15167 break; 15168 case COMPONENT_ENABLED_STATE_DEFAULT: 15169 if (!pkgSetting.restoreComponentLPw(className, userId)) { 15170 return; 15171 } 15172 break; 15173 default: 15174 Slog.e(TAG, "Invalid new component state: " + newState); 15175 return; 15176 } 15177 } 15178 scheduleWritePackageRestrictionsLocked(userId); 15179 components = mPendingBroadcasts.get(userId, packageName); 15180 final boolean newPackage = components == null; 15181 if (newPackage) { 15182 components = new ArrayList<String>(); 15183 } 15184 if (!components.contains(componentName)) { 15185 components.add(componentName); 15186 } 15187 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 15188 sendNow = true; 15189 // Purge entry from pending broadcast list if another one exists already 15190 // since we are sending one right away. 15191 mPendingBroadcasts.remove(userId, packageName); 15192 } else { 15193 if (newPackage) { 15194 mPendingBroadcasts.put(userId, packageName, components); 15195 } 15196 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 15197 // Schedule a message 15198 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 15199 } 15200 } 15201 } 15202 15203 long callingId = Binder.clearCallingIdentity(); 15204 try { 15205 if (sendNow) { 15206 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 15207 sendPackageChangedBroadcast(packageName, 15208 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 15209 } 15210 } finally { 15211 Binder.restoreCallingIdentity(callingId); 15212 } 15213 } 15214 15215 private void sendPackageChangedBroadcast(String packageName, 15216 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 15217 if (DEBUG_INSTALL) 15218 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 15219 + componentNames); 15220 Bundle extras = new Bundle(4); 15221 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 15222 String nameList[] = new String[componentNames.size()]; 15223 componentNames.toArray(nameList); 15224 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 15225 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 15226 extras.putInt(Intent.EXTRA_UID, packageUid); 15227 // If this is not reporting a change of the overall package, then only send it 15228 // to registered receivers. We don't want to launch a swath of apps for every 15229 // little component state change. 15230 final int flags = !componentNames.contains(packageName) 15231 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 15232 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 15233 new int[] {UserHandle.getUserId(packageUid)}); 15234 } 15235 15236 @Override 15237 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 15238 if (!sUserManager.exists(userId)) return; 15239 final int uid = Binder.getCallingUid(); 15240 final int permission = mContext.checkCallingOrSelfPermission( 15241 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 15242 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 15243 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 15244 // writer 15245 synchronized (mPackages) { 15246 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 15247 allowedByPermission, uid, userId)) { 15248 scheduleWritePackageRestrictionsLocked(userId); 15249 } 15250 } 15251 } 15252 15253 @Override 15254 public String getInstallerPackageName(String packageName) { 15255 // reader 15256 synchronized (mPackages) { 15257 return mSettings.getInstallerPackageNameLPr(packageName); 15258 } 15259 } 15260 15261 @Override 15262 public int getApplicationEnabledSetting(String packageName, int userId) { 15263 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 15264 int uid = Binder.getCallingUid(); 15265 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 15266 // reader 15267 synchronized (mPackages) { 15268 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 15269 } 15270 } 15271 15272 @Override 15273 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 15274 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 15275 int uid = Binder.getCallingUid(); 15276 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 15277 // reader 15278 synchronized (mPackages) { 15279 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 15280 } 15281 } 15282 15283 @Override 15284 public void enterSafeMode() { 15285 enforceSystemOrRoot("Only the system can request entering safe mode"); 15286 15287 if (!mSystemReady) { 15288 mSafeMode = true; 15289 } 15290 } 15291 15292 @Override 15293 public void systemReady() { 15294 mSystemReady = true; 15295 15296 // Read the compatibilty setting when the system is ready. 15297 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 15298 mContext.getContentResolver(), 15299 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 15300 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 15301 if (DEBUG_SETTINGS) { 15302 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 15303 } 15304 15305 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 15306 15307 synchronized (mPackages) { 15308 // Verify that all of the preferred activity components actually 15309 // exist. It is possible for applications to be updated and at 15310 // that point remove a previously declared activity component that 15311 // had been set as a preferred activity. We try to clean this up 15312 // the next time we encounter that preferred activity, but it is 15313 // possible for the user flow to never be able to return to that 15314 // situation so here we do a sanity check to make sure we haven't 15315 // left any junk around. 15316 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 15317 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 15318 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 15319 removed.clear(); 15320 for (PreferredActivity pa : pir.filterSet()) { 15321 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 15322 removed.add(pa); 15323 } 15324 } 15325 if (removed.size() > 0) { 15326 for (int r=0; r<removed.size(); r++) { 15327 PreferredActivity pa = removed.get(r); 15328 Slog.w(TAG, "Removing dangling preferred activity: " 15329 + pa.mPref.mComponent); 15330 pir.removeFilter(pa); 15331 } 15332 mSettings.writePackageRestrictionsLPr( 15333 mSettings.mPreferredActivities.keyAt(i)); 15334 } 15335 } 15336 15337 for (int userId : UserManagerService.getInstance().getUserIds()) { 15338 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 15339 grantPermissionsUserIds = ArrayUtils.appendInt( 15340 grantPermissionsUserIds, userId); 15341 } 15342 } 15343 } 15344 sUserManager.systemReady(); 15345 15346 // If we upgraded grant all default permissions before kicking off. 15347 for (int userId : grantPermissionsUserIds) { 15348 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 15349 } 15350 15351 // Kick off any messages waiting for system ready 15352 if (mPostSystemReadyMessages != null) { 15353 for (Message msg : mPostSystemReadyMessages) { 15354 msg.sendToTarget(); 15355 } 15356 mPostSystemReadyMessages = null; 15357 } 15358 15359 // Watch for external volumes that come and go over time 15360 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15361 storage.registerListener(mStorageListener); 15362 15363 mInstallerService.systemReady(); 15364 mPackageDexOptimizer.systemReady(); 15365 15366 MountServiceInternal mountServiceInternal = LocalServices.getService( 15367 MountServiceInternal.class); 15368 mountServiceInternal.addExternalStoragePolicy( 15369 new MountServiceInternal.ExternalStorageMountPolicy() { 15370 @Override 15371 public int getMountMode(int uid, String packageName) { 15372 if (Process.isIsolated(uid)) { 15373 return Zygote.MOUNT_EXTERNAL_NONE; 15374 } 15375 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 15376 return Zygote.MOUNT_EXTERNAL_DEFAULT; 15377 } 15378 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 15379 return Zygote.MOUNT_EXTERNAL_DEFAULT; 15380 } 15381 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 15382 return Zygote.MOUNT_EXTERNAL_READ; 15383 } 15384 return Zygote.MOUNT_EXTERNAL_WRITE; 15385 } 15386 15387 @Override 15388 public boolean hasExternalStorage(int uid, String packageName) { 15389 return true; 15390 } 15391 }); 15392 } 15393 15394 @Override 15395 public boolean isSafeMode() { 15396 return mSafeMode; 15397 } 15398 15399 @Override 15400 public boolean hasSystemUidErrors() { 15401 return mHasSystemUidErrors; 15402 } 15403 15404 static String arrayToString(int[] array) { 15405 StringBuffer buf = new StringBuffer(128); 15406 buf.append('['); 15407 if (array != null) { 15408 for (int i=0; i<array.length; i++) { 15409 if (i > 0) buf.append(", "); 15410 buf.append(array[i]); 15411 } 15412 } 15413 buf.append(']'); 15414 return buf.toString(); 15415 } 15416 15417 static class DumpState { 15418 public static final int DUMP_LIBS = 1 << 0; 15419 public static final int DUMP_FEATURES = 1 << 1; 15420 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 15421 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 15422 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 15423 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 15424 public static final int DUMP_PERMISSIONS = 1 << 6; 15425 public static final int DUMP_PACKAGES = 1 << 7; 15426 public static final int DUMP_SHARED_USERS = 1 << 8; 15427 public static final int DUMP_MESSAGES = 1 << 9; 15428 public static final int DUMP_PROVIDERS = 1 << 10; 15429 public static final int DUMP_VERIFIERS = 1 << 11; 15430 public static final int DUMP_PREFERRED = 1 << 12; 15431 public static final int DUMP_PREFERRED_XML = 1 << 13; 15432 public static final int DUMP_KEYSETS = 1 << 14; 15433 public static final int DUMP_VERSION = 1 << 15; 15434 public static final int DUMP_INSTALLS = 1 << 16; 15435 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 15436 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 15437 15438 public static final int OPTION_SHOW_FILTERS = 1 << 0; 15439 15440 private int mTypes; 15441 15442 private int mOptions; 15443 15444 private boolean mTitlePrinted; 15445 15446 private SharedUserSetting mSharedUser; 15447 15448 public boolean isDumping(int type) { 15449 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 15450 return true; 15451 } 15452 15453 return (mTypes & type) != 0; 15454 } 15455 15456 public void setDump(int type) { 15457 mTypes |= type; 15458 } 15459 15460 public boolean isOptionEnabled(int option) { 15461 return (mOptions & option) != 0; 15462 } 15463 15464 public void setOptionEnabled(int option) { 15465 mOptions |= option; 15466 } 15467 15468 public boolean onTitlePrinted() { 15469 final boolean printed = mTitlePrinted; 15470 mTitlePrinted = true; 15471 return printed; 15472 } 15473 15474 public boolean getTitlePrinted() { 15475 return mTitlePrinted; 15476 } 15477 15478 public void setTitlePrinted(boolean enabled) { 15479 mTitlePrinted = enabled; 15480 } 15481 15482 public SharedUserSetting getSharedUser() { 15483 return mSharedUser; 15484 } 15485 15486 public void setSharedUser(SharedUserSetting user) { 15487 mSharedUser = user; 15488 } 15489 } 15490 15491 @Override 15492 public void onShellCommand(FileDescriptor in, FileDescriptor out, 15493 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 15494 (new PackageManagerShellCommand(this)).exec( 15495 this, in, out, err, args, resultReceiver); 15496 } 15497 15498 @Override 15499 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 15500 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 15501 != PackageManager.PERMISSION_GRANTED) { 15502 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 15503 + Binder.getCallingPid() 15504 + ", uid=" + Binder.getCallingUid() 15505 + " without permission " 15506 + android.Manifest.permission.DUMP); 15507 return; 15508 } 15509 15510 DumpState dumpState = new DumpState(); 15511 boolean fullPreferred = false; 15512 boolean checkin = false; 15513 15514 String packageName = null; 15515 ArraySet<String> permissionNames = null; 15516 15517 int opti = 0; 15518 while (opti < args.length) { 15519 String opt = args[opti]; 15520 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 15521 break; 15522 } 15523 opti++; 15524 15525 if ("-a".equals(opt)) { 15526 // Right now we only know how to print all. 15527 } else if ("-h".equals(opt)) { 15528 pw.println("Package manager dump options:"); 15529 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 15530 pw.println(" --checkin: dump for a checkin"); 15531 pw.println(" -f: print details of intent filters"); 15532 pw.println(" -h: print this help"); 15533 pw.println(" cmd may be one of:"); 15534 pw.println(" l[ibraries]: list known shared libraries"); 15535 pw.println(" f[eatures]: list device features"); 15536 pw.println(" k[eysets]: print known keysets"); 15537 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 15538 pw.println(" perm[issions]: dump permissions"); 15539 pw.println(" permission [name ...]: dump declaration and use of given permission"); 15540 pw.println(" pref[erred]: print preferred package settings"); 15541 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 15542 pw.println(" prov[iders]: dump content providers"); 15543 pw.println(" p[ackages]: dump installed packages"); 15544 pw.println(" s[hared-users]: dump shared user IDs"); 15545 pw.println(" m[essages]: print collected runtime messages"); 15546 pw.println(" v[erifiers]: print package verifier info"); 15547 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 15548 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 15549 pw.println(" version: print database version info"); 15550 pw.println(" write: write current settings now"); 15551 pw.println(" installs: details about install sessions"); 15552 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 15553 pw.println(" <package.name>: info about given package"); 15554 return; 15555 } else if ("--checkin".equals(opt)) { 15556 checkin = true; 15557 } else if ("-f".equals(opt)) { 15558 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 15559 } else { 15560 pw.println("Unknown argument: " + opt + "; use -h for help"); 15561 } 15562 } 15563 15564 // Is the caller requesting to dump a particular piece of data? 15565 if (opti < args.length) { 15566 String cmd = args[opti]; 15567 opti++; 15568 // Is this a package name? 15569 if ("android".equals(cmd) || cmd.contains(".")) { 15570 packageName = cmd; 15571 // When dumping a single package, we always dump all of its 15572 // filter information since the amount of data will be reasonable. 15573 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 15574 } else if ("check-permission".equals(cmd)) { 15575 if (opti >= args.length) { 15576 pw.println("Error: check-permission missing permission argument"); 15577 return; 15578 } 15579 String perm = args[opti]; 15580 opti++; 15581 if (opti >= args.length) { 15582 pw.println("Error: check-permission missing package argument"); 15583 return; 15584 } 15585 String pkg = args[opti]; 15586 opti++; 15587 int user = UserHandle.getUserId(Binder.getCallingUid()); 15588 if (opti < args.length) { 15589 try { 15590 user = Integer.parseInt(args[opti]); 15591 } catch (NumberFormatException e) { 15592 pw.println("Error: check-permission user argument is not a number: " 15593 + args[opti]); 15594 return; 15595 } 15596 } 15597 pw.println(checkPermission(perm, pkg, user)); 15598 return; 15599 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 15600 dumpState.setDump(DumpState.DUMP_LIBS); 15601 } else if ("f".equals(cmd) || "features".equals(cmd)) { 15602 dumpState.setDump(DumpState.DUMP_FEATURES); 15603 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 15604 if (opti >= args.length) { 15605 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 15606 | DumpState.DUMP_SERVICE_RESOLVERS 15607 | DumpState.DUMP_RECEIVER_RESOLVERS 15608 | DumpState.DUMP_CONTENT_RESOLVERS); 15609 } else { 15610 while (opti < args.length) { 15611 String name = args[opti]; 15612 if ("a".equals(name) || "activity".equals(name)) { 15613 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 15614 } else if ("s".equals(name) || "service".equals(name)) { 15615 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 15616 } else if ("r".equals(name) || "receiver".equals(name)) { 15617 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 15618 } else if ("c".equals(name) || "content".equals(name)) { 15619 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 15620 } else { 15621 pw.println("Error: unknown resolver table type: " + name); 15622 return; 15623 } 15624 opti++; 15625 } 15626 } 15627 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 15628 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 15629 } else if ("permission".equals(cmd)) { 15630 if (opti >= args.length) { 15631 pw.println("Error: permission requires permission name"); 15632 return; 15633 } 15634 permissionNames = new ArraySet<>(); 15635 while (opti < args.length) { 15636 permissionNames.add(args[opti]); 15637 opti++; 15638 } 15639 dumpState.setDump(DumpState.DUMP_PERMISSIONS 15640 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 15641 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 15642 dumpState.setDump(DumpState.DUMP_PREFERRED); 15643 } else if ("preferred-xml".equals(cmd)) { 15644 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 15645 if (opti < args.length && "--full".equals(args[opti])) { 15646 fullPreferred = true; 15647 opti++; 15648 } 15649 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 15650 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 15651 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 15652 dumpState.setDump(DumpState.DUMP_PACKAGES); 15653 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 15654 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 15655 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 15656 dumpState.setDump(DumpState.DUMP_PROVIDERS); 15657 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 15658 dumpState.setDump(DumpState.DUMP_MESSAGES); 15659 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 15660 dumpState.setDump(DumpState.DUMP_VERIFIERS); 15661 } else if ("i".equals(cmd) || "ifv".equals(cmd) 15662 || "intent-filter-verifiers".equals(cmd)) { 15663 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 15664 } else if ("version".equals(cmd)) { 15665 dumpState.setDump(DumpState.DUMP_VERSION); 15666 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 15667 dumpState.setDump(DumpState.DUMP_KEYSETS); 15668 } else if ("installs".equals(cmd)) { 15669 dumpState.setDump(DumpState.DUMP_INSTALLS); 15670 } else if ("write".equals(cmd)) { 15671 synchronized (mPackages) { 15672 mSettings.writeLPr(); 15673 pw.println("Settings written."); 15674 return; 15675 } 15676 } 15677 } 15678 15679 if (checkin) { 15680 pw.println("vers,1"); 15681 } 15682 15683 // reader 15684 synchronized (mPackages) { 15685 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 15686 if (!checkin) { 15687 if (dumpState.onTitlePrinted()) 15688 pw.println(); 15689 pw.println("Database versions:"); 15690 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 15691 } 15692 } 15693 15694 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 15695 if (!checkin) { 15696 if (dumpState.onTitlePrinted()) 15697 pw.println(); 15698 pw.println("Verifiers:"); 15699 pw.print(" Required: "); 15700 pw.print(mRequiredVerifierPackage); 15701 pw.print(" (uid="); 15702 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 15703 pw.println(")"); 15704 } else if (mRequiredVerifierPackage != null) { 15705 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 15706 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 15707 } 15708 } 15709 15710 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 15711 packageName == null) { 15712 if (mIntentFilterVerifierComponent != null) { 15713 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 15714 if (!checkin) { 15715 if (dumpState.onTitlePrinted()) 15716 pw.println(); 15717 pw.println("Intent Filter Verifier:"); 15718 pw.print(" Using: "); 15719 pw.print(verifierPackageName); 15720 pw.print(" (uid="); 15721 pw.print(getPackageUid(verifierPackageName, 0)); 15722 pw.println(")"); 15723 } else if (verifierPackageName != null) { 15724 pw.print("ifv,"); pw.print(verifierPackageName); 15725 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 15726 } 15727 } else { 15728 pw.println(); 15729 pw.println("No Intent Filter Verifier available!"); 15730 } 15731 } 15732 15733 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 15734 boolean printedHeader = false; 15735 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 15736 while (it.hasNext()) { 15737 String name = it.next(); 15738 SharedLibraryEntry ent = mSharedLibraries.get(name); 15739 if (!checkin) { 15740 if (!printedHeader) { 15741 if (dumpState.onTitlePrinted()) 15742 pw.println(); 15743 pw.println("Libraries:"); 15744 printedHeader = true; 15745 } 15746 pw.print(" "); 15747 } else { 15748 pw.print("lib,"); 15749 } 15750 pw.print(name); 15751 if (!checkin) { 15752 pw.print(" -> "); 15753 } 15754 if (ent.path != null) { 15755 if (!checkin) { 15756 pw.print("(jar) "); 15757 pw.print(ent.path); 15758 } else { 15759 pw.print(",jar,"); 15760 pw.print(ent.path); 15761 } 15762 } else { 15763 if (!checkin) { 15764 pw.print("(apk) "); 15765 pw.print(ent.apk); 15766 } else { 15767 pw.print(",apk,"); 15768 pw.print(ent.apk); 15769 } 15770 } 15771 pw.println(); 15772 } 15773 } 15774 15775 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 15776 if (dumpState.onTitlePrinted()) 15777 pw.println(); 15778 if (!checkin) { 15779 pw.println("Features:"); 15780 } 15781 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 15782 while (it.hasNext()) { 15783 String name = it.next(); 15784 if (!checkin) { 15785 pw.print(" "); 15786 } else { 15787 pw.print("feat,"); 15788 } 15789 pw.println(name); 15790 } 15791 } 15792 15793 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 15794 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 15795 : "Activity Resolver Table:", " ", packageName, 15796 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15797 dumpState.setTitlePrinted(true); 15798 } 15799 } 15800 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 15801 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 15802 : "Receiver Resolver Table:", " ", packageName, 15803 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15804 dumpState.setTitlePrinted(true); 15805 } 15806 } 15807 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 15808 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 15809 : "Service Resolver Table:", " ", packageName, 15810 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15811 dumpState.setTitlePrinted(true); 15812 } 15813 } 15814 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 15815 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 15816 : "Provider Resolver Table:", " ", packageName, 15817 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15818 dumpState.setTitlePrinted(true); 15819 } 15820 } 15821 15822 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 15823 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 15824 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 15825 int user = mSettings.mPreferredActivities.keyAt(i); 15826 if (pir.dump(pw, 15827 dumpState.getTitlePrinted() 15828 ? "\nPreferred Activities User " + user + ":" 15829 : "Preferred Activities User " + user + ":", " ", 15830 packageName, true, false)) { 15831 dumpState.setTitlePrinted(true); 15832 } 15833 } 15834 } 15835 15836 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 15837 pw.flush(); 15838 FileOutputStream fout = new FileOutputStream(fd); 15839 BufferedOutputStream str = new BufferedOutputStream(fout); 15840 XmlSerializer serializer = new FastXmlSerializer(); 15841 try { 15842 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 15843 serializer.startDocument(null, true); 15844 serializer.setFeature( 15845 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 15846 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 15847 serializer.endDocument(); 15848 serializer.flush(); 15849 } catch (IllegalArgumentException e) { 15850 pw.println("Failed writing: " + e); 15851 } catch (IllegalStateException e) { 15852 pw.println("Failed writing: " + e); 15853 } catch (IOException e) { 15854 pw.println("Failed writing: " + e); 15855 } 15856 } 15857 15858 if (!checkin 15859 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 15860 && packageName == null) { 15861 pw.println(); 15862 int count = mSettings.mPackages.size(); 15863 if (count == 0) { 15864 pw.println("No applications!"); 15865 pw.println(); 15866 } else { 15867 final String prefix = " "; 15868 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 15869 if (allPackageSettings.size() == 0) { 15870 pw.println("No domain preferred apps!"); 15871 pw.println(); 15872 } else { 15873 pw.println("App verification status:"); 15874 pw.println(); 15875 count = 0; 15876 for (PackageSetting ps : allPackageSettings) { 15877 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 15878 if (ivi == null || ivi.getPackageName() == null) continue; 15879 pw.println(prefix + "Package: " + ivi.getPackageName()); 15880 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 15881 pw.println(prefix + "Status: " + ivi.getStatusString()); 15882 pw.println(); 15883 count++; 15884 } 15885 if (count == 0) { 15886 pw.println(prefix + "No app verification established."); 15887 pw.println(); 15888 } 15889 for (int userId : sUserManager.getUserIds()) { 15890 pw.println("App linkages for user " + userId + ":"); 15891 pw.println(); 15892 count = 0; 15893 for (PackageSetting ps : allPackageSettings) { 15894 final long status = ps.getDomainVerificationStatusForUser(userId); 15895 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 15896 continue; 15897 } 15898 pw.println(prefix + "Package: " + ps.name); 15899 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 15900 String statusStr = IntentFilterVerificationInfo. 15901 getStatusStringFromValue(status); 15902 pw.println(prefix + "Status: " + statusStr); 15903 pw.println(); 15904 count++; 15905 } 15906 if (count == 0) { 15907 pw.println(prefix + "No configured app linkages."); 15908 pw.println(); 15909 } 15910 } 15911 } 15912 } 15913 } 15914 15915 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 15916 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 15917 if (packageName == null && permissionNames == null) { 15918 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 15919 if (iperm == 0) { 15920 if (dumpState.onTitlePrinted()) 15921 pw.println(); 15922 pw.println("AppOp Permissions:"); 15923 } 15924 pw.print(" AppOp Permission "); 15925 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 15926 pw.println(":"); 15927 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 15928 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 15929 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 15930 } 15931 } 15932 } 15933 } 15934 15935 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 15936 boolean printedSomething = false; 15937 for (PackageParser.Provider p : mProviders.mProviders.values()) { 15938 if (packageName != null && !packageName.equals(p.info.packageName)) { 15939 continue; 15940 } 15941 if (!printedSomething) { 15942 if (dumpState.onTitlePrinted()) 15943 pw.println(); 15944 pw.println("Registered ContentProviders:"); 15945 printedSomething = true; 15946 } 15947 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 15948 pw.print(" "); pw.println(p.toString()); 15949 } 15950 printedSomething = false; 15951 for (Map.Entry<String, PackageParser.Provider> entry : 15952 mProvidersByAuthority.entrySet()) { 15953 PackageParser.Provider p = entry.getValue(); 15954 if (packageName != null && !packageName.equals(p.info.packageName)) { 15955 continue; 15956 } 15957 if (!printedSomething) { 15958 if (dumpState.onTitlePrinted()) 15959 pw.println(); 15960 pw.println("ContentProvider Authorities:"); 15961 printedSomething = true; 15962 } 15963 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 15964 pw.print(" "); pw.println(p.toString()); 15965 if (p.info != null && p.info.applicationInfo != null) { 15966 final String appInfo = p.info.applicationInfo.toString(); 15967 pw.print(" applicationInfo="); pw.println(appInfo); 15968 } 15969 } 15970 } 15971 15972 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 15973 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 15974 } 15975 15976 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 15977 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 15978 } 15979 15980 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 15981 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 15982 } 15983 15984 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 15985 // XXX should handle packageName != null by dumping only install data that 15986 // the given package is involved with. 15987 if (dumpState.onTitlePrinted()) pw.println(); 15988 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 15989 } 15990 15991 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 15992 if (dumpState.onTitlePrinted()) pw.println(); 15993 mSettings.dumpReadMessagesLPr(pw, dumpState); 15994 15995 pw.println(); 15996 pw.println("Package warning messages:"); 15997 BufferedReader in = null; 15998 String line = null; 15999 try { 16000 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 16001 while ((line = in.readLine()) != null) { 16002 if (line.contains("ignored: updated version")) continue; 16003 pw.println(line); 16004 } 16005 } catch (IOException ignored) { 16006 } finally { 16007 IoUtils.closeQuietly(in); 16008 } 16009 } 16010 16011 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 16012 BufferedReader in = null; 16013 String line = null; 16014 try { 16015 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 16016 while ((line = in.readLine()) != null) { 16017 if (line.contains("ignored: updated version")) continue; 16018 pw.print("msg,"); 16019 pw.println(line); 16020 } 16021 } catch (IOException ignored) { 16022 } finally { 16023 IoUtils.closeQuietly(in); 16024 } 16025 } 16026 } 16027 } 16028 16029 private String dumpDomainString(String packageName) { 16030 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName); 16031 List<IntentFilter> filters = getAllIntentFilters(packageName); 16032 16033 ArraySet<String> result = new ArraySet<>(); 16034 if (iviList.size() > 0) { 16035 for (IntentFilterVerificationInfo ivi : iviList) { 16036 for (String host : ivi.getDomains()) { 16037 result.add(host); 16038 } 16039 } 16040 } 16041 if (filters != null && filters.size() > 0) { 16042 for (IntentFilter filter : filters) { 16043 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 16044 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 16045 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 16046 result.addAll(filter.getHostsList()); 16047 } 16048 } 16049 } 16050 16051 StringBuilder sb = new StringBuilder(result.size() * 16); 16052 for (String domain : result) { 16053 if (sb.length() > 0) sb.append(" "); 16054 sb.append(domain); 16055 } 16056 return sb.toString(); 16057 } 16058 16059 // ------- apps on sdcard specific code ------- 16060 static final boolean DEBUG_SD_INSTALL = false; 16061 16062 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 16063 16064 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 16065 16066 private boolean mMediaMounted = false; 16067 16068 static String getEncryptKey() { 16069 try { 16070 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 16071 SD_ENCRYPTION_KEYSTORE_NAME); 16072 if (sdEncKey == null) { 16073 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 16074 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 16075 if (sdEncKey == null) { 16076 Slog.e(TAG, "Failed to create encryption keys"); 16077 return null; 16078 } 16079 } 16080 return sdEncKey; 16081 } catch (NoSuchAlgorithmException nsae) { 16082 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 16083 return null; 16084 } catch (IOException ioe) { 16085 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 16086 return null; 16087 } 16088 } 16089 16090 /* 16091 * Update media status on PackageManager. 16092 */ 16093 @Override 16094 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 16095 int callingUid = Binder.getCallingUid(); 16096 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 16097 throw new SecurityException("Media status can only be updated by the system"); 16098 } 16099 // reader; this apparently protects mMediaMounted, but should probably 16100 // be a different lock in that case. 16101 synchronized (mPackages) { 16102 Log.i(TAG, "Updating external media status from " 16103 + (mMediaMounted ? "mounted" : "unmounted") + " to " 16104 + (mediaStatus ? "mounted" : "unmounted")); 16105 if (DEBUG_SD_INSTALL) 16106 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 16107 + ", mMediaMounted=" + mMediaMounted); 16108 if (mediaStatus == mMediaMounted) { 16109 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 16110 : 0, -1); 16111 mHandler.sendMessage(msg); 16112 return; 16113 } 16114 mMediaMounted = mediaStatus; 16115 } 16116 // Queue up an async operation since the package installation may take a 16117 // little while. 16118 mHandler.post(new Runnable() { 16119 public void run() { 16120 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 16121 } 16122 }); 16123 } 16124 16125 /** 16126 * Called by MountService when the initial ASECs to scan are available. 16127 * Should block until all the ASEC containers are finished being scanned. 16128 */ 16129 public void scanAvailableAsecs() { 16130 updateExternalMediaStatusInner(true, false, false); 16131 if (mShouldRestoreconData) { 16132 SELinuxMMAC.setRestoreconDone(); 16133 mShouldRestoreconData = false; 16134 } 16135 } 16136 16137 /* 16138 * Collect information of applications on external media, map them against 16139 * existing containers and update information based on current mount status. 16140 * Please note that we always have to report status if reportStatus has been 16141 * set to true especially when unloading packages. 16142 */ 16143 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 16144 boolean externalStorage) { 16145 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 16146 int[] uidArr = EmptyArray.INT; 16147 16148 final String[] list = PackageHelper.getSecureContainerList(); 16149 if (ArrayUtils.isEmpty(list)) { 16150 Log.i(TAG, "No secure containers found"); 16151 } else { 16152 // Process list of secure containers and categorize them 16153 // as active or stale based on their package internal state. 16154 16155 // reader 16156 synchronized (mPackages) { 16157 for (String cid : list) { 16158 // Leave stages untouched for now; installer service owns them 16159 if (PackageInstallerService.isStageName(cid)) continue; 16160 16161 if (DEBUG_SD_INSTALL) 16162 Log.i(TAG, "Processing container " + cid); 16163 String pkgName = getAsecPackageName(cid); 16164 if (pkgName == null) { 16165 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 16166 continue; 16167 } 16168 if (DEBUG_SD_INSTALL) 16169 Log.i(TAG, "Looking for pkg : " + pkgName); 16170 16171 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16172 if (ps == null) { 16173 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 16174 continue; 16175 } 16176 16177 /* 16178 * Skip packages that are not external if we're unmounting 16179 * external storage. 16180 */ 16181 if (externalStorage && !isMounted && !isExternal(ps)) { 16182 continue; 16183 } 16184 16185 final AsecInstallArgs args = new AsecInstallArgs(cid, 16186 getAppDexInstructionSets(ps), ps.isForwardLocked()); 16187 // The package status is changed only if the code path 16188 // matches between settings and the container id. 16189 if (ps.codePathString != null 16190 && ps.codePathString.startsWith(args.getCodePath())) { 16191 if (DEBUG_SD_INSTALL) { 16192 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 16193 + " at code path: " + ps.codePathString); 16194 } 16195 16196 // We do have a valid package installed on sdcard 16197 processCids.put(args, ps.codePathString); 16198 final int uid = ps.appId; 16199 if (uid != -1) { 16200 uidArr = ArrayUtils.appendInt(uidArr, uid); 16201 } 16202 } else { 16203 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 16204 + ps.codePathString); 16205 } 16206 } 16207 } 16208 16209 Arrays.sort(uidArr); 16210 } 16211 16212 // Process packages with valid entries. 16213 if (isMounted) { 16214 if (DEBUG_SD_INSTALL) 16215 Log.i(TAG, "Loading packages"); 16216 loadMediaPackages(processCids, uidArr, externalStorage); 16217 startCleaningPackages(); 16218 mInstallerService.onSecureContainersAvailable(); 16219 } else { 16220 if (DEBUG_SD_INSTALL) 16221 Log.i(TAG, "Unloading packages"); 16222 unloadMediaPackages(processCids, uidArr, reportStatus); 16223 } 16224 } 16225 16226 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 16227 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 16228 final int size = infos.size(); 16229 final String[] packageNames = new String[size]; 16230 final int[] packageUids = new int[size]; 16231 for (int i = 0; i < size; i++) { 16232 final ApplicationInfo info = infos.get(i); 16233 packageNames[i] = info.packageName; 16234 packageUids[i] = info.uid; 16235 } 16236 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 16237 finishedReceiver); 16238 } 16239 16240 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 16241 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 16242 sendResourcesChangedBroadcast(mediaStatus, replacing, 16243 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 16244 } 16245 16246 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 16247 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 16248 int size = pkgList.length; 16249 if (size > 0) { 16250 // Send broadcasts here 16251 Bundle extras = new Bundle(); 16252 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 16253 if (uidArr != null) { 16254 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 16255 } 16256 if (replacing) { 16257 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 16258 } 16259 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 16260 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 16261 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 16262 } 16263 } 16264 16265 /* 16266 * Look at potentially valid container ids from processCids If package 16267 * information doesn't match the one on record or package scanning fails, 16268 * the cid is added to list of removeCids. We currently don't delete stale 16269 * containers. 16270 */ 16271 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 16272 boolean externalStorage) { 16273 ArrayList<String> pkgList = new ArrayList<String>(); 16274 Set<AsecInstallArgs> keys = processCids.keySet(); 16275 16276 for (AsecInstallArgs args : keys) { 16277 String codePath = processCids.get(args); 16278 if (DEBUG_SD_INSTALL) 16279 Log.i(TAG, "Loading container : " + args.cid); 16280 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 16281 try { 16282 // Make sure there are no container errors first. 16283 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 16284 Slog.e(TAG, "Failed to mount cid : " + args.cid 16285 + " when installing from sdcard"); 16286 continue; 16287 } 16288 // Check code path here. 16289 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 16290 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 16291 + " does not match one in settings " + codePath); 16292 continue; 16293 } 16294 // Parse package 16295 int parseFlags = mDefParseFlags; 16296 if (args.isExternalAsec()) { 16297 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 16298 } 16299 if (args.isFwdLocked()) { 16300 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 16301 } 16302 16303 synchronized (mInstallLock) { 16304 PackageParser.Package pkg = null; 16305 try { 16306 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null); 16307 } catch (PackageManagerException e) { 16308 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 16309 } 16310 // Scan the package 16311 if (pkg != null) { 16312 /* 16313 * TODO why is the lock being held? doPostInstall is 16314 * called in other places without the lock. This needs 16315 * to be straightened out. 16316 */ 16317 // writer 16318 synchronized (mPackages) { 16319 retCode = PackageManager.INSTALL_SUCCEEDED; 16320 pkgList.add(pkg.packageName); 16321 // Post process args 16322 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 16323 pkg.applicationInfo.uid); 16324 } 16325 } else { 16326 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 16327 } 16328 } 16329 16330 } finally { 16331 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 16332 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 16333 } 16334 } 16335 } 16336 // writer 16337 synchronized (mPackages) { 16338 // If the platform SDK has changed since the last time we booted, 16339 // we need to re-grant app permission to catch any new ones that 16340 // appear. This is really a hack, and means that apps can in some 16341 // cases get permissions that the user didn't initially explicitly 16342 // allow... it would be nice to have some better way to handle 16343 // this situation. 16344 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 16345 : mSettings.getInternalVersion(); 16346 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 16347 : StorageManager.UUID_PRIVATE_INTERNAL; 16348 16349 int updateFlags = UPDATE_PERMISSIONS_ALL; 16350 if (ver.sdkVersion != mSdkVersion) { 16351 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 16352 + mSdkVersion + "; regranting permissions for external"); 16353 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 16354 } 16355 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 16356 16357 // Yay, everything is now upgraded 16358 ver.forceCurrent(); 16359 16360 // can downgrade to reader 16361 // Persist settings 16362 mSettings.writeLPr(); 16363 } 16364 // Send a broadcast to let everyone know we are done processing 16365 if (pkgList.size() > 0) { 16366 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 16367 } 16368 } 16369 16370 /* 16371 * Utility method to unload a list of specified containers 16372 */ 16373 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 16374 // Just unmount all valid containers. 16375 for (AsecInstallArgs arg : cidArgs) { 16376 synchronized (mInstallLock) { 16377 arg.doPostDeleteLI(false); 16378 } 16379 } 16380 } 16381 16382 /* 16383 * Unload packages mounted on external media. This involves deleting package 16384 * data from internal structures, sending broadcasts about diabled packages, 16385 * gc'ing to free up references, unmounting all secure containers 16386 * corresponding to packages on external media, and posting a 16387 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 16388 * that we always have to post this message if status has been requested no 16389 * matter what. 16390 */ 16391 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 16392 final boolean reportStatus) { 16393 if (DEBUG_SD_INSTALL) 16394 Log.i(TAG, "unloading media packages"); 16395 ArrayList<String> pkgList = new ArrayList<String>(); 16396 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 16397 final Set<AsecInstallArgs> keys = processCids.keySet(); 16398 for (AsecInstallArgs args : keys) { 16399 String pkgName = args.getPackageName(); 16400 if (DEBUG_SD_INSTALL) 16401 Log.i(TAG, "Trying to unload pkg : " + pkgName); 16402 // Delete package internally 16403 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 16404 synchronized (mInstallLock) { 16405 boolean res = deletePackageLI(pkgName, null, false, null, null, 16406 PackageManager.DELETE_KEEP_DATA, outInfo, false); 16407 if (res) { 16408 pkgList.add(pkgName); 16409 } else { 16410 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 16411 failedList.add(args); 16412 } 16413 } 16414 } 16415 16416 // reader 16417 synchronized (mPackages) { 16418 // We didn't update the settings after removing each package; 16419 // write them now for all packages. 16420 mSettings.writeLPr(); 16421 } 16422 16423 // We have to absolutely send UPDATED_MEDIA_STATUS only 16424 // after confirming that all the receivers processed the ordered 16425 // broadcast when packages get disabled, force a gc to clean things up. 16426 // and unload all the containers. 16427 if (pkgList.size() > 0) { 16428 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 16429 new IIntentReceiver.Stub() { 16430 public void performReceive(Intent intent, int resultCode, String data, 16431 Bundle extras, boolean ordered, boolean sticky, 16432 int sendingUser) throws RemoteException { 16433 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 16434 reportStatus ? 1 : 0, 1, keys); 16435 mHandler.sendMessage(msg); 16436 } 16437 }); 16438 } else { 16439 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 16440 keys); 16441 mHandler.sendMessage(msg); 16442 } 16443 } 16444 16445 private void loadPrivatePackages(final VolumeInfo vol) { 16446 mHandler.post(new Runnable() { 16447 @Override 16448 public void run() { 16449 loadPrivatePackagesInner(vol); 16450 } 16451 }); 16452 } 16453 16454 private void loadPrivatePackagesInner(VolumeInfo vol) { 16455 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 16456 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 16457 16458 final VersionInfo ver; 16459 final List<PackageSetting> packages; 16460 synchronized (mPackages) { 16461 ver = mSettings.findOrCreateVersion(vol.fsUuid); 16462 packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 16463 } 16464 16465 for (PackageSetting ps : packages) { 16466 synchronized (mInstallLock) { 16467 final PackageParser.Package pkg; 16468 try { 16469 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 16470 loaded.add(pkg.applicationInfo); 16471 } catch (PackageManagerException e) { 16472 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 16473 } 16474 16475 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 16476 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 16477 } 16478 } 16479 } 16480 16481 synchronized (mPackages) { 16482 int updateFlags = UPDATE_PERMISSIONS_ALL; 16483 if (ver.sdkVersion != mSdkVersion) { 16484 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 16485 + mSdkVersion + "; regranting permissions for " + vol.fsUuid); 16486 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 16487 } 16488 updatePermissionsLPw(null, null, vol.fsUuid, updateFlags); 16489 16490 // Yay, everything is now upgraded 16491 ver.forceCurrent(); 16492 16493 mSettings.writeLPr(); 16494 } 16495 16496 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 16497 sendResourcesChangedBroadcast(true, false, loaded, null); 16498 } 16499 16500 private void unloadPrivatePackages(final VolumeInfo vol) { 16501 mHandler.post(new Runnable() { 16502 @Override 16503 public void run() { 16504 unloadPrivatePackagesInner(vol); 16505 } 16506 }); 16507 } 16508 16509 private void unloadPrivatePackagesInner(VolumeInfo vol) { 16510 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 16511 synchronized (mInstallLock) { 16512 synchronized (mPackages) { 16513 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 16514 for (PackageSetting ps : packages) { 16515 if (ps.pkg == null) continue; 16516 16517 final ApplicationInfo info = ps.pkg.applicationInfo; 16518 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 16519 if (deletePackageLI(ps.name, null, false, null, null, 16520 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 16521 unloaded.add(info); 16522 } else { 16523 Slog.w(TAG, "Failed to unload " + ps.codePath); 16524 } 16525 } 16526 16527 mSettings.writeLPr(); 16528 } 16529 } 16530 16531 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 16532 sendResourcesChangedBroadcast(false, false, unloaded, null); 16533 } 16534 16535 /** 16536 * Examine all users present on given mounted volume, and destroy data 16537 * belonging to users that are no longer valid, or whose user ID has been 16538 * recycled. 16539 */ 16540 private void reconcileUsers(String volumeUuid) { 16541 final File[] files = FileUtils 16542 .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid)); 16543 for (File file : files) { 16544 if (!file.isDirectory()) continue; 16545 16546 final int userId; 16547 final UserInfo info; 16548 try { 16549 userId = Integer.parseInt(file.getName()); 16550 info = sUserManager.getUserInfo(userId); 16551 } catch (NumberFormatException e) { 16552 Slog.w(TAG, "Invalid user directory " + file); 16553 continue; 16554 } 16555 16556 boolean destroyUser = false; 16557 if (info == null) { 16558 logCriticalInfo(Log.WARN, "Destroying user directory " + file 16559 + " because no matching user was found"); 16560 destroyUser = true; 16561 } else { 16562 try { 16563 UserManagerService.enforceSerialNumber(file, info.serialNumber); 16564 } catch (IOException e) { 16565 logCriticalInfo(Log.WARN, "Destroying user directory " + file 16566 + " because we failed to enforce serial number: " + e); 16567 destroyUser = true; 16568 } 16569 } 16570 16571 if (destroyUser) { 16572 synchronized (mInstallLock) { 16573 mInstaller.removeUserDataDirs(volumeUuid, userId); 16574 } 16575 } 16576 } 16577 16578 final StorageManager sm = mContext.getSystemService(StorageManager.class); 16579 final UserManager um = mContext.getSystemService(UserManager.class); 16580 for (UserInfo user : um.getUsers()) { 16581 final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id); 16582 if (userDir.exists()) continue; 16583 16584 try { 16585 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, user.isEphemeral()); 16586 UserManagerService.enforceSerialNumber(userDir, user.serialNumber); 16587 } catch (IOException e) { 16588 Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e); 16589 } 16590 } 16591 } 16592 16593 /** 16594 * Examine all apps present on given mounted volume, and destroy apps that 16595 * aren't expected, either due to uninstallation or reinstallation on 16596 * another volume. 16597 */ 16598 private void reconcileApps(String volumeUuid) { 16599 final File[] files = FileUtils 16600 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 16601 for (File file : files) { 16602 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 16603 && !PackageInstallerService.isStageName(file.getName()); 16604 if (!isPackage) { 16605 // Ignore entries which are not packages 16606 continue; 16607 } 16608 16609 boolean destroyApp = false; 16610 String packageName = null; 16611 try { 16612 final PackageLite pkg = PackageParser.parsePackageLite(file, 16613 PackageParser.PARSE_MUST_BE_APK); 16614 packageName = pkg.packageName; 16615 16616 synchronized (mPackages) { 16617 final PackageSetting ps = mSettings.mPackages.get(packageName); 16618 if (ps == null) { 16619 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + " 16620 + volumeUuid + " because we found no install record"); 16621 destroyApp = true; 16622 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 16623 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on " 16624 + volumeUuid + " because we expected it on " + ps.volumeUuid); 16625 destroyApp = true; 16626 } 16627 } 16628 16629 } catch (PackageParserException e) { 16630 logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e); 16631 destroyApp = true; 16632 } 16633 16634 if (destroyApp) { 16635 synchronized (mInstallLock) { 16636 if (packageName != null) { 16637 removeDataDirsLI(volumeUuid, packageName); 16638 } 16639 if (file.isDirectory()) { 16640 mInstaller.rmPackageDir(file.getAbsolutePath()); 16641 } else { 16642 file.delete(); 16643 } 16644 } 16645 } 16646 } 16647 } 16648 16649 private void unfreezePackage(String packageName) { 16650 synchronized (mPackages) { 16651 final PackageSetting ps = mSettings.mPackages.get(packageName); 16652 if (ps != null) { 16653 ps.frozen = false; 16654 } 16655 } 16656 } 16657 16658 @Override 16659 public int movePackage(final String packageName, final String volumeUuid) { 16660 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 16661 16662 final int moveId = mNextMoveId.getAndIncrement(); 16663 mHandler.post(new Runnable() { 16664 @Override 16665 public void run() { 16666 try { 16667 movePackageInternal(packageName, volumeUuid, moveId); 16668 } catch (PackageManagerException e) { 16669 Slog.w(TAG, "Failed to move " + packageName, e); 16670 mMoveCallbacks.notifyStatusChanged(moveId, 16671 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 16672 } 16673 } 16674 }); 16675 return moveId; 16676 } 16677 16678 private void movePackageInternal(final String packageName, final String volumeUuid, 16679 final int moveId) throws PackageManagerException { 16680 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 16681 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16682 final PackageManager pm = mContext.getPackageManager(); 16683 16684 final boolean currentAsec; 16685 final String currentVolumeUuid; 16686 final File codeFile; 16687 final String installerPackageName; 16688 final String packageAbiOverride; 16689 final int appId; 16690 final String seinfo; 16691 final String label; 16692 16693 // reader 16694 synchronized (mPackages) { 16695 final PackageParser.Package pkg = mPackages.get(packageName); 16696 final PackageSetting ps = mSettings.mPackages.get(packageName); 16697 if (pkg == null || ps == null) { 16698 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 16699 } 16700 16701 if (pkg.applicationInfo.isSystemApp()) { 16702 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 16703 "Cannot move system application"); 16704 } 16705 16706 if (pkg.applicationInfo.isExternalAsec()) { 16707 currentAsec = true; 16708 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 16709 } else if (pkg.applicationInfo.isForwardLocked()) { 16710 currentAsec = true; 16711 currentVolumeUuid = "forward_locked"; 16712 } else { 16713 currentAsec = false; 16714 currentVolumeUuid = ps.volumeUuid; 16715 16716 final File probe = new File(pkg.codePath); 16717 final File probeOat = new File(probe, "oat"); 16718 if (!probe.isDirectory() || !probeOat.isDirectory()) { 16719 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16720 "Move only supported for modern cluster style installs"); 16721 } 16722 } 16723 16724 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 16725 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16726 "Package already moved to " + volumeUuid); 16727 } 16728 16729 if (ps.frozen) { 16730 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 16731 "Failed to move already frozen package"); 16732 } 16733 ps.frozen = true; 16734 16735 codeFile = new File(pkg.codePath); 16736 installerPackageName = ps.installerPackageName; 16737 packageAbiOverride = ps.cpuAbiOverrideString; 16738 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16739 seinfo = pkg.applicationInfo.seinfo; 16740 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 16741 } 16742 16743 // Now that we're guarded by frozen state, kill app during move 16744 final long token = Binder.clearCallingIdentity(); 16745 try { 16746 killApplication(packageName, appId, "move pkg"); 16747 } finally { 16748 Binder.restoreCallingIdentity(token); 16749 } 16750 16751 final Bundle extras = new Bundle(); 16752 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 16753 extras.putString(Intent.EXTRA_TITLE, label); 16754 mMoveCallbacks.notifyCreated(moveId, extras); 16755 16756 int installFlags; 16757 final boolean moveCompleteApp; 16758 final File measurePath; 16759 16760 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 16761 installFlags = INSTALL_INTERNAL; 16762 moveCompleteApp = !currentAsec; 16763 measurePath = Environment.getDataAppDirectory(volumeUuid); 16764 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 16765 installFlags = INSTALL_EXTERNAL; 16766 moveCompleteApp = false; 16767 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 16768 } else { 16769 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 16770 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 16771 || !volume.isMountedWritable()) { 16772 unfreezePackage(packageName); 16773 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16774 "Move location not mounted private volume"); 16775 } 16776 16777 Preconditions.checkState(!currentAsec); 16778 16779 installFlags = INSTALL_INTERNAL; 16780 moveCompleteApp = true; 16781 measurePath = Environment.getDataAppDirectory(volumeUuid); 16782 } 16783 16784 final PackageStats stats = new PackageStats(null, -1); 16785 synchronized (mInstaller) { 16786 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 16787 unfreezePackage(packageName); 16788 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16789 "Failed to measure package size"); 16790 } 16791 } 16792 16793 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 16794 + stats.dataSize); 16795 16796 final long startFreeBytes = measurePath.getFreeSpace(); 16797 final long sizeBytes; 16798 if (moveCompleteApp) { 16799 sizeBytes = stats.codeSize + stats.dataSize; 16800 } else { 16801 sizeBytes = stats.codeSize; 16802 } 16803 16804 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 16805 unfreezePackage(packageName); 16806 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16807 "Not enough free space to move"); 16808 } 16809 16810 mMoveCallbacks.notifyStatusChanged(moveId, 10); 16811 16812 final CountDownLatch installedLatch = new CountDownLatch(1); 16813 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 16814 @Override 16815 public void onUserActionRequired(Intent intent) throws RemoteException { 16816 throw new IllegalStateException(); 16817 } 16818 16819 @Override 16820 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 16821 Bundle extras) throws RemoteException { 16822 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 16823 + PackageManager.installStatusToString(returnCode, msg)); 16824 16825 installedLatch.countDown(); 16826 16827 // Regardless of success or failure of the move operation, 16828 // always unfreeze the package 16829 unfreezePackage(packageName); 16830 16831 final int status = PackageManager.installStatusToPublicStatus(returnCode); 16832 switch (status) { 16833 case PackageInstaller.STATUS_SUCCESS: 16834 mMoveCallbacks.notifyStatusChanged(moveId, 16835 PackageManager.MOVE_SUCCEEDED); 16836 break; 16837 case PackageInstaller.STATUS_FAILURE_STORAGE: 16838 mMoveCallbacks.notifyStatusChanged(moveId, 16839 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 16840 break; 16841 default: 16842 mMoveCallbacks.notifyStatusChanged(moveId, 16843 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 16844 break; 16845 } 16846 } 16847 }; 16848 16849 final MoveInfo move; 16850 if (moveCompleteApp) { 16851 // Kick off a thread to report progress estimates 16852 new Thread() { 16853 @Override 16854 public void run() { 16855 while (true) { 16856 try { 16857 if (installedLatch.await(1, TimeUnit.SECONDS)) { 16858 break; 16859 } 16860 } catch (InterruptedException ignored) { 16861 } 16862 16863 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 16864 final int progress = 10 + (int) MathUtils.constrain( 16865 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 16866 mMoveCallbacks.notifyStatusChanged(moveId, progress); 16867 } 16868 } 16869 }.start(); 16870 16871 final String dataAppName = codeFile.getName(); 16872 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 16873 dataAppName, appId, seinfo); 16874 } else { 16875 move = null; 16876 } 16877 16878 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 16879 16880 final Message msg = mHandler.obtainMessage(INIT_COPY); 16881 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 16882 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 16883 installerPackageName, volumeUuid, null, user, packageAbiOverride, null); 16884 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 16885 msg.obj = params; 16886 16887 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 16888 System.identityHashCode(msg.obj)); 16889 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 16890 System.identityHashCode(msg.obj)); 16891 16892 mHandler.sendMessage(msg); 16893 } 16894 16895 @Override 16896 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 16897 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 16898 16899 final int realMoveId = mNextMoveId.getAndIncrement(); 16900 final Bundle extras = new Bundle(); 16901 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 16902 mMoveCallbacks.notifyCreated(realMoveId, extras); 16903 16904 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 16905 @Override 16906 public void onCreated(int moveId, Bundle extras) { 16907 // Ignored 16908 } 16909 16910 @Override 16911 public void onStatusChanged(int moveId, int status, long estMillis) { 16912 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 16913 } 16914 }; 16915 16916 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16917 storage.setPrimaryStorageUuid(volumeUuid, callback); 16918 return realMoveId; 16919 } 16920 16921 @Override 16922 public int getMoveStatus(int moveId) { 16923 mContext.enforceCallingOrSelfPermission( 16924 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16925 return mMoveCallbacks.mLastStatus.get(moveId); 16926 } 16927 16928 @Override 16929 public void registerMoveCallback(IPackageMoveObserver callback) { 16930 mContext.enforceCallingOrSelfPermission( 16931 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16932 mMoveCallbacks.register(callback); 16933 } 16934 16935 @Override 16936 public void unregisterMoveCallback(IPackageMoveObserver callback) { 16937 mContext.enforceCallingOrSelfPermission( 16938 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16939 mMoveCallbacks.unregister(callback); 16940 } 16941 16942 @Override 16943 public boolean setInstallLocation(int loc) { 16944 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 16945 null); 16946 if (getInstallLocation() == loc) { 16947 return true; 16948 } 16949 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 16950 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 16951 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 16952 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 16953 return true; 16954 } 16955 return false; 16956 } 16957 16958 @Override 16959 public int getInstallLocation() { 16960 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 16961 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 16962 PackageHelper.APP_INSTALL_AUTO); 16963 } 16964 16965 /** Called by UserManagerService */ 16966 void cleanUpUser(UserManagerService userManager, int userHandle) { 16967 synchronized (mPackages) { 16968 mDirtyUsers.remove(userHandle); 16969 mUserNeedsBadging.delete(userHandle); 16970 mSettings.removeUserLPw(userHandle); 16971 mPendingBroadcasts.remove(userHandle); 16972 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 16973 } 16974 synchronized (mInstallLock) { 16975 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16976 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 16977 final String volumeUuid = vol.getFsUuid(); 16978 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 16979 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 16980 } 16981 synchronized (mPackages) { 16982 removeUnusedPackagesLILPw(userManager, userHandle); 16983 } 16984 } 16985 } 16986 16987 /** 16988 * We're removing userHandle and would like to remove any downloaded packages 16989 * that are no longer in use by any other user. 16990 * @param userHandle the user being removed 16991 */ 16992 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 16993 final boolean DEBUG_CLEAN_APKS = false; 16994 int [] users = userManager.getUserIds(); 16995 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 16996 while (psit.hasNext()) { 16997 PackageSetting ps = psit.next(); 16998 if (ps.pkg == null) { 16999 continue; 17000 } 17001 final String packageName = ps.pkg.packageName; 17002 // Skip over if system app 17003 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 17004 continue; 17005 } 17006 if (DEBUG_CLEAN_APKS) { 17007 Slog.i(TAG, "Checking package " + packageName); 17008 } 17009 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 17010 if (keep) { 17011 if (DEBUG_CLEAN_APKS) { 17012 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 17013 } 17014 } else { 17015 for (int i = 0; i < users.length; i++) { 17016 if (users[i] != userHandle && ps.getInstalled(users[i])) { 17017 keep = true; 17018 if (DEBUG_CLEAN_APKS) { 17019 Slog.i(TAG, " Keeping package " + packageName + " for user " 17020 + users[i]); 17021 } 17022 break; 17023 } 17024 } 17025 } 17026 if (!keep) { 17027 if (DEBUG_CLEAN_APKS) { 17028 Slog.i(TAG, " Removing package " + packageName); 17029 } 17030 mHandler.post(new Runnable() { 17031 public void run() { 17032 deletePackageX(packageName, userHandle, 0); 17033 } //end run 17034 }); 17035 } 17036 } 17037 } 17038 17039 /** Called by UserManagerService */ 17040 void createNewUser(int userHandle) { 17041 synchronized (mInstallLock) { 17042 mInstaller.createUserConfig(userHandle); 17043 mSettings.createNewUserLI(this, mInstaller, userHandle); 17044 } 17045 synchronized (mPackages) { 17046 applyFactoryDefaultBrowserLPw(userHandle); 17047 primeDomainVerificationsLPw(userHandle); 17048 } 17049 } 17050 17051 void newUserCreated(final int userHandle) { 17052 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 17053 // If permission review for legacy apps is required, we represent 17054 // dagerous permissions for such apps as always granted runtime 17055 // permissions to keep per user flag state whether review is needed. 17056 // Hence, if a new user is added we have to propagate dangerous 17057 // permission grants for these legacy apps. 17058 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 17059 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 17060 | UPDATE_PERMISSIONS_REPLACE_ALL); 17061 } 17062 } 17063 17064 @Override 17065 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 17066 mContext.enforceCallingOrSelfPermission( 17067 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 17068 "Only package verification agents can read the verifier device identity"); 17069 17070 synchronized (mPackages) { 17071 return mSettings.getVerifierDeviceIdentityLPw(); 17072 } 17073 } 17074 17075 @Override 17076 public void setPermissionEnforced(String permission, boolean enforced) { 17077 // TODO: Now that we no longer change GID for storage, this should to away. 17078 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 17079 "setPermissionEnforced"); 17080 if (READ_EXTERNAL_STORAGE.equals(permission)) { 17081 synchronized (mPackages) { 17082 if (mSettings.mReadExternalStorageEnforced == null 17083 || mSettings.mReadExternalStorageEnforced != enforced) { 17084 mSettings.mReadExternalStorageEnforced = enforced; 17085 mSettings.writeLPr(); 17086 } 17087 } 17088 // kill any non-foreground processes so we restart them and 17089 // grant/revoke the GID. 17090 final IActivityManager am = ActivityManagerNative.getDefault(); 17091 if (am != null) { 17092 final long token = Binder.clearCallingIdentity(); 17093 try { 17094 am.killProcessesBelowForeground("setPermissionEnforcement"); 17095 } catch (RemoteException e) { 17096 } finally { 17097 Binder.restoreCallingIdentity(token); 17098 } 17099 } 17100 } else { 17101 throw new IllegalArgumentException("No selective enforcement for " + permission); 17102 } 17103 } 17104 17105 @Override 17106 @Deprecated 17107 public boolean isPermissionEnforced(String permission) { 17108 return true; 17109 } 17110 17111 @Override 17112 public boolean isStorageLow() { 17113 final long token = Binder.clearCallingIdentity(); 17114 try { 17115 final DeviceStorageMonitorInternal 17116 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 17117 if (dsm != null) { 17118 return dsm.isMemoryLow(); 17119 } else { 17120 return false; 17121 } 17122 } finally { 17123 Binder.restoreCallingIdentity(token); 17124 } 17125 } 17126 17127 @Override 17128 public IPackageInstaller getPackageInstaller() { 17129 return mInstallerService; 17130 } 17131 17132 private boolean userNeedsBadging(int userId) { 17133 int index = mUserNeedsBadging.indexOfKey(userId); 17134 if (index < 0) { 17135 final UserInfo userInfo; 17136 final long token = Binder.clearCallingIdentity(); 17137 try { 17138 userInfo = sUserManager.getUserInfo(userId); 17139 } finally { 17140 Binder.restoreCallingIdentity(token); 17141 } 17142 final boolean b; 17143 if (userInfo != null && userInfo.isManagedProfile()) { 17144 b = true; 17145 } else { 17146 b = false; 17147 } 17148 mUserNeedsBadging.put(userId, b); 17149 return b; 17150 } 17151 return mUserNeedsBadging.valueAt(index); 17152 } 17153 17154 @Override 17155 public KeySet getKeySetByAlias(String packageName, String alias) { 17156 if (packageName == null || alias == null) { 17157 return null; 17158 } 17159 synchronized(mPackages) { 17160 final PackageParser.Package pkg = mPackages.get(packageName); 17161 if (pkg == null) { 17162 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 17163 throw new IllegalArgumentException("Unknown package: " + packageName); 17164 } 17165 KeySetManagerService ksms = mSettings.mKeySetManagerService; 17166 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 17167 } 17168 } 17169 17170 @Override 17171 public KeySet getSigningKeySet(String packageName) { 17172 if (packageName == null) { 17173 return null; 17174 } 17175 synchronized(mPackages) { 17176 final PackageParser.Package pkg = mPackages.get(packageName); 17177 if (pkg == null) { 17178 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 17179 throw new IllegalArgumentException("Unknown package: " + packageName); 17180 } 17181 if (pkg.applicationInfo.uid != Binder.getCallingUid() 17182 && Process.SYSTEM_UID != Binder.getCallingUid()) { 17183 throw new SecurityException("May not access signing KeySet of other apps."); 17184 } 17185 KeySetManagerService ksms = mSettings.mKeySetManagerService; 17186 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 17187 } 17188 } 17189 17190 @Override 17191 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 17192 if (packageName == null || ks == null) { 17193 return false; 17194 } 17195 synchronized(mPackages) { 17196 final PackageParser.Package pkg = mPackages.get(packageName); 17197 if (pkg == null) { 17198 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 17199 throw new IllegalArgumentException("Unknown package: " + packageName); 17200 } 17201 IBinder ksh = ks.getToken(); 17202 if (ksh instanceof KeySetHandle) { 17203 KeySetManagerService ksms = mSettings.mKeySetManagerService; 17204 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 17205 } 17206 return false; 17207 } 17208 } 17209 17210 @Override 17211 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 17212 if (packageName == null || ks == null) { 17213 return false; 17214 } 17215 synchronized(mPackages) { 17216 final PackageParser.Package pkg = mPackages.get(packageName); 17217 if (pkg == null) { 17218 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 17219 throw new IllegalArgumentException("Unknown package: " + packageName); 17220 } 17221 IBinder ksh = ks.getToken(); 17222 if (ksh instanceof KeySetHandle) { 17223 KeySetManagerService ksms = mSettings.mKeySetManagerService; 17224 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 17225 } 17226 return false; 17227 } 17228 } 17229 17230 private void deletePackageIfUnusedLPr(final String packageName) { 17231 PackageSetting ps = mSettings.mPackages.get(packageName); 17232 if (ps == null) { 17233 return; 17234 } 17235 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 17236 // TODO Implement atomic delete if package is unused 17237 // It is currently possible that the package will be deleted even if it is installed 17238 // after this method returns. 17239 mHandler.post(new Runnable() { 17240 public void run() { 17241 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 17242 } 17243 }); 17244 } 17245 } 17246 17247 /** 17248 * Check and throw if the given before/after packages would be considered a 17249 * downgrade. 17250 */ 17251 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 17252 throws PackageManagerException { 17253 if (after.versionCode < before.mVersionCode) { 17254 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 17255 "Update version code " + after.versionCode + " is older than current " 17256 + before.mVersionCode); 17257 } else if (after.versionCode == before.mVersionCode) { 17258 if (after.baseRevisionCode < before.baseRevisionCode) { 17259 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 17260 "Update base revision code " + after.baseRevisionCode 17261 + " is older than current " + before.baseRevisionCode); 17262 } 17263 17264 if (!ArrayUtils.isEmpty(after.splitNames)) { 17265 for (int i = 0; i < after.splitNames.length; i++) { 17266 final String splitName = after.splitNames[i]; 17267 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 17268 if (j != -1) { 17269 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 17270 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 17271 "Update split " + splitName + " revision code " 17272 + after.splitRevisionCodes[i] + " is older than current " 17273 + before.splitRevisionCodes[j]); 17274 } 17275 } 17276 } 17277 } 17278 } 17279 } 17280 17281 private static class MoveCallbacks extends Handler { 17282 private static final int MSG_CREATED = 1; 17283 private static final int MSG_STATUS_CHANGED = 2; 17284 17285 private final RemoteCallbackList<IPackageMoveObserver> 17286 mCallbacks = new RemoteCallbackList<>(); 17287 17288 private final SparseIntArray mLastStatus = new SparseIntArray(); 17289 17290 public MoveCallbacks(Looper looper) { 17291 super(looper); 17292 } 17293 17294 public void register(IPackageMoveObserver callback) { 17295 mCallbacks.register(callback); 17296 } 17297 17298 public void unregister(IPackageMoveObserver callback) { 17299 mCallbacks.unregister(callback); 17300 } 17301 17302 @Override 17303 public void handleMessage(Message msg) { 17304 final SomeArgs args = (SomeArgs) msg.obj; 17305 final int n = mCallbacks.beginBroadcast(); 17306 for (int i = 0; i < n; i++) { 17307 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 17308 try { 17309 invokeCallback(callback, msg.what, args); 17310 } catch (RemoteException ignored) { 17311 } 17312 } 17313 mCallbacks.finishBroadcast(); 17314 args.recycle(); 17315 } 17316 17317 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 17318 throws RemoteException { 17319 switch (what) { 17320 case MSG_CREATED: { 17321 callback.onCreated(args.argi1, (Bundle) args.arg2); 17322 break; 17323 } 17324 case MSG_STATUS_CHANGED: { 17325 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 17326 break; 17327 } 17328 } 17329 } 17330 17331 private void notifyCreated(int moveId, Bundle extras) { 17332 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 17333 17334 final SomeArgs args = SomeArgs.obtain(); 17335 args.argi1 = moveId; 17336 args.arg2 = extras; 17337 obtainMessage(MSG_CREATED, args).sendToTarget(); 17338 } 17339 17340 private void notifyStatusChanged(int moveId, int status) { 17341 notifyStatusChanged(moveId, status, -1); 17342 } 17343 17344 private void notifyStatusChanged(int moveId, int status, long estMillis) { 17345 Slog.v(TAG, "Move " + moveId + " status " + status); 17346 17347 final SomeArgs args = SomeArgs.obtain(); 17348 args.argi1 = moveId; 17349 args.argi2 = status; 17350 args.arg3 = estMillis; 17351 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 17352 17353 synchronized (mLastStatus) { 17354 mLastStatus.put(moveId, status); 17355 } 17356 } 17357 } 17358 17359 private final static class OnPermissionChangeListeners extends Handler { 17360 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 17361 17362 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 17363 new RemoteCallbackList<>(); 17364 17365 public OnPermissionChangeListeners(Looper looper) { 17366 super(looper); 17367 } 17368 17369 @Override 17370 public void handleMessage(Message msg) { 17371 switch (msg.what) { 17372 case MSG_ON_PERMISSIONS_CHANGED: { 17373 final int uid = msg.arg1; 17374 handleOnPermissionsChanged(uid); 17375 } break; 17376 } 17377 } 17378 17379 public void addListenerLocked(IOnPermissionsChangeListener listener) { 17380 mPermissionListeners.register(listener); 17381 17382 } 17383 17384 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 17385 mPermissionListeners.unregister(listener); 17386 } 17387 17388 public void onPermissionsChanged(int uid) { 17389 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 17390 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 17391 } 17392 } 17393 17394 private void handleOnPermissionsChanged(int uid) { 17395 final int count = mPermissionListeners.beginBroadcast(); 17396 try { 17397 for (int i = 0; i < count; i++) { 17398 IOnPermissionsChangeListener callback = mPermissionListeners 17399 .getBroadcastItem(i); 17400 try { 17401 callback.onPermissionsChanged(uid); 17402 } catch (RemoteException e) { 17403 Log.e(TAG, "Permission listener is dead", e); 17404 } 17405 } 17406 } finally { 17407 mPermissionListeners.finishBroadcast(); 17408 } 17409 } 17410 } 17411 17412 private class PackageManagerInternalImpl extends PackageManagerInternal { 17413 @Override 17414 public void setLocationPackagesProvider(PackagesProvider provider) { 17415 synchronized (mPackages) { 17416 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 17417 } 17418 } 17419 17420 @Override 17421 public void setImePackagesProvider(PackagesProvider provider) { 17422 synchronized (mPackages) { 17423 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 17424 } 17425 } 17426 17427 @Override 17428 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 17429 synchronized (mPackages) { 17430 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 17431 } 17432 } 17433 17434 @Override 17435 public void setSmsAppPackagesProvider(PackagesProvider provider) { 17436 synchronized (mPackages) { 17437 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 17438 } 17439 } 17440 17441 @Override 17442 public void setDialerAppPackagesProvider(PackagesProvider provider) { 17443 synchronized (mPackages) { 17444 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 17445 } 17446 } 17447 17448 @Override 17449 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 17450 synchronized (mPackages) { 17451 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 17452 } 17453 } 17454 17455 @Override 17456 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 17457 synchronized (mPackages) { 17458 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 17459 } 17460 } 17461 17462 @Override 17463 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 17464 synchronized (mPackages) { 17465 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 17466 packageName, userId); 17467 } 17468 } 17469 17470 @Override 17471 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 17472 synchronized (mPackages) { 17473 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 17474 packageName, userId); 17475 } 17476 } 17477 17478 @Override 17479 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 17480 synchronized (mPackages) { 17481 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 17482 packageName, userId); 17483 } 17484 } 17485 17486 @Override 17487 public void setKeepUninstalledPackages(final List<String> packageList) { 17488 Preconditions.checkNotNull(packageList); 17489 List<String> removedFromList = null; 17490 synchronized (mPackages) { 17491 if (mKeepUninstalledPackages != null) { 17492 final int packagesCount = mKeepUninstalledPackages.size(); 17493 for (int i = 0; i < packagesCount; i++) { 17494 String oldPackage = mKeepUninstalledPackages.get(i); 17495 if (packageList != null && packageList.contains(oldPackage)) { 17496 continue; 17497 } 17498 if (removedFromList == null) { 17499 removedFromList = new ArrayList<>(); 17500 } 17501 removedFromList.add(oldPackage); 17502 } 17503 } 17504 mKeepUninstalledPackages = new ArrayList<>(packageList); 17505 if (removedFromList != null) { 17506 final int removedCount = removedFromList.size(); 17507 for (int i = 0; i < removedCount; i++) { 17508 deletePackageIfUnusedLPr(removedFromList.get(i)); 17509 } 17510 } 17511 } 17512 } 17513 17514 @Override 17515 public boolean isPermissionsReviewRequired(String packageName, int userId) { 17516 synchronized (mPackages) { 17517 // If we do not support permission review, done. 17518 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 17519 return false; 17520 } 17521 17522 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 17523 if (packageSetting == null) { 17524 return false; 17525 } 17526 17527 // Permission review applies only to apps not supporting the new permission model. 17528 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 17529 return false; 17530 } 17531 17532 // Legacy apps have the permission and get user consent on launch. 17533 PermissionsState permissionsState = packageSetting.getPermissionsState(); 17534 return permissionsState.isPermissionReviewRequired(userId); 17535 } 17536 } 17537 } 17538 17539 @Override 17540 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 17541 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 17542 synchronized (mPackages) { 17543 final long identity = Binder.clearCallingIdentity(); 17544 try { 17545 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 17546 packageNames, userId); 17547 } finally { 17548 Binder.restoreCallingIdentity(identity); 17549 } 17550 } 17551 } 17552 17553 private static void enforceSystemOrPhoneCaller(String tag) { 17554 int callingUid = Binder.getCallingUid(); 17555 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 17556 throw new SecurityException( 17557 "Cannot call " + tag + " from UID " + callingUid); 17558 } 17559 } 17560} 17561