PackageManagerService.java revision b3523c45dd764ba9926ee70a04cfee78b10e7ab4
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 21import static android.Manifest.permission.WRITE_MEDIA_STORAGE; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 27import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 28import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 29import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 31import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 32import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 34import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 35import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 36import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 37import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 40import static android.content.pm.PackageManager.INSTALL_FAILED_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.app.usage.UsageStats; 97import android.app.usage.UsageStatsManager; 98import android.content.BroadcastReceiver; 99import android.content.ComponentName; 100import android.content.Context; 101import android.content.IIntentReceiver; 102import android.content.Intent; 103import android.content.IntentFilter; 104import android.content.IntentSender; 105import android.content.IntentSender.SendIntentException; 106import android.content.ServiceConnection; 107import android.content.pm.ActivityInfo; 108import android.content.pm.ApplicationInfo; 109import android.content.pm.AppsQueryHelper; 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.res.Resources; 149import android.hardware.display.DisplayManager; 150import android.net.Uri; 151import android.os.Debug; 152import android.os.Binder; 153import android.os.Build; 154import android.os.Bundle; 155import android.os.Environment; 156import android.os.Environment.UserEnvironment; 157import android.os.FileUtils; 158import android.os.Handler; 159import android.os.IBinder; 160import android.os.Looper; 161import android.os.Message; 162import android.os.Parcel; 163import android.os.ParcelFileDescriptor; 164import android.os.Process; 165import android.os.RemoteCallbackList; 166import android.os.RemoteException; 167import android.os.ResultReceiver; 168import android.os.SELinux; 169import android.os.ServiceManager; 170import android.os.SystemClock; 171import android.os.SystemProperties; 172import android.os.Trace; 173import android.os.UserHandle; 174import android.os.UserManager; 175import android.os.storage.IMountService; 176import android.os.storage.MountServiceInternal; 177import android.os.storage.StorageEventListener; 178import android.os.storage.StorageManager; 179import android.os.storage.VolumeInfo; 180import android.os.storage.VolumeRecord; 181import android.security.KeyStore; 182import android.security.SystemKeyStore; 183import android.system.ErrnoException; 184import android.system.Os; 185import android.system.StructStat; 186import android.text.TextUtils; 187import android.text.format.DateUtils; 188import android.util.ArrayMap; 189import android.util.ArraySet; 190import android.util.AtomicFile; 191import android.util.DisplayMetrics; 192import android.util.EventLog; 193import android.util.ExceptionUtils; 194import android.util.Log; 195import android.util.LogPrinter; 196import android.util.MathUtils; 197import android.util.PrintStreamPrinter; 198import android.util.Slog; 199import android.util.SparseArray; 200import android.util.SparseBooleanArray; 201import android.util.SparseIntArray; 202import android.util.Xml; 203import android.view.Display; 204 205import dalvik.system.DexFile; 206import dalvik.system.VMRuntime; 207 208import libcore.io.IoUtils; 209import libcore.util.EmptyArray; 210 211import com.android.internal.R; 212import com.android.internal.annotations.GuardedBy; 213import com.android.internal.app.EphemeralResolveInfo; 214import com.android.internal.app.IMediaContainerService; 215import com.android.internal.app.ResolverActivity; 216import com.android.internal.content.NativeLibraryHelper; 217import com.android.internal.content.PackageHelper; 218import com.android.internal.os.IParcelFileDescriptorFactory; 219import com.android.internal.os.SomeArgs; 220import com.android.internal.os.Zygote; 221import com.android.internal.util.ArrayUtils; 222import com.android.internal.util.FastPrintWriter; 223import com.android.internal.util.FastXmlSerializer; 224import com.android.internal.util.IndentingPrintWriter; 225import com.android.internal.util.Preconditions; 226import com.android.server.EventLogTags; 227import com.android.server.FgThread; 228import com.android.server.IntentResolver; 229import com.android.server.LocalServices; 230import com.android.server.ServiceThread; 231import com.android.server.SystemConfig; 232import com.android.server.Watchdog; 233import com.android.server.pm.PermissionsState.PermissionState; 234import com.android.server.pm.Settings.DatabaseVersion; 235import com.android.server.pm.Settings.VersionInfo; 236import com.android.server.storage.DeviceStorageMonitorInternal; 237 238import org.xmlpull.v1.XmlPullParser; 239import org.xmlpull.v1.XmlPullParserException; 240import org.xmlpull.v1.XmlSerializer; 241 242import java.io.BufferedInputStream; 243import java.io.BufferedOutputStream; 244import java.io.BufferedReader; 245import java.io.ByteArrayInputStream; 246import java.io.ByteArrayOutputStream; 247import java.io.File; 248import java.io.FileDescriptor; 249import java.io.FileNotFoundException; 250import java.io.FileOutputStream; 251import java.io.FileReader; 252import java.io.FilenameFilter; 253import java.io.IOException; 254import java.io.InputStream; 255import java.io.PrintWriter; 256import java.nio.charset.StandardCharsets; 257import java.security.MessageDigest; 258import java.security.NoSuchAlgorithmException; 259import java.security.PublicKey; 260import java.security.cert.CertificateEncodingException; 261import java.security.cert.CertificateException; 262import java.text.SimpleDateFormat; 263import java.util.ArrayList; 264import java.util.Arrays; 265import java.util.Collection; 266import java.util.Collections; 267import java.util.Comparator; 268import java.util.Date; 269import java.util.Iterator; 270import java.util.List; 271import java.util.Map; 272import java.util.Objects; 273import java.util.Set; 274import java.util.concurrent.CountDownLatch; 275import java.util.concurrent.TimeUnit; 276import java.util.concurrent.atomic.AtomicBoolean; 277import java.util.concurrent.atomic.AtomicInteger; 278import java.util.concurrent.atomic.AtomicLong; 279 280/** 281 * Keep track of all those .apks everywhere. 282 * 283 * This is very central to the platform's security; please run the unit 284 * tests whenever making modifications here: 285 * 286runtest -c android.content.pm.PackageManagerTests frameworks-core 287 * 288 * {@hide} 289 */ 290public class PackageManagerService extends IPackageManager.Stub { 291 static final String TAG = "PackageManager"; 292 static final boolean DEBUG_SETTINGS = false; 293 static final boolean DEBUG_PREFERRED = false; 294 static final boolean DEBUG_UPGRADE = false; 295 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 296 private static final boolean DEBUG_BACKUP = false; 297 private static final boolean DEBUG_INSTALL = false; 298 private static final boolean DEBUG_REMOVE = false; 299 private static final boolean DEBUG_BROADCASTS = false; 300 private static final boolean DEBUG_SHOW_INFO = false; 301 private static final boolean DEBUG_PACKAGE_INFO = false; 302 private static final boolean DEBUG_INTENT_MATCHING = false; 303 private static final boolean DEBUG_PACKAGE_SCANNING = false; 304 private static final boolean DEBUG_VERIFY = false; 305 private static final boolean DEBUG_DEXOPT = false; 306 private static final boolean DEBUG_ABI_SELECTION = false; 307 private static final boolean DEBUG_EPHEMERAL = false; 308 309 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 310 311 private static final int RADIO_UID = Process.PHONE_UID; 312 private static final int LOG_UID = Process.LOG_UID; 313 private static final int NFC_UID = Process.NFC_UID; 314 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 315 private static final int SHELL_UID = Process.SHELL_UID; 316 317 // Cap the size of permission trees that 3rd party apps can define 318 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 319 320 // Suffix used during package installation when copying/moving 321 // package apks to install directory. 322 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 323 324 static final int SCAN_NO_DEX = 1<<1; 325 static final int SCAN_FORCE_DEX = 1<<2; 326 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 327 static final int SCAN_NEW_INSTALL = 1<<4; 328 static final int SCAN_NO_PATHS = 1<<5; 329 static final int SCAN_UPDATE_TIME = 1<<6; 330 static final int SCAN_DEFER_DEX = 1<<7; 331 static final int SCAN_BOOTING = 1<<8; 332 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 333 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 334 static final int SCAN_REPLACING = 1<<11; 335 static final int SCAN_REQUIRE_KNOWN = 1<<12; 336 static final int SCAN_MOVE = 1<<13; 337 static final int SCAN_INITIAL = 1<<14; 338 339 static final int REMOVE_CHATTY = 1<<16; 340 341 private static final int[] EMPTY_INT_ARRAY = new int[0]; 342 343 /** 344 * Timeout (in milliseconds) after which the watchdog should declare that 345 * our handler thread is wedged. The usual default for such things is one 346 * minute but we sometimes do very lengthy I/O operations on this thread, 347 * such as installing multi-gigabyte applications, so ours needs to be longer. 348 */ 349 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 350 351 /** 352 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 353 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 354 * settings entry if available, otherwise we use the hardcoded default. If it's been 355 * more than this long since the last fstrim, we force one during the boot sequence. 356 * 357 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 358 * one gets run at the next available charging+idle time. This final mandatory 359 * no-fstrim check kicks in only of the other scheduling criteria is never met. 360 */ 361 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 362 363 /** 364 * Whether verification is enabled by default. 365 */ 366 private static final boolean DEFAULT_VERIFY_ENABLE = true; 367 368 /** 369 * The default maximum time to wait for the verification agent to return in 370 * milliseconds. 371 */ 372 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 373 374 /** 375 * The default response for package verification timeout. 376 * 377 * This can be either PackageManager.VERIFICATION_ALLOW or 378 * PackageManager.VERIFICATION_REJECT. 379 */ 380 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 381 382 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 383 384 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 385 DEFAULT_CONTAINER_PACKAGE, 386 "com.android.defcontainer.DefaultContainerService"); 387 388 private static final String KILL_APP_REASON_GIDS_CHANGED = 389 "permission grant or revoke changed gids"; 390 391 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 392 "permissions revoked"; 393 394 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 395 396 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 397 398 /** Permission grant: not grant the permission. */ 399 private static final int GRANT_DENIED = 1; 400 401 /** Permission grant: grant the permission as an install permission. */ 402 private static final int GRANT_INSTALL = 2; 403 404 /** Permission grant: grant the permission as a runtime one. */ 405 private static final int GRANT_RUNTIME = 3; 406 407 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 408 private static final int GRANT_UPGRADE = 4; 409 410 /** Canonical intent used to identify what counts as a "web browser" app */ 411 private static final Intent sBrowserIntent; 412 static { 413 sBrowserIntent = new Intent(); 414 sBrowserIntent.setAction(Intent.ACTION_VIEW); 415 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 416 sBrowserIntent.setData(Uri.parse("http:")); 417 } 418 419 final ServiceThread mHandlerThread; 420 421 final PackageHandler mHandler; 422 423 /** 424 * Messages for {@link #mHandler} that need to wait for system ready before 425 * being dispatched. 426 */ 427 private ArrayList<Message> mPostSystemReadyMessages; 428 429 final int mSdkVersion = Build.VERSION.SDK_INT; 430 431 final Context mContext; 432 final boolean mFactoryTest; 433 final boolean mOnlyCore; 434 final DisplayMetrics mMetrics; 435 final int mDefParseFlags; 436 final String[] mSeparateProcesses; 437 final boolean mIsUpgrade; 438 439 // This is where all application persistent data goes. 440 final File mAppDataDir; 441 442 // This is where all application persistent data goes for secondary users. 443 final File mUserAppDataDir; 444 445 /** The location for ASEC container files on internal storage. */ 446 final String mAsecInternalPath; 447 448 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 449 // LOCK HELD. Can be called with mInstallLock held. 450 @GuardedBy("mInstallLock") 451 final Installer mInstaller; 452 453 /** Directory where installed third-party apps stored */ 454 final File mAppInstallDir; 455 456 /** 457 * Directory to which applications installed internally have their 458 * 32 bit native libraries copied. 459 */ 460 private File mAppLib32InstallDir; 461 462 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 463 // apps. 464 final File mDrmAppPrivateInstallDir; 465 466 // ---------------------------------------------------------------- 467 468 // Lock for state used when installing and doing other long running 469 // operations. Methods that must be called with this lock held have 470 // the suffix "LI". 471 final Object mInstallLock = new Object(); 472 473 // ---------------------------------------------------------------- 474 475 // Keys are String (package name), values are Package. This also serves 476 // as the lock for the global state. Methods that must be called with 477 // this lock held have the prefix "LP". 478 @GuardedBy("mPackages") 479 final ArrayMap<String, PackageParser.Package> mPackages = 480 new ArrayMap<String, PackageParser.Package>(); 481 482 // Tracks available target package names -> overlay package paths. 483 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 484 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 485 486 /** 487 * Tracks new system packages [received in an OTA] that we expect to 488 * find updated user-installed versions. Keys are package name, values 489 * are package location. 490 */ 491 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 492 493 /** 494 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 495 */ 496 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 497 /** 498 * Whether or not system app permissions should be promoted from install to runtime. 499 */ 500 boolean mPromoteSystemApps; 501 502 final Settings mSettings; 503 boolean mRestoredSettings; 504 505 // System configuration read by SystemConfig. 506 final int[] mGlobalGids; 507 final SparseArray<ArraySet<String>> mSystemPermissions; 508 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 509 510 // If mac_permissions.xml was found for seinfo labeling. 511 boolean mFoundPolicyFile; 512 513 // If a recursive restorecon of /data/data/<pkg> is needed. 514 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 515 516 public static final class SharedLibraryEntry { 517 public final String path; 518 public final String apk; 519 520 SharedLibraryEntry(String _path, String _apk) { 521 path = _path; 522 apk = _apk; 523 } 524 } 525 526 // Currently known shared libraries. 527 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 528 new ArrayMap<String, SharedLibraryEntry>(); 529 530 // All available activities, for your resolving pleasure. 531 final ActivityIntentResolver mActivities = 532 new ActivityIntentResolver(); 533 534 // All available receivers, for your resolving pleasure. 535 final ActivityIntentResolver mReceivers = 536 new ActivityIntentResolver(); 537 538 // All available services, for your resolving pleasure. 539 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 540 541 // All available providers, for your resolving pleasure. 542 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 543 544 // Mapping from provider base names (first directory in content URI codePath) 545 // to the provider information. 546 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 547 new ArrayMap<String, PackageParser.Provider>(); 548 549 // Mapping from instrumentation class names to info about them. 550 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 551 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 552 553 // Mapping from permission names to info about them. 554 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 555 new ArrayMap<String, PackageParser.PermissionGroup>(); 556 557 // Packages whose data we have transfered into another package, thus 558 // should no longer exist. 559 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 560 561 // Broadcast actions that are only available to the system. 562 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 563 564 /** List of packages waiting for verification. */ 565 final SparseArray<PackageVerificationState> mPendingVerification 566 = new SparseArray<PackageVerificationState>(); 567 568 /** Set of packages associated with each app op permission. */ 569 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 570 571 final PackageInstallerService mInstallerService; 572 573 private final PackageDexOptimizer mPackageDexOptimizer; 574 575 private AtomicInteger mNextMoveId = new AtomicInteger(); 576 private final MoveCallbacks mMoveCallbacks; 577 578 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 579 580 // Cache of users who need badging. 581 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 582 583 /** Token for keys in mPendingVerification. */ 584 private int mPendingVerificationToken = 0; 585 586 volatile boolean mSystemReady; 587 volatile boolean mSafeMode; 588 volatile boolean mHasSystemUidErrors; 589 590 ApplicationInfo mAndroidApplication; 591 final ActivityInfo mResolveActivity = new ActivityInfo(); 592 final ResolveInfo mResolveInfo = new ResolveInfo(); 593 ComponentName mResolveComponentName; 594 PackageParser.Package mPlatformPackage; 595 ComponentName mCustomResolverComponentName; 596 597 boolean mResolverReplaced = false; 598 599 private final ComponentName mIntentFilterVerifierComponent; 600 private int mIntentFilterVerificationToken = 0; 601 602 /** Component that knows whether or not an ephemeral application exists */ 603 final ComponentName mEphemeralResolverComponent; 604 /** The service connection to the ephemeral resolver */ 605 final EphemeralResolverConnection mEphemeralResolverConnection; 606 607 /** Component used to install ephemeral applications */ 608 final ComponentName mEphemeralInstallerComponent; 609 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 610 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 611 612 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 613 = new SparseArray<IntentFilterVerificationState>(); 614 615 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 616 new DefaultPermissionGrantPolicy(this); 617 618 // List of packages names to keep cached, even if they are uninstalled for all users 619 private List<String> mKeepUninstalledPackages; 620 621 private static class IFVerificationParams { 622 PackageParser.Package pkg; 623 boolean replacing; 624 int userId; 625 int verifierUid; 626 627 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 628 int _userId, int _verifierUid) { 629 pkg = _pkg; 630 replacing = _replacing; 631 userId = _userId; 632 replacing = _replacing; 633 verifierUid = _verifierUid; 634 } 635 } 636 637 private interface IntentFilterVerifier<T extends IntentFilter> { 638 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 639 T filter, String packageName); 640 void startVerifications(int userId); 641 void receiveVerificationResponse(int verificationId); 642 } 643 644 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 645 private Context mContext; 646 private ComponentName mIntentFilterVerifierComponent; 647 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 648 649 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 650 mContext = context; 651 mIntentFilterVerifierComponent = verifierComponent; 652 } 653 654 private String getDefaultScheme() { 655 return IntentFilter.SCHEME_HTTPS; 656 } 657 658 @Override 659 public void startVerifications(int userId) { 660 // Launch verifications requests 661 int count = mCurrentIntentFilterVerifications.size(); 662 for (int n=0; n<count; n++) { 663 int verificationId = mCurrentIntentFilterVerifications.get(n); 664 final IntentFilterVerificationState ivs = 665 mIntentFilterVerificationStates.get(verificationId); 666 667 String packageName = ivs.getPackageName(); 668 669 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 670 final int filterCount = filters.size(); 671 ArraySet<String> domainsSet = new ArraySet<>(); 672 for (int m=0; m<filterCount; m++) { 673 PackageParser.ActivityIntentInfo filter = filters.get(m); 674 domainsSet.addAll(filter.getHostsList()); 675 } 676 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 677 synchronized (mPackages) { 678 if (mSettings.createIntentFilterVerificationIfNeededLPw( 679 packageName, domainsList) != null) { 680 scheduleWriteSettingsLocked(); 681 } 682 } 683 sendVerificationRequest(userId, verificationId, ivs); 684 } 685 mCurrentIntentFilterVerifications.clear(); 686 } 687 688 private void sendVerificationRequest(int userId, int verificationId, 689 IntentFilterVerificationState ivs) { 690 691 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 692 verificationIntent.putExtra( 693 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 694 verificationId); 695 verificationIntent.putExtra( 696 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 697 getDefaultScheme()); 698 verificationIntent.putExtra( 699 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 700 ivs.getHostsString()); 701 verificationIntent.putExtra( 702 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 703 ivs.getPackageName()); 704 verificationIntent.setComponent(mIntentFilterVerifierComponent); 705 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 706 707 UserHandle user = new UserHandle(userId); 708 mContext.sendBroadcastAsUser(verificationIntent, user); 709 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 710 "Sending IntentFilter verification broadcast"); 711 } 712 713 public void receiveVerificationResponse(int verificationId) { 714 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 715 716 final boolean verified = ivs.isVerified(); 717 718 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 719 final int count = filters.size(); 720 if (DEBUG_DOMAIN_VERIFICATION) { 721 Slog.i(TAG, "Received verification response " + verificationId 722 + " for " + count + " filters, verified=" + verified); 723 } 724 for (int n=0; n<count; n++) { 725 PackageParser.ActivityIntentInfo filter = filters.get(n); 726 filter.setVerified(verified); 727 728 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 729 + " verified with result:" + verified + " and hosts:" 730 + ivs.getHostsString()); 731 } 732 733 mIntentFilterVerificationStates.remove(verificationId); 734 735 final String packageName = ivs.getPackageName(); 736 IntentFilterVerificationInfo ivi = null; 737 738 synchronized (mPackages) { 739 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 740 } 741 if (ivi == null) { 742 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 743 + verificationId + " packageName:" + packageName); 744 return; 745 } 746 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 747 "Updating IntentFilterVerificationInfo for package " + packageName 748 +" verificationId:" + verificationId); 749 750 synchronized (mPackages) { 751 if (verified) { 752 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 753 } else { 754 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 755 } 756 scheduleWriteSettingsLocked(); 757 758 final int userId = ivs.getUserId(); 759 if (userId != UserHandle.USER_ALL) { 760 final int userStatus = 761 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 762 763 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 764 boolean needUpdate = false; 765 766 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 767 // already been set by the User thru the Disambiguation dialog 768 switch (userStatus) { 769 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 770 if (verified) { 771 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 772 } else { 773 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 774 } 775 needUpdate = true; 776 break; 777 778 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 779 if (verified) { 780 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 781 needUpdate = true; 782 } 783 break; 784 785 default: 786 // Nothing to do 787 } 788 789 if (needUpdate) { 790 mSettings.updateIntentFilterVerificationStatusLPw( 791 packageName, updatedStatus, userId); 792 scheduleWritePackageRestrictionsLocked(userId); 793 } 794 } 795 } 796 } 797 798 @Override 799 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 800 ActivityIntentInfo filter, String packageName) { 801 if (!hasValidDomains(filter)) { 802 return false; 803 } 804 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 805 if (ivs == null) { 806 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 807 packageName); 808 } 809 if (DEBUG_DOMAIN_VERIFICATION) { 810 Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter); 811 } 812 ivs.addFilter(filter); 813 return true; 814 } 815 816 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 817 int userId, int verificationId, String packageName) { 818 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 819 verifierUid, userId, packageName); 820 ivs.setPendingState(); 821 synchronized (mPackages) { 822 mIntentFilterVerificationStates.append(verificationId, ivs); 823 mCurrentIntentFilterVerifications.add(verificationId); 824 } 825 return ivs; 826 } 827 } 828 829 private static boolean hasValidDomains(ActivityIntentInfo filter) { 830 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 831 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 832 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 833 } 834 835 private IntentFilterVerifier mIntentFilterVerifier; 836 837 // Set of pending broadcasts for aggregating enable/disable of components. 838 static class PendingPackageBroadcasts { 839 // for each user id, a map of <package name -> components within that package> 840 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 841 842 public PendingPackageBroadcasts() { 843 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 844 } 845 846 public ArrayList<String> get(int userId, String packageName) { 847 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 848 return packages.get(packageName); 849 } 850 851 public void put(int userId, String packageName, ArrayList<String> components) { 852 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 853 packages.put(packageName, components); 854 } 855 856 public void remove(int userId, String packageName) { 857 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 858 if (packages != null) { 859 packages.remove(packageName); 860 } 861 } 862 863 public void remove(int userId) { 864 mUidMap.remove(userId); 865 } 866 867 public int userIdCount() { 868 return mUidMap.size(); 869 } 870 871 public int userIdAt(int n) { 872 return mUidMap.keyAt(n); 873 } 874 875 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 876 return mUidMap.get(userId); 877 } 878 879 public int size() { 880 // total number of pending broadcast entries across all userIds 881 int num = 0; 882 for (int i = 0; i< mUidMap.size(); i++) { 883 num += mUidMap.valueAt(i).size(); 884 } 885 return num; 886 } 887 888 public void clear() { 889 mUidMap.clear(); 890 } 891 892 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 893 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 894 if (map == null) { 895 map = new ArrayMap<String, ArrayList<String>>(); 896 mUidMap.put(userId, map); 897 } 898 return map; 899 } 900 } 901 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 902 903 // Service Connection to remote media container service to copy 904 // package uri's from external media onto secure containers 905 // or internal storage. 906 private IMediaContainerService mContainerService = null; 907 908 static final int SEND_PENDING_BROADCAST = 1; 909 static final int MCS_BOUND = 3; 910 static final int END_COPY = 4; 911 static final int INIT_COPY = 5; 912 static final int MCS_UNBIND = 6; 913 static final int START_CLEANING_PACKAGE = 7; 914 static final int FIND_INSTALL_LOC = 8; 915 static final int POST_INSTALL = 9; 916 static final int MCS_RECONNECT = 10; 917 static final int MCS_GIVE_UP = 11; 918 static final int UPDATED_MEDIA_STATUS = 12; 919 static final int WRITE_SETTINGS = 13; 920 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 921 static final int PACKAGE_VERIFIED = 15; 922 static final int CHECK_PENDING_VERIFICATION = 16; 923 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 924 static final int INTENT_FILTER_VERIFIED = 18; 925 926 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 927 928 // Delay time in millisecs 929 static final int BROADCAST_DELAY = 10 * 1000; 930 931 static UserManagerService sUserManager; 932 933 // Stores a list of users whose package restrictions file needs to be updated 934 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 935 936 final private DefaultContainerConnection mDefContainerConn = 937 new DefaultContainerConnection(); 938 class DefaultContainerConnection implements ServiceConnection { 939 public void onServiceConnected(ComponentName name, IBinder service) { 940 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 941 IMediaContainerService imcs = 942 IMediaContainerService.Stub.asInterface(service); 943 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 944 } 945 946 public void onServiceDisconnected(ComponentName name) { 947 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 948 } 949 } 950 951 // Recordkeeping of restore-after-install operations that are currently in flight 952 // between the Package Manager and the Backup Manager 953 class PostInstallData { 954 public InstallArgs args; 955 public PackageInstalledInfo res; 956 957 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 958 args = _a; 959 res = _r; 960 } 961 } 962 963 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 964 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 965 966 // XML tags for backup/restore of various bits of state 967 private static final String TAG_PREFERRED_BACKUP = "pa"; 968 private static final String TAG_DEFAULT_APPS = "da"; 969 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 970 971 final String mRequiredVerifierPackage; 972 final String mRequiredInstallerPackage; 973 974 private final PackageUsage mPackageUsage = new PackageUsage(); 975 976 private class PackageUsage { 977 private static final int WRITE_INTERVAL 978 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 979 980 private final Object mFileLock = new Object(); 981 private final AtomicLong mLastWritten = new AtomicLong(0); 982 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 983 984 private boolean mIsHistoricalPackageUsageAvailable = true; 985 986 boolean isHistoricalPackageUsageAvailable() { 987 return mIsHistoricalPackageUsageAvailable; 988 } 989 990 void write(boolean force) { 991 if (force) { 992 writeInternal(); 993 return; 994 } 995 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 996 && !DEBUG_DEXOPT) { 997 return; 998 } 999 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 1000 new Thread("PackageUsage_DiskWriter") { 1001 @Override 1002 public void run() { 1003 try { 1004 writeInternal(); 1005 } finally { 1006 mBackgroundWriteRunning.set(false); 1007 } 1008 } 1009 }.start(); 1010 } 1011 } 1012 1013 private void writeInternal() { 1014 synchronized (mPackages) { 1015 synchronized (mFileLock) { 1016 AtomicFile file = getFile(); 1017 FileOutputStream f = null; 1018 try { 1019 f = file.startWrite(); 1020 BufferedOutputStream out = new BufferedOutputStream(f); 1021 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1022 StringBuilder sb = new StringBuilder(); 1023 for (PackageParser.Package pkg : mPackages.values()) { 1024 if (pkg.mLastPackageUsageTimeInMills == 0) { 1025 continue; 1026 } 1027 sb.setLength(0); 1028 sb.append(pkg.packageName); 1029 sb.append(' '); 1030 sb.append((long)pkg.mLastPackageUsageTimeInMills); 1031 sb.append('\n'); 1032 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1033 } 1034 out.flush(); 1035 file.finishWrite(f); 1036 } catch (IOException e) { 1037 if (f != null) { 1038 file.failWrite(f); 1039 } 1040 Log.e(TAG, "Failed to write package usage times", e); 1041 } 1042 } 1043 } 1044 mLastWritten.set(SystemClock.elapsedRealtime()); 1045 } 1046 1047 void readLP() { 1048 synchronized (mFileLock) { 1049 AtomicFile file = getFile(); 1050 BufferedInputStream in = null; 1051 try { 1052 in = new BufferedInputStream(file.openRead()); 1053 StringBuffer sb = new StringBuffer(); 1054 while (true) { 1055 String packageName = readToken(in, sb, ' '); 1056 if (packageName == null) { 1057 break; 1058 } 1059 String timeInMillisString = readToken(in, sb, '\n'); 1060 if (timeInMillisString == null) { 1061 throw new IOException("Failed to find last usage time for package " 1062 + packageName); 1063 } 1064 PackageParser.Package pkg = mPackages.get(packageName); 1065 if (pkg == null) { 1066 continue; 1067 } 1068 long timeInMillis; 1069 try { 1070 timeInMillis = Long.parseLong(timeInMillisString.toString()); 1071 } catch (NumberFormatException e) { 1072 throw new IOException("Failed to parse " + timeInMillisString 1073 + " as a long.", e); 1074 } 1075 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1076 } 1077 } catch (FileNotFoundException expected) { 1078 mIsHistoricalPackageUsageAvailable = false; 1079 } catch (IOException e) { 1080 Log.w(TAG, "Failed to read package usage times", e); 1081 } finally { 1082 IoUtils.closeQuietly(in); 1083 } 1084 } 1085 mLastWritten.set(SystemClock.elapsedRealtime()); 1086 } 1087 1088 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1089 throws IOException { 1090 sb.setLength(0); 1091 while (true) { 1092 int ch = in.read(); 1093 if (ch == -1) { 1094 if (sb.length() == 0) { 1095 return null; 1096 } 1097 throw new IOException("Unexpected EOF"); 1098 } 1099 if (ch == endOfToken) { 1100 return sb.toString(); 1101 } 1102 sb.append((char)ch); 1103 } 1104 } 1105 1106 private AtomicFile getFile() { 1107 File dataDir = Environment.getDataDirectory(); 1108 File systemDir = new File(dataDir, "system"); 1109 File fname = new File(systemDir, "package-usage.list"); 1110 return new AtomicFile(fname); 1111 } 1112 } 1113 1114 class PackageHandler extends Handler { 1115 private boolean mBound = false; 1116 final ArrayList<HandlerParams> mPendingInstalls = 1117 new ArrayList<HandlerParams>(); 1118 1119 private boolean connectToService() { 1120 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1121 " DefaultContainerService"); 1122 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1123 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1124 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1125 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1126 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1127 mBound = true; 1128 return true; 1129 } 1130 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1131 return false; 1132 } 1133 1134 private void disconnectService() { 1135 mContainerService = null; 1136 mBound = false; 1137 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1138 mContext.unbindService(mDefContainerConn); 1139 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1140 } 1141 1142 PackageHandler(Looper looper) { 1143 super(looper); 1144 } 1145 1146 public void handleMessage(Message msg) { 1147 try { 1148 doHandleMessage(msg); 1149 } finally { 1150 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1151 } 1152 } 1153 1154 void doHandleMessage(Message msg) { 1155 switch (msg.what) { 1156 case INIT_COPY: { 1157 HandlerParams params = (HandlerParams) msg.obj; 1158 int idx = mPendingInstalls.size(); 1159 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1160 // If a bind was already initiated we dont really 1161 // need to do anything. The pending install 1162 // will be processed later on. 1163 if (!mBound) { 1164 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1165 System.identityHashCode(mHandler)); 1166 // If this is the only one pending we might 1167 // have to bind to the service again. 1168 if (!connectToService()) { 1169 Slog.e(TAG, "Failed to bind to media container service"); 1170 params.serviceError(); 1171 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1172 System.identityHashCode(mHandler)); 1173 if (params.traceMethod != null) { 1174 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1175 params.traceCookie); 1176 } 1177 return; 1178 } else { 1179 // Once we bind to the service, the first 1180 // pending request will be processed. 1181 mPendingInstalls.add(idx, params); 1182 } 1183 } else { 1184 mPendingInstalls.add(idx, params); 1185 // Already bound to the service. Just make 1186 // sure we trigger off processing the first request. 1187 if (idx == 0) { 1188 mHandler.sendEmptyMessage(MCS_BOUND); 1189 } 1190 } 1191 break; 1192 } 1193 case MCS_BOUND: { 1194 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1195 if (msg.obj != null) { 1196 mContainerService = (IMediaContainerService) msg.obj; 1197 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1198 System.identityHashCode(mHandler)); 1199 } 1200 if (mContainerService == null) { 1201 if (!mBound) { 1202 // Something seriously wrong since we are not bound and we are not 1203 // waiting for connection. Bail out. 1204 Slog.e(TAG, "Cannot bind to media container service"); 1205 for (HandlerParams params : mPendingInstalls) { 1206 // Indicate service bind error 1207 params.serviceError(); 1208 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1209 System.identityHashCode(params)); 1210 if (params.traceMethod != null) { 1211 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1212 params.traceMethod, params.traceCookie); 1213 } 1214 return; 1215 } 1216 mPendingInstalls.clear(); 1217 } else { 1218 Slog.w(TAG, "Waiting to connect to media container service"); 1219 } 1220 } else if (mPendingInstalls.size() > 0) { 1221 HandlerParams params = mPendingInstalls.get(0); 1222 if (params != null) { 1223 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1224 System.identityHashCode(params)); 1225 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1226 if (params.startCopy()) { 1227 // We are done... look for more work or to 1228 // go idle. 1229 if (DEBUG_SD_INSTALL) Log.i(TAG, 1230 "Checking for more work or unbind..."); 1231 // Delete pending install 1232 if (mPendingInstalls.size() > 0) { 1233 mPendingInstalls.remove(0); 1234 } 1235 if (mPendingInstalls.size() == 0) { 1236 if (mBound) { 1237 if (DEBUG_SD_INSTALL) Log.i(TAG, 1238 "Posting delayed MCS_UNBIND"); 1239 removeMessages(MCS_UNBIND); 1240 Message ubmsg = obtainMessage(MCS_UNBIND); 1241 // Unbind after a little delay, to avoid 1242 // continual thrashing. 1243 sendMessageDelayed(ubmsg, 10000); 1244 } 1245 } else { 1246 // There are more pending requests in queue. 1247 // Just post MCS_BOUND message to trigger processing 1248 // of next pending install. 1249 if (DEBUG_SD_INSTALL) Log.i(TAG, 1250 "Posting MCS_BOUND for next work"); 1251 mHandler.sendEmptyMessage(MCS_BOUND); 1252 } 1253 } 1254 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1255 } 1256 } else { 1257 // Should never happen ideally. 1258 Slog.w(TAG, "Empty queue"); 1259 } 1260 break; 1261 } 1262 case MCS_RECONNECT: { 1263 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1264 if (mPendingInstalls.size() > 0) { 1265 if (mBound) { 1266 disconnectService(); 1267 } 1268 if (!connectToService()) { 1269 Slog.e(TAG, "Failed to bind to media container service"); 1270 for (HandlerParams params : mPendingInstalls) { 1271 // Indicate service bind error 1272 params.serviceError(); 1273 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1274 System.identityHashCode(params)); 1275 } 1276 mPendingInstalls.clear(); 1277 } 1278 } 1279 break; 1280 } 1281 case MCS_UNBIND: { 1282 // If there is no actual work left, then time to unbind. 1283 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1284 1285 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1286 if (mBound) { 1287 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1288 1289 disconnectService(); 1290 } 1291 } else if (mPendingInstalls.size() > 0) { 1292 // There are more pending requests in queue. 1293 // Just post MCS_BOUND message to trigger processing 1294 // of next pending install. 1295 mHandler.sendEmptyMessage(MCS_BOUND); 1296 } 1297 1298 break; 1299 } 1300 case MCS_GIVE_UP: { 1301 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1302 HandlerParams params = mPendingInstalls.remove(0); 1303 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1304 System.identityHashCode(params)); 1305 break; 1306 } 1307 case SEND_PENDING_BROADCAST: { 1308 String packages[]; 1309 ArrayList<String> components[]; 1310 int size = 0; 1311 int uids[]; 1312 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1313 synchronized (mPackages) { 1314 if (mPendingBroadcasts == null) { 1315 return; 1316 } 1317 size = mPendingBroadcasts.size(); 1318 if (size <= 0) { 1319 // Nothing to be done. Just return 1320 return; 1321 } 1322 packages = new String[size]; 1323 components = new ArrayList[size]; 1324 uids = new int[size]; 1325 int i = 0; // filling out the above arrays 1326 1327 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1328 int packageUserId = mPendingBroadcasts.userIdAt(n); 1329 Iterator<Map.Entry<String, ArrayList<String>>> it 1330 = mPendingBroadcasts.packagesForUserId(packageUserId) 1331 .entrySet().iterator(); 1332 while (it.hasNext() && i < size) { 1333 Map.Entry<String, ArrayList<String>> ent = it.next(); 1334 packages[i] = ent.getKey(); 1335 components[i] = ent.getValue(); 1336 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1337 uids[i] = (ps != null) 1338 ? UserHandle.getUid(packageUserId, ps.appId) 1339 : -1; 1340 i++; 1341 } 1342 } 1343 size = i; 1344 mPendingBroadcasts.clear(); 1345 } 1346 // Send broadcasts 1347 for (int i = 0; i < size; i++) { 1348 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1349 } 1350 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1351 break; 1352 } 1353 case START_CLEANING_PACKAGE: { 1354 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1355 final String packageName = (String)msg.obj; 1356 final int userId = msg.arg1; 1357 final boolean andCode = msg.arg2 != 0; 1358 synchronized (mPackages) { 1359 if (userId == UserHandle.USER_ALL) { 1360 int[] users = sUserManager.getUserIds(); 1361 for (int user : users) { 1362 mSettings.addPackageToCleanLPw( 1363 new PackageCleanItem(user, packageName, andCode)); 1364 } 1365 } else { 1366 mSettings.addPackageToCleanLPw( 1367 new PackageCleanItem(userId, packageName, andCode)); 1368 } 1369 } 1370 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1371 startCleaningPackages(); 1372 } break; 1373 case POST_INSTALL: { 1374 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 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 // Determine the set of users who are adding this 1400 // package for the first time vs. those who are seeing 1401 // an update. 1402 int[] firstUsers; 1403 int[] updateUsers = new int[0]; 1404 if (res.origUsers == null || res.origUsers.length == 0) { 1405 firstUsers = res.newUsers; 1406 } else { 1407 firstUsers = new int[0]; 1408 for (int i=0; i<res.newUsers.length; i++) { 1409 int user = res.newUsers[i]; 1410 boolean isNew = true; 1411 for (int j=0; j<res.origUsers.length; j++) { 1412 if (res.origUsers[j] == user) { 1413 isNew = false; 1414 break; 1415 } 1416 } 1417 if (isNew) { 1418 int[] newFirst = new int[firstUsers.length+1]; 1419 System.arraycopy(firstUsers, 0, newFirst, 0, 1420 firstUsers.length); 1421 newFirst[firstUsers.length] = user; 1422 firstUsers = newFirst; 1423 } else { 1424 int[] newUpdate = new int[updateUsers.length+1]; 1425 System.arraycopy(updateUsers, 0, newUpdate, 0, 1426 updateUsers.length); 1427 newUpdate[updateUsers.length] = user; 1428 updateUsers = newUpdate; 1429 } 1430 } 1431 } 1432 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1433 packageName, extras, 0, null, null, firstUsers); 1434 final boolean update = res.removedInfo.removedPackage != null; 1435 if (update) { 1436 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1437 } 1438 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1439 packageName, extras, 0, null, null, updateUsers); 1440 if (update) { 1441 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1442 packageName, extras, 0, null, null, updateUsers); 1443 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1444 null, null, 0, packageName, null, updateUsers); 1445 1446 // treat asec-hosted packages like removable media on upgrade 1447 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1448 if (DEBUG_INSTALL) { 1449 Slog.i(TAG, "upgrading pkg " + res.pkg 1450 + " is ASEC-hosted -> AVAILABLE"); 1451 } 1452 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1453 ArrayList<String> pkgList = new ArrayList<String>(1); 1454 pkgList.add(packageName); 1455 sendResourcesChangedBroadcast(true, true, 1456 pkgList,uidArray, null); 1457 } 1458 } 1459 if (res.removedInfo.args != null) { 1460 // Remove the replaced package's older resources safely now 1461 deleteOld = true; 1462 } 1463 1464 // If this app is a browser and it's newly-installed for some 1465 // users, clear any default-browser state in those users 1466 if (firstUsers.length > 0) { 1467 // the app's nature doesn't depend on the user, so we can just 1468 // check its browser nature in any user and generalize. 1469 if (packageIsBrowser(packageName, firstUsers[0])) { 1470 synchronized (mPackages) { 1471 for (int userId : firstUsers) { 1472 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1473 } 1474 } 1475 } 1476 } 1477 // Log current value of "unknown sources" setting 1478 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1479 getUnknownSourcesSettings()); 1480 } 1481 // Force a gc to clear up things 1482 Runtime.getRuntime().gc(); 1483 // We delete after a gc for applications on sdcard. 1484 if (deleteOld) { 1485 synchronized (mInstallLock) { 1486 res.removedInfo.args.doPostDeleteLI(true); 1487 } 1488 } 1489 if (args.observer != null) { 1490 try { 1491 Bundle extras = extrasForInstallResult(res); 1492 args.observer.onPackageInstalled(res.name, res.returnCode, 1493 res.returnMsg, extras); 1494 } catch (RemoteException e) { 1495 Slog.i(TAG, "Observer no longer exists."); 1496 } 1497 } 1498 if (args.traceMethod != null) { 1499 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1500 args.traceCookie); 1501 } 1502 return; 1503 } else { 1504 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1505 } 1506 1507 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1508 } break; 1509 case UPDATED_MEDIA_STATUS: { 1510 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1511 boolean reportStatus = msg.arg1 == 1; 1512 boolean doGc = msg.arg2 == 1; 1513 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1514 if (doGc) { 1515 // Force a gc to clear up stale containers. 1516 Runtime.getRuntime().gc(); 1517 } 1518 if (msg.obj != null) { 1519 @SuppressWarnings("unchecked") 1520 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1521 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1522 // Unload containers 1523 unloadAllContainers(args); 1524 } 1525 if (reportStatus) { 1526 try { 1527 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1528 PackageHelper.getMountService().finishMediaUpdate(); 1529 } catch (RemoteException e) { 1530 Log.e(TAG, "MountService not running?"); 1531 } 1532 } 1533 } break; 1534 case WRITE_SETTINGS: { 1535 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1536 synchronized (mPackages) { 1537 removeMessages(WRITE_SETTINGS); 1538 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1539 mSettings.writeLPr(); 1540 mDirtyUsers.clear(); 1541 } 1542 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1543 } break; 1544 case WRITE_PACKAGE_RESTRICTIONS: { 1545 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1546 synchronized (mPackages) { 1547 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1548 for (int userId : mDirtyUsers) { 1549 mSettings.writePackageRestrictionsLPr(userId); 1550 } 1551 mDirtyUsers.clear(); 1552 } 1553 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1554 } break; 1555 case CHECK_PENDING_VERIFICATION: { 1556 final int verificationId = msg.arg1; 1557 final PackageVerificationState state = mPendingVerification.get(verificationId); 1558 1559 if ((state != null) && !state.timeoutExtended()) { 1560 final InstallArgs args = state.getInstallArgs(); 1561 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1562 1563 Slog.i(TAG, "Verification timed out for " + originUri); 1564 mPendingVerification.remove(verificationId); 1565 1566 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1567 1568 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1569 Slog.i(TAG, "Continuing with installation of " + originUri); 1570 state.setVerifierResponse(Binder.getCallingUid(), 1571 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1572 broadcastPackageVerified(verificationId, originUri, 1573 PackageManager.VERIFICATION_ALLOW, 1574 state.getInstallArgs().getUser()); 1575 try { 1576 ret = args.copyApk(mContainerService, true); 1577 } catch (RemoteException e) { 1578 Slog.e(TAG, "Could not contact the ContainerService"); 1579 } 1580 } else { 1581 broadcastPackageVerified(verificationId, originUri, 1582 PackageManager.VERIFICATION_REJECT, 1583 state.getInstallArgs().getUser()); 1584 } 1585 1586 Trace.asyncTraceEnd( 1587 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1588 1589 processPendingInstall(args, ret); 1590 mHandler.sendEmptyMessage(MCS_UNBIND); 1591 } 1592 break; 1593 } 1594 case PACKAGE_VERIFIED: { 1595 final int verificationId = msg.arg1; 1596 1597 final PackageVerificationState state = mPendingVerification.get(verificationId); 1598 if (state == null) { 1599 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1600 break; 1601 } 1602 1603 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1604 1605 state.setVerifierResponse(response.callerUid, response.code); 1606 1607 if (state.isVerificationComplete()) { 1608 mPendingVerification.remove(verificationId); 1609 1610 final InstallArgs args = state.getInstallArgs(); 1611 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1612 1613 int ret; 1614 if (state.isInstallAllowed()) { 1615 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1616 broadcastPackageVerified(verificationId, originUri, 1617 response.code, state.getInstallArgs().getUser()); 1618 try { 1619 ret = args.copyApk(mContainerService, true); 1620 } catch (RemoteException e) { 1621 Slog.e(TAG, "Could not contact the ContainerService"); 1622 } 1623 } else { 1624 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1625 } 1626 1627 Trace.asyncTraceEnd( 1628 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1629 1630 processPendingInstall(args, ret); 1631 mHandler.sendEmptyMessage(MCS_UNBIND); 1632 } 1633 1634 break; 1635 } 1636 case START_INTENT_FILTER_VERIFICATIONS: { 1637 IFVerificationParams params = (IFVerificationParams) msg.obj; 1638 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1639 params.replacing, params.pkg); 1640 break; 1641 } 1642 case INTENT_FILTER_VERIFIED: { 1643 final int verificationId = msg.arg1; 1644 1645 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1646 verificationId); 1647 if (state == null) { 1648 Slog.w(TAG, "Invalid IntentFilter verification token " 1649 + verificationId + " received"); 1650 break; 1651 } 1652 1653 final int userId = state.getUserId(); 1654 1655 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1656 "Processing IntentFilter verification with token:" 1657 + verificationId + " and userId:" + userId); 1658 1659 final IntentFilterVerificationResponse response = 1660 (IntentFilterVerificationResponse) msg.obj; 1661 1662 state.setVerifierResponse(response.callerUid, response.code); 1663 1664 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1665 "IntentFilter verification with token:" + verificationId 1666 + " and userId:" + userId 1667 + " is settings verifier response with response code:" 1668 + response.code); 1669 1670 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1671 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1672 + response.getFailedDomainsString()); 1673 } 1674 1675 if (state.isVerificationComplete()) { 1676 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1677 } else { 1678 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1679 "IntentFilter verification with token:" + verificationId 1680 + " was not said to be complete"); 1681 } 1682 1683 break; 1684 } 1685 } 1686 } 1687 } 1688 1689 private StorageEventListener mStorageListener = new StorageEventListener() { 1690 @Override 1691 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1692 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1693 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1694 final String volumeUuid = vol.getFsUuid(); 1695 1696 // Clean up any users or apps that were removed or recreated 1697 // while this volume was missing 1698 reconcileUsers(volumeUuid); 1699 reconcileApps(volumeUuid); 1700 1701 // Clean up any install sessions that expired or were 1702 // cancelled while this volume was missing 1703 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1704 1705 loadPrivatePackages(vol); 1706 1707 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1708 unloadPrivatePackages(vol); 1709 } 1710 } 1711 1712 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1713 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1714 updateExternalMediaStatus(true, false); 1715 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1716 updateExternalMediaStatus(false, false); 1717 } 1718 } 1719 } 1720 1721 @Override 1722 public void onVolumeForgotten(String fsUuid) { 1723 if (TextUtils.isEmpty(fsUuid)) { 1724 Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1725 return; 1726 } 1727 1728 // Remove any apps installed on the forgotten volume 1729 synchronized (mPackages) { 1730 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1731 for (PackageSetting ps : packages) { 1732 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1733 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1734 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1735 } 1736 1737 mSettings.onVolumeForgotten(fsUuid); 1738 mSettings.writeLPr(); 1739 } 1740 } 1741 }; 1742 1743 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId, 1744 String[] grantedPermissions) { 1745 if (userId >= UserHandle.USER_SYSTEM) { 1746 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1747 } else if (userId == UserHandle.USER_ALL) { 1748 final int[] userIds; 1749 synchronized (mPackages) { 1750 userIds = UserManagerService.getInstance().getUserIds(); 1751 } 1752 for (int someUserId : userIds) { 1753 grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions); 1754 } 1755 } 1756 1757 // We could have touched GID membership, so flush out packages.list 1758 synchronized (mPackages) { 1759 mSettings.writePackageListLPr(); 1760 } 1761 } 1762 1763 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1764 String[] grantedPermissions) { 1765 SettingBase sb = (SettingBase) pkg.mExtras; 1766 if (sb == null) { 1767 return; 1768 } 1769 1770 PermissionsState permissionsState = sb.getPermissionsState(); 1771 1772 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 1773 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 1774 1775 synchronized (mPackages) { 1776 for (String permission : pkg.requestedPermissions) { 1777 BasePermission bp = mSettings.mPermissions.get(permission); 1778 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 1779 && (grantedPermissions == null 1780 || ArrayUtils.contains(grantedPermissions, permission))) { 1781 final int flags = permissionsState.getPermissionFlags(permission, userId); 1782 // Installer cannot change immutable permissions. 1783 if ((flags & immutableFlags) == 0) { 1784 grantRuntimePermission(pkg.packageName, permission, userId); 1785 } 1786 } 1787 } 1788 } 1789 } 1790 1791 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1792 Bundle extras = null; 1793 switch (res.returnCode) { 1794 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1795 extras = new Bundle(); 1796 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1797 res.origPermission); 1798 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1799 res.origPackage); 1800 break; 1801 } 1802 case PackageManager.INSTALL_SUCCEEDED: { 1803 extras = new Bundle(); 1804 extras.putBoolean(Intent.EXTRA_REPLACING, 1805 res.removedInfo != null && res.removedInfo.removedPackage != null); 1806 break; 1807 } 1808 } 1809 return extras; 1810 } 1811 1812 void scheduleWriteSettingsLocked() { 1813 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1814 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1815 } 1816 } 1817 1818 void scheduleWritePackageRestrictionsLocked(int userId) { 1819 if (!sUserManager.exists(userId)) return; 1820 mDirtyUsers.add(userId); 1821 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1822 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1823 } 1824 } 1825 1826 public static PackageManagerService main(Context context, Installer installer, 1827 boolean factoryTest, boolean onlyCore) { 1828 PackageManagerService m = new PackageManagerService(context, installer, 1829 factoryTest, onlyCore); 1830 m.enableSystemUserApps(); 1831 ServiceManager.addService("package", m); 1832 return m; 1833 } 1834 1835 private void enableSystemUserApps() { 1836 if (!UserManager.isSplitSystemUser()) { 1837 return; 1838 } 1839 // For system user, enable apps based on the following conditions: 1840 // - app is whitelisted or belong to one of these groups: 1841 // -- system app which has no launcher icons 1842 // -- system app which has INTERACT_ACROSS_USERS permission 1843 // -- system IME app 1844 // - app is not in the blacklist 1845 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 1846 Set<String> enableApps = new ArraySet<>(); 1847 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 1848 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 1849 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 1850 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 1851 enableApps.addAll(wlApps); 1852 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 1853 enableApps.removeAll(blApps); 1854 1855 List<String> systemApps = queryHelper.queryApps(0, /* systemAppsOnly */ true, 1856 UserHandle.SYSTEM); 1857 final int systemAppsSize = systemApps.size(); 1858 synchronized (mPackages) { 1859 for (int i = 0; i < systemAppsSize; i++) { 1860 String pName = systemApps.get(i); 1861 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 1862 // Should not happen, but we shouldn't be failing if it does 1863 if (pkgSetting == null) { 1864 continue; 1865 } 1866 boolean installed = enableApps.contains(pName); 1867 pkgSetting.setInstalled(installed, UserHandle.USER_SYSTEM); 1868 } 1869 } 1870 } 1871 1872 static String[] splitString(String str, char sep) { 1873 int count = 1; 1874 int i = 0; 1875 while ((i=str.indexOf(sep, i)) >= 0) { 1876 count++; 1877 i++; 1878 } 1879 1880 String[] res = new String[count]; 1881 i=0; 1882 count = 0; 1883 int lastI=0; 1884 while ((i=str.indexOf(sep, i)) >= 0) { 1885 res[count] = str.substring(lastI, i); 1886 count++; 1887 i++; 1888 lastI = i; 1889 } 1890 res[count] = str.substring(lastI, str.length()); 1891 return res; 1892 } 1893 1894 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1895 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1896 Context.DISPLAY_SERVICE); 1897 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1898 } 1899 1900 public PackageManagerService(Context context, Installer installer, 1901 boolean factoryTest, boolean onlyCore) { 1902 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1903 SystemClock.uptimeMillis()); 1904 1905 if (mSdkVersion <= 0) { 1906 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1907 } 1908 1909 mContext = context; 1910 mFactoryTest = factoryTest; 1911 mOnlyCore = onlyCore; 1912 mMetrics = new DisplayMetrics(); 1913 mSettings = new Settings(mPackages); 1914 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1915 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1916 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1917 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1918 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1919 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1920 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1921 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1922 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1923 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1924 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1925 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1926 1927 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1928 if (separateProcesses != null && separateProcesses.length() > 0) { 1929 if ("*".equals(separateProcesses)) { 1930 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1931 mSeparateProcesses = null; 1932 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1933 } else { 1934 mDefParseFlags = 0; 1935 mSeparateProcesses = separateProcesses.split(","); 1936 Slog.w(TAG, "Running with debug.separate_processes: " 1937 + separateProcesses); 1938 } 1939 } else { 1940 mDefParseFlags = 0; 1941 mSeparateProcesses = null; 1942 } 1943 1944 mInstaller = installer; 1945 mPackageDexOptimizer = new PackageDexOptimizer(this); 1946 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1947 1948 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 1949 FgThread.get().getLooper()); 1950 1951 getDefaultDisplayMetrics(context, mMetrics); 1952 1953 SystemConfig systemConfig = SystemConfig.getInstance(); 1954 mGlobalGids = systemConfig.getGlobalGids(); 1955 mSystemPermissions = systemConfig.getSystemPermissions(); 1956 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1957 1958 synchronized (mInstallLock) { 1959 // writer 1960 synchronized (mPackages) { 1961 mHandlerThread = new ServiceThread(TAG, 1962 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1963 mHandlerThread.start(); 1964 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1965 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1966 1967 File dataDir = Environment.getDataDirectory(); 1968 mAppDataDir = new File(dataDir, "data"); 1969 mAppInstallDir = new File(dataDir, "app"); 1970 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1971 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1972 mUserAppDataDir = new File(dataDir, "user"); 1973 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1974 1975 sUserManager = new UserManagerService(context, this, mPackages); 1976 1977 // Propagate permission configuration in to package manager. 1978 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1979 = systemConfig.getPermissions(); 1980 for (int i=0; i<permConfig.size(); i++) { 1981 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1982 BasePermission bp = mSettings.mPermissions.get(perm.name); 1983 if (bp == null) { 1984 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1985 mSettings.mPermissions.put(perm.name, bp); 1986 } 1987 if (perm.gids != null) { 1988 bp.setGids(perm.gids, perm.perUser); 1989 } 1990 } 1991 1992 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1993 for (int i=0; i<libConfig.size(); i++) { 1994 mSharedLibraries.put(libConfig.keyAt(i), 1995 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1996 } 1997 1998 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1999 2000 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 2001 2002 String customResolverActivity = Resources.getSystem().getString( 2003 R.string.config_customResolverActivity); 2004 if (TextUtils.isEmpty(customResolverActivity)) { 2005 customResolverActivity = null; 2006 } else { 2007 mCustomResolverComponentName = ComponentName.unflattenFromString( 2008 customResolverActivity); 2009 } 2010 2011 long startTime = SystemClock.uptimeMillis(); 2012 2013 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2014 startTime); 2015 2016 // Set flag to monitor and not change apk file paths when 2017 // scanning install directories. 2018 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2019 2020 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2021 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2022 2023 if (bootClassPath == null) { 2024 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2025 } 2026 2027 if (systemServerClassPath == null) { 2028 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2029 } 2030 2031 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2032 final String[] dexCodeInstructionSets = 2033 getDexCodeInstructionSets( 2034 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2035 2036 /** 2037 * Ensure all external libraries have had dexopt run on them. 2038 */ 2039 if (mSharedLibraries.size() > 0) { 2040 // NOTE: For now, we're compiling these system "shared libraries" 2041 // (and framework jars) into all available architectures. It's possible 2042 // to compile them only when we come across an app that uses them (there's 2043 // already logic for that in scanPackageLI) but that adds some complexity. 2044 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2045 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2046 final String lib = libEntry.path; 2047 if (lib == null) { 2048 continue; 2049 } 2050 2051 try { 2052 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 2053 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2054 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2055 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/); 2056 } 2057 } catch (FileNotFoundException e) { 2058 Slog.w(TAG, "Library not found: " + lib); 2059 } catch (IOException e) { 2060 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2061 + e.getMessage()); 2062 } 2063 } 2064 } 2065 } 2066 2067 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2068 2069 final VersionInfo ver = mSettings.getInternalVersion(); 2070 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2071 // when upgrading from pre-M, promote system app permissions from install to runtime 2072 mPromoteSystemApps = 2073 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2074 2075 // save off the names of pre-existing system packages prior to scanning; we don't 2076 // want to automatically grant runtime permissions for new system apps 2077 if (mPromoteSystemApps) { 2078 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2079 while (pkgSettingIter.hasNext()) { 2080 PackageSetting ps = pkgSettingIter.next(); 2081 if (isSystemApp(ps)) { 2082 mExistingSystemPackages.add(ps.name); 2083 } 2084 } 2085 } 2086 2087 // Collect vendor overlay packages. 2088 // (Do this before scanning any apps.) 2089 // For security and version matching reason, only consider 2090 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2091 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2092 scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2093 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2094 2095 // Find base frameworks (resource packages without code). 2096 scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2097 | PackageParser.PARSE_IS_SYSTEM_DIR 2098 | PackageParser.PARSE_IS_PRIVILEGED, 2099 scanFlags | SCAN_NO_DEX, 0); 2100 2101 // Collected privileged system packages. 2102 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2103 scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2104 | PackageParser.PARSE_IS_SYSTEM_DIR 2105 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2106 2107 // Collect ordinary system packages. 2108 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2109 scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2110 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2111 2112 // Collect all vendor packages. 2113 File vendorAppDir = new File("/vendor/app"); 2114 try { 2115 vendorAppDir = vendorAppDir.getCanonicalFile(); 2116 } catch (IOException e) { 2117 // failed to look up canonical path, continue with original one 2118 } 2119 scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2120 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2121 2122 // Collect all OEM packages. 2123 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2124 scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2125 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2126 2127 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 2128 mInstaller.moveFiles(); 2129 2130 // Prune any system packages that no longer exist. 2131 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2132 if (!mOnlyCore) { 2133 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2134 while (psit.hasNext()) { 2135 PackageSetting ps = psit.next(); 2136 2137 /* 2138 * If this is not a system app, it can't be a 2139 * disable system app. 2140 */ 2141 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2142 continue; 2143 } 2144 2145 /* 2146 * If the package is scanned, it's not erased. 2147 */ 2148 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2149 if (scannedPkg != null) { 2150 /* 2151 * If the system app is both scanned and in the 2152 * disabled packages list, then it must have been 2153 * added via OTA. Remove it from the currently 2154 * scanned package so the previously user-installed 2155 * application can be scanned. 2156 */ 2157 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2158 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2159 + ps.name + "; removing system app. Last known codePath=" 2160 + ps.codePathString + ", installStatus=" + ps.installStatus 2161 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2162 + scannedPkg.mVersionCode); 2163 removePackageLI(ps, true); 2164 mExpectingBetter.put(ps.name, ps.codePath); 2165 } 2166 2167 continue; 2168 } 2169 2170 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2171 psit.remove(); 2172 logCriticalInfo(Log.WARN, "System package " + ps.name 2173 + " no longer exists; wiping its data"); 2174 removeDataDirsLI(null, ps.name); 2175 } else { 2176 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2177 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2178 possiblyDeletedUpdatedSystemApps.add(ps.name); 2179 } 2180 } 2181 } 2182 } 2183 2184 //look for any incomplete package installations 2185 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2186 //clean up list 2187 for(int i = 0; i < deletePkgsList.size(); i++) { 2188 //clean up here 2189 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2190 } 2191 //delete tmp files 2192 deleteTempPackageFiles(); 2193 2194 // Remove any shared userIDs that have no associated packages 2195 mSettings.pruneSharedUsersLPw(); 2196 2197 if (!mOnlyCore) { 2198 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2199 SystemClock.uptimeMillis()); 2200 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2201 2202 scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2203 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2204 2205 /** 2206 * Remove disable package settings for any updated system 2207 * apps that were removed via an OTA. If they're not a 2208 * previously-updated app, remove them completely. 2209 * Otherwise, just revoke their system-level permissions. 2210 */ 2211 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2212 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2213 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2214 2215 String msg; 2216 if (deletedPkg == null) { 2217 msg = "Updated system package " + deletedAppName 2218 + " no longer exists; wiping its data"; 2219 removeDataDirsLI(null, deletedAppName); 2220 } else { 2221 msg = "Updated system app + " + deletedAppName 2222 + " no longer present; removing system privileges for " 2223 + deletedAppName; 2224 2225 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2226 2227 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2228 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2229 } 2230 logCriticalInfo(Log.WARN, msg); 2231 } 2232 2233 /** 2234 * Make sure all system apps that we expected to appear on 2235 * the userdata partition actually showed up. If they never 2236 * appeared, crawl back and revive the system version. 2237 */ 2238 for (int i = 0; i < mExpectingBetter.size(); i++) { 2239 final String packageName = mExpectingBetter.keyAt(i); 2240 if (!mPackages.containsKey(packageName)) { 2241 final File scanFile = mExpectingBetter.valueAt(i); 2242 2243 logCriticalInfo(Log.WARN, "Expected better " + packageName 2244 + " but never showed up; reverting to system"); 2245 2246 final int reparseFlags; 2247 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2248 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2249 | PackageParser.PARSE_IS_SYSTEM_DIR 2250 | PackageParser.PARSE_IS_PRIVILEGED; 2251 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2252 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2253 | PackageParser.PARSE_IS_SYSTEM_DIR; 2254 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2255 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2256 | PackageParser.PARSE_IS_SYSTEM_DIR; 2257 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2258 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2259 | PackageParser.PARSE_IS_SYSTEM_DIR; 2260 } else { 2261 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2262 continue; 2263 } 2264 2265 mSettings.enableSystemPackageLPw(packageName); 2266 2267 try { 2268 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2269 } catch (PackageManagerException e) { 2270 Slog.e(TAG, "Failed to parse original system package: " 2271 + e.getMessage()); 2272 } 2273 } 2274 } 2275 } 2276 mExpectingBetter.clear(); 2277 2278 // Now that we know all of the shared libraries, update all clients to have 2279 // the correct library paths. 2280 updateAllSharedLibrariesLPw(); 2281 2282 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2283 // NOTE: We ignore potential failures here during a system scan (like 2284 // the rest of the commands above) because there's precious little we 2285 // can do about it. A settings error is reported, though. 2286 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2287 false /* boot complete */); 2288 } 2289 2290 // Now that we know all the packages we are keeping, 2291 // read and update their last usage times. 2292 mPackageUsage.readLP(); 2293 2294 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2295 SystemClock.uptimeMillis()); 2296 Slog.i(TAG, "Time to scan packages: " 2297 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2298 + " seconds"); 2299 2300 // If the platform SDK has changed since the last time we booted, 2301 // we need to re-grant app permission to catch any new ones that 2302 // appear. This is really a hack, and means that apps can in some 2303 // cases get permissions that the user didn't initially explicitly 2304 // allow... it would be nice to have some better way to handle 2305 // this situation. 2306 int updateFlags = UPDATE_PERMISSIONS_ALL; 2307 if (ver.sdkVersion != mSdkVersion) { 2308 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2309 + mSdkVersion + "; regranting permissions for internal storage"); 2310 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2311 } 2312 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2313 ver.sdkVersion = mSdkVersion; 2314 2315 // If this is the first boot or an update from pre-M, and it is a normal 2316 // boot, then we need to initialize the default preferred apps across 2317 // all defined users. 2318 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2319 for (UserInfo user : sUserManager.getUsers(true)) { 2320 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2321 applyFactoryDefaultBrowserLPw(user.id); 2322 primeDomainVerificationsLPw(user.id); 2323 } 2324 } 2325 2326 // If this is first boot after an OTA, and a normal boot, then 2327 // we need to clear code cache directories. 2328 if (mIsUpgrade && !onlyCore) { 2329 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2330 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2331 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2332 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2333 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2334 } 2335 } 2336 ver.fingerprint = Build.FINGERPRINT; 2337 } 2338 2339 checkDefaultBrowser(); 2340 2341 // clear only after permissions and other defaults have been updated 2342 mExistingSystemPackages.clear(); 2343 mPromoteSystemApps = false; 2344 2345 // All the changes are done during package scanning. 2346 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2347 2348 // can downgrade to reader 2349 mSettings.writeLPr(); 2350 2351 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2352 SystemClock.uptimeMillis()); 2353 2354 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2355 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2356 2357 mInstallerService = new PackageInstallerService(context, this); 2358 2359 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2360 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2361 mIntentFilterVerifierComponent); 2362 2363 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2364 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2365 // both the installer and resolver must be present to enable ephemeral 2366 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2367 if (DEBUG_EPHEMERAL) { 2368 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2369 + " installer:" + ephemeralInstallerComponent); 2370 } 2371 mEphemeralResolverComponent = ephemeralResolverComponent; 2372 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2373 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2374 mEphemeralResolverConnection = 2375 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2376 } else { 2377 if (DEBUG_EPHEMERAL) { 2378 final String missingComponent = 2379 (ephemeralResolverComponent == null) 2380 ? (ephemeralInstallerComponent == null) 2381 ? "resolver and installer" 2382 : "resolver" 2383 : "installer"; 2384 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2385 } 2386 mEphemeralResolverComponent = null; 2387 mEphemeralInstallerComponent = null; 2388 mEphemeralResolverConnection = null; 2389 } 2390 } // synchronized (mPackages) 2391 } // synchronized (mInstallLock) 2392 2393 // Now after opening every single application zip, make sure they 2394 // are all flushed. Not really needed, but keeps things nice and 2395 // tidy. 2396 Runtime.getRuntime().gc(); 2397 2398 // The initial scanning above does many calls into installd while 2399 // holding the mPackages lock, but we're mostly interested in yelling 2400 // once we have a booted system. 2401 mInstaller.setWarnIfHeld(mPackages); 2402 2403 // Expose private service for system components to use. 2404 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2405 } 2406 2407 @Override 2408 public boolean isFirstBoot() { 2409 return !mRestoredSettings; 2410 } 2411 2412 @Override 2413 public boolean isOnlyCoreApps() { 2414 return mOnlyCore; 2415 } 2416 2417 @Override 2418 public boolean isUpgrade() { 2419 return mIsUpgrade; 2420 } 2421 2422 private String getRequiredVerifierLPr() { 2423 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2424 // We only care about verifier that's installed under system user. 2425 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2426 PackageManager.GET_DISABLED_COMPONENTS, UserHandle.USER_SYSTEM); 2427 2428 String requiredVerifier = null; 2429 2430 final int N = receivers.size(); 2431 for (int i = 0; i < N; i++) { 2432 final ResolveInfo info = receivers.get(i); 2433 2434 if (info.activityInfo == null) { 2435 continue; 2436 } 2437 2438 final String packageName = info.activityInfo.packageName; 2439 2440 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2441 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2442 continue; 2443 } 2444 2445 if (requiredVerifier != null) { 2446 throw new RuntimeException("There can be only one required verifier"); 2447 } 2448 2449 requiredVerifier = packageName; 2450 } 2451 2452 return requiredVerifier; 2453 } 2454 2455 private String getRequiredInstallerLPr() { 2456 Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2457 installerIntent.addCategory(Intent.CATEGORY_DEFAULT); 2458 installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2459 2460 final List<ResolveInfo> installers = queryIntentActivities(installerIntent, 2461 PACKAGE_MIME_TYPE, 0, UserHandle.USER_SYSTEM); 2462 2463 String requiredInstaller = null; 2464 2465 final int N = installers.size(); 2466 for (int i = 0; i < N; i++) { 2467 final ResolveInfo info = installers.get(i); 2468 final String packageName = info.activityInfo.packageName; 2469 2470 if (!info.activityInfo.applicationInfo.isSystemApp()) { 2471 continue; 2472 } 2473 2474 if (requiredInstaller != null) { 2475 throw new RuntimeException("There must be one required installer"); 2476 } 2477 2478 requiredInstaller = packageName; 2479 } 2480 2481 if (requiredInstaller == null) { 2482 throw new RuntimeException("There must be one required installer"); 2483 } 2484 2485 return requiredInstaller; 2486 } 2487 2488 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2489 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2490 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2491 PackageManager.GET_DISABLED_COMPONENTS, UserHandle.USER_SYSTEM); 2492 2493 ComponentName verifierComponentName = null; 2494 2495 int priority = -1000; 2496 final int N = receivers.size(); 2497 for (int i = 0; i < N; i++) { 2498 final ResolveInfo info = receivers.get(i); 2499 2500 if (info.activityInfo == null) { 2501 continue; 2502 } 2503 2504 final String packageName = info.activityInfo.packageName; 2505 2506 final PackageSetting ps = mSettings.mPackages.get(packageName); 2507 if (ps == null) { 2508 continue; 2509 } 2510 2511 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2512 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2513 continue; 2514 } 2515 2516 // Select the IntentFilterVerifier with the highest priority 2517 if (priority < info.priority) { 2518 priority = info.priority; 2519 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2520 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: " 2521 + verifierComponentName + " with priority: " + info.priority); 2522 } 2523 } 2524 2525 return verifierComponentName; 2526 } 2527 2528 private ComponentName getEphemeralResolverLPr() { 2529 final String[] packageArray = 2530 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2531 if (packageArray.length == 0) { 2532 if (DEBUG_EPHEMERAL) { 2533 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2534 } 2535 return null; 2536 } 2537 2538 Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2539 final List<ResolveInfo> resolvers = queryIntentServices(resolverIntent, 2540 null /*resolvedType*/, 0 /*flags*/, UserHandle.USER_SYSTEM); 2541 2542 final int N = resolvers.size(); 2543 if (N == 0) { 2544 if (DEBUG_EPHEMERAL) { 2545 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2546 } 2547 return null; 2548 } 2549 2550 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2551 for (int i = 0; i < N; i++) { 2552 final ResolveInfo info = resolvers.get(i); 2553 2554 if (info.serviceInfo == null) { 2555 continue; 2556 } 2557 2558 final String packageName = info.serviceInfo.packageName; 2559 if (!possiblePackages.contains(packageName)) { 2560 if (DEBUG_EPHEMERAL) { 2561 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2562 + " pkg: " + packageName + ", info:" + info); 2563 } 2564 continue; 2565 } 2566 2567 if (DEBUG_EPHEMERAL) { 2568 Slog.v(TAG, "Ephemeral resolver found;" 2569 + " pkg: " + packageName + ", info:" + info); 2570 } 2571 return new ComponentName(packageName, info.serviceInfo.name); 2572 } 2573 if (DEBUG_EPHEMERAL) { 2574 Slog.v(TAG, "Ephemeral resolver NOT found"); 2575 } 2576 return null; 2577 } 2578 2579 private ComponentName getEphemeralInstallerLPr() { 2580 Intent installerIntent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2581 installerIntent.addCategory(Intent.CATEGORY_DEFAULT); 2582 installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2583 final List<ResolveInfo> installers = queryIntentActivities(installerIntent, 2584 PACKAGE_MIME_TYPE, 0 /*flags*/, 0 /*userId*/); 2585 2586 ComponentName ephemeralInstaller = null; 2587 2588 final int N = installers.size(); 2589 for (int i = 0; i < N; i++) { 2590 final ResolveInfo info = installers.get(i); 2591 final String packageName = info.activityInfo.packageName; 2592 2593 if (!info.activityInfo.applicationInfo.isSystemApp()) { 2594 if (DEBUG_EPHEMERAL) { 2595 Slog.d(TAG, "Ephemeral installer is not system app;" 2596 + " pkg: " + packageName + ", info:" + info); 2597 } 2598 continue; 2599 } 2600 2601 if (ephemeralInstaller != null) { 2602 throw new RuntimeException("There must only be one ephemeral installer"); 2603 } 2604 2605 ephemeralInstaller = new ComponentName(packageName, info.activityInfo.name); 2606 } 2607 2608 return ephemeralInstaller; 2609 } 2610 2611 private void primeDomainVerificationsLPw(int userId) { 2612 if (DEBUG_DOMAIN_VERIFICATION) { 2613 Slog.d(TAG, "Priming domain verifications in user " + userId); 2614 } 2615 2616 SystemConfig systemConfig = SystemConfig.getInstance(); 2617 ArraySet<String> packages = systemConfig.getLinkedApps(); 2618 ArraySet<String> domains = new ArraySet<String>(); 2619 2620 for (String packageName : packages) { 2621 PackageParser.Package pkg = mPackages.get(packageName); 2622 if (pkg != null) { 2623 if (!pkg.isSystemApp()) { 2624 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2625 continue; 2626 } 2627 2628 domains.clear(); 2629 for (PackageParser.Activity a : pkg.activities) { 2630 for (ActivityIntentInfo filter : a.intents) { 2631 if (hasValidDomains(filter)) { 2632 domains.addAll(filter.getHostsList()); 2633 } 2634 } 2635 } 2636 2637 if (domains.size() > 0) { 2638 if (DEBUG_DOMAIN_VERIFICATION) { 2639 Slog.v(TAG, " + " + packageName); 2640 } 2641 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2642 // state w.r.t. the formal app-linkage "no verification attempted" state; 2643 // and then 'always' in the per-user state actually used for intent resolution. 2644 final IntentFilterVerificationInfo ivi; 2645 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2646 new ArrayList<String>(domains)); 2647 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2648 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2649 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2650 } else { 2651 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2652 + "' does not handle web links"); 2653 } 2654 } else { 2655 Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>"); 2656 } 2657 } 2658 2659 scheduleWritePackageRestrictionsLocked(userId); 2660 scheduleWriteSettingsLocked(); 2661 } 2662 2663 private void applyFactoryDefaultBrowserLPw(int userId) { 2664 // The default browser app's package name is stored in a string resource, 2665 // with a product-specific overlay used for vendor customization. 2666 String browserPkg = mContext.getResources().getString( 2667 com.android.internal.R.string.default_browser); 2668 if (!TextUtils.isEmpty(browserPkg)) { 2669 // non-empty string => required to be a known package 2670 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2671 if (ps == null) { 2672 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2673 browserPkg = null; 2674 } else { 2675 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2676 } 2677 } 2678 2679 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2680 // default. If there's more than one, just leave everything alone. 2681 if (browserPkg == null) { 2682 calculateDefaultBrowserLPw(userId); 2683 } 2684 } 2685 2686 private void calculateDefaultBrowserLPw(int userId) { 2687 List<String> allBrowsers = resolveAllBrowserApps(userId); 2688 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2689 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2690 } 2691 2692 private List<String> resolveAllBrowserApps(int userId) { 2693 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2694 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2695 PackageManager.MATCH_ALL, userId); 2696 2697 final int count = list.size(); 2698 List<String> result = new ArrayList<String>(count); 2699 for (int i=0; i<count; i++) { 2700 ResolveInfo info = list.get(i); 2701 if (info.activityInfo == null 2702 || !info.handleAllWebDataURI 2703 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2704 || result.contains(info.activityInfo.packageName)) { 2705 continue; 2706 } 2707 result.add(info.activityInfo.packageName); 2708 } 2709 2710 return result; 2711 } 2712 2713 private boolean packageIsBrowser(String packageName, int userId) { 2714 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2715 PackageManager.MATCH_ALL, userId); 2716 final int N = list.size(); 2717 for (int i = 0; i < N; i++) { 2718 ResolveInfo info = list.get(i); 2719 if (packageName.equals(info.activityInfo.packageName)) { 2720 return true; 2721 } 2722 } 2723 return false; 2724 } 2725 2726 private void checkDefaultBrowser() { 2727 final int myUserId = UserHandle.myUserId(); 2728 final String packageName = getDefaultBrowserPackageName(myUserId); 2729 if (packageName != null) { 2730 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2731 if (info == null) { 2732 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2733 synchronized (mPackages) { 2734 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2735 } 2736 } 2737 } 2738 } 2739 2740 @Override 2741 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2742 throws RemoteException { 2743 try { 2744 return super.onTransact(code, data, reply, flags); 2745 } catch (RuntimeException e) { 2746 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2747 Slog.wtf(TAG, "Package Manager Crash", e); 2748 } 2749 throw e; 2750 } 2751 } 2752 2753 void cleanupInstallFailedPackage(PackageSetting ps) { 2754 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2755 2756 removeDataDirsLI(ps.volumeUuid, ps.name); 2757 if (ps.codePath != null) { 2758 if (ps.codePath.isDirectory()) { 2759 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2760 } else { 2761 ps.codePath.delete(); 2762 } 2763 } 2764 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2765 if (ps.resourcePath.isDirectory()) { 2766 FileUtils.deleteContents(ps.resourcePath); 2767 } 2768 ps.resourcePath.delete(); 2769 } 2770 mSettings.removePackageLPw(ps.name); 2771 } 2772 2773 static int[] appendInts(int[] cur, int[] add) { 2774 if (add == null) return cur; 2775 if (cur == null) return add; 2776 final int N = add.length; 2777 for (int i=0; i<N; i++) { 2778 cur = appendInt(cur, add[i]); 2779 } 2780 return cur; 2781 } 2782 2783 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2784 if (!sUserManager.exists(userId)) return null; 2785 final PackageSetting ps = (PackageSetting) p.mExtras; 2786 if (ps == null) { 2787 return null; 2788 } 2789 2790 final PermissionsState permissionsState = ps.getPermissionsState(); 2791 2792 final int[] gids = permissionsState.computeGids(userId); 2793 final Set<String> permissions = permissionsState.getPermissions(userId); 2794 final PackageUserState state = ps.readUserState(userId); 2795 2796 return PackageParser.generatePackageInfo(p, gids, flags, 2797 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2798 } 2799 2800 @Override 2801 public void checkPackageStartable(String packageName, int userId) { 2802 final boolean userKeyUnlocked = isUserKeyUnlocked(userId); 2803 2804 synchronized (mPackages) { 2805 final PackageSetting ps = mSettings.mPackages.get(packageName); 2806 if (ps == null) { 2807 throw new SecurityException("Package " + packageName + " was not found!"); 2808 } 2809 2810 if (ps.frozen) { 2811 throw new SecurityException("Package " + packageName + " is currently frozen!"); 2812 } 2813 2814 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isEncryptionAware() 2815 || ps.pkg.applicationInfo.isPartiallyEncryptionAware())) { 2816 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 2817 } 2818 } 2819 } 2820 2821 @Override 2822 public boolean isPackageAvailable(String packageName, int userId) { 2823 if (!sUserManager.exists(userId)) return false; 2824 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2825 synchronized (mPackages) { 2826 PackageParser.Package p = mPackages.get(packageName); 2827 if (p != null) { 2828 final PackageSetting ps = (PackageSetting) p.mExtras; 2829 if (ps != null) { 2830 final PackageUserState state = ps.readUserState(userId); 2831 if (state != null) { 2832 return PackageParser.isAvailable(state); 2833 } 2834 } 2835 } 2836 } 2837 return false; 2838 } 2839 2840 @Override 2841 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2842 if (!sUserManager.exists(userId)) return null; 2843 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2844 // reader 2845 synchronized (mPackages) { 2846 PackageParser.Package p = mPackages.get(packageName); 2847 if (DEBUG_PACKAGE_INFO) 2848 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2849 if (p != null) { 2850 return generatePackageInfo(p, flags, userId); 2851 } 2852 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2853 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2854 } 2855 } 2856 return null; 2857 } 2858 2859 @Override 2860 public String[] currentToCanonicalPackageNames(String[] names) { 2861 String[] out = new String[names.length]; 2862 // reader 2863 synchronized (mPackages) { 2864 for (int i=names.length-1; i>=0; i--) { 2865 PackageSetting ps = mSettings.mPackages.get(names[i]); 2866 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2867 } 2868 } 2869 return out; 2870 } 2871 2872 @Override 2873 public String[] canonicalToCurrentPackageNames(String[] names) { 2874 String[] out = new String[names.length]; 2875 // reader 2876 synchronized (mPackages) { 2877 for (int i=names.length-1; i>=0; i--) { 2878 String cur = mSettings.mRenamedPackages.get(names[i]); 2879 out[i] = cur != null ? cur : names[i]; 2880 } 2881 } 2882 return out; 2883 } 2884 2885 @Override 2886 public int getPackageUid(String packageName, int userId) { 2887 return getPackageUidEtc(packageName, 0, userId); 2888 } 2889 2890 @Override 2891 public int getPackageUidEtc(String packageName, int flags, int userId) { 2892 if (!sUserManager.exists(userId)) return -1; 2893 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2894 2895 // reader 2896 synchronized (mPackages) { 2897 final PackageParser.Package p = mPackages.get(packageName); 2898 if (p != null) { 2899 return UserHandle.getUid(userId, p.applicationInfo.uid); 2900 } 2901 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2902 final PackageSetting ps = mSettings.mPackages.get(packageName); 2903 if (ps != null) { 2904 return UserHandle.getUid(userId, ps.appId); 2905 } 2906 } 2907 } 2908 2909 return -1; 2910 } 2911 2912 @Override 2913 public int[] getPackageGids(String packageName, int userId) { 2914 return getPackageGidsEtc(packageName, 0, userId); 2915 } 2916 2917 @Override 2918 public int[] getPackageGidsEtc(String packageName, int flags, int userId) { 2919 if (!sUserManager.exists(userId)) { 2920 return null; 2921 } 2922 2923 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2924 "getPackageGids"); 2925 2926 // reader 2927 synchronized (mPackages) { 2928 final PackageParser.Package p = mPackages.get(packageName); 2929 if (p != null) { 2930 PackageSetting ps = (PackageSetting) p.mExtras; 2931 return ps.getPermissionsState().computeGids(userId); 2932 } 2933 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2934 final PackageSetting ps = mSettings.mPackages.get(packageName); 2935 if (ps != null) { 2936 return ps.getPermissionsState().computeGids(userId); 2937 } 2938 } 2939 } 2940 2941 return null; 2942 } 2943 2944 static PermissionInfo generatePermissionInfo( 2945 BasePermission bp, int flags) { 2946 if (bp.perm != null) { 2947 return PackageParser.generatePermissionInfo(bp.perm, flags); 2948 } 2949 PermissionInfo pi = new PermissionInfo(); 2950 pi.name = bp.name; 2951 pi.packageName = bp.sourcePackage; 2952 pi.nonLocalizedLabel = bp.name; 2953 pi.protectionLevel = bp.protectionLevel; 2954 return pi; 2955 } 2956 2957 @Override 2958 public PermissionInfo getPermissionInfo(String name, int flags) { 2959 // reader 2960 synchronized (mPackages) { 2961 final BasePermission p = mSettings.mPermissions.get(name); 2962 if (p != null) { 2963 return generatePermissionInfo(p, flags); 2964 } 2965 return null; 2966 } 2967 } 2968 2969 @Override 2970 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2971 // reader 2972 synchronized (mPackages) { 2973 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2974 for (BasePermission p : mSettings.mPermissions.values()) { 2975 if (group == null) { 2976 if (p.perm == null || p.perm.info.group == null) { 2977 out.add(generatePermissionInfo(p, flags)); 2978 } 2979 } else { 2980 if (p.perm != null && group.equals(p.perm.info.group)) { 2981 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2982 } 2983 } 2984 } 2985 2986 if (out.size() > 0) { 2987 return out; 2988 } 2989 return mPermissionGroups.containsKey(group) ? out : null; 2990 } 2991 } 2992 2993 @Override 2994 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2995 // reader 2996 synchronized (mPackages) { 2997 return PackageParser.generatePermissionGroupInfo( 2998 mPermissionGroups.get(name), flags); 2999 } 3000 } 3001 3002 @Override 3003 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3004 // reader 3005 synchronized (mPackages) { 3006 final int N = mPermissionGroups.size(); 3007 ArrayList<PermissionGroupInfo> out 3008 = new ArrayList<PermissionGroupInfo>(N); 3009 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3010 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3011 } 3012 return out; 3013 } 3014 } 3015 3016 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3017 int userId) { 3018 if (!sUserManager.exists(userId)) return null; 3019 PackageSetting ps = mSettings.mPackages.get(packageName); 3020 if (ps != null) { 3021 if (ps.pkg == null) { 3022 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 3023 flags, userId); 3024 if (pInfo != null) { 3025 return pInfo.applicationInfo; 3026 } 3027 return null; 3028 } 3029 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3030 ps.readUserState(userId), userId); 3031 } 3032 return null; 3033 } 3034 3035 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 3036 int userId) { 3037 if (!sUserManager.exists(userId)) return null; 3038 PackageSetting ps = mSettings.mPackages.get(packageName); 3039 if (ps != null) { 3040 PackageParser.Package pkg = ps.pkg; 3041 if (pkg == null) { 3042 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 3043 return null; 3044 } 3045 // Only data remains, so we aren't worried about code paths 3046 pkg = new PackageParser.Package(packageName); 3047 pkg.applicationInfo.packageName = packageName; 3048 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 3049 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 3050 pkg.applicationInfo.uid = ps.appId; 3051 pkg.applicationInfo.initForUser(userId); 3052 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 3053 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 3054 } 3055 return generatePackageInfo(pkg, flags, userId); 3056 } 3057 return null; 3058 } 3059 3060 @Override 3061 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3062 if (!sUserManager.exists(userId)) return null; 3063 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 3064 // writer 3065 synchronized (mPackages) { 3066 PackageParser.Package p = mPackages.get(packageName); 3067 if (DEBUG_PACKAGE_INFO) Log.v( 3068 TAG, "getApplicationInfo " + packageName 3069 + ": " + p); 3070 if (p != null) { 3071 PackageSetting ps = mSettings.mPackages.get(packageName); 3072 if (ps == null) return null; 3073 // Note: isEnabledLP() does not apply here - always return info 3074 return PackageParser.generateApplicationInfo( 3075 p, flags, ps.readUserState(userId), userId); 3076 } 3077 if ("android".equals(packageName)||"system".equals(packageName)) { 3078 return mAndroidApplication; 3079 } 3080 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 3081 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3082 } 3083 } 3084 return null; 3085 } 3086 3087 @Override 3088 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3089 final IPackageDataObserver observer) { 3090 mContext.enforceCallingOrSelfPermission( 3091 android.Manifest.permission.CLEAR_APP_CACHE, null); 3092 // Queue up an async operation since clearing cache may take a little while. 3093 mHandler.post(new Runnable() { 3094 public void run() { 3095 mHandler.removeCallbacks(this); 3096 int retCode = -1; 3097 synchronized (mInstallLock) { 3098 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 3099 if (retCode < 0) { 3100 Slog.w(TAG, "Couldn't clear application caches"); 3101 } 3102 } 3103 if (observer != null) { 3104 try { 3105 observer.onRemoveCompleted(null, (retCode >= 0)); 3106 } catch (RemoteException e) { 3107 Slog.w(TAG, "RemoveException when invoking call back"); 3108 } 3109 } 3110 } 3111 }); 3112 } 3113 3114 @Override 3115 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3116 final IntentSender pi) { 3117 mContext.enforceCallingOrSelfPermission( 3118 android.Manifest.permission.CLEAR_APP_CACHE, null); 3119 // Queue up an async operation since clearing cache may take a little while. 3120 mHandler.post(new Runnable() { 3121 public void run() { 3122 mHandler.removeCallbacks(this); 3123 int retCode = -1; 3124 synchronized (mInstallLock) { 3125 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 3126 if (retCode < 0) { 3127 Slog.w(TAG, "Couldn't clear application caches"); 3128 } 3129 } 3130 if(pi != null) { 3131 try { 3132 // Callback via pending intent 3133 int code = (retCode >= 0) ? 1 : 0; 3134 pi.sendIntent(null, code, null, 3135 null, null); 3136 } catch (SendIntentException e1) { 3137 Slog.i(TAG, "Failed to send pending intent"); 3138 } 3139 } 3140 } 3141 }); 3142 } 3143 3144 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3145 synchronized (mInstallLock) { 3146 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 3147 throw new IOException("Failed to free enough space"); 3148 } 3149 } 3150 } 3151 3152 /** 3153 * Return if the user key is currently unlocked. 3154 */ 3155 private boolean isUserKeyUnlocked(int userId) { 3156 if (StorageManager.isFileBasedEncryptionEnabled()) { 3157 final IMountService mount = IMountService.Stub 3158 .asInterface(ServiceManager.getService("mount")); 3159 if (mount == null) { 3160 Slog.w(TAG, "Early during boot, assuming locked"); 3161 return false; 3162 } 3163 final long token = Binder.clearCallingIdentity(); 3164 try { 3165 return mount.isUserKeyUnlocked(userId); 3166 } catch (RemoteException e) { 3167 throw e.rethrowAsRuntimeException(); 3168 } finally { 3169 Binder.restoreCallingIdentity(token); 3170 } 3171 } else { 3172 return true; 3173 } 3174 } 3175 3176 /** 3177 * Augment the given flags depending on current user running state. This is 3178 * purposefully done before acquiring {@link #mPackages} lock. 3179 */ 3180 private int augmentFlagsForUser(int flags, int userId) { 3181 if (!isUserKeyUnlocked(userId)) { 3182 flags |= PackageManager.MATCH_ENCRYPTION_AWARE_ONLY; 3183 } 3184 return flags; 3185 } 3186 3187 @Override 3188 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3189 if (!sUserManager.exists(userId)) return null; 3190 flags = augmentFlagsForUser(flags, userId); 3191 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 3192 synchronized (mPackages) { 3193 PackageParser.Activity a = mActivities.mActivities.get(component); 3194 3195 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3196 if (a != null && mSettings.isEnabledAndVisibleLPr(a.info, flags, userId)) { 3197 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3198 if (ps == null) return null; 3199 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3200 userId); 3201 } 3202 if (mResolveComponentName.equals(component)) { 3203 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3204 new PackageUserState(), userId); 3205 } 3206 } 3207 return null; 3208 } 3209 3210 @Override 3211 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3212 String resolvedType) { 3213 synchronized (mPackages) { 3214 if (component.equals(mResolveComponentName)) { 3215 // The resolver supports EVERYTHING! 3216 return true; 3217 } 3218 PackageParser.Activity a = mActivities.mActivities.get(component); 3219 if (a == null) { 3220 return false; 3221 } 3222 for (int i=0; i<a.intents.size(); i++) { 3223 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3224 intent.getData(), intent.getCategories(), TAG) >= 0) { 3225 return true; 3226 } 3227 } 3228 return false; 3229 } 3230 } 3231 3232 @Override 3233 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3234 if (!sUserManager.exists(userId)) return null; 3235 flags = augmentFlagsForUser(flags, userId); 3236 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 3237 synchronized (mPackages) { 3238 PackageParser.Activity a = mReceivers.mActivities.get(component); 3239 if (DEBUG_PACKAGE_INFO) Log.v( 3240 TAG, "getReceiverInfo " + component + ": " + a); 3241 if (a != null && mSettings.isEnabledAndVisibleLPr(a.info, flags, userId)) { 3242 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3243 if (ps == null) return null; 3244 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3245 userId); 3246 } 3247 } 3248 return null; 3249 } 3250 3251 @Override 3252 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3253 if (!sUserManager.exists(userId)) return null; 3254 flags = augmentFlagsForUser(flags, userId); 3255 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 3256 synchronized (mPackages) { 3257 PackageParser.Service s = mServices.mServices.get(component); 3258 if (DEBUG_PACKAGE_INFO) Log.v( 3259 TAG, "getServiceInfo " + component + ": " + s); 3260 if (s != null && mSettings.isEnabledAndVisibleLPr(s.info, flags, userId)) { 3261 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3262 if (ps == null) return null; 3263 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3264 userId); 3265 } 3266 } 3267 return null; 3268 } 3269 3270 @Override 3271 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3272 if (!sUserManager.exists(userId)) return null; 3273 flags = augmentFlagsForUser(flags, userId); 3274 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 3275 synchronized (mPackages) { 3276 PackageParser.Provider p = mProviders.mProviders.get(component); 3277 if (DEBUG_PACKAGE_INFO) Log.v( 3278 TAG, "getProviderInfo " + component + ": " + p); 3279 if (p != null && mSettings.isEnabledAndVisibleLPr(p.info, flags, userId)) { 3280 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3281 if (ps == null) return null; 3282 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3283 userId); 3284 } 3285 } 3286 return null; 3287 } 3288 3289 @Override 3290 public String[] getSystemSharedLibraryNames() { 3291 Set<String> libSet; 3292 synchronized (mPackages) { 3293 libSet = mSharedLibraries.keySet(); 3294 int size = libSet.size(); 3295 if (size > 0) { 3296 String[] libs = new String[size]; 3297 libSet.toArray(libs); 3298 return libs; 3299 } 3300 } 3301 return null; 3302 } 3303 3304 /** 3305 * @hide 3306 */ 3307 PackageParser.Package findSharedNonSystemLibrary(String libName) { 3308 synchronized (mPackages) { 3309 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 3310 if (lib != null && lib.apk != null) { 3311 return mPackages.get(lib.apk); 3312 } 3313 } 3314 return null; 3315 } 3316 3317 @Override 3318 public FeatureInfo[] getSystemAvailableFeatures() { 3319 Collection<FeatureInfo> featSet; 3320 synchronized (mPackages) { 3321 featSet = mAvailableFeatures.values(); 3322 int size = featSet.size(); 3323 if (size > 0) { 3324 FeatureInfo[] features = new FeatureInfo[size+1]; 3325 featSet.toArray(features); 3326 FeatureInfo fi = new FeatureInfo(); 3327 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3328 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3329 features[size] = fi; 3330 return features; 3331 } 3332 } 3333 return null; 3334 } 3335 3336 @Override 3337 public boolean hasSystemFeature(String name) { 3338 synchronized (mPackages) { 3339 return mAvailableFeatures.containsKey(name); 3340 } 3341 } 3342 3343 private void checkValidCaller(int uid, int userId) { 3344 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 3345 return; 3346 3347 throw new SecurityException("Caller uid=" + uid 3348 + " is not privileged to communicate with user=" + userId); 3349 } 3350 3351 @Override 3352 public int checkPermission(String permName, String pkgName, int userId) { 3353 if (!sUserManager.exists(userId)) { 3354 return PackageManager.PERMISSION_DENIED; 3355 } 3356 3357 synchronized (mPackages) { 3358 final PackageParser.Package p = mPackages.get(pkgName); 3359 if (p != null && p.mExtras != null) { 3360 final PackageSetting ps = (PackageSetting) p.mExtras; 3361 final PermissionsState permissionsState = ps.getPermissionsState(); 3362 if (permissionsState.hasPermission(permName, userId)) { 3363 return PackageManager.PERMISSION_GRANTED; 3364 } 3365 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3366 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3367 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3368 return PackageManager.PERMISSION_GRANTED; 3369 } 3370 } 3371 } 3372 3373 return PackageManager.PERMISSION_DENIED; 3374 } 3375 3376 @Override 3377 public int checkUidPermission(String permName, int uid) { 3378 final int userId = UserHandle.getUserId(uid); 3379 3380 if (!sUserManager.exists(userId)) { 3381 return PackageManager.PERMISSION_DENIED; 3382 } 3383 3384 synchronized (mPackages) { 3385 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3386 if (obj != null) { 3387 final SettingBase ps = (SettingBase) obj; 3388 final PermissionsState permissionsState = ps.getPermissionsState(); 3389 if (permissionsState.hasPermission(permName, userId)) { 3390 return PackageManager.PERMISSION_GRANTED; 3391 } 3392 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3393 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3394 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3395 return PackageManager.PERMISSION_GRANTED; 3396 } 3397 } else { 3398 ArraySet<String> perms = mSystemPermissions.get(uid); 3399 if (perms != null) { 3400 if (perms.contains(permName)) { 3401 return PackageManager.PERMISSION_GRANTED; 3402 } 3403 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3404 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3405 return PackageManager.PERMISSION_GRANTED; 3406 } 3407 } 3408 } 3409 } 3410 3411 return PackageManager.PERMISSION_DENIED; 3412 } 3413 3414 @Override 3415 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3416 if (UserHandle.getCallingUserId() != userId) { 3417 mContext.enforceCallingPermission( 3418 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3419 "isPermissionRevokedByPolicy for user " + userId); 3420 } 3421 3422 if (checkPermission(permission, packageName, userId) 3423 == PackageManager.PERMISSION_GRANTED) { 3424 return false; 3425 } 3426 3427 final long identity = Binder.clearCallingIdentity(); 3428 try { 3429 final int flags = getPermissionFlags(permission, packageName, userId); 3430 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3431 } finally { 3432 Binder.restoreCallingIdentity(identity); 3433 } 3434 } 3435 3436 @Override 3437 public String getPermissionControllerPackageName() { 3438 synchronized (mPackages) { 3439 return mRequiredInstallerPackage; 3440 } 3441 } 3442 3443 /** 3444 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3445 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3446 * @param checkShell TODO(yamasani): 3447 * @param message the message to log on security exception 3448 */ 3449 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3450 boolean checkShell, String message) { 3451 if (userId < 0) { 3452 throw new IllegalArgumentException("Invalid userId " + userId); 3453 } 3454 if (checkShell) { 3455 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3456 } 3457 if (userId == UserHandle.getUserId(callingUid)) return; 3458 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3459 if (requireFullPermission) { 3460 mContext.enforceCallingOrSelfPermission( 3461 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3462 } else { 3463 try { 3464 mContext.enforceCallingOrSelfPermission( 3465 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3466 } catch (SecurityException se) { 3467 mContext.enforceCallingOrSelfPermission( 3468 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3469 } 3470 } 3471 } 3472 } 3473 3474 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3475 if (callingUid == Process.SHELL_UID) { 3476 if (userHandle >= 0 3477 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3478 throw new SecurityException("Shell does not have permission to access user " 3479 + userHandle); 3480 } else if (userHandle < 0) { 3481 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3482 + Debug.getCallers(3)); 3483 } 3484 } 3485 } 3486 3487 private BasePermission findPermissionTreeLP(String permName) { 3488 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3489 if (permName.startsWith(bp.name) && 3490 permName.length() > bp.name.length() && 3491 permName.charAt(bp.name.length()) == '.') { 3492 return bp; 3493 } 3494 } 3495 return null; 3496 } 3497 3498 private BasePermission checkPermissionTreeLP(String permName) { 3499 if (permName != null) { 3500 BasePermission bp = findPermissionTreeLP(permName); 3501 if (bp != null) { 3502 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3503 return bp; 3504 } 3505 throw new SecurityException("Calling uid " 3506 + Binder.getCallingUid() 3507 + " is not allowed to add to permission tree " 3508 + bp.name + " owned by uid " + bp.uid); 3509 } 3510 } 3511 throw new SecurityException("No permission tree found for " + permName); 3512 } 3513 3514 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3515 if (s1 == null) { 3516 return s2 == null; 3517 } 3518 if (s2 == null) { 3519 return false; 3520 } 3521 if (s1.getClass() != s2.getClass()) { 3522 return false; 3523 } 3524 return s1.equals(s2); 3525 } 3526 3527 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3528 if (pi1.icon != pi2.icon) return false; 3529 if (pi1.logo != pi2.logo) return false; 3530 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3531 if (!compareStrings(pi1.name, pi2.name)) return false; 3532 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3533 // We'll take care of setting this one. 3534 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3535 // These are not currently stored in settings. 3536 //if (!compareStrings(pi1.group, pi2.group)) return false; 3537 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3538 //if (pi1.labelRes != pi2.labelRes) return false; 3539 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3540 return true; 3541 } 3542 3543 int permissionInfoFootprint(PermissionInfo info) { 3544 int size = info.name.length(); 3545 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3546 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3547 return size; 3548 } 3549 3550 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3551 int size = 0; 3552 for (BasePermission perm : mSettings.mPermissions.values()) { 3553 if (perm.uid == tree.uid) { 3554 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3555 } 3556 } 3557 return size; 3558 } 3559 3560 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3561 // We calculate the max size of permissions defined by this uid and throw 3562 // if that plus the size of 'info' would exceed our stated maximum. 3563 if (tree.uid != Process.SYSTEM_UID) { 3564 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3565 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3566 throw new SecurityException("Permission tree size cap exceeded"); 3567 } 3568 } 3569 } 3570 3571 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3572 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3573 throw new SecurityException("Label must be specified in permission"); 3574 } 3575 BasePermission tree = checkPermissionTreeLP(info.name); 3576 BasePermission bp = mSettings.mPermissions.get(info.name); 3577 boolean added = bp == null; 3578 boolean changed = true; 3579 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3580 if (added) { 3581 enforcePermissionCapLocked(info, tree); 3582 bp = new BasePermission(info.name, tree.sourcePackage, 3583 BasePermission.TYPE_DYNAMIC); 3584 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3585 throw new SecurityException( 3586 "Not allowed to modify non-dynamic permission " 3587 + info.name); 3588 } else { 3589 if (bp.protectionLevel == fixedLevel 3590 && bp.perm.owner.equals(tree.perm.owner) 3591 && bp.uid == tree.uid 3592 && comparePermissionInfos(bp.perm.info, info)) { 3593 changed = false; 3594 } 3595 } 3596 bp.protectionLevel = fixedLevel; 3597 info = new PermissionInfo(info); 3598 info.protectionLevel = fixedLevel; 3599 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3600 bp.perm.info.packageName = tree.perm.info.packageName; 3601 bp.uid = tree.uid; 3602 if (added) { 3603 mSettings.mPermissions.put(info.name, bp); 3604 } 3605 if (changed) { 3606 if (!async) { 3607 mSettings.writeLPr(); 3608 } else { 3609 scheduleWriteSettingsLocked(); 3610 } 3611 } 3612 return added; 3613 } 3614 3615 @Override 3616 public boolean addPermission(PermissionInfo info) { 3617 synchronized (mPackages) { 3618 return addPermissionLocked(info, false); 3619 } 3620 } 3621 3622 @Override 3623 public boolean addPermissionAsync(PermissionInfo info) { 3624 synchronized (mPackages) { 3625 return addPermissionLocked(info, true); 3626 } 3627 } 3628 3629 @Override 3630 public void removePermission(String name) { 3631 synchronized (mPackages) { 3632 checkPermissionTreeLP(name); 3633 BasePermission bp = mSettings.mPermissions.get(name); 3634 if (bp != null) { 3635 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3636 throw new SecurityException( 3637 "Not allowed to modify non-dynamic permission " 3638 + name); 3639 } 3640 mSettings.mPermissions.remove(name); 3641 mSettings.writeLPr(); 3642 } 3643 } 3644 } 3645 3646 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 3647 BasePermission bp) { 3648 int index = pkg.requestedPermissions.indexOf(bp.name); 3649 if (index == -1) { 3650 throw new SecurityException("Package " + pkg.packageName 3651 + " has not requested permission " + bp.name); 3652 } 3653 if (!bp.isRuntime() && !bp.isDevelopment()) { 3654 throw new SecurityException("Permission " + bp.name 3655 + " is not a changeable permission type"); 3656 } 3657 } 3658 3659 @Override 3660 public void grantRuntimePermission(String packageName, String name, final int userId) { 3661 if (!sUserManager.exists(userId)) { 3662 Log.e(TAG, "No such user:" + userId); 3663 return; 3664 } 3665 3666 mContext.enforceCallingOrSelfPermission( 3667 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3668 "grantRuntimePermission"); 3669 3670 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3671 "grantRuntimePermission"); 3672 3673 final int uid; 3674 final SettingBase sb; 3675 3676 synchronized (mPackages) { 3677 final PackageParser.Package pkg = mPackages.get(packageName); 3678 if (pkg == null) { 3679 throw new IllegalArgumentException("Unknown package: " + packageName); 3680 } 3681 3682 final BasePermission bp = mSettings.mPermissions.get(name); 3683 if (bp == null) { 3684 throw new IllegalArgumentException("Unknown permission: " + name); 3685 } 3686 3687 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3688 3689 // If a permission review is required for legacy apps we represent 3690 // their permissions as always granted runtime ones since we need 3691 // to keep the review required permission flag per user while an 3692 // install permission's state is shared across all users. 3693 if (Build.PERMISSIONS_REVIEW_REQUIRED 3694 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 3695 && bp.isRuntime()) { 3696 return; 3697 } 3698 3699 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3700 sb = (SettingBase) pkg.mExtras; 3701 if (sb == null) { 3702 throw new IllegalArgumentException("Unknown package: " + packageName); 3703 } 3704 3705 final PermissionsState permissionsState = sb.getPermissionsState(); 3706 3707 final int flags = permissionsState.getPermissionFlags(name, userId); 3708 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3709 throw new SecurityException("Cannot grant system fixed permission: " 3710 + name + " for package: " + packageName); 3711 } 3712 3713 if (bp.isDevelopment()) { 3714 // Development permissions must be handled specially, since they are not 3715 // normal runtime permissions. For now they apply to all users. 3716 if (permissionsState.grantInstallPermission(bp) != 3717 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3718 scheduleWriteSettingsLocked(); 3719 } 3720 return; 3721 } 3722 3723 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 3724 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 3725 return; 3726 } 3727 3728 final int result = permissionsState.grantRuntimePermission(bp, userId); 3729 switch (result) { 3730 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3731 return; 3732 } 3733 3734 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3735 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3736 mHandler.post(new Runnable() { 3737 @Override 3738 public void run() { 3739 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 3740 } 3741 }); 3742 } 3743 break; 3744 } 3745 3746 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3747 3748 // Not critical if that is lost - app has to request again. 3749 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3750 } 3751 3752 // Only need to do this if user is initialized. Otherwise it's a new user 3753 // and there are no processes running as the user yet and there's no need 3754 // to make an expensive call to remount processes for the changed permissions. 3755 if (READ_EXTERNAL_STORAGE.equals(name) 3756 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3757 final long token = Binder.clearCallingIdentity(); 3758 try { 3759 if (sUserManager.isInitialized(userId)) { 3760 MountServiceInternal mountServiceInternal = LocalServices.getService( 3761 MountServiceInternal.class); 3762 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 3763 } 3764 } finally { 3765 Binder.restoreCallingIdentity(token); 3766 } 3767 } 3768 } 3769 3770 @Override 3771 public void revokeRuntimePermission(String packageName, String name, int userId) { 3772 if (!sUserManager.exists(userId)) { 3773 Log.e(TAG, "No such user:" + userId); 3774 return; 3775 } 3776 3777 mContext.enforceCallingOrSelfPermission( 3778 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3779 "revokeRuntimePermission"); 3780 3781 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3782 "revokeRuntimePermission"); 3783 3784 final int appId; 3785 3786 synchronized (mPackages) { 3787 final PackageParser.Package pkg = mPackages.get(packageName); 3788 if (pkg == null) { 3789 throw new IllegalArgumentException("Unknown package: " + packageName); 3790 } 3791 3792 final BasePermission bp = mSettings.mPermissions.get(name); 3793 if (bp == null) { 3794 throw new IllegalArgumentException("Unknown permission: " + name); 3795 } 3796 3797 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3798 3799 // If a permission review is required for legacy apps we represent 3800 // their permissions as always granted runtime ones since we need 3801 // to keep the review required permission flag per user while an 3802 // install permission's state is shared across all users. 3803 if (Build.PERMISSIONS_REVIEW_REQUIRED 3804 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 3805 && bp.isRuntime()) { 3806 return; 3807 } 3808 3809 SettingBase sb = (SettingBase) pkg.mExtras; 3810 if (sb == null) { 3811 throw new IllegalArgumentException("Unknown package: " + packageName); 3812 } 3813 3814 final PermissionsState permissionsState = sb.getPermissionsState(); 3815 3816 final int flags = permissionsState.getPermissionFlags(name, userId); 3817 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3818 throw new SecurityException("Cannot revoke system fixed permission: " 3819 + name + " for package: " + packageName); 3820 } 3821 3822 if (bp.isDevelopment()) { 3823 // Development permissions must be handled specially, since they are not 3824 // normal runtime permissions. For now they apply to all users. 3825 if (permissionsState.revokeInstallPermission(bp) != 3826 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3827 scheduleWriteSettingsLocked(); 3828 } 3829 return; 3830 } 3831 3832 if (permissionsState.revokeRuntimePermission(bp, userId) == 3833 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3834 return; 3835 } 3836 3837 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3838 3839 // Critical, after this call app should never have the permission. 3840 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3841 3842 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3843 } 3844 3845 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3846 } 3847 3848 @Override 3849 public void resetRuntimePermissions() { 3850 mContext.enforceCallingOrSelfPermission( 3851 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3852 "revokeRuntimePermission"); 3853 3854 int callingUid = Binder.getCallingUid(); 3855 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3856 mContext.enforceCallingOrSelfPermission( 3857 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3858 "resetRuntimePermissions"); 3859 } 3860 3861 synchronized (mPackages) { 3862 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 3863 for (int userId : UserManagerService.getInstance().getUserIds()) { 3864 final int packageCount = mPackages.size(); 3865 for (int i = 0; i < packageCount; i++) { 3866 PackageParser.Package pkg = mPackages.valueAt(i); 3867 if (!(pkg.mExtras instanceof PackageSetting)) { 3868 continue; 3869 } 3870 PackageSetting ps = (PackageSetting) pkg.mExtras; 3871 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 3872 } 3873 } 3874 } 3875 } 3876 3877 @Override 3878 public int getPermissionFlags(String name, String packageName, int userId) { 3879 if (!sUserManager.exists(userId)) { 3880 return 0; 3881 } 3882 3883 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 3884 3885 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3886 "getPermissionFlags"); 3887 3888 synchronized (mPackages) { 3889 final PackageParser.Package pkg = mPackages.get(packageName); 3890 if (pkg == null) { 3891 throw new IllegalArgumentException("Unknown package: " + packageName); 3892 } 3893 3894 final BasePermission bp = mSettings.mPermissions.get(name); 3895 if (bp == null) { 3896 throw new IllegalArgumentException("Unknown permission: " + name); 3897 } 3898 3899 SettingBase sb = (SettingBase) pkg.mExtras; 3900 if (sb == null) { 3901 throw new IllegalArgumentException("Unknown package: " + packageName); 3902 } 3903 3904 PermissionsState permissionsState = sb.getPermissionsState(); 3905 return permissionsState.getPermissionFlags(name, userId); 3906 } 3907 } 3908 3909 @Override 3910 public void updatePermissionFlags(String name, String packageName, int flagMask, 3911 int flagValues, int userId) { 3912 if (!sUserManager.exists(userId)) { 3913 return; 3914 } 3915 3916 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 3917 3918 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3919 "updatePermissionFlags"); 3920 3921 // Only the system can change these flags and nothing else. 3922 if (getCallingUid() != Process.SYSTEM_UID) { 3923 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3924 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3925 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3926 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3927 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 3928 } 3929 3930 synchronized (mPackages) { 3931 final PackageParser.Package pkg = mPackages.get(packageName); 3932 if (pkg == null) { 3933 throw new IllegalArgumentException("Unknown package: " + packageName); 3934 } 3935 3936 final BasePermission bp = mSettings.mPermissions.get(name); 3937 if (bp == null) { 3938 throw new IllegalArgumentException("Unknown permission: " + name); 3939 } 3940 3941 SettingBase sb = (SettingBase) pkg.mExtras; 3942 if (sb == null) { 3943 throw new IllegalArgumentException("Unknown package: " + packageName); 3944 } 3945 3946 PermissionsState permissionsState = sb.getPermissionsState(); 3947 3948 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 3949 3950 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3951 // Install and runtime permissions are stored in different places, 3952 // so figure out what permission changed and persist the change. 3953 if (permissionsState.getInstallPermissionState(name) != null) { 3954 scheduleWriteSettingsLocked(); 3955 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 3956 || hadState) { 3957 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3958 } 3959 } 3960 } 3961 } 3962 3963 /** 3964 * Update the permission flags for all packages and runtime permissions of a user in order 3965 * to allow device or profile owner to remove POLICY_FIXED. 3966 */ 3967 @Override 3968 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 3969 if (!sUserManager.exists(userId)) { 3970 return; 3971 } 3972 3973 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 3974 3975 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3976 "updatePermissionFlagsForAllApps"); 3977 3978 // Only the system can change system fixed flags. 3979 if (getCallingUid() != Process.SYSTEM_UID) { 3980 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3981 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3982 } 3983 3984 synchronized (mPackages) { 3985 boolean changed = false; 3986 final int packageCount = mPackages.size(); 3987 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 3988 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 3989 SettingBase sb = (SettingBase) pkg.mExtras; 3990 if (sb == null) { 3991 continue; 3992 } 3993 PermissionsState permissionsState = sb.getPermissionsState(); 3994 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 3995 userId, flagMask, flagValues); 3996 } 3997 if (changed) { 3998 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3999 } 4000 } 4001 } 4002 4003 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4004 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4005 != PackageManager.PERMISSION_GRANTED 4006 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4007 != PackageManager.PERMISSION_GRANTED) { 4008 throw new SecurityException(message + " requires " 4009 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4010 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4011 } 4012 } 4013 4014 @Override 4015 public boolean shouldShowRequestPermissionRationale(String permissionName, 4016 String packageName, int userId) { 4017 if (UserHandle.getCallingUserId() != userId) { 4018 mContext.enforceCallingPermission( 4019 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4020 "canShowRequestPermissionRationale for user " + userId); 4021 } 4022 4023 final int uid = getPackageUid(packageName, userId); 4024 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4025 return false; 4026 } 4027 4028 if (checkPermission(permissionName, packageName, userId) 4029 == PackageManager.PERMISSION_GRANTED) { 4030 return false; 4031 } 4032 4033 final int flags; 4034 4035 final long identity = Binder.clearCallingIdentity(); 4036 try { 4037 flags = getPermissionFlags(permissionName, 4038 packageName, userId); 4039 } finally { 4040 Binder.restoreCallingIdentity(identity); 4041 } 4042 4043 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4044 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4045 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4046 4047 if ((flags & fixedFlags) != 0) { 4048 return false; 4049 } 4050 4051 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4052 } 4053 4054 @Override 4055 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4056 mContext.enforceCallingOrSelfPermission( 4057 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4058 "addOnPermissionsChangeListener"); 4059 4060 synchronized (mPackages) { 4061 mOnPermissionChangeListeners.addListenerLocked(listener); 4062 } 4063 } 4064 4065 @Override 4066 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4067 synchronized (mPackages) { 4068 mOnPermissionChangeListeners.removeListenerLocked(listener); 4069 } 4070 } 4071 4072 @Override 4073 public boolean isProtectedBroadcast(String actionName) { 4074 synchronized (mPackages) { 4075 return mProtectedBroadcasts.contains(actionName); 4076 } 4077 } 4078 4079 @Override 4080 public int checkSignatures(String pkg1, String pkg2) { 4081 synchronized (mPackages) { 4082 final PackageParser.Package p1 = mPackages.get(pkg1); 4083 final PackageParser.Package p2 = mPackages.get(pkg2); 4084 if (p1 == null || p1.mExtras == null 4085 || p2 == null || p2.mExtras == null) { 4086 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4087 } 4088 return compareSignatures(p1.mSignatures, p2.mSignatures); 4089 } 4090 } 4091 4092 @Override 4093 public int checkUidSignatures(int uid1, int uid2) { 4094 // Map to base uids. 4095 uid1 = UserHandle.getAppId(uid1); 4096 uid2 = UserHandle.getAppId(uid2); 4097 // reader 4098 synchronized (mPackages) { 4099 Signature[] s1; 4100 Signature[] s2; 4101 Object obj = mSettings.getUserIdLPr(uid1); 4102 if (obj != null) { 4103 if (obj instanceof SharedUserSetting) { 4104 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4105 } else if (obj instanceof PackageSetting) { 4106 s1 = ((PackageSetting)obj).signatures.mSignatures; 4107 } else { 4108 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4109 } 4110 } else { 4111 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4112 } 4113 obj = mSettings.getUserIdLPr(uid2); 4114 if (obj != null) { 4115 if (obj instanceof SharedUserSetting) { 4116 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4117 } else if (obj instanceof PackageSetting) { 4118 s2 = ((PackageSetting)obj).signatures.mSignatures; 4119 } else { 4120 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4121 } 4122 } else { 4123 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4124 } 4125 return compareSignatures(s1, s2); 4126 } 4127 } 4128 4129 private void killUid(int appId, int userId, String reason) { 4130 final long identity = Binder.clearCallingIdentity(); 4131 try { 4132 IActivityManager am = ActivityManagerNative.getDefault(); 4133 if (am != null) { 4134 try { 4135 am.killUid(appId, userId, reason); 4136 } catch (RemoteException e) { 4137 /* ignore - same process */ 4138 } 4139 } 4140 } finally { 4141 Binder.restoreCallingIdentity(identity); 4142 } 4143 } 4144 4145 /** 4146 * Compares two sets of signatures. Returns: 4147 * <br /> 4148 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4149 * <br /> 4150 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4151 * <br /> 4152 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4153 * <br /> 4154 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4155 * <br /> 4156 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4157 */ 4158 static int compareSignatures(Signature[] s1, Signature[] s2) { 4159 if (s1 == null) { 4160 return s2 == null 4161 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4162 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4163 } 4164 4165 if (s2 == null) { 4166 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4167 } 4168 4169 if (s1.length != s2.length) { 4170 return PackageManager.SIGNATURE_NO_MATCH; 4171 } 4172 4173 // Since both signature sets are of size 1, we can compare without HashSets. 4174 if (s1.length == 1) { 4175 return s1[0].equals(s2[0]) ? 4176 PackageManager.SIGNATURE_MATCH : 4177 PackageManager.SIGNATURE_NO_MATCH; 4178 } 4179 4180 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4181 for (Signature sig : s1) { 4182 set1.add(sig); 4183 } 4184 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4185 for (Signature sig : s2) { 4186 set2.add(sig); 4187 } 4188 // Make sure s2 contains all signatures in s1. 4189 if (set1.equals(set2)) { 4190 return PackageManager.SIGNATURE_MATCH; 4191 } 4192 return PackageManager.SIGNATURE_NO_MATCH; 4193 } 4194 4195 /** 4196 * If the database version for this type of package (internal storage or 4197 * external storage) is less than the version where package signatures 4198 * were updated, return true. 4199 */ 4200 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4201 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4202 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4203 } 4204 4205 /** 4206 * Used for backward compatibility to make sure any packages with 4207 * certificate chains get upgraded to the new style. {@code existingSigs} 4208 * will be in the old format (since they were stored on disk from before the 4209 * system upgrade) and {@code scannedSigs} will be in the newer format. 4210 */ 4211 private int compareSignaturesCompat(PackageSignatures existingSigs, 4212 PackageParser.Package scannedPkg) { 4213 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4214 return PackageManager.SIGNATURE_NO_MATCH; 4215 } 4216 4217 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4218 for (Signature sig : existingSigs.mSignatures) { 4219 existingSet.add(sig); 4220 } 4221 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4222 for (Signature sig : scannedPkg.mSignatures) { 4223 try { 4224 Signature[] chainSignatures = sig.getChainSignatures(); 4225 for (Signature chainSig : chainSignatures) { 4226 scannedCompatSet.add(chainSig); 4227 } 4228 } catch (CertificateEncodingException e) { 4229 scannedCompatSet.add(sig); 4230 } 4231 } 4232 /* 4233 * Make sure the expanded scanned set contains all signatures in the 4234 * existing one. 4235 */ 4236 if (scannedCompatSet.equals(existingSet)) { 4237 // Migrate the old signatures to the new scheme. 4238 existingSigs.assignSignatures(scannedPkg.mSignatures); 4239 // The new KeySets will be re-added later in the scanning process. 4240 synchronized (mPackages) { 4241 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4242 } 4243 return PackageManager.SIGNATURE_MATCH; 4244 } 4245 return PackageManager.SIGNATURE_NO_MATCH; 4246 } 4247 4248 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4249 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4250 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4251 } 4252 4253 private int compareSignaturesRecover(PackageSignatures existingSigs, 4254 PackageParser.Package scannedPkg) { 4255 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4256 return PackageManager.SIGNATURE_NO_MATCH; 4257 } 4258 4259 String msg = null; 4260 try { 4261 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4262 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4263 + scannedPkg.packageName); 4264 return PackageManager.SIGNATURE_MATCH; 4265 } 4266 } catch (CertificateException e) { 4267 msg = e.getMessage(); 4268 } 4269 4270 logCriticalInfo(Log.INFO, 4271 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4272 return PackageManager.SIGNATURE_NO_MATCH; 4273 } 4274 4275 @Override 4276 public String[] getPackagesForUid(int uid) { 4277 uid = UserHandle.getAppId(uid); 4278 // reader 4279 synchronized (mPackages) { 4280 Object obj = mSettings.getUserIdLPr(uid); 4281 if (obj instanceof SharedUserSetting) { 4282 final SharedUserSetting sus = (SharedUserSetting) obj; 4283 final int N = sus.packages.size(); 4284 final String[] res = new String[N]; 4285 final Iterator<PackageSetting> it = sus.packages.iterator(); 4286 int i = 0; 4287 while (it.hasNext()) { 4288 res[i++] = it.next().name; 4289 } 4290 return res; 4291 } else if (obj instanceof PackageSetting) { 4292 final PackageSetting ps = (PackageSetting) obj; 4293 return new String[] { ps.name }; 4294 } 4295 } 4296 return null; 4297 } 4298 4299 @Override 4300 public String getNameForUid(int uid) { 4301 // reader 4302 synchronized (mPackages) { 4303 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4304 if (obj instanceof SharedUserSetting) { 4305 final SharedUserSetting sus = (SharedUserSetting) obj; 4306 return sus.name + ":" + sus.userId; 4307 } else if (obj instanceof PackageSetting) { 4308 final PackageSetting ps = (PackageSetting) obj; 4309 return ps.name; 4310 } 4311 } 4312 return null; 4313 } 4314 4315 @Override 4316 public int getUidForSharedUser(String sharedUserName) { 4317 if(sharedUserName == null) { 4318 return -1; 4319 } 4320 // reader 4321 synchronized (mPackages) { 4322 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4323 if (suid == null) { 4324 return -1; 4325 } 4326 return suid.userId; 4327 } 4328 } 4329 4330 @Override 4331 public int getFlagsForUid(int uid) { 4332 synchronized (mPackages) { 4333 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4334 if (obj instanceof SharedUserSetting) { 4335 final SharedUserSetting sus = (SharedUserSetting) obj; 4336 return sus.pkgFlags; 4337 } else if (obj instanceof PackageSetting) { 4338 final PackageSetting ps = (PackageSetting) obj; 4339 return ps.pkgFlags; 4340 } 4341 } 4342 return 0; 4343 } 4344 4345 @Override 4346 public int getPrivateFlagsForUid(int uid) { 4347 synchronized (mPackages) { 4348 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4349 if (obj instanceof SharedUserSetting) { 4350 final SharedUserSetting sus = (SharedUserSetting) obj; 4351 return sus.pkgPrivateFlags; 4352 } else if (obj instanceof PackageSetting) { 4353 final PackageSetting ps = (PackageSetting) obj; 4354 return ps.pkgPrivateFlags; 4355 } 4356 } 4357 return 0; 4358 } 4359 4360 @Override 4361 public boolean isUidPrivileged(int uid) { 4362 uid = UserHandle.getAppId(uid); 4363 // reader 4364 synchronized (mPackages) { 4365 Object obj = mSettings.getUserIdLPr(uid); 4366 if (obj instanceof SharedUserSetting) { 4367 final SharedUserSetting sus = (SharedUserSetting) obj; 4368 final Iterator<PackageSetting> it = sus.packages.iterator(); 4369 while (it.hasNext()) { 4370 if (it.next().isPrivileged()) { 4371 return true; 4372 } 4373 } 4374 } else if (obj instanceof PackageSetting) { 4375 final PackageSetting ps = (PackageSetting) obj; 4376 return ps.isPrivileged(); 4377 } 4378 } 4379 return false; 4380 } 4381 4382 @Override 4383 public String[] getAppOpPermissionPackages(String permissionName) { 4384 synchronized (mPackages) { 4385 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4386 if (pkgs == null) { 4387 return null; 4388 } 4389 return pkgs.toArray(new String[pkgs.size()]); 4390 } 4391 } 4392 4393 @Override 4394 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4395 int flags, int userId) { 4396 if (!sUserManager.exists(userId)) return null; 4397 flags = augmentFlagsForUser(flags, userId); 4398 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 4399 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4400 return chooseBestActivity(intent, resolvedType, flags, query, userId); 4401 } 4402 4403 @Override 4404 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4405 IntentFilter filter, int match, ComponentName activity) { 4406 final int userId = UserHandle.getCallingUserId(); 4407 if (DEBUG_PREFERRED) { 4408 Log.v(TAG, "setLastChosenActivity intent=" + intent 4409 + " resolvedType=" + resolvedType 4410 + " flags=" + flags 4411 + " filter=" + filter 4412 + " match=" + match 4413 + " activity=" + activity); 4414 filter.dump(new PrintStreamPrinter(System.out), " "); 4415 } 4416 intent.setComponent(null); 4417 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4418 // Find any earlier preferred or last chosen entries and nuke them 4419 findPreferredActivity(intent, resolvedType, 4420 flags, query, 0, false, true, false, userId); 4421 // Add the new activity as the last chosen for this filter 4422 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4423 "Setting last chosen"); 4424 } 4425 4426 @Override 4427 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4428 final int userId = UserHandle.getCallingUserId(); 4429 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4430 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4431 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4432 false, false, false, userId); 4433 } 4434 4435 private boolean isEphemeralAvailable(Intent intent, String resolvedType, int userId) { 4436 MessageDigest digest = null; 4437 try { 4438 digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM); 4439 } catch (NoSuchAlgorithmException e) { 4440 // If we can't create a digest, ignore ephemeral apps. 4441 return false; 4442 } 4443 4444 final byte[] hostBytes = intent.getData().getHost().getBytes(); 4445 final byte[] digestBytes = digest.digest(hostBytes); 4446 int shaPrefix = 4447 digestBytes[0] << 24 4448 | digestBytes[1] << 16 4449 | digestBytes[2] << 8 4450 | digestBytes[3] << 0; 4451 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4452 mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix); 4453 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4454 // No hash prefix match; there are no ephemeral apps for this domain. 4455 return false; 4456 } 4457 for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) { 4458 EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i); 4459 if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) { 4460 continue; 4461 } 4462 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4463 // No filters; this should never happen. 4464 if (filters.isEmpty()) { 4465 continue; 4466 } 4467 // We have a domain match; resolve the filters to see if anything matches. 4468 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4469 for (int j = filters.size() - 1; j >= 0; --j) { 4470 ephemeralResolver.addFilter(filters.get(j)); 4471 } 4472 List<ResolveInfo> ephemeralResolveList = ephemeralResolver.queryIntent( 4473 intent, resolvedType, false /*defaultOnly*/, userId); 4474 return !ephemeralResolveList.isEmpty(); 4475 } 4476 // Hash or filter mis-match; no ephemeral apps for this domain. 4477 return false; 4478 } 4479 4480 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4481 int flags, List<ResolveInfo> query, int userId) { 4482 final boolean isWebUri = hasWebURI(intent); 4483 // Check whether or not an ephemeral app exists to handle the URI. 4484 if (isWebUri && mEphemeralResolverConnection != null) { 4485 // Deny ephemeral apps if the user choose _ALWAYS or _ALWAYS_ASK for intent resolution. 4486 boolean hasAlwaysHandler = false; 4487 synchronized (mPackages) { 4488 final int count = query.size(); 4489 for (int n=0; n<count; n++) { 4490 ResolveInfo info = query.get(n); 4491 String packageName = info.activityInfo.packageName; 4492 PackageSetting ps = mSettings.mPackages.get(packageName); 4493 if (ps != null) { 4494 // Try to get the status from User settings first 4495 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4496 int status = (int) (packedStatus >> 32); 4497 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4498 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4499 hasAlwaysHandler = true; 4500 break; 4501 } 4502 } 4503 } 4504 } 4505 4506 // Only consider installing an ephemeral app if there isn't already a verified handler. 4507 // We've determined that there's an ephemeral app available for the URI, ignore any 4508 // ResolveInfo's and just return the ephemeral installer 4509 if (!hasAlwaysHandler && isEphemeralAvailable(intent, resolvedType, userId)) { 4510 if (DEBUG_EPHEMERAL) { 4511 Slog.v(TAG, "Resolving to the ephemeral installer"); 4512 } 4513 // ditch the result and return a ResolveInfo to launch the ephemeral installer 4514 ResolveInfo ri = new ResolveInfo(mEphemeralInstallerInfo); 4515 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4516 // make a deep copy of the applicationInfo 4517 ri.activityInfo.applicationInfo = new ApplicationInfo( 4518 ri.activityInfo.applicationInfo); 4519 if (userId != 0) { 4520 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4521 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4522 } 4523 return ri; 4524 } 4525 } 4526 if (query != null) { 4527 final int N = query.size(); 4528 if (N == 1) { 4529 return query.get(0); 4530 } else if (N > 1) { 4531 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4532 // If there is more than one activity with the same priority, 4533 // then let the user decide between them. 4534 ResolveInfo r0 = query.get(0); 4535 ResolveInfo r1 = query.get(1); 4536 if (DEBUG_INTENT_MATCHING || debug) { 4537 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4538 + r1.activityInfo.name + "=" + r1.priority); 4539 } 4540 // If the first activity has a higher priority, or a different 4541 // default, then it is always desireable to pick it. 4542 if (r0.priority != r1.priority 4543 || r0.preferredOrder != r1.preferredOrder 4544 || r0.isDefault != r1.isDefault) { 4545 return query.get(0); 4546 } 4547 // If we have saved a preference for a preferred activity for 4548 // this Intent, use that. 4549 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4550 flags, query, r0.priority, true, false, debug, userId); 4551 if (ri != null) { 4552 return ri; 4553 } 4554 ri = new ResolveInfo(mResolveInfo); 4555 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4556 ri.activityInfo.applicationInfo = new ApplicationInfo( 4557 ri.activityInfo.applicationInfo); 4558 if (userId != 0) { 4559 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4560 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4561 } 4562 // Make sure that the resolver is displayable in car mode 4563 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 4564 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 4565 return ri; 4566 } 4567 } 4568 return null; 4569 } 4570 4571 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4572 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4573 final int N = query.size(); 4574 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4575 .get(userId); 4576 // Get the list of persistent preferred activities that handle the intent 4577 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4578 List<PersistentPreferredActivity> pprefs = ppir != null 4579 ? ppir.queryIntent(intent, resolvedType, 4580 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4581 : null; 4582 if (pprefs != null && pprefs.size() > 0) { 4583 final int M = pprefs.size(); 4584 for (int i=0; i<M; i++) { 4585 final PersistentPreferredActivity ppa = pprefs.get(i); 4586 if (DEBUG_PREFERRED || debug) { 4587 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4588 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4589 + "\n component=" + ppa.mComponent); 4590 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4591 } 4592 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4593 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4594 if (DEBUG_PREFERRED || debug) { 4595 Slog.v(TAG, "Found persistent preferred activity:"); 4596 if (ai != null) { 4597 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4598 } else { 4599 Slog.v(TAG, " null"); 4600 } 4601 } 4602 if (ai == null) { 4603 // This previously registered persistent preferred activity 4604 // component is no longer known. Ignore it and do NOT remove it. 4605 continue; 4606 } 4607 for (int j=0; j<N; j++) { 4608 final ResolveInfo ri = query.get(j); 4609 if (!ri.activityInfo.applicationInfo.packageName 4610 .equals(ai.applicationInfo.packageName)) { 4611 continue; 4612 } 4613 if (!ri.activityInfo.name.equals(ai.name)) { 4614 continue; 4615 } 4616 // Found a persistent preference that can handle the intent. 4617 if (DEBUG_PREFERRED || debug) { 4618 Slog.v(TAG, "Returning persistent preferred activity: " + 4619 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4620 } 4621 return ri; 4622 } 4623 } 4624 } 4625 return null; 4626 } 4627 4628 // TODO: handle preferred activities missing while user has amnesia 4629 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4630 List<ResolveInfo> query, int priority, boolean always, 4631 boolean removeMatches, boolean debug, int userId) { 4632 if (!sUserManager.exists(userId)) return null; 4633 flags = augmentFlagsForUser(flags, userId); 4634 // writer 4635 synchronized (mPackages) { 4636 if (intent.getSelector() != null) { 4637 intent = intent.getSelector(); 4638 } 4639 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4640 4641 // Try to find a matching persistent preferred activity. 4642 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4643 debug, userId); 4644 4645 // If a persistent preferred activity matched, use it. 4646 if (pri != null) { 4647 return pri; 4648 } 4649 4650 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4651 // Get the list of preferred activities that handle the intent 4652 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4653 List<PreferredActivity> prefs = pir != null 4654 ? pir.queryIntent(intent, resolvedType, 4655 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4656 : null; 4657 if (prefs != null && prefs.size() > 0) { 4658 boolean changed = false; 4659 try { 4660 // First figure out how good the original match set is. 4661 // We will only allow preferred activities that came 4662 // from the same match quality. 4663 int match = 0; 4664 4665 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4666 4667 final int N = query.size(); 4668 for (int j=0; j<N; j++) { 4669 final ResolveInfo ri = query.get(j); 4670 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4671 + ": 0x" + Integer.toHexString(match)); 4672 if (ri.match > match) { 4673 match = ri.match; 4674 } 4675 } 4676 4677 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4678 + Integer.toHexString(match)); 4679 4680 match &= IntentFilter.MATCH_CATEGORY_MASK; 4681 final int M = prefs.size(); 4682 for (int i=0; i<M; i++) { 4683 final PreferredActivity pa = prefs.get(i); 4684 if (DEBUG_PREFERRED || debug) { 4685 Slog.v(TAG, "Checking PreferredActivity ds=" 4686 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4687 + "\n component=" + pa.mPref.mComponent); 4688 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4689 } 4690 if (pa.mPref.mMatch != match) { 4691 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4692 + Integer.toHexString(pa.mPref.mMatch)); 4693 continue; 4694 } 4695 // If it's not an "always" type preferred activity and that's what we're 4696 // looking for, skip it. 4697 if (always && !pa.mPref.mAlways) { 4698 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4699 continue; 4700 } 4701 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4702 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4703 if (DEBUG_PREFERRED || debug) { 4704 Slog.v(TAG, "Found preferred activity:"); 4705 if (ai != null) { 4706 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4707 } else { 4708 Slog.v(TAG, " null"); 4709 } 4710 } 4711 if (ai == null) { 4712 // This previously registered preferred activity 4713 // component is no longer known. Most likely an update 4714 // to the app was installed and in the new version this 4715 // component no longer exists. Clean it up by removing 4716 // it from the preferred activities list, and skip it. 4717 Slog.w(TAG, "Removing dangling preferred activity: " 4718 + pa.mPref.mComponent); 4719 pir.removeFilter(pa); 4720 changed = true; 4721 continue; 4722 } 4723 for (int j=0; j<N; j++) { 4724 final ResolveInfo ri = query.get(j); 4725 if (!ri.activityInfo.applicationInfo.packageName 4726 .equals(ai.applicationInfo.packageName)) { 4727 continue; 4728 } 4729 if (!ri.activityInfo.name.equals(ai.name)) { 4730 continue; 4731 } 4732 4733 if (removeMatches) { 4734 pir.removeFilter(pa); 4735 changed = true; 4736 if (DEBUG_PREFERRED) { 4737 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4738 } 4739 break; 4740 } 4741 4742 // Okay we found a previously set preferred or last chosen app. 4743 // If the result set is different from when this 4744 // was created, we need to clear it and re-ask the 4745 // user their preference, if we're looking for an "always" type entry. 4746 if (always && !pa.mPref.sameSet(query)) { 4747 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4748 + intent + " type " + resolvedType); 4749 if (DEBUG_PREFERRED) { 4750 Slog.v(TAG, "Removing preferred activity since set changed " 4751 + pa.mPref.mComponent); 4752 } 4753 pir.removeFilter(pa); 4754 // Re-add the filter as a "last chosen" entry (!always) 4755 PreferredActivity lastChosen = new PreferredActivity( 4756 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4757 pir.addFilter(lastChosen); 4758 changed = true; 4759 return null; 4760 } 4761 4762 // Yay! Either the set matched or we're looking for the last chosen 4763 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4764 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4765 return ri; 4766 } 4767 } 4768 } finally { 4769 if (changed) { 4770 if (DEBUG_PREFERRED) { 4771 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4772 } 4773 scheduleWritePackageRestrictionsLocked(userId); 4774 } 4775 } 4776 } 4777 } 4778 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4779 return null; 4780 } 4781 4782 /* 4783 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4784 */ 4785 @Override 4786 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4787 int targetUserId) { 4788 mContext.enforceCallingOrSelfPermission( 4789 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4790 List<CrossProfileIntentFilter> matches = 4791 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4792 if (matches != null) { 4793 int size = matches.size(); 4794 for (int i = 0; i < size; i++) { 4795 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4796 } 4797 } 4798 if (hasWebURI(intent)) { 4799 // cross-profile app linking works only towards the parent. 4800 final UserInfo parent = getProfileParent(sourceUserId); 4801 synchronized(mPackages) { 4802 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 4803 intent, resolvedType, 0, sourceUserId, parent.id); 4804 return xpDomainInfo != null; 4805 } 4806 } 4807 return false; 4808 } 4809 4810 private UserInfo getProfileParent(int userId) { 4811 final long identity = Binder.clearCallingIdentity(); 4812 try { 4813 return sUserManager.getProfileParent(userId); 4814 } finally { 4815 Binder.restoreCallingIdentity(identity); 4816 } 4817 } 4818 4819 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4820 String resolvedType, int userId) { 4821 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4822 if (resolver != null) { 4823 return resolver.queryIntent(intent, resolvedType, false, userId); 4824 } 4825 return null; 4826 } 4827 4828 @Override 4829 public List<ResolveInfo> queryIntentActivities(Intent intent, 4830 String resolvedType, int flags, int userId) { 4831 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4832 flags = augmentFlagsForUser(flags, userId); 4833 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4834 ComponentName comp = intent.getComponent(); 4835 if (comp == null) { 4836 if (intent.getSelector() != null) { 4837 intent = intent.getSelector(); 4838 comp = intent.getComponent(); 4839 } 4840 } 4841 4842 if (comp != null) { 4843 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4844 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4845 if (ai != null) { 4846 final ResolveInfo ri = new ResolveInfo(); 4847 ri.activityInfo = ai; 4848 list.add(ri); 4849 } 4850 return list; 4851 } 4852 4853 // reader 4854 synchronized (mPackages) { 4855 final String pkgName = intent.getPackage(); 4856 if (pkgName == null) { 4857 List<CrossProfileIntentFilter> matchingFilters = 4858 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4859 // Check for results that need to skip the current profile. 4860 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4861 resolvedType, flags, userId); 4862 if (xpResolveInfo != null) { 4863 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4864 result.add(xpResolveInfo); 4865 return filterIfNotSystemUser(result, userId); 4866 } 4867 4868 // Check for results in the current profile. 4869 List<ResolveInfo> result = mActivities.queryIntent( 4870 intent, resolvedType, flags, userId); 4871 result = filterIfNotSystemUser(result, userId); 4872 4873 // Check for cross profile results. 4874 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 4875 xpResolveInfo = queryCrossProfileIntents( 4876 matchingFilters, intent, resolvedType, flags, userId, 4877 hasNonNegativePriorityResult); 4878 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4879 boolean isVisibleToUser = filterIfNotSystemUser( 4880 Collections.singletonList(xpResolveInfo), userId).size() > 0; 4881 if (isVisibleToUser) { 4882 result.add(xpResolveInfo); 4883 Collections.sort(result, mResolvePrioritySorter); 4884 } 4885 } 4886 if (hasWebURI(intent)) { 4887 CrossProfileDomainInfo xpDomainInfo = null; 4888 final UserInfo parent = getProfileParent(userId); 4889 if (parent != null) { 4890 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 4891 flags, userId, parent.id); 4892 } 4893 if (xpDomainInfo != null) { 4894 if (xpResolveInfo != null) { 4895 // If we didn't remove it, the cross-profile ResolveInfo would be twice 4896 // in the result. 4897 result.remove(xpResolveInfo); 4898 } 4899 if (result.size() == 0) { 4900 result.add(xpDomainInfo.resolveInfo); 4901 return result; 4902 } 4903 } else if (result.size() <= 1) { 4904 return result; 4905 } 4906 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 4907 xpDomainInfo, userId); 4908 Collections.sort(result, mResolvePrioritySorter); 4909 } 4910 return result; 4911 } 4912 final PackageParser.Package pkg = mPackages.get(pkgName); 4913 if (pkg != null) { 4914 return filterIfNotSystemUser( 4915 mActivities.queryIntentForPackage( 4916 intent, resolvedType, flags, pkg.activities, userId), 4917 userId); 4918 } 4919 return new ArrayList<ResolveInfo>(); 4920 } 4921 } 4922 4923 private static class CrossProfileDomainInfo { 4924 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 4925 ResolveInfo resolveInfo; 4926 /* Best domain verification status of the activities found in the other profile */ 4927 int bestDomainVerificationStatus; 4928 } 4929 4930 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 4931 String resolvedType, int flags, int sourceUserId, int parentUserId) { 4932 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 4933 sourceUserId)) { 4934 return null; 4935 } 4936 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4937 resolvedType, flags, parentUserId); 4938 4939 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 4940 return null; 4941 } 4942 CrossProfileDomainInfo result = null; 4943 int size = resultTargetUser.size(); 4944 for (int i = 0; i < size; i++) { 4945 ResolveInfo riTargetUser = resultTargetUser.get(i); 4946 // Intent filter verification is only for filters that specify a host. So don't return 4947 // those that handle all web uris. 4948 if (riTargetUser.handleAllWebDataURI) { 4949 continue; 4950 } 4951 String packageName = riTargetUser.activityInfo.packageName; 4952 PackageSetting ps = mSettings.mPackages.get(packageName); 4953 if (ps == null) { 4954 continue; 4955 } 4956 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 4957 int status = (int)(verificationState >> 32); 4958 if (result == null) { 4959 result = new CrossProfileDomainInfo(); 4960 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 4961 sourceUserId, parentUserId); 4962 result.bestDomainVerificationStatus = status; 4963 } else { 4964 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 4965 result.bestDomainVerificationStatus); 4966 } 4967 } 4968 // Don't consider matches with status NEVER across profiles. 4969 if (result != null && result.bestDomainVerificationStatus 4970 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4971 return null; 4972 } 4973 return result; 4974 } 4975 4976 /** 4977 * Verification statuses are ordered from the worse to the best, except for 4978 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 4979 */ 4980 private int bestDomainVerificationStatus(int status1, int status2) { 4981 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4982 return status2; 4983 } 4984 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4985 return status1; 4986 } 4987 return (int) MathUtils.max(status1, status2); 4988 } 4989 4990 private boolean isUserEnabled(int userId) { 4991 long callingId = Binder.clearCallingIdentity(); 4992 try { 4993 UserInfo userInfo = sUserManager.getUserInfo(userId); 4994 return userInfo != null && userInfo.isEnabled(); 4995 } finally { 4996 Binder.restoreCallingIdentity(callingId); 4997 } 4998 } 4999 5000 /** 5001 * Filter out activities with systemUserOnly flag set, when current user is not System. 5002 * 5003 * @return filtered list 5004 */ 5005 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5006 if (userId == UserHandle.USER_SYSTEM) { 5007 return resolveInfos; 5008 } 5009 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5010 ResolveInfo info = resolveInfos.get(i); 5011 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5012 resolveInfos.remove(i); 5013 } 5014 } 5015 return resolveInfos; 5016 } 5017 5018 /** 5019 * @param resolveInfos list of resolve infos in descending priority order 5020 * @return if the list contains a resolve info with non-negative priority 5021 */ 5022 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5023 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5024 } 5025 5026 private static boolean hasWebURI(Intent intent) { 5027 if (intent.getData() == null) { 5028 return false; 5029 } 5030 final String scheme = intent.getScheme(); 5031 if (TextUtils.isEmpty(scheme)) { 5032 return false; 5033 } 5034 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5035 } 5036 5037 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5038 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5039 int userId) { 5040 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5041 5042 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5043 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5044 candidates.size()); 5045 } 5046 5047 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5048 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5049 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5050 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5051 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5052 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5053 5054 synchronized (mPackages) { 5055 final int count = candidates.size(); 5056 // First, try to use linked apps. Partition the candidates into four lists: 5057 // one for the final results, one for the "do not use ever", one for "undefined status" 5058 // and finally one for "browser app type". 5059 for (int n=0; n<count; n++) { 5060 ResolveInfo info = candidates.get(n); 5061 String packageName = info.activityInfo.packageName; 5062 PackageSetting ps = mSettings.mPackages.get(packageName); 5063 if (ps != null) { 5064 // Add to the special match all list (Browser use case) 5065 if (info.handleAllWebDataURI) { 5066 matchAllList.add(info); 5067 continue; 5068 } 5069 // Try to get the status from User settings first 5070 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5071 int status = (int)(packedStatus >> 32); 5072 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5073 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5074 if (DEBUG_DOMAIN_VERIFICATION) { 5075 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5076 + " : linkgen=" + linkGeneration); 5077 } 5078 // Use link-enabled generation as preferredOrder, i.e. 5079 // prefer newly-enabled over earlier-enabled. 5080 info.preferredOrder = linkGeneration; 5081 alwaysList.add(info); 5082 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5083 if (DEBUG_DOMAIN_VERIFICATION) { 5084 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5085 } 5086 neverList.add(info); 5087 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5088 if (DEBUG_DOMAIN_VERIFICATION) { 5089 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5090 } 5091 alwaysAskList.add(info); 5092 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5093 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5094 if (DEBUG_DOMAIN_VERIFICATION) { 5095 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5096 } 5097 undefinedList.add(info); 5098 } 5099 } 5100 } 5101 5102 // We'll want to include browser possibilities in a few cases 5103 boolean includeBrowser = false; 5104 5105 // First try to add the "always" resolution(s) for the current user, if any 5106 if (alwaysList.size() > 0) { 5107 result.addAll(alwaysList); 5108 } else { 5109 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5110 result.addAll(undefinedList); 5111 // Maybe add one for the other profile. 5112 if (xpDomainInfo != null && ( 5113 xpDomainInfo.bestDomainVerificationStatus 5114 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5115 result.add(xpDomainInfo.resolveInfo); 5116 } 5117 includeBrowser = true; 5118 } 5119 5120 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5121 // If there were 'always' entries their preferred order has been set, so we also 5122 // back that off to make the alternatives equivalent 5123 if (alwaysAskList.size() > 0) { 5124 for (ResolveInfo i : result) { 5125 i.preferredOrder = 0; 5126 } 5127 result.addAll(alwaysAskList); 5128 includeBrowser = true; 5129 } 5130 5131 if (includeBrowser) { 5132 // Also add browsers (all of them or only the default one) 5133 if (DEBUG_DOMAIN_VERIFICATION) { 5134 Slog.v(TAG, " ...including browsers in candidate set"); 5135 } 5136 if ((matchFlags & MATCH_ALL) != 0) { 5137 result.addAll(matchAllList); 5138 } else { 5139 // Browser/generic handling case. If there's a default browser, go straight 5140 // to that (but only if there is no other higher-priority match). 5141 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5142 int maxMatchPrio = 0; 5143 ResolveInfo defaultBrowserMatch = null; 5144 final int numCandidates = matchAllList.size(); 5145 for (int n = 0; n < numCandidates; n++) { 5146 ResolveInfo info = matchAllList.get(n); 5147 // track the highest overall match priority... 5148 if (info.priority > maxMatchPrio) { 5149 maxMatchPrio = info.priority; 5150 } 5151 // ...and the highest-priority default browser match 5152 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5153 if (defaultBrowserMatch == null 5154 || (defaultBrowserMatch.priority < info.priority)) { 5155 if (debug) { 5156 Slog.v(TAG, "Considering default browser match " + info); 5157 } 5158 defaultBrowserMatch = info; 5159 } 5160 } 5161 } 5162 if (defaultBrowserMatch != null 5163 && defaultBrowserMatch.priority >= maxMatchPrio 5164 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5165 { 5166 if (debug) { 5167 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5168 } 5169 result.add(defaultBrowserMatch); 5170 } else { 5171 result.addAll(matchAllList); 5172 } 5173 } 5174 5175 // If there is nothing selected, add all candidates and remove the ones that the user 5176 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5177 if (result.size() == 0) { 5178 result.addAll(candidates); 5179 result.removeAll(neverList); 5180 } 5181 } 5182 } 5183 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5184 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5185 result.size()); 5186 for (ResolveInfo info : result) { 5187 Slog.v(TAG, " + " + info.activityInfo); 5188 } 5189 } 5190 return result; 5191 } 5192 5193 // Returns a packed value as a long: 5194 // 5195 // high 'int'-sized word: link status: undefined/ask/never/always. 5196 // low 'int'-sized word: relative priority among 'always' results. 5197 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5198 long result = ps.getDomainVerificationStatusForUser(userId); 5199 // if none available, get the master status 5200 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5201 if (ps.getIntentFilterVerificationInfo() != null) { 5202 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5203 } 5204 } 5205 return result; 5206 } 5207 5208 private ResolveInfo querySkipCurrentProfileIntents( 5209 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5210 int flags, int sourceUserId) { 5211 if (matchingFilters != null) { 5212 int size = matchingFilters.size(); 5213 for (int i = 0; i < size; i ++) { 5214 CrossProfileIntentFilter filter = matchingFilters.get(i); 5215 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5216 // Checking if there are activities in the target user that can handle the 5217 // intent. 5218 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5219 resolvedType, flags, sourceUserId); 5220 if (resolveInfo != null) { 5221 return resolveInfo; 5222 } 5223 } 5224 } 5225 } 5226 return null; 5227 } 5228 5229 // Return matching ResolveInfo in target user if any. 5230 private ResolveInfo queryCrossProfileIntents( 5231 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5232 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5233 if (matchingFilters != null) { 5234 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5235 // match the same intent. For performance reasons, it is better not to 5236 // run queryIntent twice for the same userId 5237 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5238 int size = matchingFilters.size(); 5239 for (int i = 0; i < size; i++) { 5240 CrossProfileIntentFilter filter = matchingFilters.get(i); 5241 int targetUserId = filter.getTargetUserId(); 5242 boolean skipCurrentProfile = 5243 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5244 boolean skipCurrentProfileIfNoMatchFound = 5245 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5246 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5247 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5248 // Checking if there are activities in the target user that can handle the 5249 // intent. 5250 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5251 resolvedType, flags, sourceUserId); 5252 if (resolveInfo != null) return resolveInfo; 5253 alreadyTriedUserIds.put(targetUserId, true); 5254 } 5255 } 5256 } 5257 return null; 5258 } 5259 5260 /** 5261 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5262 * will forward the intent to the filter's target user. 5263 * Otherwise, returns null. 5264 */ 5265 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5266 String resolvedType, int flags, int sourceUserId) { 5267 int targetUserId = filter.getTargetUserId(); 5268 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5269 resolvedType, flags, targetUserId); 5270 if (resultTargetUser != null && !resultTargetUser.isEmpty() 5271 && isUserEnabled(targetUserId)) { 5272 return createForwardingResolveInfoUnchecked(filter, sourceUserId, targetUserId); 5273 } 5274 return null; 5275 } 5276 5277 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5278 int sourceUserId, int targetUserId) { 5279 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5280 long ident = Binder.clearCallingIdentity(); 5281 boolean targetIsProfile; 5282 try { 5283 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5284 } finally { 5285 Binder.restoreCallingIdentity(ident); 5286 } 5287 String className; 5288 if (targetIsProfile) { 5289 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5290 } else { 5291 className = FORWARD_INTENT_TO_PARENT; 5292 } 5293 ComponentName forwardingActivityComponentName = new ComponentName( 5294 mAndroidApplication.packageName, className); 5295 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5296 sourceUserId); 5297 if (!targetIsProfile) { 5298 forwardingActivityInfo.showUserIcon = targetUserId; 5299 forwardingResolveInfo.noResourceId = true; 5300 } 5301 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5302 forwardingResolveInfo.priority = 0; 5303 forwardingResolveInfo.preferredOrder = 0; 5304 forwardingResolveInfo.match = 0; 5305 forwardingResolveInfo.isDefault = true; 5306 forwardingResolveInfo.filter = filter; 5307 forwardingResolveInfo.targetUserId = targetUserId; 5308 return forwardingResolveInfo; 5309 } 5310 5311 @Override 5312 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5313 Intent[] specifics, String[] specificTypes, Intent intent, 5314 String resolvedType, int flags, int userId) { 5315 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5316 flags = augmentFlagsForUser(flags, userId); 5317 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 5318 false, "query intent activity options"); 5319 final String resultsAction = intent.getAction(); 5320 5321 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 5322 | PackageManager.GET_RESOLVED_FILTER, userId); 5323 5324 if (DEBUG_INTENT_MATCHING) { 5325 Log.v(TAG, "Query " + intent + ": " + results); 5326 } 5327 5328 int specificsPos = 0; 5329 int N; 5330 5331 // todo: note that the algorithm used here is O(N^2). This 5332 // isn't a problem in our current environment, but if we start running 5333 // into situations where we have more than 5 or 10 matches then this 5334 // should probably be changed to something smarter... 5335 5336 // First we go through and resolve each of the specific items 5337 // that were supplied, taking care of removing any corresponding 5338 // duplicate items in the generic resolve list. 5339 if (specifics != null) { 5340 for (int i=0; i<specifics.length; i++) { 5341 final Intent sintent = specifics[i]; 5342 if (sintent == null) { 5343 continue; 5344 } 5345 5346 if (DEBUG_INTENT_MATCHING) { 5347 Log.v(TAG, "Specific #" + i + ": " + sintent); 5348 } 5349 5350 String action = sintent.getAction(); 5351 if (resultsAction != null && resultsAction.equals(action)) { 5352 // If this action was explicitly requested, then don't 5353 // remove things that have it. 5354 action = null; 5355 } 5356 5357 ResolveInfo ri = null; 5358 ActivityInfo ai = null; 5359 5360 ComponentName comp = sintent.getComponent(); 5361 if (comp == null) { 5362 ri = resolveIntent( 5363 sintent, 5364 specificTypes != null ? specificTypes[i] : null, 5365 flags, userId); 5366 if (ri == null) { 5367 continue; 5368 } 5369 if (ri == mResolveInfo) { 5370 // ACK! Must do something better with this. 5371 } 5372 ai = ri.activityInfo; 5373 comp = new ComponentName(ai.applicationInfo.packageName, 5374 ai.name); 5375 } else { 5376 ai = getActivityInfo(comp, flags, userId); 5377 if (ai == null) { 5378 continue; 5379 } 5380 } 5381 5382 // Look for any generic query activities that are duplicates 5383 // of this specific one, and remove them from the results. 5384 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5385 N = results.size(); 5386 int j; 5387 for (j=specificsPos; j<N; j++) { 5388 ResolveInfo sri = results.get(j); 5389 if ((sri.activityInfo.name.equals(comp.getClassName()) 5390 && sri.activityInfo.applicationInfo.packageName.equals( 5391 comp.getPackageName())) 5392 || (action != null && sri.filter.matchAction(action))) { 5393 results.remove(j); 5394 if (DEBUG_INTENT_MATCHING) Log.v( 5395 TAG, "Removing duplicate item from " + j 5396 + " due to specific " + specificsPos); 5397 if (ri == null) { 5398 ri = sri; 5399 } 5400 j--; 5401 N--; 5402 } 5403 } 5404 5405 // Add this specific item to its proper place. 5406 if (ri == null) { 5407 ri = new ResolveInfo(); 5408 ri.activityInfo = ai; 5409 } 5410 results.add(specificsPos, ri); 5411 ri.specificIndex = i; 5412 specificsPos++; 5413 } 5414 } 5415 5416 // Now we go through the remaining generic results and remove any 5417 // duplicate actions that are found here. 5418 N = results.size(); 5419 for (int i=specificsPos; i<N-1; i++) { 5420 final ResolveInfo rii = results.get(i); 5421 if (rii.filter == null) { 5422 continue; 5423 } 5424 5425 // Iterate over all of the actions of this result's intent 5426 // filter... typically this should be just one. 5427 final Iterator<String> it = rii.filter.actionsIterator(); 5428 if (it == null) { 5429 continue; 5430 } 5431 while (it.hasNext()) { 5432 final String action = it.next(); 5433 if (resultsAction != null && resultsAction.equals(action)) { 5434 // If this action was explicitly requested, then don't 5435 // remove things that have it. 5436 continue; 5437 } 5438 for (int j=i+1; j<N; j++) { 5439 final ResolveInfo rij = results.get(j); 5440 if (rij.filter != null && rij.filter.hasAction(action)) { 5441 results.remove(j); 5442 if (DEBUG_INTENT_MATCHING) Log.v( 5443 TAG, "Removing duplicate item from " + j 5444 + " due to action " + action + " at " + i); 5445 j--; 5446 N--; 5447 } 5448 } 5449 } 5450 5451 // If the caller didn't request filter information, drop it now 5452 // so we don't have to marshall/unmarshall it. 5453 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5454 rii.filter = null; 5455 } 5456 } 5457 5458 // Filter out the caller activity if so requested. 5459 if (caller != null) { 5460 N = results.size(); 5461 for (int i=0; i<N; i++) { 5462 ActivityInfo ainfo = results.get(i).activityInfo; 5463 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5464 && caller.getClassName().equals(ainfo.name)) { 5465 results.remove(i); 5466 break; 5467 } 5468 } 5469 } 5470 5471 // If the caller didn't request filter information, 5472 // drop them now so we don't have to 5473 // marshall/unmarshall it. 5474 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5475 N = results.size(); 5476 for (int i=0; i<N; i++) { 5477 results.get(i).filter = null; 5478 } 5479 } 5480 5481 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5482 return results; 5483 } 5484 5485 @Override 5486 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 5487 int userId) { 5488 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5489 flags = augmentFlagsForUser(flags, userId); 5490 ComponentName comp = intent.getComponent(); 5491 if (comp == null) { 5492 if (intent.getSelector() != null) { 5493 intent = intent.getSelector(); 5494 comp = intent.getComponent(); 5495 } 5496 } 5497 if (comp != null) { 5498 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5499 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5500 if (ai != null) { 5501 ResolveInfo ri = new ResolveInfo(); 5502 ri.activityInfo = ai; 5503 list.add(ri); 5504 } 5505 return list; 5506 } 5507 5508 // reader 5509 synchronized (mPackages) { 5510 String pkgName = intent.getPackage(); 5511 if (pkgName == null) { 5512 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5513 } 5514 final PackageParser.Package pkg = mPackages.get(pkgName); 5515 if (pkg != null) { 5516 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5517 userId); 5518 } 5519 return null; 5520 } 5521 } 5522 5523 @Override 5524 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5525 if (!sUserManager.exists(userId)) return null; 5526 flags = augmentFlagsForUser(flags, userId); 5527 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 5528 if (query != null) { 5529 if (query.size() >= 1) { 5530 // If there is more than one service with the same priority, 5531 // just arbitrarily pick the first one. 5532 return query.get(0); 5533 } 5534 } 5535 return null; 5536 } 5537 5538 @Override 5539 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 5540 int userId) { 5541 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5542 flags = augmentFlagsForUser(flags, userId); 5543 ComponentName comp = intent.getComponent(); 5544 if (comp == null) { 5545 if (intent.getSelector() != null) { 5546 intent = intent.getSelector(); 5547 comp = intent.getComponent(); 5548 } 5549 } 5550 if (comp != null) { 5551 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5552 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5553 if (si != null) { 5554 final ResolveInfo ri = new ResolveInfo(); 5555 ri.serviceInfo = si; 5556 list.add(ri); 5557 } 5558 return list; 5559 } 5560 5561 // reader 5562 synchronized (mPackages) { 5563 String pkgName = intent.getPackage(); 5564 if (pkgName == null) { 5565 return mServices.queryIntent(intent, resolvedType, flags, userId); 5566 } 5567 final PackageParser.Package pkg = mPackages.get(pkgName); 5568 if (pkg != null) { 5569 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5570 userId); 5571 } 5572 return null; 5573 } 5574 } 5575 5576 @Override 5577 public List<ResolveInfo> queryIntentContentProviders( 5578 Intent intent, String resolvedType, int flags, int userId) { 5579 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5580 flags = augmentFlagsForUser(flags, userId); 5581 ComponentName comp = intent.getComponent(); 5582 if (comp == null) { 5583 if (intent.getSelector() != null) { 5584 intent = intent.getSelector(); 5585 comp = intent.getComponent(); 5586 } 5587 } 5588 if (comp != null) { 5589 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5590 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5591 if (pi != null) { 5592 final ResolveInfo ri = new ResolveInfo(); 5593 ri.providerInfo = pi; 5594 list.add(ri); 5595 } 5596 return list; 5597 } 5598 5599 // reader 5600 synchronized (mPackages) { 5601 String pkgName = intent.getPackage(); 5602 if (pkgName == null) { 5603 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5604 } 5605 final PackageParser.Package pkg = mPackages.get(pkgName); 5606 if (pkg != null) { 5607 return mProviders.queryIntentForPackage( 5608 intent, resolvedType, flags, pkg.providers, userId); 5609 } 5610 return null; 5611 } 5612 } 5613 5614 @Override 5615 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5616 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5617 5618 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 5619 5620 // writer 5621 synchronized (mPackages) { 5622 ArrayList<PackageInfo> list; 5623 if (listUninstalled) { 5624 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5625 for (PackageSetting ps : mSettings.mPackages.values()) { 5626 PackageInfo pi; 5627 if (ps.pkg != null) { 5628 pi = generatePackageInfo(ps.pkg, flags, userId); 5629 } else { 5630 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5631 } 5632 if (pi != null) { 5633 list.add(pi); 5634 } 5635 } 5636 } else { 5637 list = new ArrayList<PackageInfo>(mPackages.size()); 5638 for (PackageParser.Package p : mPackages.values()) { 5639 PackageInfo pi = generatePackageInfo(p, flags, userId); 5640 if (pi != null) { 5641 list.add(pi); 5642 } 5643 } 5644 } 5645 5646 return new ParceledListSlice<PackageInfo>(list); 5647 } 5648 } 5649 5650 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5651 String[] permissions, boolean[] tmp, int flags, int userId) { 5652 int numMatch = 0; 5653 final PermissionsState permissionsState = ps.getPermissionsState(); 5654 for (int i=0; i<permissions.length; i++) { 5655 final String permission = permissions[i]; 5656 if (permissionsState.hasPermission(permission, userId)) { 5657 tmp[i] = true; 5658 numMatch++; 5659 } else { 5660 tmp[i] = false; 5661 } 5662 } 5663 if (numMatch == 0) { 5664 return; 5665 } 5666 PackageInfo pi; 5667 if (ps.pkg != null) { 5668 pi = generatePackageInfo(ps.pkg, flags, userId); 5669 } else { 5670 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5671 } 5672 // The above might return null in cases of uninstalled apps or install-state 5673 // skew across users/profiles. 5674 if (pi != null) { 5675 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5676 if (numMatch == permissions.length) { 5677 pi.requestedPermissions = permissions; 5678 } else { 5679 pi.requestedPermissions = new String[numMatch]; 5680 numMatch = 0; 5681 for (int i=0; i<permissions.length; i++) { 5682 if (tmp[i]) { 5683 pi.requestedPermissions[numMatch] = permissions[i]; 5684 numMatch++; 5685 } 5686 } 5687 } 5688 } 5689 list.add(pi); 5690 } 5691 } 5692 5693 @Override 5694 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5695 String[] permissions, int flags, int userId) { 5696 if (!sUserManager.exists(userId)) return null; 5697 flags = augmentFlagsForUser(flags, userId); 5698 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5699 5700 // writer 5701 synchronized (mPackages) { 5702 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5703 boolean[] tmpBools = new boolean[permissions.length]; 5704 if (listUninstalled) { 5705 for (PackageSetting ps : mSettings.mPackages.values()) { 5706 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5707 } 5708 } else { 5709 for (PackageParser.Package pkg : mPackages.values()) { 5710 PackageSetting ps = (PackageSetting)pkg.mExtras; 5711 if (ps != null) { 5712 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5713 userId); 5714 } 5715 } 5716 } 5717 5718 return new ParceledListSlice<PackageInfo>(list); 5719 } 5720 } 5721 5722 @Override 5723 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5724 if (!sUserManager.exists(userId)) return null; 5725 flags = augmentFlagsForUser(flags, userId); 5726 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5727 5728 // writer 5729 synchronized (mPackages) { 5730 ArrayList<ApplicationInfo> list; 5731 if (listUninstalled) { 5732 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5733 for (PackageSetting ps : mSettings.mPackages.values()) { 5734 ApplicationInfo ai; 5735 if (ps.pkg != null) { 5736 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5737 ps.readUserState(userId), userId); 5738 } else { 5739 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5740 } 5741 if (ai != null) { 5742 list.add(ai); 5743 } 5744 } 5745 } else { 5746 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5747 for (PackageParser.Package p : mPackages.values()) { 5748 if (p.mExtras != null) { 5749 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5750 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5751 if (ai != null) { 5752 list.add(ai); 5753 } 5754 } 5755 } 5756 } 5757 5758 return new ParceledListSlice<ApplicationInfo>(list); 5759 } 5760 } 5761 5762 public List<ApplicationInfo> getPersistentApplications(int flags) { 5763 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 5764 5765 // reader 5766 synchronized (mPackages) { 5767 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 5768 final int userId = UserHandle.getCallingUserId(); 5769 while (i.hasNext()) { 5770 final PackageParser.Package p = i.next(); 5771 if (p.applicationInfo != null 5772 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 5773 && (!mSafeMode || isSystemApp(p))) { 5774 PackageSetting ps = mSettings.mPackages.get(p.packageName); 5775 if (ps != null) { 5776 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5777 ps.readUserState(userId), userId); 5778 if (ai != null) { 5779 finalList.add(ai); 5780 } 5781 } 5782 } 5783 } 5784 } 5785 5786 return finalList; 5787 } 5788 5789 @Override 5790 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 5791 if (!sUserManager.exists(userId)) return null; 5792 flags = augmentFlagsForUser(flags, userId); 5793 // reader 5794 synchronized (mPackages) { 5795 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 5796 PackageSetting ps = provider != null 5797 ? mSettings.mPackages.get(provider.owner.packageName) 5798 : null; 5799 return ps != null 5800 && mSettings.isEnabledAndVisibleLPr(provider.info, flags, userId) 5801 && (!mSafeMode || (provider.info.applicationInfo.flags 5802 &ApplicationInfo.FLAG_SYSTEM) != 0) 5803 ? PackageParser.generateProviderInfo(provider, flags, 5804 ps.readUserState(userId), userId) 5805 : null; 5806 } 5807 } 5808 5809 /** 5810 * @deprecated 5811 */ 5812 @Deprecated 5813 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 5814 // reader 5815 synchronized (mPackages) { 5816 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 5817 .entrySet().iterator(); 5818 final int userId = UserHandle.getCallingUserId(); 5819 while (i.hasNext()) { 5820 Map.Entry<String, PackageParser.Provider> entry = i.next(); 5821 PackageParser.Provider p = entry.getValue(); 5822 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5823 5824 if (ps != null && p.syncable 5825 && (!mSafeMode || (p.info.applicationInfo.flags 5826 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 5827 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 5828 ps.readUserState(userId), userId); 5829 if (info != null) { 5830 outNames.add(entry.getKey()); 5831 outInfo.add(info); 5832 } 5833 } 5834 } 5835 } 5836 } 5837 5838 @Override 5839 public ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 5840 int uid, int flags) { 5841 final int userId = processName != null ? UserHandle.getUserId(uid) 5842 : UserHandle.getCallingUserId(); 5843 if (!sUserManager.exists(userId)) return null; 5844 flags = augmentFlagsForUser(flags, userId); 5845 5846 ArrayList<ProviderInfo> finalList = null; 5847 // reader 5848 synchronized (mPackages) { 5849 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 5850 while (i.hasNext()) { 5851 final PackageParser.Provider p = i.next(); 5852 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5853 if (ps != null && p.info.authority != null 5854 && (processName == null 5855 || (p.info.processName.equals(processName) 5856 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 5857 && mSettings.isEnabledAndVisibleLPr(p.info, flags, userId) 5858 && (!mSafeMode 5859 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 5860 if (finalList == null) { 5861 finalList = new ArrayList<ProviderInfo>(3); 5862 } 5863 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 5864 ps.readUserState(userId), userId); 5865 if (info != null) { 5866 finalList.add(info); 5867 } 5868 } 5869 } 5870 } 5871 5872 if (finalList != null) { 5873 Collections.sort(finalList, mProviderInitOrderSorter); 5874 return new ParceledListSlice<ProviderInfo>(finalList); 5875 } 5876 5877 return null; 5878 } 5879 5880 @Override 5881 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 5882 int flags) { 5883 // reader 5884 synchronized (mPackages) { 5885 final PackageParser.Instrumentation i = mInstrumentation.get(name); 5886 return PackageParser.generateInstrumentationInfo(i, flags); 5887 } 5888 } 5889 5890 @Override 5891 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 5892 int flags) { 5893 ArrayList<InstrumentationInfo> finalList = 5894 new ArrayList<InstrumentationInfo>(); 5895 5896 // reader 5897 synchronized (mPackages) { 5898 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 5899 while (i.hasNext()) { 5900 final PackageParser.Instrumentation p = i.next(); 5901 if (targetPackage == null 5902 || targetPackage.equals(p.info.targetPackage)) { 5903 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 5904 flags); 5905 if (ii != null) { 5906 finalList.add(ii); 5907 } 5908 } 5909 } 5910 } 5911 5912 return finalList; 5913 } 5914 5915 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 5916 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 5917 if (overlays == null) { 5918 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 5919 return; 5920 } 5921 for (PackageParser.Package opkg : overlays.values()) { 5922 // Not much to do if idmap fails: we already logged the error 5923 // and we certainly don't want to abort installation of pkg simply 5924 // because an overlay didn't fit properly. For these reasons, 5925 // ignore the return value of createIdmapForPackagePairLI. 5926 createIdmapForPackagePairLI(pkg, opkg); 5927 } 5928 } 5929 5930 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 5931 PackageParser.Package opkg) { 5932 if (!opkg.mTrustedOverlay) { 5933 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 5934 opkg.baseCodePath + ": overlay not trusted"); 5935 return false; 5936 } 5937 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 5938 if (overlaySet == null) { 5939 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 5940 opkg.baseCodePath + " but target package has no known overlays"); 5941 return false; 5942 } 5943 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 5944 // TODO: generate idmap for split APKs 5945 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 5946 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 5947 + opkg.baseCodePath); 5948 return false; 5949 } 5950 PackageParser.Package[] overlayArray = 5951 overlaySet.values().toArray(new PackageParser.Package[0]); 5952 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 5953 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 5954 return p1.mOverlayPriority - p2.mOverlayPriority; 5955 } 5956 }; 5957 Arrays.sort(overlayArray, cmp); 5958 5959 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 5960 int i = 0; 5961 for (PackageParser.Package p : overlayArray) { 5962 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 5963 } 5964 return true; 5965 } 5966 5967 private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5968 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 5969 try { 5970 scanDirLI(dir, parseFlags, scanFlags, currentTime); 5971 } finally { 5972 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5973 } 5974 } 5975 5976 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5977 final File[] files = dir.listFiles(); 5978 if (ArrayUtils.isEmpty(files)) { 5979 Log.d(TAG, "No files in app dir " + dir); 5980 return; 5981 } 5982 5983 if (DEBUG_PACKAGE_SCANNING) { 5984 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 5985 + " flags=0x" + Integer.toHexString(parseFlags)); 5986 } 5987 5988 for (File file : files) { 5989 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 5990 && !PackageInstallerService.isStageName(file.getName()); 5991 if (!isPackage) { 5992 // Ignore entries which are not packages 5993 continue; 5994 } 5995 try { 5996 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 5997 scanFlags, currentTime, null); 5998 } catch (PackageManagerException e) { 5999 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6000 6001 // Delete invalid userdata apps 6002 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6003 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6004 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6005 if (file.isDirectory()) { 6006 mInstaller.rmPackageDir(file.getAbsolutePath()); 6007 } else { 6008 file.delete(); 6009 } 6010 } 6011 } 6012 } 6013 } 6014 6015 private static File getSettingsProblemFile() { 6016 File dataDir = Environment.getDataDirectory(); 6017 File systemDir = new File(dataDir, "system"); 6018 File fname = new File(systemDir, "uiderrors.txt"); 6019 return fname; 6020 } 6021 6022 static void reportSettingsProblem(int priority, String msg) { 6023 logCriticalInfo(priority, msg); 6024 } 6025 6026 static void logCriticalInfo(int priority, String msg) { 6027 Slog.println(priority, TAG, msg); 6028 EventLogTags.writePmCriticalInfo(msg); 6029 try { 6030 File fname = getSettingsProblemFile(); 6031 FileOutputStream out = new FileOutputStream(fname, true); 6032 PrintWriter pw = new FastPrintWriter(out); 6033 SimpleDateFormat formatter = new SimpleDateFormat(); 6034 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6035 pw.println(dateString + ": " + msg); 6036 pw.close(); 6037 FileUtils.setPermissions( 6038 fname.toString(), 6039 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6040 -1, -1); 6041 } catch (java.io.IOException e) { 6042 } 6043 } 6044 6045 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 6046 PackageParser.Package pkg, File srcFile, int parseFlags) 6047 throws PackageManagerException { 6048 if (ps != null 6049 && ps.codePath.equals(srcFile) 6050 && ps.timeStamp == srcFile.lastModified() 6051 && !isCompatSignatureUpdateNeeded(pkg) 6052 && !isRecoverSignatureUpdateNeeded(pkg)) { 6053 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6054 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6055 ArraySet<PublicKey> signingKs; 6056 synchronized (mPackages) { 6057 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6058 } 6059 if (ps.signatures.mSignatures != null 6060 && ps.signatures.mSignatures.length != 0 6061 && signingKs != null) { 6062 // Optimization: reuse the existing cached certificates 6063 // if the package appears to be unchanged. 6064 pkg.mSignatures = ps.signatures.mSignatures; 6065 pkg.mSigningKeys = signingKs; 6066 return; 6067 } 6068 6069 Slog.w(TAG, "PackageSetting for " + ps.name 6070 + " is missing signatures. Collecting certs again to recover them."); 6071 } else { 6072 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6073 } 6074 6075 try { 6076 pp.collectCertificates(pkg, parseFlags); 6077 pp.collectManifestDigest(pkg); 6078 } catch (PackageParserException e) { 6079 throw PackageManagerException.from(e); 6080 } 6081 } 6082 6083 /** 6084 * Traces a package scan. 6085 * @see #scanPackageLI(File, int, int, long, UserHandle) 6086 */ 6087 private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags, 6088 long currentTime, UserHandle user) throws PackageManagerException { 6089 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6090 try { 6091 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6092 } finally { 6093 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6094 } 6095 } 6096 6097 /** 6098 * Scans a package and returns the newly parsed package. 6099 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6100 */ 6101 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6102 long currentTime, UserHandle user) throws PackageManagerException { 6103 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6104 parseFlags |= mDefParseFlags; 6105 PackageParser pp = new PackageParser(); 6106 pp.setSeparateProcesses(mSeparateProcesses); 6107 pp.setOnlyCoreApps(mOnlyCore); 6108 pp.setDisplayMetrics(mMetrics); 6109 6110 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6111 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6112 } 6113 6114 final PackageParser.Package pkg; 6115 try { 6116 pkg = pp.parsePackage(scanFile, parseFlags); 6117 } catch (PackageParserException e) { 6118 throw PackageManagerException.from(e); 6119 } 6120 6121 PackageSetting ps = null; 6122 PackageSetting updatedPkg; 6123 // reader 6124 synchronized (mPackages) { 6125 // Look to see if we already know about this package. 6126 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6127 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6128 // This package has been renamed to its original name. Let's 6129 // use that. 6130 ps = mSettings.peekPackageLPr(oldName); 6131 } 6132 // If there was no original package, see one for the real package name. 6133 if (ps == null) { 6134 ps = mSettings.peekPackageLPr(pkg.packageName); 6135 } 6136 // Check to see if this package could be hiding/updating a system 6137 // package. Must look for it either under the original or real 6138 // package name depending on our state. 6139 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6140 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6141 } 6142 boolean updatedPkgBetter = false; 6143 // First check if this is a system package that may involve an update 6144 if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6145 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6146 // it needs to drop FLAG_PRIVILEGED. 6147 if (locationIsPrivileged(scanFile)) { 6148 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6149 } else { 6150 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6151 } 6152 6153 if (ps != null && !ps.codePath.equals(scanFile)) { 6154 // The path has changed from what was last scanned... check the 6155 // version of the new path against what we have stored to determine 6156 // what to do. 6157 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6158 if (pkg.mVersionCode <= ps.versionCode) { 6159 // The system package has been updated and the code path does not match 6160 // Ignore entry. Skip it. 6161 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6162 + " ignored: updated version " + ps.versionCode 6163 + " better than this " + pkg.mVersionCode); 6164 if (!updatedPkg.codePath.equals(scanFile)) { 6165 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 6166 + ps.name + " changing from " + updatedPkg.codePathString 6167 + " to " + scanFile); 6168 updatedPkg.codePath = scanFile; 6169 updatedPkg.codePathString = scanFile.toString(); 6170 updatedPkg.resourcePath = scanFile; 6171 updatedPkg.resourcePathString = scanFile.toString(); 6172 } 6173 updatedPkg.pkg = pkg; 6174 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6175 "Package " + ps.name + " at " + scanFile 6176 + " ignored: updated version " + ps.versionCode 6177 + " better than this " + pkg.mVersionCode); 6178 } else { 6179 // The current app on the system partition is better than 6180 // what we have updated to on the data partition; switch 6181 // back to the system partition version. 6182 // At this point, its safely assumed that package installation for 6183 // apps in system partition will go through. If not there won't be a working 6184 // version of the app 6185 // writer 6186 synchronized (mPackages) { 6187 // Just remove the loaded entries from package lists. 6188 mPackages.remove(ps.name); 6189 } 6190 6191 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6192 + " reverting from " + ps.codePathString 6193 + ": new version " + pkg.mVersionCode 6194 + " better than installed " + ps.versionCode); 6195 6196 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6197 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6198 synchronized (mInstallLock) { 6199 args.cleanUpResourcesLI(); 6200 } 6201 synchronized (mPackages) { 6202 mSettings.enableSystemPackageLPw(ps.name); 6203 } 6204 updatedPkgBetter = true; 6205 } 6206 } 6207 } 6208 6209 if (updatedPkg != null) { 6210 // An updated system app will not have the PARSE_IS_SYSTEM flag set 6211 // initially 6212 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 6213 6214 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 6215 // flag set initially 6216 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 6217 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 6218 } 6219 } 6220 6221 // Verify certificates against what was last scanned 6222 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 6223 6224 /* 6225 * A new system app appeared, but we already had a non-system one of the 6226 * same name installed earlier. 6227 */ 6228 boolean shouldHideSystemApp = false; 6229 if (updatedPkg == null && ps != null 6230 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 6231 /* 6232 * Check to make sure the signatures match first. If they don't, 6233 * wipe the installed application and its data. 6234 */ 6235 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 6236 != PackageManager.SIGNATURE_MATCH) { 6237 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 6238 + " signatures don't match existing userdata copy; removing"); 6239 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 6240 ps = null; 6241 } else { 6242 /* 6243 * If the newly-added system app is an older version than the 6244 * already installed version, hide it. It will be scanned later 6245 * and re-added like an update. 6246 */ 6247 if (pkg.mVersionCode <= ps.versionCode) { 6248 shouldHideSystemApp = true; 6249 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 6250 + " but new version " + pkg.mVersionCode + " better than installed " 6251 + ps.versionCode + "; hiding system"); 6252 } else { 6253 /* 6254 * The newly found system app is a newer version that the 6255 * one previously installed. Simply remove the 6256 * already-installed application and replace it with our own 6257 * while keeping the application data. 6258 */ 6259 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6260 + " reverting from " + ps.codePathString + ": new version " 6261 + pkg.mVersionCode + " better than installed " + ps.versionCode); 6262 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6263 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6264 synchronized (mInstallLock) { 6265 args.cleanUpResourcesLI(); 6266 } 6267 } 6268 } 6269 } 6270 6271 // The apk is forward locked (not public) if its code and resources 6272 // are kept in different files. (except for app in either system or 6273 // vendor path). 6274 // TODO grab this value from PackageSettings 6275 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6276 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 6277 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 6278 } 6279 } 6280 6281 // TODO: extend to support forward-locked splits 6282 String resourcePath = null; 6283 String baseResourcePath = null; 6284 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 6285 if (ps != null && ps.resourcePathString != null) { 6286 resourcePath = ps.resourcePathString; 6287 baseResourcePath = ps.resourcePathString; 6288 } else { 6289 // Should not happen at all. Just log an error. 6290 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 6291 } 6292 } else { 6293 resourcePath = pkg.codePath; 6294 baseResourcePath = pkg.baseCodePath; 6295 } 6296 6297 // Set application objects path explicitly. 6298 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 6299 pkg.applicationInfo.setCodePath(pkg.codePath); 6300 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 6301 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 6302 pkg.applicationInfo.setResourcePath(resourcePath); 6303 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 6304 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 6305 6306 // Note that we invoke the following method only if we are about to unpack an application 6307 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 6308 | SCAN_UPDATE_SIGNATURE, currentTime, user); 6309 6310 /* 6311 * If the system app should be overridden by a previously installed 6312 * data, hide the system app now and let the /data/app scan pick it up 6313 * again. 6314 */ 6315 if (shouldHideSystemApp) { 6316 synchronized (mPackages) { 6317 mSettings.disableSystemPackageLPw(pkg.packageName); 6318 } 6319 } 6320 6321 return scannedPkg; 6322 } 6323 6324 private static String fixProcessName(String defProcessName, 6325 String processName, int uid) { 6326 if (processName == null) { 6327 return defProcessName; 6328 } 6329 return processName; 6330 } 6331 6332 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 6333 throws PackageManagerException { 6334 if (pkgSetting.signatures.mSignatures != null) { 6335 // Already existing package. Make sure signatures match 6336 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 6337 == PackageManager.SIGNATURE_MATCH; 6338 if (!match) { 6339 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 6340 == PackageManager.SIGNATURE_MATCH; 6341 } 6342 if (!match) { 6343 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 6344 == PackageManager.SIGNATURE_MATCH; 6345 } 6346 if (!match) { 6347 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 6348 + pkg.packageName + " signatures do not match the " 6349 + "previously installed version; ignoring!"); 6350 } 6351 } 6352 6353 // Check for shared user signatures 6354 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 6355 // Already existing package. Make sure signatures match 6356 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6357 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 6358 if (!match) { 6359 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 6360 == PackageManager.SIGNATURE_MATCH; 6361 } 6362 if (!match) { 6363 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 6364 == PackageManager.SIGNATURE_MATCH; 6365 } 6366 if (!match) { 6367 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 6368 "Package " + pkg.packageName 6369 + " has no signatures that match those in shared user " 6370 + pkgSetting.sharedUser.name + "; ignoring!"); 6371 } 6372 } 6373 } 6374 6375 /** 6376 * Enforces that only the system UID or root's UID can call a method exposed 6377 * via Binder. 6378 * 6379 * @param message used as message if SecurityException is thrown 6380 * @throws SecurityException if the caller is not system or root 6381 */ 6382 private static final void enforceSystemOrRoot(String message) { 6383 final int uid = Binder.getCallingUid(); 6384 if (uid != Process.SYSTEM_UID && uid != 0) { 6385 throw new SecurityException(message); 6386 } 6387 } 6388 6389 @Override 6390 public void performFstrimIfNeeded() { 6391 enforceSystemOrRoot("Only the system can request fstrim"); 6392 6393 // Before everything else, see whether we need to fstrim. 6394 try { 6395 IMountService ms = PackageHelper.getMountService(); 6396 if (ms != null) { 6397 final boolean isUpgrade = isUpgrade(); 6398 boolean doTrim = isUpgrade; 6399 if (doTrim) { 6400 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 6401 } else { 6402 final long interval = android.provider.Settings.Global.getLong( 6403 mContext.getContentResolver(), 6404 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 6405 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 6406 if (interval > 0) { 6407 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 6408 if (timeSinceLast > interval) { 6409 doTrim = true; 6410 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 6411 + "; running immediately"); 6412 } 6413 } 6414 } 6415 if (doTrim) { 6416 if (!isFirstBoot()) { 6417 try { 6418 ActivityManagerNative.getDefault().showBootMessage( 6419 mContext.getResources().getString( 6420 R.string.android_upgrading_fstrim), true); 6421 } catch (RemoteException e) { 6422 } 6423 } 6424 ms.runMaintenance(); 6425 } 6426 } else { 6427 Slog.e(TAG, "Mount service unavailable!"); 6428 } 6429 } catch (RemoteException e) { 6430 // Can't happen; MountService is local 6431 } 6432 } 6433 6434 private ArraySet<String> getPackageNamesForIntent(Intent intent, int userId) { 6435 List<ResolveInfo> ris = null; 6436 try { 6437 ris = AppGlobals.getPackageManager().queryIntentReceivers( 6438 intent, null, 0, userId); 6439 } catch (RemoteException e) { 6440 } 6441 ArraySet<String> pkgNames = new ArraySet<String>(); 6442 if (ris != null) { 6443 for (ResolveInfo ri : ris) { 6444 pkgNames.add(ri.activityInfo.packageName); 6445 } 6446 } 6447 return pkgNames; 6448 } 6449 6450 @Override 6451 public void notifyPackageUse(String packageName) { 6452 synchronized (mPackages) { 6453 PackageParser.Package p = mPackages.get(packageName); 6454 if (p == null) { 6455 return; 6456 } 6457 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6458 } 6459 } 6460 6461 @Override 6462 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6463 return performDexOptTraced(packageName, instructionSet); 6464 } 6465 6466 public boolean performDexOpt(String packageName, String instructionSet) { 6467 return performDexOptTraced(packageName, instructionSet); 6468 } 6469 6470 private boolean performDexOptTraced(String packageName, String instructionSet) { 6471 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 6472 try { 6473 return performDexOptInternal(packageName, instructionSet); 6474 } finally { 6475 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6476 } 6477 } 6478 6479 private boolean performDexOptInternal(String packageName, String instructionSet) { 6480 PackageParser.Package p; 6481 final String targetInstructionSet; 6482 synchronized (mPackages) { 6483 p = mPackages.get(packageName); 6484 if (p == null) { 6485 return false; 6486 } 6487 mPackageUsage.write(false); 6488 6489 targetInstructionSet = instructionSet != null ? instructionSet : 6490 getPrimaryInstructionSet(p.applicationInfo); 6491 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 6492 return false; 6493 } 6494 } 6495 long callingId = Binder.clearCallingIdentity(); 6496 try { 6497 synchronized (mInstallLock) { 6498 final String[] instructionSets = new String[] { targetInstructionSet }; 6499 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 6500 true /* inclDependencies */); 6501 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6502 } 6503 } finally { 6504 Binder.restoreCallingIdentity(callingId); 6505 } 6506 } 6507 6508 public ArraySet<String> getPackagesThatNeedDexOpt() { 6509 ArraySet<String> pkgs = null; 6510 synchronized (mPackages) { 6511 for (PackageParser.Package p : mPackages.values()) { 6512 if (DEBUG_DEXOPT) { 6513 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 6514 } 6515 if (!p.mDexOptPerformed.isEmpty()) { 6516 continue; 6517 } 6518 if (pkgs == null) { 6519 pkgs = new ArraySet<String>(); 6520 } 6521 pkgs.add(p.packageName); 6522 } 6523 } 6524 return pkgs; 6525 } 6526 6527 public void shutdown() { 6528 mPackageUsage.write(true); 6529 } 6530 6531 @Override 6532 public void forceDexOpt(String packageName) { 6533 enforceSystemOrRoot("forceDexOpt"); 6534 6535 PackageParser.Package pkg; 6536 synchronized (mPackages) { 6537 pkg = mPackages.get(packageName); 6538 if (pkg == null) { 6539 throw new IllegalArgumentException("Missing package: " + packageName); 6540 } 6541 } 6542 6543 synchronized (mInstallLock) { 6544 final String[] instructionSets = new String[] { 6545 getPrimaryInstructionSet(pkg.applicationInfo) }; 6546 6547 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 6548 6549 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 6550 true /* inclDependencies */); 6551 6552 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6553 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 6554 throw new IllegalStateException("Failed to dexopt: " + res); 6555 } 6556 } 6557 } 6558 6559 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 6560 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 6561 Slog.w(TAG, "Unable to update from " + oldPkg.name 6562 + " to " + newPkg.packageName 6563 + ": old package not in system partition"); 6564 return false; 6565 } else if (mPackages.get(oldPkg.name) != null) { 6566 Slog.w(TAG, "Unable to update from " + oldPkg.name 6567 + " to " + newPkg.packageName 6568 + ": old package still exists"); 6569 return false; 6570 } 6571 return true; 6572 } 6573 6574 private void createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) 6575 throws PackageManagerException { 6576 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 6577 if (res != 0) { 6578 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6579 "Failed to install " + packageName + ": " + res); 6580 } 6581 6582 final int[] users = sUserManager.getUserIds(); 6583 for (int user : users) { 6584 if (user != 0) { 6585 res = mInstaller.createUserData(volumeUuid, packageName, 6586 UserHandle.getUid(user, uid), user, seinfo); 6587 if (res != 0) { 6588 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6589 "Failed to createUserData " + packageName + ": " + res); 6590 } 6591 } 6592 } 6593 } 6594 6595 private int removeDataDirsLI(String volumeUuid, String packageName) { 6596 int[] users = sUserManager.getUserIds(); 6597 int res = 0; 6598 for (int user : users) { 6599 int resInner = mInstaller.remove(volumeUuid, packageName, user); 6600 if (resInner < 0) { 6601 res = resInner; 6602 } 6603 } 6604 6605 return res; 6606 } 6607 6608 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 6609 int[] users = sUserManager.getUserIds(); 6610 int res = 0; 6611 for (int user : users) { 6612 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 6613 if (resInner < 0) { 6614 res = resInner; 6615 } 6616 } 6617 return res; 6618 } 6619 6620 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 6621 PackageParser.Package changingLib) { 6622 if (file.path != null) { 6623 usesLibraryFiles.add(file.path); 6624 return; 6625 } 6626 PackageParser.Package p = mPackages.get(file.apk); 6627 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 6628 // If we are doing this while in the middle of updating a library apk, 6629 // then we need to make sure to use that new apk for determining the 6630 // dependencies here. (We haven't yet finished committing the new apk 6631 // to the package manager state.) 6632 if (p == null || p.packageName.equals(changingLib.packageName)) { 6633 p = changingLib; 6634 } 6635 } 6636 if (p != null) { 6637 usesLibraryFiles.addAll(p.getAllCodePaths()); 6638 } 6639 } 6640 6641 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 6642 PackageParser.Package changingLib) throws PackageManagerException { 6643 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 6644 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 6645 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 6646 for (int i=0; i<N; i++) { 6647 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 6648 if (file == null) { 6649 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 6650 "Package " + pkg.packageName + " requires unavailable shared library " 6651 + pkg.usesLibraries.get(i) + "; failing!"); 6652 } 6653 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6654 } 6655 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 6656 for (int i=0; i<N; i++) { 6657 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 6658 if (file == null) { 6659 Slog.w(TAG, "Package " + pkg.packageName 6660 + " desires unavailable shared library " 6661 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 6662 } else { 6663 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6664 } 6665 } 6666 N = usesLibraryFiles.size(); 6667 if (N > 0) { 6668 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 6669 } else { 6670 pkg.usesLibraryFiles = null; 6671 } 6672 } 6673 } 6674 6675 private static boolean hasString(List<String> list, List<String> which) { 6676 if (list == null) { 6677 return false; 6678 } 6679 for (int i=list.size()-1; i>=0; i--) { 6680 for (int j=which.size()-1; j>=0; j--) { 6681 if (which.get(j).equals(list.get(i))) { 6682 return true; 6683 } 6684 } 6685 } 6686 return false; 6687 } 6688 6689 private void updateAllSharedLibrariesLPw() { 6690 for (PackageParser.Package pkg : mPackages.values()) { 6691 try { 6692 updateSharedLibrariesLPw(pkg, null); 6693 } catch (PackageManagerException e) { 6694 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6695 } 6696 } 6697 } 6698 6699 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 6700 PackageParser.Package changingPkg) { 6701 ArrayList<PackageParser.Package> res = null; 6702 for (PackageParser.Package pkg : mPackages.values()) { 6703 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 6704 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 6705 if (res == null) { 6706 res = new ArrayList<PackageParser.Package>(); 6707 } 6708 res.add(pkg); 6709 try { 6710 updateSharedLibrariesLPw(pkg, changingPkg); 6711 } catch (PackageManagerException e) { 6712 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6713 } 6714 } 6715 } 6716 return res; 6717 } 6718 6719 /** 6720 * Derive the value of the {@code cpuAbiOverride} based on the provided 6721 * value and an optional stored value from the package settings. 6722 */ 6723 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 6724 String cpuAbiOverride = null; 6725 6726 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 6727 cpuAbiOverride = null; 6728 } else if (abiOverride != null) { 6729 cpuAbiOverride = abiOverride; 6730 } else if (settings != null) { 6731 cpuAbiOverride = settings.cpuAbiOverrideString; 6732 } 6733 6734 return cpuAbiOverride; 6735 } 6736 6737 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags, 6738 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6739 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6740 try { 6741 return scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user); 6742 } finally { 6743 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6744 } 6745 } 6746 6747 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 6748 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6749 boolean success = false; 6750 try { 6751 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 6752 currentTime, user); 6753 success = true; 6754 return res; 6755 } finally { 6756 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 6757 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 6758 } 6759 } 6760 } 6761 6762 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 6763 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6764 final File scanFile = new File(pkg.codePath); 6765 if (pkg.applicationInfo.getCodePath() == null || 6766 pkg.applicationInfo.getResourcePath() == null) { 6767 // Bail out. The resource and code paths haven't been set. 6768 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 6769 "Code and resource paths haven't been set correctly"); 6770 } 6771 6772 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 6773 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 6774 } else { 6775 // Only allow system apps to be flagged as core apps. 6776 pkg.coreApp = false; 6777 } 6778 6779 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 6780 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6781 } 6782 6783 if (mCustomResolverComponentName != null && 6784 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 6785 setUpCustomResolverActivity(pkg); 6786 } 6787 6788 if (pkg.packageName.equals("android")) { 6789 synchronized (mPackages) { 6790 if (mAndroidApplication != null) { 6791 Slog.w(TAG, "*************************************************"); 6792 Slog.w(TAG, "Core android package being redefined. Skipping."); 6793 Slog.w(TAG, " file=" + scanFile); 6794 Slog.w(TAG, "*************************************************"); 6795 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6796 "Core android package being redefined. Skipping."); 6797 } 6798 6799 // Set up information for our fall-back user intent resolution activity. 6800 mPlatformPackage = pkg; 6801 pkg.mVersionCode = mSdkVersion; 6802 mAndroidApplication = pkg.applicationInfo; 6803 6804 if (!mResolverReplaced) { 6805 mResolveActivity.applicationInfo = mAndroidApplication; 6806 mResolveActivity.name = ResolverActivity.class.getName(); 6807 mResolveActivity.packageName = mAndroidApplication.packageName; 6808 mResolveActivity.processName = "system:ui"; 6809 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6810 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 6811 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 6812 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 6813 mResolveActivity.exported = true; 6814 mResolveActivity.enabled = true; 6815 mResolveInfo.activityInfo = mResolveActivity; 6816 mResolveInfo.priority = 0; 6817 mResolveInfo.preferredOrder = 0; 6818 mResolveInfo.match = 0; 6819 mResolveComponentName = new ComponentName( 6820 mAndroidApplication.packageName, mResolveActivity.name); 6821 } 6822 } 6823 } 6824 6825 if (DEBUG_PACKAGE_SCANNING) { 6826 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6827 Log.d(TAG, "Scanning package " + pkg.packageName); 6828 } 6829 6830 if (mPackages.containsKey(pkg.packageName) 6831 || mSharedLibraries.containsKey(pkg.packageName)) { 6832 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6833 "Application package " + pkg.packageName 6834 + " already installed. Skipping duplicate."); 6835 } 6836 6837 // If we're only installing presumed-existing packages, require that the 6838 // scanned APK is both already known and at the path previously established 6839 // for it. Previously unknown packages we pick up normally, but if we have an 6840 // a priori expectation about this package's install presence, enforce it. 6841 // With a singular exception for new system packages. When an OTA contains 6842 // a new system package, we allow the codepath to change from a system location 6843 // to the user-installed location. If we don't allow this change, any newer, 6844 // user-installed version of the application will be ignored. 6845 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 6846 if (mExpectingBetter.containsKey(pkg.packageName)) { 6847 logCriticalInfo(Log.WARN, 6848 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 6849 } else { 6850 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 6851 if (known != null) { 6852 if (DEBUG_PACKAGE_SCANNING) { 6853 Log.d(TAG, "Examining " + pkg.codePath 6854 + " and requiring known paths " + known.codePathString 6855 + " & " + known.resourcePathString); 6856 } 6857 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6858 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6859 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6860 "Application package " + pkg.packageName 6861 + " found at " + pkg.applicationInfo.getCodePath() 6862 + " but expected at " + known.codePathString + "; ignoring."); 6863 } 6864 } 6865 } 6866 } 6867 6868 // Initialize package source and resource directories 6869 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6870 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6871 6872 SharedUserSetting suid = null; 6873 PackageSetting pkgSetting = null; 6874 6875 if (!isSystemApp(pkg)) { 6876 // Only system apps can use these features. 6877 pkg.mOriginalPackages = null; 6878 pkg.mRealPackage = null; 6879 pkg.mAdoptPermissions = null; 6880 } 6881 6882 // writer 6883 synchronized (mPackages) { 6884 if (pkg.mSharedUserId != null) { 6885 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 6886 if (suid == null) { 6887 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6888 "Creating application package " + pkg.packageName 6889 + " for shared user failed"); 6890 } 6891 if (DEBUG_PACKAGE_SCANNING) { 6892 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6893 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 6894 + "): packages=" + suid.packages); 6895 } 6896 } 6897 6898 // Check if we are renaming from an original package name. 6899 PackageSetting origPackage = null; 6900 String realName = null; 6901 if (pkg.mOriginalPackages != null) { 6902 // This package may need to be renamed to a previously 6903 // installed name. Let's check on that... 6904 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 6905 if (pkg.mOriginalPackages.contains(renamed)) { 6906 // This package had originally been installed as the 6907 // original name, and we have already taken care of 6908 // transitioning to the new one. Just update the new 6909 // one to continue using the old name. 6910 realName = pkg.mRealPackage; 6911 if (!pkg.packageName.equals(renamed)) { 6912 // Callers into this function may have already taken 6913 // care of renaming the package; only do it here if 6914 // it is not already done. 6915 pkg.setPackageName(renamed); 6916 } 6917 6918 } else { 6919 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 6920 if ((origPackage = mSettings.peekPackageLPr( 6921 pkg.mOriginalPackages.get(i))) != null) { 6922 // We do have the package already installed under its 6923 // original name... should we use it? 6924 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 6925 // New package is not compatible with original. 6926 origPackage = null; 6927 continue; 6928 } else if (origPackage.sharedUser != null) { 6929 // Make sure uid is compatible between packages. 6930 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 6931 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 6932 + " to " + pkg.packageName + ": old uid " 6933 + origPackage.sharedUser.name 6934 + " differs from " + pkg.mSharedUserId); 6935 origPackage = null; 6936 continue; 6937 } 6938 } else { 6939 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6940 + pkg.packageName + " to old name " + origPackage.name); 6941 } 6942 break; 6943 } 6944 } 6945 } 6946 } 6947 6948 if (mTransferedPackages.contains(pkg.packageName)) { 6949 Slog.w(TAG, "Package " + pkg.packageName 6950 + " was transferred to another, but its .apk remains"); 6951 } 6952 6953 // Just create the setting, don't add it yet. For already existing packages 6954 // the PkgSetting exists already and doesn't have to be created. 6955 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6956 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6957 pkg.applicationInfo.primaryCpuAbi, 6958 pkg.applicationInfo.secondaryCpuAbi, 6959 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6960 user, false); 6961 if (pkgSetting == null) { 6962 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6963 "Creating application package " + pkg.packageName + " failed"); 6964 } 6965 6966 if (pkgSetting.origPackage != null) { 6967 // If we are first transitioning from an original package, 6968 // fix up the new package's name now. We need to do this after 6969 // looking up the package under its new name, so getPackageLP 6970 // can take care of fiddling things correctly. 6971 pkg.setPackageName(origPackage.name); 6972 6973 // File a report about this. 6974 String msg = "New package " + pkgSetting.realName 6975 + " renamed to replace old package " + pkgSetting.name; 6976 reportSettingsProblem(Log.WARN, msg); 6977 6978 // Make a note of it. 6979 mTransferedPackages.add(origPackage.name); 6980 6981 // No longer need to retain this. 6982 pkgSetting.origPackage = null; 6983 } 6984 6985 if (realName != null) { 6986 // Make a note of it. 6987 mTransferedPackages.add(pkg.packageName); 6988 } 6989 6990 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6991 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6992 } 6993 6994 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6995 // Check all shared libraries and map to their actual file path. 6996 // We only do this here for apps not on a system dir, because those 6997 // are the only ones that can fail an install due to this. We 6998 // will take care of the system apps by updating all of their 6999 // library paths after the scan is done. 7000 updateSharedLibrariesLPw(pkg, null); 7001 } 7002 7003 if (mFoundPolicyFile) { 7004 SELinuxMMAC.assignSeinfoValue(pkg); 7005 } 7006 7007 pkg.applicationInfo.uid = pkgSetting.appId; 7008 pkg.mExtras = pkgSetting; 7009 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 7010 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 7011 // We just determined the app is signed correctly, so bring 7012 // over the latest parsed certs. 7013 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7014 } else { 7015 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7016 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7017 "Package " + pkg.packageName + " upgrade keys do not match the " 7018 + "previously installed version"); 7019 } else { 7020 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7021 String msg = "System package " + pkg.packageName 7022 + " signature changed; retaining data."; 7023 reportSettingsProblem(Log.WARN, msg); 7024 } 7025 } 7026 } else { 7027 try { 7028 verifySignaturesLP(pkgSetting, pkg); 7029 // We just determined the app is signed correctly, so bring 7030 // over the latest parsed certs. 7031 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7032 } catch (PackageManagerException e) { 7033 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7034 throw e; 7035 } 7036 // The signature has changed, but this package is in the system 7037 // image... let's recover! 7038 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7039 // However... if this package is part of a shared user, but it 7040 // doesn't match the signature of the shared user, let's fail. 7041 // What this means is that you can't change the signatures 7042 // associated with an overall shared user, which doesn't seem all 7043 // that unreasonable. 7044 if (pkgSetting.sharedUser != null) { 7045 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7046 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 7047 throw new PackageManagerException( 7048 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 7049 "Signature mismatch for shared user : " 7050 + pkgSetting.sharedUser); 7051 } 7052 } 7053 // File a report about this. 7054 String msg = "System package " + pkg.packageName 7055 + " signature changed; retaining data."; 7056 reportSettingsProblem(Log.WARN, msg); 7057 } 7058 } 7059 // Verify that this new package doesn't have any content providers 7060 // that conflict with existing packages. Only do this if the 7061 // package isn't already installed, since we don't want to break 7062 // things that are installed. 7063 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 7064 final int N = pkg.providers.size(); 7065 int i; 7066 for (i=0; i<N; i++) { 7067 PackageParser.Provider p = pkg.providers.get(i); 7068 if (p.info.authority != null) { 7069 String names[] = p.info.authority.split(";"); 7070 for (int j = 0; j < names.length; j++) { 7071 if (mProvidersByAuthority.containsKey(names[j])) { 7072 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7073 final String otherPackageName = 7074 ((other != null && other.getComponentName() != null) ? 7075 other.getComponentName().getPackageName() : "?"); 7076 throw new PackageManagerException( 7077 INSTALL_FAILED_CONFLICTING_PROVIDER, 7078 "Can't install because provider name " + names[j] 7079 + " (in package " + pkg.applicationInfo.packageName 7080 + ") is already used by " + otherPackageName); 7081 } 7082 } 7083 } 7084 } 7085 } 7086 7087 if (pkg.mAdoptPermissions != null) { 7088 // This package wants to adopt ownership of permissions from 7089 // another package. 7090 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 7091 final String origName = pkg.mAdoptPermissions.get(i); 7092 final PackageSetting orig = mSettings.peekPackageLPr(origName); 7093 if (orig != null) { 7094 if (verifyPackageUpdateLPr(orig, pkg)) { 7095 Slog.i(TAG, "Adopting permissions from " + origName + " to " 7096 + pkg.packageName); 7097 mSettings.transferPermissionsLPw(origName, pkg.packageName); 7098 } 7099 } 7100 } 7101 } 7102 } 7103 7104 final String pkgName = pkg.packageName; 7105 7106 final long scanFileTime = scanFile.lastModified(); 7107 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 7108 pkg.applicationInfo.processName = fixProcessName( 7109 pkg.applicationInfo.packageName, 7110 pkg.applicationInfo.processName, 7111 pkg.applicationInfo.uid); 7112 7113 if (pkg != mPlatformPackage) { 7114 // This is a normal package, need to make its data directory. 7115 final File dataPath = Environment.getDataUserCredentialEncryptedPackageDirectory( 7116 pkg.volumeUuid, UserHandle.USER_SYSTEM, pkg.packageName); 7117 7118 boolean uidError = false; 7119 if (dataPath.exists()) { 7120 int currentUid = 0; 7121 try { 7122 StructStat stat = Os.stat(dataPath.getPath()); 7123 currentUid = stat.st_uid; 7124 } catch (ErrnoException e) { 7125 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 7126 } 7127 7128 // If we have mismatched owners for the data path, we have a problem. 7129 if (currentUid != pkg.applicationInfo.uid) { 7130 boolean recovered = false; 7131 if (currentUid == 0) { 7132 // The directory somehow became owned by root. Wow. 7133 // This is probably because the system was stopped while 7134 // installd was in the middle of messing with its libs 7135 // directory. Ask installd to fix that. 7136 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 7137 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 7138 if (ret >= 0) { 7139 recovered = true; 7140 String msg = "Package " + pkg.packageName 7141 + " unexpectedly changed to uid 0; recovered to " + 7142 + pkg.applicationInfo.uid; 7143 reportSettingsProblem(Log.WARN, msg); 7144 } 7145 } 7146 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 7147 || (scanFlags&SCAN_BOOTING) != 0)) { 7148 // If this is a system app, we can at least delete its 7149 // current data so the application will still work. 7150 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 7151 if (ret >= 0) { 7152 // TODO: Kill the processes first 7153 // Old data gone! 7154 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 7155 ? "System package " : "Third party package "; 7156 String msg = prefix + pkg.packageName 7157 + " has changed from uid: " 7158 + currentUid + " to " 7159 + pkg.applicationInfo.uid + "; old data erased"; 7160 reportSettingsProblem(Log.WARN, msg); 7161 recovered = true; 7162 } 7163 if (!recovered) { 7164 mHasSystemUidErrors = true; 7165 } 7166 } else if (!recovered) { 7167 // If we allow this install to proceed, we will be broken. 7168 // Abort, abort! 7169 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 7170 "scanPackageLI"); 7171 } 7172 if (!recovered) { 7173 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 7174 + pkg.applicationInfo.uid + "/fs_" 7175 + currentUid; 7176 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 7177 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 7178 String msg = "Package " + pkg.packageName 7179 + " has mismatched uid: " 7180 + currentUid + " on disk, " 7181 + pkg.applicationInfo.uid + " in settings"; 7182 // writer 7183 synchronized (mPackages) { 7184 mSettings.mReadMessages.append(msg); 7185 mSettings.mReadMessages.append('\n'); 7186 uidError = true; 7187 if (!pkgSetting.uidError) { 7188 reportSettingsProblem(Log.ERROR, msg); 7189 } 7190 } 7191 } 7192 } 7193 7194 // Ensure that directories are prepared 7195 createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 7196 pkg.applicationInfo.seinfo); 7197 7198 if (mShouldRestoreconData) { 7199 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 7200 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 7201 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 7202 } 7203 } else { 7204 if (DEBUG_PACKAGE_SCANNING) { 7205 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7206 Log.v(TAG, "Want this data dir: " + dataPath); 7207 } 7208 createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 7209 pkg.applicationInfo.seinfo); 7210 } 7211 7212 // Get all of our default paths setup 7213 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 7214 7215 pkgSetting.uidError = uidError; 7216 } 7217 7218 final String path = scanFile.getPath(); 7219 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 7220 7221 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 7222 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 7223 7224 // Some system apps still use directory structure for native libraries 7225 // in which case we might end up not detecting abi solely based on apk 7226 // structure. Try to detect abi based on directory structure. 7227 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 7228 pkg.applicationInfo.primaryCpuAbi == null) { 7229 setBundledAppAbisAndRoots(pkg, pkgSetting); 7230 setNativeLibraryPaths(pkg); 7231 } 7232 7233 } else { 7234 if ((scanFlags & SCAN_MOVE) != 0) { 7235 // We haven't run dex-opt for this move (since we've moved the compiled output too) 7236 // but we already have this packages package info in the PackageSetting. We just 7237 // use that and derive the native library path based on the new codepath. 7238 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 7239 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 7240 } 7241 7242 // Set native library paths again. For moves, the path will be updated based on the 7243 // ABIs we've determined above. For non-moves, the path will be updated based on the 7244 // ABIs we determined during compilation, but the path will depend on the final 7245 // package path (after the rename away from the stage path). 7246 setNativeLibraryPaths(pkg); 7247 } 7248 7249 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 7250 final int[] userIds = sUserManager.getUserIds(); 7251 synchronized (mInstallLock) { 7252 // Make sure all user data directories are ready to roll; we're okay 7253 // if they already exist 7254 if (!TextUtils.isEmpty(pkg.volumeUuid)) { 7255 for (int userId : userIds) { 7256 if (userId != UserHandle.USER_SYSTEM) { 7257 mInstaller.createUserData(pkg.volumeUuid, pkg.packageName, 7258 UserHandle.getUid(userId, pkg.applicationInfo.uid), userId, 7259 pkg.applicationInfo.seinfo); 7260 } 7261 } 7262 } 7263 7264 // Create a native library symlink only if we have native libraries 7265 // and if the native libraries are 32 bit libraries. We do not provide 7266 // this symlink for 64 bit libraries. 7267 if (pkg.applicationInfo.primaryCpuAbi != null && 7268 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 7269 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "linkNativeLib"); 7270 try { 7271 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 7272 for (int userId : userIds) { 7273 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 7274 nativeLibPath, userId) < 0) { 7275 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7276 "Failed linking native library dir (user=" + userId + ")"); 7277 } 7278 } 7279 } finally { 7280 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7281 } 7282 } 7283 } 7284 7285 // This is a special case for the "system" package, where the ABI is 7286 // dictated by the zygote configuration (and init.rc). We should keep track 7287 // of this ABI so that we can deal with "normal" applications that run under 7288 // the same UID correctly. 7289 if (mPlatformPackage == pkg) { 7290 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 7291 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 7292 } 7293 7294 // If there's a mismatch between the abi-override in the package setting 7295 // and the abiOverride specified for the install. Warn about this because we 7296 // would've already compiled the app without taking the package setting into 7297 // account. 7298 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 7299 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 7300 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 7301 " for package: " + pkg.packageName); 7302 } 7303 } 7304 7305 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7306 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7307 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 7308 7309 // Copy the derived override back to the parsed package, so that we can 7310 // update the package settings accordingly. 7311 pkg.cpuAbiOverride = cpuAbiOverride; 7312 7313 if (DEBUG_ABI_SELECTION) { 7314 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 7315 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 7316 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 7317 } 7318 7319 // Push the derived path down into PackageSettings so we know what to 7320 // clean up at uninstall time. 7321 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 7322 7323 if (DEBUG_ABI_SELECTION) { 7324 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 7325 " primary=" + pkg.applicationInfo.primaryCpuAbi + 7326 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 7327 } 7328 7329 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 7330 // We don't do this here during boot because we can do it all 7331 // at once after scanning all existing packages. 7332 // 7333 // We also do this *before* we perform dexopt on this package, so that 7334 // we can avoid redundant dexopts, and also to make sure we've got the 7335 // code and package path correct. 7336 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 7337 pkg, true /* boot complete */); 7338 } 7339 7340 if (mFactoryTest && pkg.requestedPermissions.contains( 7341 android.Manifest.permission.FACTORY_TEST)) { 7342 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 7343 } 7344 7345 ArrayList<PackageParser.Package> clientLibPkgs = null; 7346 7347 // writer 7348 synchronized (mPackages) { 7349 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7350 // Only system apps can add new shared libraries. 7351 if (pkg.libraryNames != null) { 7352 for (int i=0; i<pkg.libraryNames.size(); i++) { 7353 String name = pkg.libraryNames.get(i); 7354 boolean allowed = false; 7355 if (pkg.isUpdatedSystemApp()) { 7356 // New library entries can only be added through the 7357 // system image. This is important to get rid of a lot 7358 // of nasty edge cases: for example if we allowed a non- 7359 // system update of the app to add a library, then uninstalling 7360 // the update would make the library go away, and assumptions 7361 // we made such as through app install filtering would now 7362 // have allowed apps on the device which aren't compatible 7363 // with it. Better to just have the restriction here, be 7364 // conservative, and create many fewer cases that can negatively 7365 // impact the user experience. 7366 final PackageSetting sysPs = mSettings 7367 .getDisabledSystemPkgLPr(pkg.packageName); 7368 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 7369 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 7370 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 7371 allowed = true; 7372 break; 7373 } 7374 } 7375 } 7376 } else { 7377 allowed = true; 7378 } 7379 if (allowed) { 7380 if (!mSharedLibraries.containsKey(name)) { 7381 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 7382 } else if (!name.equals(pkg.packageName)) { 7383 Slog.w(TAG, "Package " + pkg.packageName + " library " 7384 + name + " already exists; skipping"); 7385 } 7386 } else { 7387 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 7388 + name + " that is not declared on system image; skipping"); 7389 } 7390 } 7391 if ((scanFlags & SCAN_BOOTING) == 0) { 7392 // If we are not booting, we need to update any applications 7393 // that are clients of our shared library. If we are booting, 7394 // this will all be done once the scan is complete. 7395 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 7396 } 7397 } 7398 } 7399 } 7400 7401 // Request the ActivityManager to kill the process(only for existing packages) 7402 // so that we do not end up in a confused state while the user is still using the older 7403 // version of the application while the new one gets installed. 7404 if ((scanFlags & SCAN_REPLACING) != 0) { 7405 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication"); 7406 7407 killApplication(pkg.applicationInfo.packageName, 7408 pkg.applicationInfo.uid, "replace pkg"); 7409 7410 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7411 } 7412 7413 // Also need to kill any apps that are dependent on the library. 7414 if (clientLibPkgs != null) { 7415 for (int i=0; i<clientLibPkgs.size(); i++) { 7416 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7417 killApplication(clientPkg.applicationInfo.packageName, 7418 clientPkg.applicationInfo.uid, "update lib"); 7419 } 7420 } 7421 7422 // Make sure we're not adding any bogus keyset info 7423 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7424 ksms.assertScannedPackageValid(pkg); 7425 7426 // writer 7427 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 7428 7429 boolean createIdmapFailed = false; 7430 synchronized (mPackages) { 7431 // We don't expect installation to fail beyond this point 7432 7433 // Add the new setting to mSettings 7434 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 7435 // Add the new setting to mPackages 7436 mPackages.put(pkg.applicationInfo.packageName, pkg); 7437 // Make sure we don't accidentally delete its data. 7438 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 7439 while (iter.hasNext()) { 7440 PackageCleanItem item = iter.next(); 7441 if (pkgName.equals(item.packageName)) { 7442 iter.remove(); 7443 } 7444 } 7445 7446 // Take care of first install / last update times. 7447 if (currentTime != 0) { 7448 if (pkgSetting.firstInstallTime == 0) { 7449 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7450 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7451 pkgSetting.lastUpdateTime = currentTime; 7452 } 7453 } else if (pkgSetting.firstInstallTime == 0) { 7454 // We need *something*. Take time time stamp of the file. 7455 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7456 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7457 if (scanFileTime != pkgSetting.timeStamp) { 7458 // A package on the system image has changed; consider this 7459 // to be an update. 7460 pkgSetting.lastUpdateTime = scanFileTime; 7461 } 7462 } 7463 7464 // Add the package's KeySets to the global KeySetManagerService 7465 ksms.addScannedPackageLPw(pkg); 7466 7467 int N = pkg.providers.size(); 7468 StringBuilder r = null; 7469 int i; 7470 for (i=0; i<N; i++) { 7471 PackageParser.Provider p = pkg.providers.get(i); 7472 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7473 p.info.processName, pkg.applicationInfo.uid); 7474 mProviders.addProvider(p); 7475 p.syncable = p.info.isSyncable; 7476 if (p.info.authority != null) { 7477 String names[] = p.info.authority.split(";"); 7478 p.info.authority = null; 7479 for (int j = 0; j < names.length; j++) { 7480 if (j == 1 && p.syncable) { 7481 // We only want the first authority for a provider to possibly be 7482 // syncable, so if we already added this provider using a different 7483 // authority clear the syncable flag. We copy the provider before 7484 // changing it because the mProviders object contains a reference 7485 // to a provider that we don't want to change. 7486 // Only do this for the second authority since the resulting provider 7487 // object can be the same for all future authorities for this provider. 7488 p = new PackageParser.Provider(p); 7489 p.syncable = false; 7490 } 7491 if (!mProvidersByAuthority.containsKey(names[j])) { 7492 mProvidersByAuthority.put(names[j], p); 7493 if (p.info.authority == null) { 7494 p.info.authority = names[j]; 7495 } else { 7496 p.info.authority = p.info.authority + ";" + names[j]; 7497 } 7498 if (DEBUG_PACKAGE_SCANNING) { 7499 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7500 Log.d(TAG, "Registered content provider: " + names[j] 7501 + ", className = " + p.info.name + ", isSyncable = " 7502 + p.info.isSyncable); 7503 } 7504 } else { 7505 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7506 Slog.w(TAG, "Skipping provider name " + names[j] + 7507 " (in package " + pkg.applicationInfo.packageName + 7508 "): name already used by " 7509 + ((other != null && other.getComponentName() != null) 7510 ? other.getComponentName().getPackageName() : "?")); 7511 } 7512 } 7513 } 7514 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7515 if (r == null) { 7516 r = new StringBuilder(256); 7517 } else { 7518 r.append(' '); 7519 } 7520 r.append(p.info.name); 7521 } 7522 } 7523 if (r != null) { 7524 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7525 } 7526 7527 N = pkg.services.size(); 7528 r = null; 7529 for (i=0; i<N; i++) { 7530 PackageParser.Service s = pkg.services.get(i); 7531 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 7532 s.info.processName, pkg.applicationInfo.uid); 7533 mServices.addService(s); 7534 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7535 if (r == null) { 7536 r = new StringBuilder(256); 7537 } else { 7538 r.append(' '); 7539 } 7540 r.append(s.info.name); 7541 } 7542 } 7543 if (r != null) { 7544 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 7545 } 7546 7547 N = pkg.receivers.size(); 7548 r = null; 7549 for (i=0; i<N; i++) { 7550 PackageParser.Activity a = pkg.receivers.get(i); 7551 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7552 a.info.processName, pkg.applicationInfo.uid); 7553 mReceivers.addActivity(a, "receiver"); 7554 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7555 if (r == null) { 7556 r = new StringBuilder(256); 7557 } else { 7558 r.append(' '); 7559 } 7560 r.append(a.info.name); 7561 } 7562 } 7563 if (r != null) { 7564 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 7565 } 7566 7567 N = pkg.activities.size(); 7568 r = null; 7569 for (i=0; i<N; i++) { 7570 PackageParser.Activity a = pkg.activities.get(i); 7571 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7572 a.info.processName, pkg.applicationInfo.uid); 7573 mActivities.addActivity(a, "activity"); 7574 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7575 if (r == null) { 7576 r = new StringBuilder(256); 7577 } else { 7578 r.append(' '); 7579 } 7580 r.append(a.info.name); 7581 } 7582 } 7583 if (r != null) { 7584 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 7585 } 7586 7587 N = pkg.permissionGroups.size(); 7588 r = null; 7589 for (i=0; i<N; i++) { 7590 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 7591 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 7592 if (cur == null) { 7593 mPermissionGroups.put(pg.info.name, pg); 7594 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7595 if (r == null) { 7596 r = new StringBuilder(256); 7597 } else { 7598 r.append(' '); 7599 } 7600 r.append(pg.info.name); 7601 } 7602 } else { 7603 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 7604 + pg.info.packageName + " ignored: original from " 7605 + cur.info.packageName); 7606 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7607 if (r == null) { 7608 r = new StringBuilder(256); 7609 } else { 7610 r.append(' '); 7611 } 7612 r.append("DUP:"); 7613 r.append(pg.info.name); 7614 } 7615 } 7616 } 7617 if (r != null) { 7618 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 7619 } 7620 7621 N = pkg.permissions.size(); 7622 r = null; 7623 for (i=0; i<N; i++) { 7624 PackageParser.Permission p = pkg.permissions.get(i); 7625 7626 // Assume by default that we did not install this permission into the system. 7627 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 7628 7629 // Now that permission groups have a special meaning, we ignore permission 7630 // groups for legacy apps to prevent unexpected behavior. In particular, 7631 // permissions for one app being granted to someone just becuase they happen 7632 // to be in a group defined by another app (before this had no implications). 7633 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 7634 p.group = mPermissionGroups.get(p.info.group); 7635 // Warn for a permission in an unknown group. 7636 if (p.info.group != null && p.group == null) { 7637 Slog.w(TAG, "Permission " + p.info.name + " from package " 7638 + p.info.packageName + " in an unknown group " + p.info.group); 7639 } 7640 } 7641 7642 ArrayMap<String, BasePermission> permissionMap = 7643 p.tree ? mSettings.mPermissionTrees 7644 : mSettings.mPermissions; 7645 BasePermission bp = permissionMap.get(p.info.name); 7646 7647 // Allow system apps to redefine non-system permissions 7648 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 7649 final boolean currentOwnerIsSystem = (bp.perm != null 7650 && isSystemApp(bp.perm.owner)); 7651 if (isSystemApp(p.owner)) { 7652 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 7653 // It's a built-in permission and no owner, take ownership now 7654 bp.packageSetting = pkgSetting; 7655 bp.perm = p; 7656 bp.uid = pkg.applicationInfo.uid; 7657 bp.sourcePackage = p.info.packageName; 7658 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7659 } else if (!currentOwnerIsSystem) { 7660 String msg = "New decl " + p.owner + " of permission " 7661 + p.info.name + " is system; overriding " + bp.sourcePackage; 7662 reportSettingsProblem(Log.WARN, msg); 7663 bp = null; 7664 } 7665 } 7666 } 7667 7668 if (bp == null) { 7669 bp = new BasePermission(p.info.name, p.info.packageName, 7670 BasePermission.TYPE_NORMAL); 7671 permissionMap.put(p.info.name, bp); 7672 } 7673 7674 if (bp.perm == null) { 7675 if (bp.sourcePackage == null 7676 || bp.sourcePackage.equals(p.info.packageName)) { 7677 BasePermission tree = findPermissionTreeLP(p.info.name); 7678 if (tree == null 7679 || tree.sourcePackage.equals(p.info.packageName)) { 7680 bp.packageSetting = pkgSetting; 7681 bp.perm = p; 7682 bp.uid = pkg.applicationInfo.uid; 7683 bp.sourcePackage = p.info.packageName; 7684 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7685 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7686 if (r == null) { 7687 r = new StringBuilder(256); 7688 } else { 7689 r.append(' '); 7690 } 7691 r.append(p.info.name); 7692 } 7693 } else { 7694 Slog.w(TAG, "Permission " + p.info.name + " from package " 7695 + p.info.packageName + " ignored: base tree " 7696 + tree.name + " is from package " 7697 + tree.sourcePackage); 7698 } 7699 } else { 7700 Slog.w(TAG, "Permission " + p.info.name + " from package " 7701 + p.info.packageName + " ignored: original from " 7702 + bp.sourcePackage); 7703 } 7704 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7705 if (r == null) { 7706 r = new StringBuilder(256); 7707 } else { 7708 r.append(' '); 7709 } 7710 r.append("DUP:"); 7711 r.append(p.info.name); 7712 } 7713 if (bp.perm == p) { 7714 bp.protectionLevel = p.info.protectionLevel; 7715 } 7716 } 7717 7718 if (r != null) { 7719 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 7720 } 7721 7722 N = pkg.instrumentation.size(); 7723 r = null; 7724 for (i=0; i<N; i++) { 7725 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7726 a.info.packageName = pkg.applicationInfo.packageName; 7727 a.info.sourceDir = pkg.applicationInfo.sourceDir; 7728 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 7729 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 7730 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 7731 a.info.dataDir = pkg.applicationInfo.dataDir; 7732 a.info.deviceEncryptedDataDir = pkg.applicationInfo.deviceEncryptedDataDir; 7733 a.info.credentialEncryptedDataDir = pkg.applicationInfo.credentialEncryptedDataDir; 7734 7735 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 7736 // need other information about the application, like the ABI and what not ? 7737 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 7738 mInstrumentation.put(a.getComponentName(), a); 7739 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7740 if (r == null) { 7741 r = new StringBuilder(256); 7742 } else { 7743 r.append(' '); 7744 } 7745 r.append(a.info.name); 7746 } 7747 } 7748 if (r != null) { 7749 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 7750 } 7751 7752 if (pkg.protectedBroadcasts != null) { 7753 N = pkg.protectedBroadcasts.size(); 7754 for (i=0; i<N; i++) { 7755 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 7756 } 7757 } 7758 7759 pkgSetting.setTimeStamp(scanFileTime); 7760 7761 // Create idmap files for pairs of (packages, overlay packages). 7762 // Note: "android", ie framework-res.apk, is handled by native layers. 7763 if (pkg.mOverlayTarget != null) { 7764 // This is an overlay package. 7765 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 7766 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 7767 mOverlays.put(pkg.mOverlayTarget, 7768 new ArrayMap<String, PackageParser.Package>()); 7769 } 7770 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 7771 map.put(pkg.packageName, pkg); 7772 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 7773 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 7774 createIdmapFailed = true; 7775 } 7776 } 7777 } else if (mOverlays.containsKey(pkg.packageName) && 7778 !pkg.packageName.equals("android")) { 7779 // This is a regular package, with one or more known overlay packages. 7780 createIdmapsForPackageLI(pkg); 7781 } 7782 } 7783 7784 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7785 7786 if (createIdmapFailed) { 7787 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7788 "scanPackageLI failed to createIdmap"); 7789 } 7790 return pkg; 7791 } 7792 7793 /** 7794 * Derive the ABI of a non-system package located at {@code scanFile}. This information 7795 * is derived purely on the basis of the contents of {@code scanFile} and 7796 * {@code cpuAbiOverride}. 7797 * 7798 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 7799 */ 7800 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 7801 String cpuAbiOverride, boolean extractLibs) 7802 throws PackageManagerException { 7803 // TODO: We can probably be smarter about this stuff. For installed apps, 7804 // we can calculate this information at install time once and for all. For 7805 // system apps, we can probably assume that this information doesn't change 7806 // after the first boot scan. As things stand, we do lots of unnecessary work. 7807 7808 // Give ourselves some initial paths; we'll come back for another 7809 // pass once we've determined ABI below. 7810 setNativeLibraryPaths(pkg); 7811 7812 // We would never need to extract libs for forward-locked and external packages, 7813 // since the container service will do it for us. We shouldn't attempt to 7814 // extract libs from system app when it was not updated. 7815 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 7816 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 7817 extractLibs = false; 7818 } 7819 7820 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7821 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7822 7823 NativeLibraryHelper.Handle handle = null; 7824 try { 7825 handle = NativeLibraryHelper.Handle.create(pkg); 7826 // TODO(multiArch): This can be null for apps that didn't go through the 7827 // usual installation process. We can calculate it again, like we 7828 // do during install time. 7829 // 7830 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7831 // unnecessary. 7832 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7833 7834 // Null out the abis so that they can be recalculated. 7835 pkg.applicationInfo.primaryCpuAbi = null; 7836 pkg.applicationInfo.secondaryCpuAbi = null; 7837 if (isMultiArch(pkg.applicationInfo)) { 7838 // Warn if we've set an abiOverride for multi-lib packages.. 7839 // By definition, we need to copy both 32 and 64 bit libraries for 7840 // such packages. 7841 if (pkg.cpuAbiOverride != null 7842 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7843 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7844 } 7845 7846 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7847 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7848 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7849 if (extractLibs) { 7850 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7851 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7852 useIsaSpecificSubdirs); 7853 } else { 7854 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7855 } 7856 } 7857 7858 maybeThrowExceptionForMultiArchCopy( 7859 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7860 7861 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7862 if (extractLibs) { 7863 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7864 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7865 useIsaSpecificSubdirs); 7866 } else { 7867 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7868 } 7869 } 7870 7871 maybeThrowExceptionForMultiArchCopy( 7872 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7873 7874 if (abi64 >= 0) { 7875 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7876 } 7877 7878 if (abi32 >= 0) { 7879 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7880 if (abi64 >= 0) { 7881 pkg.applicationInfo.secondaryCpuAbi = abi; 7882 } else { 7883 pkg.applicationInfo.primaryCpuAbi = abi; 7884 } 7885 } 7886 } else { 7887 String[] abiList = (cpuAbiOverride != null) ? 7888 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7889 7890 // Enable gross and lame hacks for apps that are built with old 7891 // SDK tools. We must scan their APKs for renderscript bitcode and 7892 // not launch them if it's present. Don't bother checking on devices 7893 // that don't have 64 bit support. 7894 boolean needsRenderScriptOverride = false; 7895 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7896 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7897 abiList = Build.SUPPORTED_32_BIT_ABIS; 7898 needsRenderScriptOverride = true; 7899 } 7900 7901 final int copyRet; 7902 if (extractLibs) { 7903 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7904 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7905 } else { 7906 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7907 } 7908 7909 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7910 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7911 "Error unpackaging native libs for app, errorCode=" + copyRet); 7912 } 7913 7914 if (copyRet >= 0) { 7915 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7916 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7917 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7918 } else if (needsRenderScriptOverride) { 7919 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7920 } 7921 } 7922 } catch (IOException ioe) { 7923 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7924 } finally { 7925 IoUtils.closeQuietly(handle); 7926 } 7927 7928 // Now that we've calculated the ABIs and determined if it's an internal app, 7929 // we will go ahead and populate the nativeLibraryPath. 7930 setNativeLibraryPaths(pkg); 7931 } 7932 7933 /** 7934 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7935 * i.e, so that all packages can be run inside a single process if required. 7936 * 7937 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7938 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7939 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7940 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7941 * updating a package that belongs to a shared user. 7942 * 7943 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7944 * adds unnecessary complexity. 7945 */ 7946 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7947 PackageParser.Package scannedPackage, boolean bootComplete) { 7948 String requiredInstructionSet = null; 7949 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7950 requiredInstructionSet = VMRuntime.getInstructionSet( 7951 scannedPackage.applicationInfo.primaryCpuAbi); 7952 } 7953 7954 PackageSetting requirer = null; 7955 for (PackageSetting ps : packagesForUser) { 7956 // If packagesForUser contains scannedPackage, we skip it. This will happen 7957 // when scannedPackage is an update of an existing package. Without this check, 7958 // we will never be able to change the ABI of any package belonging to a shared 7959 // user, even if it's compatible with other packages. 7960 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7961 if (ps.primaryCpuAbiString == null) { 7962 continue; 7963 } 7964 7965 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7966 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7967 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7968 // this but there's not much we can do. 7969 String errorMessage = "Instruction set mismatch, " 7970 + ((requirer == null) ? "[caller]" : requirer) 7971 + " requires " + requiredInstructionSet + " whereas " + ps 7972 + " requires " + instructionSet; 7973 Slog.w(TAG, errorMessage); 7974 } 7975 7976 if (requiredInstructionSet == null) { 7977 requiredInstructionSet = instructionSet; 7978 requirer = ps; 7979 } 7980 } 7981 } 7982 7983 if (requiredInstructionSet != null) { 7984 String adjustedAbi; 7985 if (requirer != null) { 7986 // requirer != null implies that either scannedPackage was null or that scannedPackage 7987 // did not require an ABI, in which case we have to adjust scannedPackage to match 7988 // the ABI of the set (which is the same as requirer's ABI) 7989 adjustedAbi = requirer.primaryCpuAbiString; 7990 if (scannedPackage != null) { 7991 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7992 } 7993 } else { 7994 // requirer == null implies that we're updating all ABIs in the set to 7995 // match scannedPackage. 7996 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7997 } 7998 7999 for (PackageSetting ps : packagesForUser) { 8000 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8001 if (ps.primaryCpuAbiString != null) { 8002 continue; 8003 } 8004 8005 ps.primaryCpuAbiString = adjustedAbi; 8006 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 8007 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 8008 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 8009 mInstaller.rmdex(ps.codePathString, 8010 getDexCodeInstructionSet(getPreferredInstructionSet())); 8011 } 8012 } 8013 } 8014 } 8015 } 8016 8017 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 8018 synchronized (mPackages) { 8019 mResolverReplaced = true; 8020 // Set up information for custom user intent resolution activity. 8021 mResolveActivity.applicationInfo = pkg.applicationInfo; 8022 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 8023 mResolveActivity.packageName = pkg.applicationInfo.packageName; 8024 mResolveActivity.processName = pkg.applicationInfo.packageName; 8025 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8026 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8027 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8028 mResolveActivity.theme = 0; 8029 mResolveActivity.exported = true; 8030 mResolveActivity.enabled = true; 8031 mResolveInfo.activityInfo = mResolveActivity; 8032 mResolveInfo.priority = 0; 8033 mResolveInfo.preferredOrder = 0; 8034 mResolveInfo.match = 0; 8035 mResolveComponentName = mCustomResolverComponentName; 8036 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 8037 mResolveComponentName); 8038 } 8039 } 8040 8041 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 8042 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 8043 8044 // Set up information for ephemeral installer activity 8045 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 8046 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 8047 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 8048 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 8049 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8050 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8051 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8052 mEphemeralInstallerActivity.theme = 0; 8053 mEphemeralInstallerActivity.exported = true; 8054 mEphemeralInstallerActivity.enabled = true; 8055 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 8056 mEphemeralInstallerInfo.priority = 0; 8057 mEphemeralInstallerInfo.preferredOrder = 0; 8058 mEphemeralInstallerInfo.match = 0; 8059 8060 if (DEBUG_EPHEMERAL) { 8061 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 8062 } 8063 } 8064 8065 private static String calculateBundledApkRoot(final String codePathString) { 8066 final File codePath = new File(codePathString); 8067 final File codeRoot; 8068 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 8069 codeRoot = Environment.getRootDirectory(); 8070 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 8071 codeRoot = Environment.getOemDirectory(); 8072 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 8073 codeRoot = Environment.getVendorDirectory(); 8074 } else { 8075 // Unrecognized code path; take its top real segment as the apk root: 8076 // e.g. /something/app/blah.apk => /something 8077 try { 8078 File f = codePath.getCanonicalFile(); 8079 File parent = f.getParentFile(); // non-null because codePath is a file 8080 File tmp; 8081 while ((tmp = parent.getParentFile()) != null) { 8082 f = parent; 8083 parent = tmp; 8084 } 8085 codeRoot = f; 8086 Slog.w(TAG, "Unrecognized code path " 8087 + codePath + " - using " + codeRoot); 8088 } catch (IOException e) { 8089 // Can't canonicalize the code path -- shenanigans? 8090 Slog.w(TAG, "Can't canonicalize code path " + codePath); 8091 return Environment.getRootDirectory().getPath(); 8092 } 8093 } 8094 return codeRoot.getPath(); 8095 } 8096 8097 /** 8098 * Derive and set the location of native libraries for the given package, 8099 * which varies depending on where and how the package was installed. 8100 */ 8101 private void setNativeLibraryPaths(PackageParser.Package pkg) { 8102 final ApplicationInfo info = pkg.applicationInfo; 8103 final String codePath = pkg.codePath; 8104 final File codeFile = new File(codePath); 8105 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 8106 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 8107 8108 info.nativeLibraryRootDir = null; 8109 info.nativeLibraryRootRequiresIsa = false; 8110 info.nativeLibraryDir = null; 8111 info.secondaryNativeLibraryDir = null; 8112 8113 if (isApkFile(codeFile)) { 8114 // Monolithic install 8115 if (bundledApp) { 8116 // If "/system/lib64/apkname" exists, assume that is the per-package 8117 // native library directory to use; otherwise use "/system/lib/apkname". 8118 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 8119 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 8120 getPrimaryInstructionSet(info)); 8121 8122 // This is a bundled system app so choose the path based on the ABI. 8123 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 8124 // is just the default path. 8125 final String apkName = deriveCodePathName(codePath); 8126 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 8127 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 8128 apkName).getAbsolutePath(); 8129 8130 if (info.secondaryCpuAbi != null) { 8131 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 8132 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 8133 secondaryLibDir, apkName).getAbsolutePath(); 8134 } 8135 } else if (asecApp) { 8136 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 8137 .getAbsolutePath(); 8138 } else { 8139 final String apkName = deriveCodePathName(codePath); 8140 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 8141 .getAbsolutePath(); 8142 } 8143 8144 info.nativeLibraryRootRequiresIsa = false; 8145 info.nativeLibraryDir = info.nativeLibraryRootDir; 8146 } else { 8147 // Cluster install 8148 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 8149 info.nativeLibraryRootRequiresIsa = true; 8150 8151 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 8152 getPrimaryInstructionSet(info)).getAbsolutePath(); 8153 8154 if (info.secondaryCpuAbi != null) { 8155 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 8156 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 8157 } 8158 } 8159 } 8160 8161 /** 8162 * Calculate the abis and roots for a bundled app. These can uniquely 8163 * be determined from the contents of the system partition, i.e whether 8164 * it contains 64 or 32 bit shared libraries etc. We do not validate any 8165 * of this information, and instead assume that the system was built 8166 * sensibly. 8167 */ 8168 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 8169 PackageSetting pkgSetting) { 8170 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 8171 8172 // If "/system/lib64/apkname" exists, assume that is the per-package 8173 // native library directory to use; otherwise use "/system/lib/apkname". 8174 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 8175 setBundledAppAbi(pkg, apkRoot, apkName); 8176 // pkgSetting might be null during rescan following uninstall of updates 8177 // to a bundled app, so accommodate that possibility. The settings in 8178 // that case will be established later from the parsed package. 8179 // 8180 // If the settings aren't null, sync them up with what we've just derived. 8181 // note that apkRoot isn't stored in the package settings. 8182 if (pkgSetting != null) { 8183 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8184 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8185 } 8186 } 8187 8188 /** 8189 * Deduces the ABI of a bundled app and sets the relevant fields on the 8190 * parsed pkg object. 8191 * 8192 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 8193 * under which system libraries are installed. 8194 * @param apkName the name of the installed package. 8195 */ 8196 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 8197 final File codeFile = new File(pkg.codePath); 8198 8199 final boolean has64BitLibs; 8200 final boolean has32BitLibs; 8201 if (isApkFile(codeFile)) { 8202 // Monolithic install 8203 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 8204 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 8205 } else { 8206 // Cluster install 8207 final File rootDir = new File(codeFile, LIB_DIR_NAME); 8208 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 8209 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 8210 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 8211 has64BitLibs = (new File(rootDir, isa)).exists(); 8212 } else { 8213 has64BitLibs = false; 8214 } 8215 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 8216 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 8217 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 8218 has32BitLibs = (new File(rootDir, isa)).exists(); 8219 } else { 8220 has32BitLibs = false; 8221 } 8222 } 8223 8224 if (has64BitLibs && !has32BitLibs) { 8225 // The package has 64 bit libs, but not 32 bit libs. Its primary 8226 // ABI should be 64 bit. We can safely assume here that the bundled 8227 // native libraries correspond to the most preferred ABI in the list. 8228 8229 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8230 pkg.applicationInfo.secondaryCpuAbi = null; 8231 } else if (has32BitLibs && !has64BitLibs) { 8232 // The package has 32 bit libs but not 64 bit libs. Its primary 8233 // ABI should be 32 bit. 8234 8235 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8236 pkg.applicationInfo.secondaryCpuAbi = null; 8237 } else if (has32BitLibs && has64BitLibs) { 8238 // The application has both 64 and 32 bit bundled libraries. We check 8239 // here that the app declares multiArch support, and warn if it doesn't. 8240 // 8241 // We will be lenient here and record both ABIs. The primary will be the 8242 // ABI that's higher on the list, i.e, a device that's configured to prefer 8243 // 64 bit apps will see a 64 bit primary ABI, 8244 8245 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 8246 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 8247 } 8248 8249 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 8250 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8251 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8252 } else { 8253 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8254 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8255 } 8256 } else { 8257 pkg.applicationInfo.primaryCpuAbi = null; 8258 pkg.applicationInfo.secondaryCpuAbi = null; 8259 } 8260 } 8261 8262 private void killApplication(String pkgName, int appId, String reason) { 8263 // Request the ActivityManager to kill the process(only for existing packages) 8264 // so that we do not end up in a confused state while the user is still using the older 8265 // version of the application while the new one gets installed. 8266 IActivityManager am = ActivityManagerNative.getDefault(); 8267 if (am != null) { 8268 try { 8269 am.killApplicationWithAppId(pkgName, appId, reason); 8270 } catch (RemoteException e) { 8271 } 8272 } 8273 } 8274 8275 void removePackageLI(PackageSetting ps, boolean chatty) { 8276 if (DEBUG_INSTALL) { 8277 if (chatty) 8278 Log.d(TAG, "Removing package " + ps.name); 8279 } 8280 8281 // writer 8282 synchronized (mPackages) { 8283 mPackages.remove(ps.name); 8284 final PackageParser.Package pkg = ps.pkg; 8285 if (pkg != null) { 8286 cleanPackageDataStructuresLILPw(pkg, chatty); 8287 } 8288 } 8289 } 8290 8291 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 8292 if (DEBUG_INSTALL) { 8293 if (chatty) 8294 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 8295 } 8296 8297 // writer 8298 synchronized (mPackages) { 8299 mPackages.remove(pkg.applicationInfo.packageName); 8300 cleanPackageDataStructuresLILPw(pkg, chatty); 8301 } 8302 } 8303 8304 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 8305 int N = pkg.providers.size(); 8306 StringBuilder r = null; 8307 int i; 8308 for (i=0; i<N; i++) { 8309 PackageParser.Provider p = pkg.providers.get(i); 8310 mProviders.removeProvider(p); 8311 if (p.info.authority == null) { 8312 8313 /* There was another ContentProvider with this authority when 8314 * this app was installed so this authority is null, 8315 * Ignore it as we don't have to unregister the provider. 8316 */ 8317 continue; 8318 } 8319 String names[] = p.info.authority.split(";"); 8320 for (int j = 0; j < names.length; j++) { 8321 if (mProvidersByAuthority.get(names[j]) == p) { 8322 mProvidersByAuthority.remove(names[j]); 8323 if (DEBUG_REMOVE) { 8324 if (chatty) 8325 Log.d(TAG, "Unregistered content provider: " + names[j] 8326 + ", className = " + p.info.name + ", isSyncable = " 8327 + p.info.isSyncable); 8328 } 8329 } 8330 } 8331 if (DEBUG_REMOVE && chatty) { 8332 if (r == null) { 8333 r = new StringBuilder(256); 8334 } else { 8335 r.append(' '); 8336 } 8337 r.append(p.info.name); 8338 } 8339 } 8340 if (r != null) { 8341 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 8342 } 8343 8344 N = pkg.services.size(); 8345 r = null; 8346 for (i=0; i<N; i++) { 8347 PackageParser.Service s = pkg.services.get(i); 8348 mServices.removeService(s); 8349 if (chatty) { 8350 if (r == null) { 8351 r = new StringBuilder(256); 8352 } else { 8353 r.append(' '); 8354 } 8355 r.append(s.info.name); 8356 } 8357 } 8358 if (r != null) { 8359 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 8360 } 8361 8362 N = pkg.receivers.size(); 8363 r = null; 8364 for (i=0; i<N; i++) { 8365 PackageParser.Activity a = pkg.receivers.get(i); 8366 mReceivers.removeActivity(a, "receiver"); 8367 if (DEBUG_REMOVE && chatty) { 8368 if (r == null) { 8369 r = new StringBuilder(256); 8370 } else { 8371 r.append(' '); 8372 } 8373 r.append(a.info.name); 8374 } 8375 } 8376 if (r != null) { 8377 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 8378 } 8379 8380 N = pkg.activities.size(); 8381 r = null; 8382 for (i=0; i<N; i++) { 8383 PackageParser.Activity a = pkg.activities.get(i); 8384 mActivities.removeActivity(a, "activity"); 8385 if (DEBUG_REMOVE && chatty) { 8386 if (r == null) { 8387 r = new StringBuilder(256); 8388 } else { 8389 r.append(' '); 8390 } 8391 r.append(a.info.name); 8392 } 8393 } 8394 if (r != null) { 8395 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 8396 } 8397 8398 N = pkg.permissions.size(); 8399 r = null; 8400 for (i=0; i<N; i++) { 8401 PackageParser.Permission p = pkg.permissions.get(i); 8402 BasePermission bp = mSettings.mPermissions.get(p.info.name); 8403 if (bp == null) { 8404 bp = mSettings.mPermissionTrees.get(p.info.name); 8405 } 8406 if (bp != null && bp.perm == p) { 8407 bp.perm = null; 8408 if (DEBUG_REMOVE && chatty) { 8409 if (r == null) { 8410 r = new StringBuilder(256); 8411 } else { 8412 r.append(' '); 8413 } 8414 r.append(p.info.name); 8415 } 8416 } 8417 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8418 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 8419 if (appOpPkgs != null) { 8420 appOpPkgs.remove(pkg.packageName); 8421 } 8422 } 8423 } 8424 if (r != null) { 8425 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8426 } 8427 8428 N = pkg.requestedPermissions.size(); 8429 r = null; 8430 for (i=0; i<N; i++) { 8431 String perm = pkg.requestedPermissions.get(i); 8432 BasePermission bp = mSettings.mPermissions.get(perm); 8433 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8434 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 8435 if (appOpPkgs != null) { 8436 appOpPkgs.remove(pkg.packageName); 8437 if (appOpPkgs.isEmpty()) { 8438 mAppOpPermissionPackages.remove(perm); 8439 } 8440 } 8441 } 8442 } 8443 if (r != null) { 8444 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8445 } 8446 8447 N = pkg.instrumentation.size(); 8448 r = null; 8449 for (i=0; i<N; i++) { 8450 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8451 mInstrumentation.remove(a.getComponentName()); 8452 if (DEBUG_REMOVE && chatty) { 8453 if (r == null) { 8454 r = new StringBuilder(256); 8455 } else { 8456 r.append(' '); 8457 } 8458 r.append(a.info.name); 8459 } 8460 } 8461 if (r != null) { 8462 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 8463 } 8464 8465 r = null; 8466 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8467 // Only system apps can hold shared libraries. 8468 if (pkg.libraryNames != null) { 8469 for (i=0; i<pkg.libraryNames.size(); i++) { 8470 String name = pkg.libraryNames.get(i); 8471 SharedLibraryEntry cur = mSharedLibraries.get(name); 8472 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 8473 mSharedLibraries.remove(name); 8474 if (DEBUG_REMOVE && chatty) { 8475 if (r == null) { 8476 r = new StringBuilder(256); 8477 } else { 8478 r.append(' '); 8479 } 8480 r.append(name); 8481 } 8482 } 8483 } 8484 } 8485 } 8486 if (r != null) { 8487 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 8488 } 8489 } 8490 8491 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 8492 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 8493 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 8494 return true; 8495 } 8496 } 8497 return false; 8498 } 8499 8500 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 8501 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 8502 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 8503 8504 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 8505 int flags) { 8506 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 8507 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 8508 } 8509 8510 private void updatePermissionsLPw(String changingPkg, 8511 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 8512 // Make sure there are no dangling permission trees. 8513 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 8514 while (it.hasNext()) { 8515 final BasePermission bp = it.next(); 8516 if (bp.packageSetting == null) { 8517 // We may not yet have parsed the package, so just see if 8518 // we still know about its settings. 8519 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8520 } 8521 if (bp.packageSetting == null) { 8522 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 8523 + " from package " + bp.sourcePackage); 8524 it.remove(); 8525 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8526 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8527 Slog.i(TAG, "Removing old permission tree: " + bp.name 8528 + " from package " + bp.sourcePackage); 8529 flags |= UPDATE_PERMISSIONS_ALL; 8530 it.remove(); 8531 } 8532 } 8533 } 8534 8535 // Make sure all dynamic permissions have been assigned to a package, 8536 // and make sure there are no dangling permissions. 8537 it = mSettings.mPermissions.values().iterator(); 8538 while (it.hasNext()) { 8539 final BasePermission bp = it.next(); 8540 if (bp.type == BasePermission.TYPE_DYNAMIC) { 8541 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 8542 + bp.name + " pkg=" + bp.sourcePackage 8543 + " info=" + bp.pendingInfo); 8544 if (bp.packageSetting == null && bp.pendingInfo != null) { 8545 final BasePermission tree = findPermissionTreeLP(bp.name); 8546 if (tree != null && tree.perm != null) { 8547 bp.packageSetting = tree.packageSetting; 8548 bp.perm = new PackageParser.Permission(tree.perm.owner, 8549 new PermissionInfo(bp.pendingInfo)); 8550 bp.perm.info.packageName = tree.perm.info.packageName; 8551 bp.perm.info.name = bp.name; 8552 bp.uid = tree.uid; 8553 } 8554 } 8555 } 8556 if (bp.packageSetting == null) { 8557 // We may not yet have parsed the package, so just see if 8558 // we still know about its settings. 8559 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8560 } 8561 if (bp.packageSetting == null) { 8562 Slog.w(TAG, "Removing dangling permission: " + bp.name 8563 + " from package " + bp.sourcePackage); 8564 it.remove(); 8565 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8566 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8567 Slog.i(TAG, "Removing old permission: " + bp.name 8568 + " from package " + bp.sourcePackage); 8569 flags |= UPDATE_PERMISSIONS_ALL; 8570 it.remove(); 8571 } 8572 } 8573 } 8574 8575 // Now update the permissions for all packages, in particular 8576 // replace the granted permissions of the system packages. 8577 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 8578 for (PackageParser.Package pkg : mPackages.values()) { 8579 if (pkg != pkgInfo) { 8580 // Only replace for packages on requested volume 8581 final String volumeUuid = getVolumeUuidForPackage(pkg); 8582 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 8583 && Objects.equals(replaceVolumeUuid, volumeUuid); 8584 grantPermissionsLPw(pkg, replace, changingPkg); 8585 } 8586 } 8587 } 8588 8589 if (pkgInfo != null) { 8590 // Only replace for packages on requested volume 8591 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 8592 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 8593 && Objects.equals(replaceVolumeUuid, volumeUuid); 8594 grantPermissionsLPw(pkgInfo, replace, changingPkg); 8595 } 8596 } 8597 8598 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 8599 String packageOfInterest) { 8600 // IMPORTANT: There are two types of permissions: install and runtime. 8601 // Install time permissions are granted when the app is installed to 8602 // all device users and users added in the future. Runtime permissions 8603 // are granted at runtime explicitly to specific users. Normal and signature 8604 // protected permissions are install time permissions. Dangerous permissions 8605 // are install permissions if the app's target SDK is Lollipop MR1 or older, 8606 // otherwise they are runtime permissions. This function does not manage 8607 // runtime permissions except for the case an app targeting Lollipop MR1 8608 // being upgraded to target a newer SDK, in which case dangerous permissions 8609 // are transformed from install time to runtime ones. 8610 8611 final PackageSetting ps = (PackageSetting) pkg.mExtras; 8612 if (ps == null) { 8613 return; 8614 } 8615 8616 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 8617 8618 PermissionsState permissionsState = ps.getPermissionsState(); 8619 PermissionsState origPermissions = permissionsState; 8620 8621 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 8622 8623 boolean runtimePermissionsRevoked = false; 8624 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 8625 8626 boolean changedInstallPermission = false; 8627 8628 if (replace) { 8629 ps.installPermissionsFixed = false; 8630 if (!ps.isSharedUser()) { 8631 origPermissions = new PermissionsState(permissionsState); 8632 permissionsState.reset(); 8633 } else { 8634 // We need to know only about runtime permission changes since the 8635 // calling code always writes the install permissions state but 8636 // the runtime ones are written only if changed. The only cases of 8637 // changed runtime permissions here are promotion of an install to 8638 // runtime and revocation of a runtime from a shared user. 8639 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 8640 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 8641 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 8642 runtimePermissionsRevoked = true; 8643 } 8644 } 8645 } 8646 8647 permissionsState.setGlobalGids(mGlobalGids); 8648 8649 final int N = pkg.requestedPermissions.size(); 8650 for (int i=0; i<N; i++) { 8651 final String name = pkg.requestedPermissions.get(i); 8652 final BasePermission bp = mSettings.mPermissions.get(name); 8653 8654 if (DEBUG_INSTALL) { 8655 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 8656 } 8657 8658 if (bp == null || bp.packageSetting == null) { 8659 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8660 Slog.w(TAG, "Unknown permission " + name 8661 + " in package " + pkg.packageName); 8662 } 8663 continue; 8664 } 8665 8666 final String perm = bp.name; 8667 boolean allowedSig = false; 8668 int grant = GRANT_DENIED; 8669 8670 // Keep track of app op permissions. 8671 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8672 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 8673 if (pkgs == null) { 8674 pkgs = new ArraySet<>(); 8675 mAppOpPermissionPackages.put(bp.name, pkgs); 8676 } 8677 pkgs.add(pkg.packageName); 8678 } 8679 8680 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 8681 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 8682 >= Build.VERSION_CODES.M; 8683 switch (level) { 8684 case PermissionInfo.PROTECTION_NORMAL: { 8685 // For all apps normal permissions are install time ones. 8686 grant = GRANT_INSTALL; 8687 } break; 8688 8689 case PermissionInfo.PROTECTION_DANGEROUS: { 8690 // If a permission review is required for legacy apps we represent 8691 // their permissions as always granted runtime ones since we need 8692 // to keep the review required permission flag per user while an 8693 // install permission's state is shared across all users. 8694 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 8695 // For legacy apps dangerous permissions are install time ones. 8696 grant = GRANT_INSTALL; 8697 } else if (origPermissions.hasInstallPermission(bp.name)) { 8698 // For legacy apps that became modern, install becomes runtime. 8699 grant = GRANT_UPGRADE; 8700 } else if (mPromoteSystemApps 8701 && isSystemApp(ps) 8702 && mExistingSystemPackages.contains(ps.name)) { 8703 // For legacy system apps, install becomes runtime. 8704 // We cannot check hasInstallPermission() for system apps since those 8705 // permissions were granted implicitly and not persisted pre-M. 8706 grant = GRANT_UPGRADE; 8707 } else { 8708 // For modern apps keep runtime permissions unchanged. 8709 grant = GRANT_RUNTIME; 8710 } 8711 } break; 8712 8713 case PermissionInfo.PROTECTION_SIGNATURE: { 8714 // For all apps signature permissions are install time ones. 8715 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 8716 if (allowedSig) { 8717 grant = GRANT_INSTALL; 8718 } 8719 } break; 8720 } 8721 8722 if (DEBUG_INSTALL) { 8723 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 8724 } 8725 8726 if (grant != GRANT_DENIED) { 8727 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 8728 // If this is an existing, non-system package, then 8729 // we can't add any new permissions to it. 8730 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 8731 // Except... if this is a permission that was added 8732 // to the platform (note: need to only do this when 8733 // updating the platform). 8734 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 8735 grant = GRANT_DENIED; 8736 } 8737 } 8738 } 8739 8740 switch (grant) { 8741 case GRANT_INSTALL: { 8742 // Revoke this as runtime permission to handle the case of 8743 // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps 8744 for (int userId : UserManagerService.getInstance().getUserIds()) { 8745 if (origPermissions.getRuntimePermissionState( 8746 bp.name, userId) != null) { 8747 // Revoke the runtime permission and clear the flags. 8748 origPermissions.revokeRuntimePermission(bp, userId); 8749 origPermissions.updatePermissionFlags(bp, userId, 8750 PackageManager.MASK_PERMISSION_FLAGS, 0); 8751 // If we revoked a permission permission, we have to write. 8752 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8753 changedRuntimePermissionUserIds, userId); 8754 } 8755 } 8756 // Grant an install permission. 8757 if (permissionsState.grantInstallPermission(bp) != 8758 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8759 changedInstallPermission = true; 8760 } 8761 } break; 8762 8763 case GRANT_RUNTIME: { 8764 // Grant previously granted runtime permissions. 8765 for (int userId : UserManagerService.getInstance().getUserIds()) { 8766 PermissionState permissionState = origPermissions 8767 .getRuntimePermissionState(bp.name, userId); 8768 int flags = permissionState != null 8769 ? permissionState.getFlags() : 0; 8770 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8771 if (permissionsState.grantRuntimePermission(bp, userId) == 8772 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8773 // If we cannot put the permission as it was, we have to write. 8774 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8775 changedRuntimePermissionUserIds, userId); 8776 } 8777 // If the app supports runtime permissions no need for a review. 8778 if (Build.PERMISSIONS_REVIEW_REQUIRED 8779 && appSupportsRuntimePermissions 8780 && (flags & PackageManager 8781 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 8782 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 8783 // Since we changed the flags, we have to write. 8784 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8785 changedRuntimePermissionUserIds, userId); 8786 } 8787 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 8788 && !appSupportsRuntimePermissions) { 8789 // For legacy apps that need a permission review, every new 8790 // runtime permission is granted but it is pending a review. 8791 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 8792 permissionsState.grantRuntimePermission(bp, userId); 8793 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 8794 // We changed the permission and flags, hence have to write. 8795 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8796 changedRuntimePermissionUserIds, userId); 8797 } 8798 } 8799 // Propagate the permission flags. 8800 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 8801 } 8802 } break; 8803 8804 case GRANT_UPGRADE: { 8805 // Grant runtime permissions for a previously held install permission. 8806 PermissionState permissionState = origPermissions 8807 .getInstallPermissionState(bp.name); 8808 final int flags = permissionState != null ? permissionState.getFlags() : 0; 8809 8810 if (origPermissions.revokeInstallPermission(bp) 8811 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 8812 // We will be transferring the permission flags, so clear them. 8813 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 8814 PackageManager.MASK_PERMISSION_FLAGS, 0); 8815 changedInstallPermission = true; 8816 } 8817 8818 // If the permission is not to be promoted to runtime we ignore it and 8819 // also its other flags as they are not applicable to install permissions. 8820 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 8821 for (int userId : currentUserIds) { 8822 if (permissionsState.grantRuntimePermission(bp, userId) != 8823 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8824 // Transfer the permission flags. 8825 permissionsState.updatePermissionFlags(bp, userId, 8826 flags, flags); 8827 // If we granted the permission, we have to write. 8828 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8829 changedRuntimePermissionUserIds, userId); 8830 } 8831 } 8832 } 8833 } break; 8834 8835 default: { 8836 if (packageOfInterest == null 8837 || packageOfInterest.equals(pkg.packageName)) { 8838 Slog.w(TAG, "Not granting permission " + perm 8839 + " to package " + pkg.packageName 8840 + " because it was previously installed without"); 8841 } 8842 } break; 8843 } 8844 } else { 8845 if (permissionsState.revokeInstallPermission(bp) != 8846 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8847 // Also drop the permission flags. 8848 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 8849 PackageManager.MASK_PERMISSION_FLAGS, 0); 8850 changedInstallPermission = true; 8851 Slog.i(TAG, "Un-granting permission " + perm 8852 + " from package " + pkg.packageName 8853 + " (protectionLevel=" + bp.protectionLevel 8854 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8855 + ")"); 8856 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 8857 // Don't print warning for app op permissions, since it is fine for them 8858 // not to be granted, there is a UI for the user to decide. 8859 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8860 Slog.w(TAG, "Not granting permission " + perm 8861 + " to package " + pkg.packageName 8862 + " (protectionLevel=" + bp.protectionLevel 8863 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8864 + ")"); 8865 } 8866 } 8867 } 8868 } 8869 8870 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 8871 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 8872 // This is the first that we have heard about this package, so the 8873 // permissions we have now selected are fixed until explicitly 8874 // changed. 8875 ps.installPermissionsFixed = true; 8876 } 8877 8878 // Persist the runtime permissions state for users with changes. If permissions 8879 // were revoked because no app in the shared user declares them we have to 8880 // write synchronously to avoid losing runtime permissions state. 8881 for (int userId : changedRuntimePermissionUserIds) { 8882 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 8883 } 8884 8885 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8886 } 8887 8888 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8889 boolean allowed = false; 8890 final int NP = PackageParser.NEW_PERMISSIONS.length; 8891 for (int ip=0; ip<NP; ip++) { 8892 final PackageParser.NewPermissionInfo npi 8893 = PackageParser.NEW_PERMISSIONS[ip]; 8894 if (npi.name.equals(perm) 8895 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8896 allowed = true; 8897 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8898 + pkg.packageName); 8899 break; 8900 } 8901 } 8902 return allowed; 8903 } 8904 8905 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 8906 BasePermission bp, PermissionsState origPermissions) { 8907 boolean allowed; 8908 allowed = (compareSignatures( 8909 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 8910 == PackageManager.SIGNATURE_MATCH) 8911 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 8912 == PackageManager.SIGNATURE_MATCH); 8913 if (!allowed && (bp.protectionLevel 8914 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 8915 if (isSystemApp(pkg)) { 8916 // For updated system applications, a system permission 8917 // is granted only if it had been defined by the original application. 8918 if (pkg.isUpdatedSystemApp()) { 8919 final PackageSetting sysPs = mSettings 8920 .getDisabledSystemPkgLPr(pkg.packageName); 8921 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 8922 // If the original was granted this permission, we take 8923 // that grant decision as read and propagate it to the 8924 // update. 8925 if (sysPs.isPrivileged()) { 8926 allowed = true; 8927 } 8928 } else { 8929 // The system apk may have been updated with an older 8930 // version of the one on the data partition, but which 8931 // granted a new system permission that it didn't have 8932 // before. In this case we do want to allow the app to 8933 // now get the new permission if the ancestral apk is 8934 // privileged to get it. 8935 if (sysPs.pkg != null && sysPs.isPrivileged()) { 8936 for (int j=0; 8937 j<sysPs.pkg.requestedPermissions.size(); j++) { 8938 if (perm.equals( 8939 sysPs.pkg.requestedPermissions.get(j))) { 8940 allowed = true; 8941 break; 8942 } 8943 } 8944 } 8945 } 8946 } else { 8947 allowed = isPrivilegedApp(pkg); 8948 } 8949 } 8950 } 8951 if (!allowed) { 8952 if (!allowed && (bp.protectionLevel 8953 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 8954 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 8955 // If this was a previously normal/dangerous permission that got moved 8956 // to a system permission as part of the runtime permission redesign, then 8957 // we still want to blindly grant it to old apps. 8958 allowed = true; 8959 } 8960 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 8961 && pkg.packageName.equals(mRequiredInstallerPackage)) { 8962 // If this permission is to be granted to the system installer and 8963 // this app is an installer, then it gets the permission. 8964 allowed = true; 8965 } 8966 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 8967 && pkg.packageName.equals(mRequiredVerifierPackage)) { 8968 // If this permission is to be granted to the system verifier and 8969 // this app is a verifier, then it gets the permission. 8970 allowed = true; 8971 } 8972 if (!allowed && (bp.protectionLevel 8973 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 8974 && isSystemApp(pkg)) { 8975 // Any pre-installed system app is allowed to get this permission. 8976 allowed = true; 8977 } 8978 if (!allowed && (bp.protectionLevel 8979 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 8980 // For development permissions, a development permission 8981 // is granted only if it was already granted. 8982 allowed = origPermissions.hasInstallPermission(perm); 8983 } 8984 } 8985 return allowed; 8986 } 8987 8988 final class ActivityIntentResolver 8989 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 8990 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8991 boolean defaultOnly, int userId) { 8992 if (!sUserManager.exists(userId)) return null; 8993 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8994 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8995 } 8996 8997 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8998 int userId) { 8999 if (!sUserManager.exists(userId)) return null; 9000 mFlags = flags; 9001 return super.queryIntent(intent, resolvedType, 9002 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9003 } 9004 9005 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9006 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 9007 if (!sUserManager.exists(userId)) return null; 9008 if (packageActivities == null) { 9009 return null; 9010 } 9011 mFlags = flags; 9012 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9013 final int N = packageActivities.size(); 9014 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 9015 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 9016 9017 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 9018 for (int i = 0; i < N; ++i) { 9019 intentFilters = packageActivities.get(i).intents; 9020 if (intentFilters != null && intentFilters.size() > 0) { 9021 PackageParser.ActivityIntentInfo[] array = 9022 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 9023 intentFilters.toArray(array); 9024 listCut.add(array); 9025 } 9026 } 9027 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9028 } 9029 9030 public final void addActivity(PackageParser.Activity a, String type) { 9031 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 9032 mActivities.put(a.getComponentName(), a); 9033 if (DEBUG_SHOW_INFO) 9034 Log.v( 9035 TAG, " " + type + " " + 9036 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 9037 if (DEBUG_SHOW_INFO) 9038 Log.v(TAG, " Class=" + a.info.name); 9039 final int NI = a.intents.size(); 9040 for (int j=0; j<NI; j++) { 9041 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 9042 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 9043 intent.setPriority(0); 9044 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 9045 + a.className + " with priority > 0, forcing to 0"); 9046 } 9047 if (DEBUG_SHOW_INFO) { 9048 Log.v(TAG, " IntentFilter:"); 9049 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9050 } 9051 if (!intent.debugCheck()) { 9052 Log.w(TAG, "==> For Activity " + a.info.name); 9053 } 9054 addFilter(intent); 9055 } 9056 } 9057 9058 public final void removeActivity(PackageParser.Activity a, String type) { 9059 mActivities.remove(a.getComponentName()); 9060 if (DEBUG_SHOW_INFO) { 9061 Log.v(TAG, " " + type + " " 9062 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 9063 : a.info.name) + ":"); 9064 Log.v(TAG, " Class=" + a.info.name); 9065 } 9066 final int NI = a.intents.size(); 9067 for (int j=0; j<NI; j++) { 9068 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 9069 if (DEBUG_SHOW_INFO) { 9070 Log.v(TAG, " IntentFilter:"); 9071 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9072 } 9073 removeFilter(intent); 9074 } 9075 } 9076 9077 @Override 9078 protected boolean allowFilterResult( 9079 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 9080 ActivityInfo filterAi = filter.activity.info; 9081 for (int i=dest.size()-1; i>=0; i--) { 9082 ActivityInfo destAi = dest.get(i).activityInfo; 9083 if (destAi.name == filterAi.name 9084 && destAi.packageName == filterAi.packageName) { 9085 return false; 9086 } 9087 } 9088 return true; 9089 } 9090 9091 @Override 9092 protected ActivityIntentInfo[] newArray(int size) { 9093 return new ActivityIntentInfo[size]; 9094 } 9095 9096 @Override 9097 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 9098 if (!sUserManager.exists(userId)) return true; 9099 PackageParser.Package p = filter.activity.owner; 9100 if (p != null) { 9101 PackageSetting ps = (PackageSetting)p.mExtras; 9102 if (ps != null) { 9103 // System apps are never considered stopped for purposes of 9104 // filtering, because there may be no way for the user to 9105 // actually re-launch them. 9106 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 9107 && ps.getStopped(userId); 9108 } 9109 } 9110 return false; 9111 } 9112 9113 @Override 9114 protected boolean isPackageForFilter(String packageName, 9115 PackageParser.ActivityIntentInfo info) { 9116 return packageName.equals(info.activity.owner.packageName); 9117 } 9118 9119 @Override 9120 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 9121 int match, int userId) { 9122 if (!sUserManager.exists(userId)) return null; 9123 if (!mSettings.isEnabledAndVisibleLPr(info.activity.info, mFlags, userId)) { 9124 return null; 9125 } 9126 final PackageParser.Activity activity = info.activity; 9127 if (mSafeMode && (activity.info.applicationInfo.flags 9128 &ApplicationInfo.FLAG_SYSTEM) == 0) { 9129 return null; 9130 } 9131 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 9132 if (ps == null) { 9133 return null; 9134 } 9135 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 9136 ps.readUserState(userId), userId); 9137 if (ai == null) { 9138 return null; 9139 } 9140 final ResolveInfo res = new ResolveInfo(); 9141 res.activityInfo = ai; 9142 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9143 res.filter = info; 9144 } 9145 if (info != null) { 9146 res.handleAllWebDataURI = info.handleAllWebDataURI(); 9147 } 9148 res.priority = info.getPriority(); 9149 res.preferredOrder = activity.owner.mPreferredOrder; 9150 //System.out.println("Result: " + res.activityInfo.className + 9151 // " = " + res.priority); 9152 res.match = match; 9153 res.isDefault = info.hasDefault; 9154 res.labelRes = info.labelRes; 9155 res.nonLocalizedLabel = info.nonLocalizedLabel; 9156 if (userNeedsBadging(userId)) { 9157 res.noResourceId = true; 9158 } else { 9159 res.icon = info.icon; 9160 } 9161 res.iconResourceId = info.icon; 9162 res.system = res.activityInfo.applicationInfo.isSystemApp(); 9163 return res; 9164 } 9165 9166 @Override 9167 protected void sortResults(List<ResolveInfo> results) { 9168 Collections.sort(results, mResolvePrioritySorter); 9169 } 9170 9171 @Override 9172 protected void dumpFilter(PrintWriter out, String prefix, 9173 PackageParser.ActivityIntentInfo filter) { 9174 out.print(prefix); out.print( 9175 Integer.toHexString(System.identityHashCode(filter.activity))); 9176 out.print(' '); 9177 filter.activity.printComponentShortName(out); 9178 out.print(" filter "); 9179 out.println(Integer.toHexString(System.identityHashCode(filter))); 9180 } 9181 9182 @Override 9183 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 9184 return filter.activity; 9185 } 9186 9187 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9188 PackageParser.Activity activity = (PackageParser.Activity)label; 9189 out.print(prefix); out.print( 9190 Integer.toHexString(System.identityHashCode(activity))); 9191 out.print(' '); 9192 activity.printComponentShortName(out); 9193 if (count > 1) { 9194 out.print(" ("); out.print(count); out.print(" filters)"); 9195 } 9196 out.println(); 9197 } 9198 9199// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9200// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9201// final List<ResolveInfo> retList = Lists.newArrayList(); 9202// while (i.hasNext()) { 9203// final ResolveInfo resolveInfo = i.next(); 9204// if (isEnabledLP(resolveInfo.activityInfo)) { 9205// retList.add(resolveInfo); 9206// } 9207// } 9208// return retList; 9209// } 9210 9211 // Keys are String (activity class name), values are Activity. 9212 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 9213 = new ArrayMap<ComponentName, PackageParser.Activity>(); 9214 private int mFlags; 9215 } 9216 9217 private final class ServiceIntentResolver 9218 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 9219 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9220 boolean defaultOnly, int userId) { 9221 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9222 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9223 } 9224 9225 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9226 int userId) { 9227 if (!sUserManager.exists(userId)) return null; 9228 mFlags = flags; 9229 return super.queryIntent(intent, resolvedType, 9230 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9231 } 9232 9233 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9234 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 9235 if (!sUserManager.exists(userId)) return null; 9236 if (packageServices == null) { 9237 return null; 9238 } 9239 mFlags = flags; 9240 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9241 final int N = packageServices.size(); 9242 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 9243 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 9244 9245 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 9246 for (int i = 0; i < N; ++i) { 9247 intentFilters = packageServices.get(i).intents; 9248 if (intentFilters != null && intentFilters.size() > 0) { 9249 PackageParser.ServiceIntentInfo[] array = 9250 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 9251 intentFilters.toArray(array); 9252 listCut.add(array); 9253 } 9254 } 9255 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9256 } 9257 9258 public final void addService(PackageParser.Service s) { 9259 mServices.put(s.getComponentName(), s); 9260 if (DEBUG_SHOW_INFO) { 9261 Log.v(TAG, " " 9262 + (s.info.nonLocalizedLabel != null 9263 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9264 Log.v(TAG, " Class=" + s.info.name); 9265 } 9266 final int NI = s.intents.size(); 9267 int j; 9268 for (j=0; j<NI; j++) { 9269 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9270 if (DEBUG_SHOW_INFO) { 9271 Log.v(TAG, " IntentFilter:"); 9272 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9273 } 9274 if (!intent.debugCheck()) { 9275 Log.w(TAG, "==> For Service " + s.info.name); 9276 } 9277 addFilter(intent); 9278 } 9279 } 9280 9281 public final void removeService(PackageParser.Service s) { 9282 mServices.remove(s.getComponentName()); 9283 if (DEBUG_SHOW_INFO) { 9284 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 9285 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9286 Log.v(TAG, " Class=" + s.info.name); 9287 } 9288 final int NI = s.intents.size(); 9289 int j; 9290 for (j=0; j<NI; j++) { 9291 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9292 if (DEBUG_SHOW_INFO) { 9293 Log.v(TAG, " IntentFilter:"); 9294 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9295 } 9296 removeFilter(intent); 9297 } 9298 } 9299 9300 @Override 9301 protected boolean allowFilterResult( 9302 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 9303 ServiceInfo filterSi = filter.service.info; 9304 for (int i=dest.size()-1; i>=0; i--) { 9305 ServiceInfo destAi = dest.get(i).serviceInfo; 9306 if (destAi.name == filterSi.name 9307 && destAi.packageName == filterSi.packageName) { 9308 return false; 9309 } 9310 } 9311 return true; 9312 } 9313 9314 @Override 9315 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 9316 return new PackageParser.ServiceIntentInfo[size]; 9317 } 9318 9319 @Override 9320 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 9321 if (!sUserManager.exists(userId)) return true; 9322 PackageParser.Package p = filter.service.owner; 9323 if (p != null) { 9324 PackageSetting ps = (PackageSetting)p.mExtras; 9325 if (ps != null) { 9326 // System apps are never considered stopped for purposes of 9327 // filtering, because there may be no way for the user to 9328 // actually re-launch them. 9329 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9330 && ps.getStopped(userId); 9331 } 9332 } 9333 return false; 9334 } 9335 9336 @Override 9337 protected boolean isPackageForFilter(String packageName, 9338 PackageParser.ServiceIntentInfo info) { 9339 return packageName.equals(info.service.owner.packageName); 9340 } 9341 9342 @Override 9343 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 9344 int match, int userId) { 9345 if (!sUserManager.exists(userId)) return null; 9346 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 9347 if (!mSettings.isEnabledAndVisibleLPr(info.service.info, mFlags, userId)) { 9348 return null; 9349 } 9350 final PackageParser.Service service = info.service; 9351 if (mSafeMode && (service.info.applicationInfo.flags 9352 &ApplicationInfo.FLAG_SYSTEM) == 0) { 9353 return null; 9354 } 9355 PackageSetting ps = (PackageSetting) service.owner.mExtras; 9356 if (ps == null) { 9357 return null; 9358 } 9359 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 9360 ps.readUserState(userId), userId); 9361 if (si == null) { 9362 return null; 9363 } 9364 final ResolveInfo res = new ResolveInfo(); 9365 res.serviceInfo = si; 9366 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9367 res.filter = filter; 9368 } 9369 res.priority = info.getPriority(); 9370 res.preferredOrder = service.owner.mPreferredOrder; 9371 res.match = match; 9372 res.isDefault = info.hasDefault; 9373 res.labelRes = info.labelRes; 9374 res.nonLocalizedLabel = info.nonLocalizedLabel; 9375 res.icon = info.icon; 9376 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 9377 return res; 9378 } 9379 9380 @Override 9381 protected void sortResults(List<ResolveInfo> results) { 9382 Collections.sort(results, mResolvePrioritySorter); 9383 } 9384 9385 @Override 9386 protected void dumpFilter(PrintWriter out, String prefix, 9387 PackageParser.ServiceIntentInfo filter) { 9388 out.print(prefix); out.print( 9389 Integer.toHexString(System.identityHashCode(filter.service))); 9390 out.print(' '); 9391 filter.service.printComponentShortName(out); 9392 out.print(" filter "); 9393 out.println(Integer.toHexString(System.identityHashCode(filter))); 9394 } 9395 9396 @Override 9397 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 9398 return filter.service; 9399 } 9400 9401 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9402 PackageParser.Service service = (PackageParser.Service)label; 9403 out.print(prefix); out.print( 9404 Integer.toHexString(System.identityHashCode(service))); 9405 out.print(' '); 9406 service.printComponentShortName(out); 9407 if (count > 1) { 9408 out.print(" ("); out.print(count); out.print(" filters)"); 9409 } 9410 out.println(); 9411 } 9412 9413// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9414// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9415// final List<ResolveInfo> retList = Lists.newArrayList(); 9416// while (i.hasNext()) { 9417// final ResolveInfo resolveInfo = (ResolveInfo) i; 9418// if (isEnabledLP(resolveInfo.serviceInfo)) { 9419// retList.add(resolveInfo); 9420// } 9421// } 9422// return retList; 9423// } 9424 9425 // Keys are String (activity class name), values are Activity. 9426 private final ArrayMap<ComponentName, PackageParser.Service> mServices 9427 = new ArrayMap<ComponentName, PackageParser.Service>(); 9428 private int mFlags; 9429 }; 9430 9431 private final class ProviderIntentResolver 9432 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 9433 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9434 boolean defaultOnly, int userId) { 9435 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9436 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9437 } 9438 9439 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9440 int userId) { 9441 if (!sUserManager.exists(userId)) 9442 return null; 9443 mFlags = flags; 9444 return super.queryIntent(intent, resolvedType, 9445 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9446 } 9447 9448 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9449 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 9450 if (!sUserManager.exists(userId)) 9451 return null; 9452 if (packageProviders == null) { 9453 return null; 9454 } 9455 mFlags = flags; 9456 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 9457 final int N = packageProviders.size(); 9458 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 9459 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 9460 9461 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 9462 for (int i = 0; i < N; ++i) { 9463 intentFilters = packageProviders.get(i).intents; 9464 if (intentFilters != null && intentFilters.size() > 0) { 9465 PackageParser.ProviderIntentInfo[] array = 9466 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 9467 intentFilters.toArray(array); 9468 listCut.add(array); 9469 } 9470 } 9471 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9472 } 9473 9474 public final void addProvider(PackageParser.Provider p) { 9475 if (mProviders.containsKey(p.getComponentName())) { 9476 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 9477 return; 9478 } 9479 9480 mProviders.put(p.getComponentName(), p); 9481 if (DEBUG_SHOW_INFO) { 9482 Log.v(TAG, " " 9483 + (p.info.nonLocalizedLabel != null 9484 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9485 Log.v(TAG, " Class=" + p.info.name); 9486 } 9487 final int NI = p.intents.size(); 9488 int j; 9489 for (j = 0; j < NI; j++) { 9490 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9491 if (DEBUG_SHOW_INFO) { 9492 Log.v(TAG, " IntentFilter:"); 9493 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9494 } 9495 if (!intent.debugCheck()) { 9496 Log.w(TAG, "==> For Provider " + p.info.name); 9497 } 9498 addFilter(intent); 9499 } 9500 } 9501 9502 public final void removeProvider(PackageParser.Provider p) { 9503 mProviders.remove(p.getComponentName()); 9504 if (DEBUG_SHOW_INFO) { 9505 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 9506 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9507 Log.v(TAG, " Class=" + p.info.name); 9508 } 9509 final int NI = p.intents.size(); 9510 int j; 9511 for (j = 0; j < NI; j++) { 9512 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9513 if (DEBUG_SHOW_INFO) { 9514 Log.v(TAG, " IntentFilter:"); 9515 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9516 } 9517 removeFilter(intent); 9518 } 9519 } 9520 9521 @Override 9522 protected boolean allowFilterResult( 9523 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 9524 ProviderInfo filterPi = filter.provider.info; 9525 for (int i = dest.size() - 1; i >= 0; i--) { 9526 ProviderInfo destPi = dest.get(i).providerInfo; 9527 if (destPi.name == filterPi.name 9528 && destPi.packageName == filterPi.packageName) { 9529 return false; 9530 } 9531 } 9532 return true; 9533 } 9534 9535 @Override 9536 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 9537 return new PackageParser.ProviderIntentInfo[size]; 9538 } 9539 9540 @Override 9541 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 9542 if (!sUserManager.exists(userId)) 9543 return true; 9544 PackageParser.Package p = filter.provider.owner; 9545 if (p != null) { 9546 PackageSetting ps = (PackageSetting) p.mExtras; 9547 if (ps != null) { 9548 // System apps are never considered stopped for purposes of 9549 // filtering, because there may be no way for the user to 9550 // actually re-launch them. 9551 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9552 && ps.getStopped(userId); 9553 } 9554 } 9555 return false; 9556 } 9557 9558 @Override 9559 protected boolean isPackageForFilter(String packageName, 9560 PackageParser.ProviderIntentInfo info) { 9561 return packageName.equals(info.provider.owner.packageName); 9562 } 9563 9564 @Override 9565 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 9566 int match, int userId) { 9567 if (!sUserManager.exists(userId)) 9568 return null; 9569 final PackageParser.ProviderIntentInfo info = filter; 9570 if (!mSettings.isEnabledAndVisibleLPr(info.provider.info, mFlags, userId)) { 9571 return null; 9572 } 9573 final PackageParser.Provider provider = info.provider; 9574 if (mSafeMode && (provider.info.applicationInfo.flags 9575 & ApplicationInfo.FLAG_SYSTEM) == 0) { 9576 return null; 9577 } 9578 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 9579 if (ps == null) { 9580 return null; 9581 } 9582 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 9583 ps.readUserState(userId), userId); 9584 if (pi == null) { 9585 return null; 9586 } 9587 final ResolveInfo res = new ResolveInfo(); 9588 res.providerInfo = pi; 9589 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 9590 res.filter = filter; 9591 } 9592 res.priority = info.getPriority(); 9593 res.preferredOrder = provider.owner.mPreferredOrder; 9594 res.match = match; 9595 res.isDefault = info.hasDefault; 9596 res.labelRes = info.labelRes; 9597 res.nonLocalizedLabel = info.nonLocalizedLabel; 9598 res.icon = info.icon; 9599 res.system = res.providerInfo.applicationInfo.isSystemApp(); 9600 return res; 9601 } 9602 9603 @Override 9604 protected void sortResults(List<ResolveInfo> results) { 9605 Collections.sort(results, mResolvePrioritySorter); 9606 } 9607 9608 @Override 9609 protected void dumpFilter(PrintWriter out, String prefix, 9610 PackageParser.ProviderIntentInfo filter) { 9611 out.print(prefix); 9612 out.print( 9613 Integer.toHexString(System.identityHashCode(filter.provider))); 9614 out.print(' '); 9615 filter.provider.printComponentShortName(out); 9616 out.print(" filter "); 9617 out.println(Integer.toHexString(System.identityHashCode(filter))); 9618 } 9619 9620 @Override 9621 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 9622 return filter.provider; 9623 } 9624 9625 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9626 PackageParser.Provider provider = (PackageParser.Provider)label; 9627 out.print(prefix); out.print( 9628 Integer.toHexString(System.identityHashCode(provider))); 9629 out.print(' '); 9630 provider.printComponentShortName(out); 9631 if (count > 1) { 9632 out.print(" ("); out.print(count); out.print(" filters)"); 9633 } 9634 out.println(); 9635 } 9636 9637 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 9638 = new ArrayMap<ComponentName, PackageParser.Provider>(); 9639 private int mFlags; 9640 } 9641 9642 private static final class EphemeralIntentResolver 9643 extends IntentResolver<IntentFilter, ResolveInfo> { 9644 @Override 9645 protected IntentFilter[] newArray(int size) { 9646 return new IntentFilter[size]; 9647 } 9648 9649 @Override 9650 protected boolean isPackageForFilter(String packageName, IntentFilter info) { 9651 return true; 9652 } 9653 9654 @Override 9655 protected ResolveInfo newResult(IntentFilter info, int match, int userId) { 9656 if (!sUserManager.exists(userId)) return null; 9657 final ResolveInfo res = new ResolveInfo(); 9658 res.filter = info; 9659 return res; 9660 } 9661 } 9662 9663 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 9664 new Comparator<ResolveInfo>() { 9665 public int compare(ResolveInfo r1, ResolveInfo r2) { 9666 int v1 = r1.priority; 9667 int v2 = r2.priority; 9668 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 9669 if (v1 != v2) { 9670 return (v1 > v2) ? -1 : 1; 9671 } 9672 v1 = r1.preferredOrder; 9673 v2 = r2.preferredOrder; 9674 if (v1 != v2) { 9675 return (v1 > v2) ? -1 : 1; 9676 } 9677 if (r1.isDefault != r2.isDefault) { 9678 return r1.isDefault ? -1 : 1; 9679 } 9680 v1 = r1.match; 9681 v2 = r2.match; 9682 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 9683 if (v1 != v2) { 9684 return (v1 > v2) ? -1 : 1; 9685 } 9686 if (r1.system != r2.system) { 9687 return r1.system ? -1 : 1; 9688 } 9689 return 0; 9690 } 9691 }; 9692 9693 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 9694 new Comparator<ProviderInfo>() { 9695 public int compare(ProviderInfo p1, ProviderInfo p2) { 9696 final int v1 = p1.initOrder; 9697 final int v2 = p2.initOrder; 9698 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 9699 } 9700 }; 9701 9702 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 9703 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 9704 final int[] userIds) { 9705 mHandler.post(new Runnable() { 9706 @Override 9707 public void run() { 9708 try { 9709 final IActivityManager am = ActivityManagerNative.getDefault(); 9710 if (am == null) return; 9711 final int[] resolvedUserIds; 9712 if (userIds == null) { 9713 resolvedUserIds = am.getRunningUserIds(); 9714 } else { 9715 resolvedUserIds = userIds; 9716 } 9717 for (int id : resolvedUserIds) { 9718 final Intent intent = new Intent(action, 9719 pkg != null ? Uri.fromParts("package", pkg, null) : null); 9720 if (extras != null) { 9721 intent.putExtras(extras); 9722 } 9723 if (targetPkg != null) { 9724 intent.setPackage(targetPkg); 9725 } 9726 // Modify the UID when posting to other users 9727 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 9728 if (uid > 0 && UserHandle.getUserId(uid) != id) { 9729 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 9730 intent.putExtra(Intent.EXTRA_UID, uid); 9731 } 9732 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 9733 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 9734 if (DEBUG_BROADCASTS) { 9735 RuntimeException here = new RuntimeException("here"); 9736 here.fillInStackTrace(); 9737 Slog.d(TAG, "Sending to user " + id + ": " 9738 + intent.toShortString(false, true, false, false) 9739 + " " + intent.getExtras(), here); 9740 } 9741 am.broadcastIntent(null, intent, null, finishedReceiver, 9742 0, null, null, null, android.app.AppOpsManager.OP_NONE, 9743 null, finishedReceiver != null, false, id); 9744 } 9745 } catch (RemoteException ex) { 9746 } 9747 } 9748 }); 9749 } 9750 9751 /** 9752 * Check if the external storage media is available. This is true if there 9753 * is a mounted external storage medium or if the external storage is 9754 * emulated. 9755 */ 9756 private boolean isExternalMediaAvailable() { 9757 return mMediaMounted || Environment.isExternalStorageEmulated(); 9758 } 9759 9760 @Override 9761 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 9762 // writer 9763 synchronized (mPackages) { 9764 if (!isExternalMediaAvailable()) { 9765 // If the external storage is no longer mounted at this point, 9766 // the caller may not have been able to delete all of this 9767 // packages files and can not delete any more. Bail. 9768 return null; 9769 } 9770 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 9771 if (lastPackage != null) { 9772 pkgs.remove(lastPackage); 9773 } 9774 if (pkgs.size() > 0) { 9775 return pkgs.get(0); 9776 } 9777 } 9778 return null; 9779 } 9780 9781 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 9782 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 9783 userId, andCode ? 1 : 0, packageName); 9784 if (mSystemReady) { 9785 msg.sendToTarget(); 9786 } else { 9787 if (mPostSystemReadyMessages == null) { 9788 mPostSystemReadyMessages = new ArrayList<>(); 9789 } 9790 mPostSystemReadyMessages.add(msg); 9791 } 9792 } 9793 9794 void startCleaningPackages() { 9795 // reader 9796 synchronized (mPackages) { 9797 if (!isExternalMediaAvailable()) { 9798 return; 9799 } 9800 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 9801 return; 9802 } 9803 } 9804 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 9805 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 9806 IActivityManager am = ActivityManagerNative.getDefault(); 9807 if (am != null) { 9808 try { 9809 am.startService(null, intent, null, mContext.getOpPackageName(), 9810 UserHandle.USER_SYSTEM); 9811 } catch (RemoteException e) { 9812 } 9813 } 9814 } 9815 9816 @Override 9817 public void installPackage(String originPath, IPackageInstallObserver2 observer, 9818 int installFlags, String installerPackageName, VerificationParams verificationParams, 9819 String packageAbiOverride) { 9820 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 9821 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 9822 } 9823 9824 @Override 9825 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 9826 int installFlags, String installerPackageName, VerificationParams verificationParams, 9827 String packageAbiOverride, int userId) { 9828 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 9829 9830 final int callingUid = Binder.getCallingUid(); 9831 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 9832 9833 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9834 try { 9835 if (observer != null) { 9836 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 9837 } 9838 } catch (RemoteException re) { 9839 } 9840 return; 9841 } 9842 9843 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 9844 installFlags |= PackageManager.INSTALL_FROM_ADB; 9845 9846 } else { 9847 // Caller holds INSTALL_PACKAGES permission, so we're less strict 9848 // about installerPackageName. 9849 9850 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 9851 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 9852 } 9853 9854 UserHandle user; 9855 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 9856 user = UserHandle.ALL; 9857 } else { 9858 user = new UserHandle(userId); 9859 } 9860 9861 // Only system components can circumvent runtime permissions when installing. 9862 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 9863 && mContext.checkCallingOrSelfPermission(Manifest.permission 9864 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 9865 throw new SecurityException("You need the " 9866 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 9867 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 9868 } 9869 9870 verificationParams.setInstallerUid(callingUid); 9871 9872 final File originFile = new File(originPath); 9873 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 9874 9875 final Message msg = mHandler.obtainMessage(INIT_COPY); 9876 final InstallParams params = new InstallParams(origin, null, observer, installFlags, 9877 installerPackageName, null, verificationParams, user, packageAbiOverride, null); 9878 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 9879 msg.obj = params; 9880 9881 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 9882 System.identityHashCode(msg.obj)); 9883 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 9884 System.identityHashCode(msg.obj)); 9885 9886 mHandler.sendMessage(msg); 9887 } 9888 9889 void installStage(String packageName, File stagedDir, String stagedCid, 9890 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 9891 String installerPackageName, int installerUid, UserHandle user) { 9892 final VerificationParams verifParams = new VerificationParams( 9893 null, sessionParams.originatingUri, sessionParams.referrerUri, 9894 sessionParams.originatingUid, null); 9895 verifParams.setInstallerUid(installerUid); 9896 9897 final OriginInfo origin; 9898 if (stagedDir != null) { 9899 origin = OriginInfo.fromStagedFile(stagedDir); 9900 } else { 9901 origin = OriginInfo.fromStagedContainer(stagedCid); 9902 } 9903 9904 final Message msg = mHandler.obtainMessage(INIT_COPY); 9905 final InstallParams params = new InstallParams(origin, null, observer, 9906 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 9907 verifParams, user, sessionParams.abiOverride, 9908 sessionParams.grantedRuntimePermissions); 9909 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 9910 msg.obj = params; 9911 9912 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 9913 System.identityHashCode(msg.obj)); 9914 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 9915 System.identityHashCode(msg.obj)); 9916 9917 mHandler.sendMessage(msg); 9918 } 9919 9920 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 9921 Bundle extras = new Bundle(1); 9922 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 9923 9924 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 9925 packageName, extras, 0, null, null, new int[] {userId}); 9926 try { 9927 IActivityManager am = ActivityManagerNative.getDefault(); 9928 final boolean isSystem = 9929 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 9930 if (isSystem && am.isUserRunning(userId, 0)) { 9931 // The just-installed/enabled app is bundled on the system, so presumed 9932 // to be able to run automatically without needing an explicit launch. 9933 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 9934 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 9935 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 9936 .setPackage(packageName); 9937 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 9938 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 9939 } 9940 } catch (RemoteException e) { 9941 // shouldn't happen 9942 Slog.w(TAG, "Unable to bootstrap installed package", e); 9943 } 9944 } 9945 9946 @Override 9947 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 9948 int userId) { 9949 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9950 PackageSetting pkgSetting; 9951 final int uid = Binder.getCallingUid(); 9952 enforceCrossUserPermission(uid, userId, true, true, 9953 "setApplicationHiddenSetting for user " + userId); 9954 9955 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 9956 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 9957 return false; 9958 } 9959 9960 long callingId = Binder.clearCallingIdentity(); 9961 try { 9962 boolean sendAdded = false; 9963 boolean sendRemoved = false; 9964 // writer 9965 synchronized (mPackages) { 9966 pkgSetting = mSettings.mPackages.get(packageName); 9967 if (pkgSetting == null) { 9968 return false; 9969 } 9970 if (pkgSetting.getHidden(userId) != hidden) { 9971 pkgSetting.setHidden(hidden, userId); 9972 mSettings.writePackageRestrictionsLPr(userId); 9973 if (hidden) { 9974 sendRemoved = true; 9975 } else { 9976 sendAdded = true; 9977 } 9978 } 9979 } 9980 if (sendAdded) { 9981 sendPackageAddedForUser(packageName, pkgSetting, userId); 9982 return true; 9983 } 9984 if (sendRemoved) { 9985 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 9986 "hiding pkg"); 9987 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 9988 return true; 9989 } 9990 } finally { 9991 Binder.restoreCallingIdentity(callingId); 9992 } 9993 return false; 9994 } 9995 9996 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 9997 int userId) { 9998 final PackageRemovedInfo info = new PackageRemovedInfo(); 9999 info.removedPackage = packageName; 10000 info.removedUsers = new int[] {userId}; 10001 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 10002 info.sendBroadcast(false, false, false); 10003 } 10004 10005 /** 10006 * Returns true if application is not found or there was an error. Otherwise it returns 10007 * the hidden state of the package for the given user. 10008 */ 10009 @Override 10010 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 10011 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10012 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 10013 false, "getApplicationHidden for user " + userId); 10014 PackageSetting pkgSetting; 10015 long callingId = Binder.clearCallingIdentity(); 10016 try { 10017 // writer 10018 synchronized (mPackages) { 10019 pkgSetting = mSettings.mPackages.get(packageName); 10020 if (pkgSetting == null) { 10021 return true; 10022 } 10023 return pkgSetting.getHidden(userId); 10024 } 10025 } finally { 10026 Binder.restoreCallingIdentity(callingId); 10027 } 10028 } 10029 10030 /** 10031 * @hide 10032 */ 10033 @Override 10034 public int installExistingPackageAsUser(String packageName, int userId) { 10035 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 10036 null); 10037 PackageSetting pkgSetting; 10038 final int uid = Binder.getCallingUid(); 10039 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 10040 + userId); 10041 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 10042 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 10043 } 10044 10045 long callingId = Binder.clearCallingIdentity(); 10046 try { 10047 boolean sendAdded = false; 10048 10049 // writer 10050 synchronized (mPackages) { 10051 pkgSetting = mSettings.mPackages.get(packageName); 10052 if (pkgSetting == null) { 10053 return PackageManager.INSTALL_FAILED_INVALID_URI; 10054 } 10055 if (!pkgSetting.getInstalled(userId)) { 10056 pkgSetting.setInstalled(true, userId); 10057 pkgSetting.setHidden(false, userId); 10058 mSettings.writePackageRestrictionsLPr(userId); 10059 sendAdded = true; 10060 } 10061 } 10062 10063 if (sendAdded) { 10064 sendPackageAddedForUser(packageName, pkgSetting, userId); 10065 } 10066 } finally { 10067 Binder.restoreCallingIdentity(callingId); 10068 } 10069 10070 return PackageManager.INSTALL_SUCCEEDED; 10071 } 10072 10073 boolean isUserRestricted(int userId, String restrictionKey) { 10074 Bundle restrictions = sUserManager.getUserRestrictions(userId); 10075 if (restrictions.getBoolean(restrictionKey, false)) { 10076 Log.w(TAG, "User is restricted: " + restrictionKey); 10077 return true; 10078 } 10079 return false; 10080 } 10081 10082 @Override 10083 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 10084 mContext.enforceCallingOrSelfPermission( 10085 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10086 "Only package verification agents can verify applications"); 10087 10088 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 10089 final PackageVerificationResponse response = new PackageVerificationResponse( 10090 verificationCode, Binder.getCallingUid()); 10091 msg.arg1 = id; 10092 msg.obj = response; 10093 mHandler.sendMessage(msg); 10094 } 10095 10096 @Override 10097 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 10098 long millisecondsToDelay) { 10099 mContext.enforceCallingOrSelfPermission( 10100 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10101 "Only package verification agents can extend verification timeouts"); 10102 10103 final PackageVerificationState state = mPendingVerification.get(id); 10104 final PackageVerificationResponse response = new PackageVerificationResponse( 10105 verificationCodeAtTimeout, Binder.getCallingUid()); 10106 10107 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 10108 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 10109 } 10110 if (millisecondsToDelay < 0) { 10111 millisecondsToDelay = 0; 10112 } 10113 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 10114 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 10115 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 10116 } 10117 10118 if ((state != null) && !state.timeoutExtended()) { 10119 state.extendTimeout(); 10120 10121 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 10122 msg.arg1 = id; 10123 msg.obj = response; 10124 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 10125 } 10126 } 10127 10128 private void broadcastPackageVerified(int verificationId, Uri packageUri, 10129 int verificationCode, UserHandle user) { 10130 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 10131 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 10132 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10133 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10134 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 10135 10136 mContext.sendBroadcastAsUser(intent, user, 10137 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 10138 } 10139 10140 private ComponentName matchComponentForVerifier(String packageName, 10141 List<ResolveInfo> receivers) { 10142 ActivityInfo targetReceiver = null; 10143 10144 final int NR = receivers.size(); 10145 for (int i = 0; i < NR; i++) { 10146 final ResolveInfo info = receivers.get(i); 10147 if (info.activityInfo == null) { 10148 continue; 10149 } 10150 10151 if (packageName.equals(info.activityInfo.packageName)) { 10152 targetReceiver = info.activityInfo; 10153 break; 10154 } 10155 } 10156 10157 if (targetReceiver == null) { 10158 return null; 10159 } 10160 10161 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 10162 } 10163 10164 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 10165 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 10166 if (pkgInfo.verifiers.length == 0) { 10167 return null; 10168 } 10169 10170 final int N = pkgInfo.verifiers.length; 10171 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 10172 for (int i = 0; i < N; i++) { 10173 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 10174 10175 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 10176 receivers); 10177 if (comp == null) { 10178 continue; 10179 } 10180 10181 final int verifierUid = getUidForVerifier(verifierInfo); 10182 if (verifierUid == -1) { 10183 continue; 10184 } 10185 10186 if (DEBUG_VERIFY) { 10187 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 10188 + " with the correct signature"); 10189 } 10190 sufficientVerifiers.add(comp); 10191 verificationState.addSufficientVerifier(verifierUid); 10192 } 10193 10194 return sufficientVerifiers; 10195 } 10196 10197 private int getUidForVerifier(VerifierInfo verifierInfo) { 10198 synchronized (mPackages) { 10199 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 10200 if (pkg == null) { 10201 return -1; 10202 } else if (pkg.mSignatures.length != 1) { 10203 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10204 + " has more than one signature; ignoring"); 10205 return -1; 10206 } 10207 10208 /* 10209 * If the public key of the package's signature does not match 10210 * our expected public key, then this is a different package and 10211 * we should skip. 10212 */ 10213 10214 final byte[] expectedPublicKey; 10215 try { 10216 final Signature verifierSig = pkg.mSignatures[0]; 10217 final PublicKey publicKey = verifierSig.getPublicKey(); 10218 expectedPublicKey = publicKey.getEncoded(); 10219 } catch (CertificateException e) { 10220 return -1; 10221 } 10222 10223 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 10224 10225 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 10226 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10227 + " does not have the expected public key; ignoring"); 10228 return -1; 10229 } 10230 10231 return pkg.applicationInfo.uid; 10232 } 10233 } 10234 10235 @Override 10236 public void finishPackageInstall(int token) { 10237 enforceSystemOrRoot("Only the system is allowed to finish installs"); 10238 10239 if (DEBUG_INSTALL) { 10240 Slog.v(TAG, "BM finishing package install for " + token); 10241 } 10242 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10243 10244 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10245 mHandler.sendMessage(msg); 10246 } 10247 10248 /** 10249 * Get the verification agent timeout. 10250 * 10251 * @return verification timeout in milliseconds 10252 */ 10253 private long getVerificationTimeout() { 10254 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 10255 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 10256 DEFAULT_VERIFICATION_TIMEOUT); 10257 } 10258 10259 /** 10260 * Get the default verification agent response code. 10261 * 10262 * @return default verification response code 10263 */ 10264 private int getDefaultVerificationResponse() { 10265 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10266 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 10267 DEFAULT_VERIFICATION_RESPONSE); 10268 } 10269 10270 /** 10271 * Check whether or not package verification has been enabled. 10272 * 10273 * @return true if verification should be performed 10274 */ 10275 private boolean isVerificationEnabled(int userId, int installFlags) { 10276 if (!DEFAULT_VERIFY_ENABLE) { 10277 return false; 10278 } 10279 // TODO: fix b/25118622; don't bypass verification 10280 if (Build.IS_DEBUGGABLE && (installFlags & PackageManager.INSTALL_QUICK) != 0) { 10281 return false; 10282 } 10283 10284 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 10285 10286 // Check if installing from ADB 10287 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 10288 // Do not run verification in a test harness environment 10289 if (ActivityManager.isRunningInTestHarness()) { 10290 return false; 10291 } 10292 if (ensureVerifyAppsEnabled) { 10293 return true; 10294 } 10295 // Check if the developer does not want package verification for ADB installs 10296 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10297 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 10298 return false; 10299 } 10300 } 10301 10302 if (ensureVerifyAppsEnabled) { 10303 return true; 10304 } 10305 10306 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10307 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 10308 } 10309 10310 @Override 10311 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 10312 throws RemoteException { 10313 mContext.enforceCallingOrSelfPermission( 10314 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 10315 "Only intentfilter verification agents can verify applications"); 10316 10317 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 10318 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 10319 Binder.getCallingUid(), verificationCode, failedDomains); 10320 msg.arg1 = id; 10321 msg.obj = response; 10322 mHandler.sendMessage(msg); 10323 } 10324 10325 @Override 10326 public int getIntentVerificationStatus(String packageName, int userId) { 10327 synchronized (mPackages) { 10328 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 10329 } 10330 } 10331 10332 @Override 10333 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 10334 mContext.enforceCallingOrSelfPermission( 10335 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10336 10337 boolean result = false; 10338 synchronized (mPackages) { 10339 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 10340 } 10341 if (result) { 10342 scheduleWritePackageRestrictionsLocked(userId); 10343 } 10344 return result; 10345 } 10346 10347 @Override 10348 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 10349 synchronized (mPackages) { 10350 return mSettings.getIntentFilterVerificationsLPr(packageName); 10351 } 10352 } 10353 10354 @Override 10355 public List<IntentFilter> getAllIntentFilters(String packageName) { 10356 if (TextUtils.isEmpty(packageName)) { 10357 return Collections.<IntentFilter>emptyList(); 10358 } 10359 synchronized (mPackages) { 10360 PackageParser.Package pkg = mPackages.get(packageName); 10361 if (pkg == null || pkg.activities == null) { 10362 return Collections.<IntentFilter>emptyList(); 10363 } 10364 final int count = pkg.activities.size(); 10365 ArrayList<IntentFilter> result = new ArrayList<>(); 10366 for (int n=0; n<count; n++) { 10367 PackageParser.Activity activity = pkg.activities.get(n); 10368 if (activity.intents != null || activity.intents.size() > 0) { 10369 result.addAll(activity.intents); 10370 } 10371 } 10372 return result; 10373 } 10374 } 10375 10376 @Override 10377 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 10378 mContext.enforceCallingOrSelfPermission( 10379 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10380 10381 synchronized (mPackages) { 10382 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 10383 if (packageName != null) { 10384 result |= updateIntentVerificationStatus(packageName, 10385 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 10386 userId); 10387 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 10388 packageName, userId); 10389 } 10390 return result; 10391 } 10392 } 10393 10394 @Override 10395 public String getDefaultBrowserPackageName(int userId) { 10396 synchronized (mPackages) { 10397 return mSettings.getDefaultBrowserPackageNameLPw(userId); 10398 } 10399 } 10400 10401 /** 10402 * Get the "allow unknown sources" setting. 10403 * 10404 * @return the current "allow unknown sources" setting 10405 */ 10406 private int getUnknownSourcesSettings() { 10407 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10408 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 10409 -1); 10410 } 10411 10412 @Override 10413 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 10414 final int uid = Binder.getCallingUid(); 10415 // writer 10416 synchronized (mPackages) { 10417 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 10418 if (targetPackageSetting == null) { 10419 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 10420 } 10421 10422 PackageSetting installerPackageSetting; 10423 if (installerPackageName != null) { 10424 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 10425 if (installerPackageSetting == null) { 10426 throw new IllegalArgumentException("Unknown installer package: " 10427 + installerPackageName); 10428 } 10429 } else { 10430 installerPackageSetting = null; 10431 } 10432 10433 Signature[] callerSignature; 10434 Object obj = mSettings.getUserIdLPr(uid); 10435 if (obj != null) { 10436 if (obj instanceof SharedUserSetting) { 10437 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 10438 } else if (obj instanceof PackageSetting) { 10439 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 10440 } else { 10441 throw new SecurityException("Bad object " + obj + " for uid " + uid); 10442 } 10443 } else { 10444 throw new SecurityException("Unknown calling uid " + uid); 10445 } 10446 10447 // Verify: can't set installerPackageName to a package that is 10448 // not signed with the same cert as the caller. 10449 if (installerPackageSetting != null) { 10450 if (compareSignatures(callerSignature, 10451 installerPackageSetting.signatures.mSignatures) 10452 != PackageManager.SIGNATURE_MATCH) { 10453 throw new SecurityException( 10454 "Caller does not have same cert as new installer package " 10455 + installerPackageName); 10456 } 10457 } 10458 10459 // Verify: if target already has an installer package, it must 10460 // be signed with the same cert as the caller. 10461 if (targetPackageSetting.installerPackageName != null) { 10462 PackageSetting setting = mSettings.mPackages.get( 10463 targetPackageSetting.installerPackageName); 10464 // If the currently set package isn't valid, then it's always 10465 // okay to change it. 10466 if (setting != null) { 10467 if (compareSignatures(callerSignature, 10468 setting.signatures.mSignatures) 10469 != PackageManager.SIGNATURE_MATCH) { 10470 throw new SecurityException( 10471 "Caller does not have same cert as old installer package " 10472 + targetPackageSetting.installerPackageName); 10473 } 10474 } 10475 } 10476 10477 // Okay! 10478 targetPackageSetting.installerPackageName = installerPackageName; 10479 scheduleWriteSettingsLocked(); 10480 } 10481 } 10482 10483 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 10484 // Queue up an async operation since the package installation may take a little while. 10485 mHandler.post(new Runnable() { 10486 public void run() { 10487 mHandler.removeCallbacks(this); 10488 // Result object to be returned 10489 PackageInstalledInfo res = new PackageInstalledInfo(); 10490 res.returnCode = currentStatus; 10491 res.uid = -1; 10492 res.pkg = null; 10493 res.removedInfo = new PackageRemovedInfo(); 10494 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10495 args.doPreInstall(res.returnCode); 10496 synchronized (mInstallLock) { 10497 installPackageTracedLI(args, res); 10498 } 10499 args.doPostInstall(res.returnCode, res.uid); 10500 } 10501 10502 // A restore should be performed at this point if (a) the install 10503 // succeeded, (b) the operation is not an update, and (c) the new 10504 // package has not opted out of backup participation. 10505 final boolean update = res.removedInfo.removedPackage != null; 10506 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 10507 boolean doRestore = !update 10508 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 10509 10510 // Set up the post-install work request bookkeeping. This will be used 10511 // and cleaned up by the post-install event handling regardless of whether 10512 // there's a restore pass performed. Token values are >= 1. 10513 int token; 10514 if (mNextInstallToken < 0) mNextInstallToken = 1; 10515 token = mNextInstallToken++; 10516 10517 PostInstallData data = new PostInstallData(args, res); 10518 mRunningInstalls.put(token, data); 10519 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 10520 10521 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 10522 // Pass responsibility to the Backup Manager. It will perform a 10523 // restore if appropriate, then pass responsibility back to the 10524 // Package Manager to run the post-install observer callbacks 10525 // and broadcasts. 10526 IBackupManager bm = IBackupManager.Stub.asInterface( 10527 ServiceManager.getService(Context.BACKUP_SERVICE)); 10528 if (bm != null) { 10529 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 10530 + " to BM for possible restore"); 10531 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10532 try { 10533 // TODO: http://b/22388012 10534 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 10535 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 10536 } else { 10537 doRestore = false; 10538 } 10539 } catch (RemoteException e) { 10540 // can't happen; the backup manager is local 10541 } catch (Exception e) { 10542 Slog.e(TAG, "Exception trying to enqueue restore", e); 10543 doRestore = false; 10544 } 10545 } else { 10546 Slog.e(TAG, "Backup Manager not found!"); 10547 doRestore = false; 10548 } 10549 } 10550 10551 if (!doRestore) { 10552 // No restore possible, or the Backup Manager was mysteriously not 10553 // available -- just fire the post-install work request directly. 10554 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 10555 10556 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 10557 10558 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10559 mHandler.sendMessage(msg); 10560 } 10561 } 10562 }); 10563 } 10564 10565 private abstract class HandlerParams { 10566 private static final int MAX_RETRIES = 4; 10567 10568 /** 10569 * Number of times startCopy() has been attempted and had a non-fatal 10570 * error. 10571 */ 10572 private int mRetries = 0; 10573 10574 /** User handle for the user requesting the information or installation. */ 10575 private final UserHandle mUser; 10576 String traceMethod; 10577 int traceCookie; 10578 10579 HandlerParams(UserHandle user) { 10580 mUser = user; 10581 } 10582 10583 UserHandle getUser() { 10584 return mUser; 10585 } 10586 10587 HandlerParams setTraceMethod(String traceMethod) { 10588 this.traceMethod = traceMethod; 10589 return this; 10590 } 10591 10592 HandlerParams setTraceCookie(int traceCookie) { 10593 this.traceCookie = traceCookie; 10594 return this; 10595 } 10596 10597 final boolean startCopy() { 10598 boolean res; 10599 try { 10600 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 10601 10602 if (++mRetries > MAX_RETRIES) { 10603 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 10604 mHandler.sendEmptyMessage(MCS_GIVE_UP); 10605 handleServiceError(); 10606 return false; 10607 } else { 10608 handleStartCopy(); 10609 res = true; 10610 } 10611 } catch (RemoteException e) { 10612 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 10613 mHandler.sendEmptyMessage(MCS_RECONNECT); 10614 res = false; 10615 } 10616 handleReturnCode(); 10617 return res; 10618 } 10619 10620 final void serviceError() { 10621 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 10622 handleServiceError(); 10623 handleReturnCode(); 10624 } 10625 10626 abstract void handleStartCopy() throws RemoteException; 10627 abstract void handleServiceError(); 10628 abstract void handleReturnCode(); 10629 } 10630 10631 class MeasureParams extends HandlerParams { 10632 private final PackageStats mStats; 10633 private boolean mSuccess; 10634 10635 private final IPackageStatsObserver mObserver; 10636 10637 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 10638 super(new UserHandle(stats.userHandle)); 10639 mObserver = observer; 10640 mStats = stats; 10641 } 10642 10643 @Override 10644 public String toString() { 10645 return "MeasureParams{" 10646 + Integer.toHexString(System.identityHashCode(this)) 10647 + " " + mStats.packageName + "}"; 10648 } 10649 10650 @Override 10651 void handleStartCopy() throws RemoteException { 10652 synchronized (mInstallLock) { 10653 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 10654 } 10655 10656 if (mSuccess) { 10657 final boolean mounted; 10658 if (Environment.isExternalStorageEmulated()) { 10659 mounted = true; 10660 } else { 10661 final String status = Environment.getExternalStorageState(); 10662 mounted = (Environment.MEDIA_MOUNTED.equals(status) 10663 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 10664 } 10665 10666 if (mounted) { 10667 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 10668 10669 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 10670 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 10671 10672 mStats.externalDataSize = calculateDirectorySize(mContainerService, 10673 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 10674 10675 // Always subtract cache size, since it's a subdirectory 10676 mStats.externalDataSize -= mStats.externalCacheSize; 10677 10678 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 10679 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 10680 10681 mStats.externalObbSize = calculateDirectorySize(mContainerService, 10682 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 10683 } 10684 } 10685 } 10686 10687 @Override 10688 void handleReturnCode() { 10689 if (mObserver != null) { 10690 try { 10691 mObserver.onGetStatsCompleted(mStats, mSuccess); 10692 } catch (RemoteException e) { 10693 Slog.i(TAG, "Observer no longer exists."); 10694 } 10695 } 10696 } 10697 10698 @Override 10699 void handleServiceError() { 10700 Slog.e(TAG, "Could not measure application " + mStats.packageName 10701 + " external storage"); 10702 } 10703 } 10704 10705 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 10706 throws RemoteException { 10707 long result = 0; 10708 for (File path : paths) { 10709 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 10710 } 10711 return result; 10712 } 10713 10714 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 10715 for (File path : paths) { 10716 try { 10717 mcs.clearDirectory(path.getAbsolutePath()); 10718 } catch (RemoteException e) { 10719 } 10720 } 10721 } 10722 10723 static class OriginInfo { 10724 /** 10725 * Location where install is coming from, before it has been 10726 * copied/renamed into place. This could be a single monolithic APK 10727 * file, or a cluster directory. This location may be untrusted. 10728 */ 10729 final File file; 10730 final String cid; 10731 10732 /** 10733 * Flag indicating that {@link #file} or {@link #cid} has already been 10734 * staged, meaning downstream users don't need to defensively copy the 10735 * contents. 10736 */ 10737 final boolean staged; 10738 10739 /** 10740 * Flag indicating that {@link #file} or {@link #cid} is an already 10741 * installed app that is being moved. 10742 */ 10743 final boolean existing; 10744 10745 final String resolvedPath; 10746 final File resolvedFile; 10747 10748 static OriginInfo fromNothing() { 10749 return new OriginInfo(null, null, false, false); 10750 } 10751 10752 static OriginInfo fromUntrustedFile(File file) { 10753 return new OriginInfo(file, null, false, false); 10754 } 10755 10756 static OriginInfo fromExistingFile(File file) { 10757 return new OriginInfo(file, null, false, true); 10758 } 10759 10760 static OriginInfo fromStagedFile(File file) { 10761 return new OriginInfo(file, null, true, false); 10762 } 10763 10764 static OriginInfo fromStagedContainer(String cid) { 10765 return new OriginInfo(null, cid, true, false); 10766 } 10767 10768 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 10769 this.file = file; 10770 this.cid = cid; 10771 this.staged = staged; 10772 this.existing = existing; 10773 10774 if (cid != null) { 10775 resolvedPath = PackageHelper.getSdDir(cid); 10776 resolvedFile = new File(resolvedPath); 10777 } else if (file != null) { 10778 resolvedPath = file.getAbsolutePath(); 10779 resolvedFile = file; 10780 } else { 10781 resolvedPath = null; 10782 resolvedFile = null; 10783 } 10784 } 10785 } 10786 10787 class MoveInfo { 10788 final int moveId; 10789 final String fromUuid; 10790 final String toUuid; 10791 final String packageName; 10792 final String dataAppName; 10793 final int appId; 10794 final String seinfo; 10795 10796 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 10797 String dataAppName, int appId, String seinfo) { 10798 this.moveId = moveId; 10799 this.fromUuid = fromUuid; 10800 this.toUuid = toUuid; 10801 this.packageName = packageName; 10802 this.dataAppName = dataAppName; 10803 this.appId = appId; 10804 this.seinfo = seinfo; 10805 } 10806 } 10807 10808 class InstallParams extends HandlerParams { 10809 final OriginInfo origin; 10810 final MoveInfo move; 10811 final IPackageInstallObserver2 observer; 10812 int installFlags; 10813 final String installerPackageName; 10814 final String volumeUuid; 10815 final VerificationParams verificationParams; 10816 private InstallArgs mArgs; 10817 private int mRet; 10818 final String packageAbiOverride; 10819 final String[] grantedRuntimePermissions; 10820 10821 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10822 int installFlags, String installerPackageName, String volumeUuid, 10823 VerificationParams verificationParams, UserHandle user, String packageAbiOverride, 10824 String[] grantedPermissions) { 10825 super(user); 10826 this.origin = origin; 10827 this.move = move; 10828 this.observer = observer; 10829 this.installFlags = installFlags; 10830 this.installerPackageName = installerPackageName; 10831 this.volumeUuid = volumeUuid; 10832 this.verificationParams = verificationParams; 10833 this.packageAbiOverride = packageAbiOverride; 10834 this.grantedRuntimePermissions = grantedPermissions; 10835 } 10836 10837 @Override 10838 public String toString() { 10839 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 10840 + " file=" + origin.file + " cid=" + origin.cid + "}"; 10841 } 10842 10843 public ManifestDigest getManifestDigest() { 10844 if (verificationParams == null) { 10845 return null; 10846 } 10847 return verificationParams.getManifestDigest(); 10848 } 10849 10850 private int installLocationPolicy(PackageInfoLite pkgLite) { 10851 String packageName = pkgLite.packageName; 10852 int installLocation = pkgLite.installLocation; 10853 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10854 // reader 10855 synchronized (mPackages) { 10856 PackageParser.Package pkg = mPackages.get(packageName); 10857 if (pkg != null) { 10858 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10859 // Check for downgrading. 10860 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 10861 try { 10862 checkDowngrade(pkg, pkgLite); 10863 } catch (PackageManagerException e) { 10864 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 10865 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 10866 } 10867 } 10868 // Check for updated system application. 10869 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10870 if (onSd) { 10871 Slog.w(TAG, "Cannot install update to system app on sdcard"); 10872 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 10873 } 10874 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10875 } else { 10876 if (onSd) { 10877 // Install flag overrides everything. 10878 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10879 } 10880 // If current upgrade specifies particular preference 10881 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 10882 // Application explicitly specified internal. 10883 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10884 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 10885 // App explictly prefers external. Let policy decide 10886 } else { 10887 // Prefer previous location 10888 if (isExternal(pkg)) { 10889 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10890 } 10891 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10892 } 10893 } 10894 } else { 10895 // Invalid install. Return error code 10896 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 10897 } 10898 } 10899 } 10900 // All the special cases have been taken care of. 10901 // Return result based on recommended install location. 10902 if (onSd) { 10903 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10904 } 10905 return pkgLite.recommendedInstallLocation; 10906 } 10907 10908 /* 10909 * Invoke remote method to get package information and install 10910 * location values. Override install location based on default 10911 * policy if needed and then create install arguments based 10912 * on the install location. 10913 */ 10914 public void handleStartCopy() throws RemoteException { 10915 int ret = PackageManager.INSTALL_SUCCEEDED; 10916 10917 // If we're already staged, we've firmly committed to an install location 10918 if (origin.staged) { 10919 if (origin.file != null) { 10920 installFlags |= PackageManager.INSTALL_INTERNAL; 10921 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10922 } else if (origin.cid != null) { 10923 installFlags |= PackageManager.INSTALL_EXTERNAL; 10924 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10925 } else { 10926 throw new IllegalStateException("Invalid stage location"); 10927 } 10928 } 10929 10930 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10931 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 10932 PackageInfoLite pkgLite = null; 10933 10934 if (onInt && onSd) { 10935 // Check if both bits are set. 10936 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 10937 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10938 } else { 10939 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 10940 packageAbiOverride); 10941 10942 /* 10943 * If we have too little free space, try to free cache 10944 * before giving up. 10945 */ 10946 if (!origin.staged && pkgLite.recommendedInstallLocation 10947 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10948 // TODO: focus freeing disk space on the target device 10949 final StorageManager storage = StorageManager.from(mContext); 10950 final long lowThreshold = storage.getStorageLowBytes( 10951 Environment.getDataDirectory()); 10952 10953 final long sizeBytes = mContainerService.calculateInstalledSize( 10954 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 10955 10956 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 10957 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 10958 installFlags, packageAbiOverride); 10959 } 10960 10961 /* 10962 * The cache free must have deleted the file we 10963 * downloaded to install. 10964 * 10965 * TODO: fix the "freeCache" call to not delete 10966 * the file we care about. 10967 */ 10968 if (pkgLite.recommendedInstallLocation 10969 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10970 pkgLite.recommendedInstallLocation 10971 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 10972 } 10973 } 10974 } 10975 10976 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10977 int loc = pkgLite.recommendedInstallLocation; 10978 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 10979 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10980 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 10981 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 10982 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10983 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10984 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 10985 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 10986 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10987 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 10988 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 10989 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 10990 } else { 10991 // Override with defaults if needed. 10992 loc = installLocationPolicy(pkgLite); 10993 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 10994 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 10995 } else if (!onSd && !onInt) { 10996 // Override install location with flags 10997 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 10998 // Set the flag to install on external media. 10999 installFlags |= PackageManager.INSTALL_EXTERNAL; 11000 installFlags &= ~PackageManager.INSTALL_INTERNAL; 11001 } else { 11002 // Make sure the flag for installing on external 11003 // media is unset 11004 installFlags |= PackageManager.INSTALL_INTERNAL; 11005 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 11006 } 11007 } 11008 } 11009 } 11010 11011 final InstallArgs args = createInstallArgs(this); 11012 mArgs = args; 11013 11014 if (ret == PackageManager.INSTALL_SUCCEEDED) { 11015 // TODO: http://b/22976637 11016 // Apps installed for "all" users use the device owner to verify the app 11017 UserHandle verifierUser = getUser(); 11018 if (verifierUser == UserHandle.ALL) { 11019 verifierUser = UserHandle.SYSTEM; 11020 } 11021 11022 /* 11023 * Determine if we have any installed package verifiers. If we 11024 * do, then we'll defer to them to verify the packages. 11025 */ 11026 final int requiredUid = mRequiredVerifierPackage == null ? -1 11027 : getPackageUid(mRequiredVerifierPackage, verifierUser.getIdentifier()); 11028 if (!origin.existing && requiredUid != -1 11029 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 11030 final Intent verification = new Intent( 11031 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 11032 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 11033 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 11034 PACKAGE_MIME_TYPE); 11035 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11036 11037 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 11038 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 11039 verifierUser.getIdentifier()); 11040 11041 if (DEBUG_VERIFY) { 11042 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 11043 + verification.toString() + " with " + pkgLite.verifiers.length 11044 + " optional verifiers"); 11045 } 11046 11047 final int verificationId = mPendingVerificationToken++; 11048 11049 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11050 11051 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 11052 installerPackageName); 11053 11054 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 11055 installFlags); 11056 11057 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 11058 pkgLite.packageName); 11059 11060 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 11061 pkgLite.versionCode); 11062 11063 if (verificationParams != null) { 11064 if (verificationParams.getVerificationURI() != null) { 11065 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 11066 verificationParams.getVerificationURI()); 11067 } 11068 if (verificationParams.getOriginatingURI() != null) { 11069 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 11070 verificationParams.getOriginatingURI()); 11071 } 11072 if (verificationParams.getReferrer() != null) { 11073 verification.putExtra(Intent.EXTRA_REFERRER, 11074 verificationParams.getReferrer()); 11075 } 11076 if (verificationParams.getOriginatingUid() >= 0) { 11077 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 11078 verificationParams.getOriginatingUid()); 11079 } 11080 if (verificationParams.getInstallerUid() >= 0) { 11081 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 11082 verificationParams.getInstallerUid()); 11083 } 11084 } 11085 11086 final PackageVerificationState verificationState = new PackageVerificationState( 11087 requiredUid, args); 11088 11089 mPendingVerification.append(verificationId, verificationState); 11090 11091 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 11092 receivers, verificationState); 11093 11094 /* 11095 * If any sufficient verifiers were listed in the package 11096 * manifest, attempt to ask them. 11097 */ 11098 if (sufficientVerifiers != null) { 11099 final int N = sufficientVerifiers.size(); 11100 if (N == 0) { 11101 Slog.i(TAG, "Additional verifiers required, but none installed."); 11102 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 11103 } else { 11104 for (int i = 0; i < N; i++) { 11105 final ComponentName verifierComponent = sufficientVerifiers.get(i); 11106 11107 final Intent sufficientIntent = new Intent(verification); 11108 sufficientIntent.setComponent(verifierComponent); 11109 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 11110 } 11111 } 11112 } 11113 11114 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 11115 mRequiredVerifierPackage, receivers); 11116 if (ret == PackageManager.INSTALL_SUCCEEDED 11117 && mRequiredVerifierPackage != null) { 11118 Trace.asyncTraceBegin( 11119 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 11120 /* 11121 * Send the intent to the required verification agent, 11122 * but only start the verification timeout after the 11123 * target BroadcastReceivers have run. 11124 */ 11125 verification.setComponent(requiredVerifierComponent); 11126 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 11127 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11128 new BroadcastReceiver() { 11129 @Override 11130 public void onReceive(Context context, Intent intent) { 11131 final Message msg = mHandler 11132 .obtainMessage(CHECK_PENDING_VERIFICATION); 11133 msg.arg1 = verificationId; 11134 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 11135 } 11136 }, null, 0, null, null); 11137 11138 /* 11139 * We don't want the copy to proceed until verification 11140 * succeeds, so null out this field. 11141 */ 11142 mArgs = null; 11143 } 11144 } else { 11145 /* 11146 * No package verification is enabled, so immediately start 11147 * the remote call to initiate copy using temporary file. 11148 */ 11149 ret = args.copyApk(mContainerService, true); 11150 } 11151 } 11152 11153 mRet = ret; 11154 } 11155 11156 @Override 11157 void handleReturnCode() { 11158 // If mArgs is null, then MCS couldn't be reached. When it 11159 // reconnects, it will try again to install. At that point, this 11160 // will succeed. 11161 if (mArgs != null) { 11162 processPendingInstall(mArgs, mRet); 11163 } 11164 } 11165 11166 @Override 11167 void handleServiceError() { 11168 mArgs = createInstallArgs(this); 11169 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11170 } 11171 11172 public boolean isForwardLocked() { 11173 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11174 } 11175 } 11176 11177 /** 11178 * Used during creation of InstallArgs 11179 * 11180 * @param installFlags package installation flags 11181 * @return true if should be installed on external storage 11182 */ 11183 private static boolean installOnExternalAsec(int installFlags) { 11184 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 11185 return false; 11186 } 11187 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 11188 return true; 11189 } 11190 return false; 11191 } 11192 11193 /** 11194 * Used during creation of InstallArgs 11195 * 11196 * @param installFlags package installation flags 11197 * @return true if should be installed as forward locked 11198 */ 11199 private static boolean installForwardLocked(int installFlags) { 11200 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11201 } 11202 11203 private InstallArgs createInstallArgs(InstallParams params) { 11204 if (params.move != null) { 11205 return new MoveInstallArgs(params); 11206 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 11207 return new AsecInstallArgs(params); 11208 } else { 11209 return new FileInstallArgs(params); 11210 } 11211 } 11212 11213 /** 11214 * Create args that describe an existing installed package. Typically used 11215 * when cleaning up old installs, or used as a move source. 11216 */ 11217 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 11218 String resourcePath, String[] instructionSets) { 11219 final boolean isInAsec; 11220 if (installOnExternalAsec(installFlags)) { 11221 /* Apps on SD card are always in ASEC containers. */ 11222 isInAsec = true; 11223 } else if (installForwardLocked(installFlags) 11224 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 11225 /* 11226 * Forward-locked apps are only in ASEC containers if they're the 11227 * new style 11228 */ 11229 isInAsec = true; 11230 } else { 11231 isInAsec = false; 11232 } 11233 11234 if (isInAsec) { 11235 return new AsecInstallArgs(codePath, instructionSets, 11236 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 11237 } else { 11238 return new FileInstallArgs(codePath, resourcePath, instructionSets); 11239 } 11240 } 11241 11242 static abstract class InstallArgs { 11243 /** @see InstallParams#origin */ 11244 final OriginInfo origin; 11245 /** @see InstallParams#move */ 11246 final MoveInfo move; 11247 11248 final IPackageInstallObserver2 observer; 11249 // Always refers to PackageManager flags only 11250 final int installFlags; 11251 final String installerPackageName; 11252 final String volumeUuid; 11253 final ManifestDigest manifestDigest; 11254 final UserHandle user; 11255 final String abiOverride; 11256 final String[] installGrantPermissions; 11257 /** If non-null, drop an async trace when the install completes */ 11258 final String traceMethod; 11259 final int traceCookie; 11260 11261 // The list of instruction sets supported by this app. This is currently 11262 // only used during the rmdex() phase to clean up resources. We can get rid of this 11263 // if we move dex files under the common app path. 11264 /* nullable */ String[] instructionSets; 11265 11266 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 11267 int installFlags, String installerPackageName, String volumeUuid, 11268 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 11269 String abiOverride, String[] installGrantPermissions, 11270 String traceMethod, int traceCookie) { 11271 this.origin = origin; 11272 this.move = move; 11273 this.installFlags = installFlags; 11274 this.observer = observer; 11275 this.installerPackageName = installerPackageName; 11276 this.volumeUuid = volumeUuid; 11277 this.manifestDigest = manifestDigest; 11278 this.user = user; 11279 this.instructionSets = instructionSets; 11280 this.abiOverride = abiOverride; 11281 this.installGrantPermissions = installGrantPermissions; 11282 this.traceMethod = traceMethod; 11283 this.traceCookie = traceCookie; 11284 } 11285 11286 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 11287 abstract int doPreInstall(int status); 11288 11289 /** 11290 * Rename package into final resting place. All paths on the given 11291 * scanned package should be updated to reflect the rename. 11292 */ 11293 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 11294 abstract int doPostInstall(int status, int uid); 11295 11296 /** @see PackageSettingBase#codePathString */ 11297 abstract String getCodePath(); 11298 /** @see PackageSettingBase#resourcePathString */ 11299 abstract String getResourcePath(); 11300 11301 // Need installer lock especially for dex file removal. 11302 abstract void cleanUpResourcesLI(); 11303 abstract boolean doPostDeleteLI(boolean delete); 11304 11305 /** 11306 * Called before the source arguments are copied. This is used mostly 11307 * for MoveParams when it needs to read the source file to put it in the 11308 * destination. 11309 */ 11310 int doPreCopy() { 11311 return PackageManager.INSTALL_SUCCEEDED; 11312 } 11313 11314 /** 11315 * Called after the source arguments are copied. This is used mostly for 11316 * MoveParams when it needs to read the source file to put it in the 11317 * destination. 11318 * 11319 * @return 11320 */ 11321 int doPostCopy(int uid) { 11322 return PackageManager.INSTALL_SUCCEEDED; 11323 } 11324 11325 protected boolean isFwdLocked() { 11326 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11327 } 11328 11329 protected boolean isExternalAsec() { 11330 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11331 } 11332 11333 UserHandle getUser() { 11334 return user; 11335 } 11336 } 11337 11338 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 11339 if (!allCodePaths.isEmpty()) { 11340 if (instructionSets == null) { 11341 throw new IllegalStateException("instructionSet == null"); 11342 } 11343 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 11344 for (String codePath : allCodePaths) { 11345 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 11346 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 11347 if (retCode < 0) { 11348 Slog.w(TAG, "Couldn't remove dex file for package: " 11349 + " at location " + codePath + ", retcode=" + retCode); 11350 // we don't consider this to be a failure of the core package deletion 11351 } 11352 } 11353 } 11354 } 11355 } 11356 11357 /** 11358 * Logic to handle installation of non-ASEC applications, including copying 11359 * and renaming logic. 11360 */ 11361 class FileInstallArgs extends InstallArgs { 11362 private File codeFile; 11363 private File resourceFile; 11364 11365 // Example topology: 11366 // /data/app/com.example/base.apk 11367 // /data/app/com.example/split_foo.apk 11368 // /data/app/com.example/lib/arm/libfoo.so 11369 // /data/app/com.example/lib/arm64/libfoo.so 11370 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 11371 11372 /** New install */ 11373 FileInstallArgs(InstallParams params) { 11374 super(params.origin, params.move, params.observer, params.installFlags, 11375 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11376 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11377 params.grantedRuntimePermissions, 11378 params.traceMethod, params.traceCookie); 11379 if (isFwdLocked()) { 11380 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 11381 } 11382 } 11383 11384 /** Existing install */ 11385 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 11386 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 11387 null, null, null, 0); 11388 this.codeFile = (codePath != null) ? new File(codePath) : null; 11389 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 11390 } 11391 11392 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11393 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 11394 try { 11395 return doCopyApk(imcs, temp); 11396 } finally { 11397 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11398 } 11399 } 11400 11401 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11402 if (origin.staged) { 11403 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 11404 codeFile = origin.file; 11405 resourceFile = origin.file; 11406 return PackageManager.INSTALL_SUCCEEDED; 11407 } 11408 11409 try { 11410 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 11411 codeFile = tempDir; 11412 resourceFile = tempDir; 11413 } catch (IOException e) { 11414 Slog.w(TAG, "Failed to create copy file: " + e); 11415 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11416 } 11417 11418 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 11419 @Override 11420 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 11421 if (!FileUtils.isValidExtFilename(name)) { 11422 throw new IllegalArgumentException("Invalid filename: " + name); 11423 } 11424 try { 11425 final File file = new File(codeFile, name); 11426 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 11427 O_RDWR | O_CREAT, 0644); 11428 Os.chmod(file.getAbsolutePath(), 0644); 11429 return new ParcelFileDescriptor(fd); 11430 } catch (ErrnoException e) { 11431 throw new RemoteException("Failed to open: " + e.getMessage()); 11432 } 11433 } 11434 }; 11435 11436 int ret = PackageManager.INSTALL_SUCCEEDED; 11437 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 11438 if (ret != PackageManager.INSTALL_SUCCEEDED) { 11439 Slog.e(TAG, "Failed to copy package"); 11440 return ret; 11441 } 11442 11443 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 11444 NativeLibraryHelper.Handle handle = null; 11445 try { 11446 handle = NativeLibraryHelper.Handle.create(codeFile); 11447 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 11448 abiOverride); 11449 } catch (IOException e) { 11450 Slog.e(TAG, "Copying native libraries failed", e); 11451 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11452 } finally { 11453 IoUtils.closeQuietly(handle); 11454 } 11455 11456 return ret; 11457 } 11458 11459 int doPreInstall(int status) { 11460 if (status != PackageManager.INSTALL_SUCCEEDED) { 11461 cleanUp(); 11462 } 11463 return status; 11464 } 11465 11466 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11467 if (status != PackageManager.INSTALL_SUCCEEDED) { 11468 cleanUp(); 11469 return false; 11470 } 11471 11472 final File targetDir = codeFile.getParentFile(); 11473 final File beforeCodeFile = codeFile; 11474 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 11475 11476 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 11477 try { 11478 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 11479 } catch (ErrnoException e) { 11480 Slog.w(TAG, "Failed to rename", e); 11481 return false; 11482 } 11483 11484 if (!SELinux.restoreconRecursive(afterCodeFile)) { 11485 Slog.w(TAG, "Failed to restorecon"); 11486 return false; 11487 } 11488 11489 // Reflect the rename internally 11490 codeFile = afterCodeFile; 11491 resourceFile = afterCodeFile; 11492 11493 // Reflect the rename in scanned details 11494 pkg.codePath = afterCodeFile.getAbsolutePath(); 11495 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11496 pkg.baseCodePath); 11497 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11498 pkg.splitCodePaths); 11499 11500 // Reflect the rename in app info 11501 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11502 pkg.applicationInfo.setCodePath(pkg.codePath); 11503 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11504 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11505 pkg.applicationInfo.setResourcePath(pkg.codePath); 11506 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11507 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11508 11509 return true; 11510 } 11511 11512 int doPostInstall(int status, int uid) { 11513 if (status != PackageManager.INSTALL_SUCCEEDED) { 11514 cleanUp(); 11515 } 11516 return status; 11517 } 11518 11519 @Override 11520 String getCodePath() { 11521 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11522 } 11523 11524 @Override 11525 String getResourcePath() { 11526 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11527 } 11528 11529 private boolean cleanUp() { 11530 if (codeFile == null || !codeFile.exists()) { 11531 return false; 11532 } 11533 11534 if (codeFile.isDirectory()) { 11535 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11536 } else { 11537 codeFile.delete(); 11538 } 11539 11540 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 11541 resourceFile.delete(); 11542 } 11543 11544 return true; 11545 } 11546 11547 void cleanUpResourcesLI() { 11548 // Try enumerating all code paths before deleting 11549 List<String> allCodePaths = Collections.EMPTY_LIST; 11550 if (codeFile != null && codeFile.exists()) { 11551 try { 11552 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11553 allCodePaths = pkg.getAllCodePaths(); 11554 } catch (PackageParserException e) { 11555 // Ignored; we tried our best 11556 } 11557 } 11558 11559 cleanUp(); 11560 removeDexFiles(allCodePaths, instructionSets); 11561 } 11562 11563 boolean doPostDeleteLI(boolean delete) { 11564 // XXX err, shouldn't we respect the delete flag? 11565 cleanUpResourcesLI(); 11566 return true; 11567 } 11568 } 11569 11570 private boolean isAsecExternal(String cid) { 11571 final String asecPath = PackageHelper.getSdFilesystem(cid); 11572 return !asecPath.startsWith(mAsecInternalPath); 11573 } 11574 11575 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 11576 PackageManagerException { 11577 if (copyRet < 0) { 11578 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 11579 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 11580 throw new PackageManagerException(copyRet, message); 11581 } 11582 } 11583 } 11584 11585 /** 11586 * Extract the MountService "container ID" from the full code path of an 11587 * .apk. 11588 */ 11589 static String cidFromCodePath(String fullCodePath) { 11590 int eidx = fullCodePath.lastIndexOf("/"); 11591 String subStr1 = fullCodePath.substring(0, eidx); 11592 int sidx = subStr1.lastIndexOf("/"); 11593 return subStr1.substring(sidx+1, eidx); 11594 } 11595 11596 /** 11597 * Logic to handle installation of ASEC applications, including copying and 11598 * renaming logic. 11599 */ 11600 class AsecInstallArgs extends InstallArgs { 11601 static final String RES_FILE_NAME = "pkg.apk"; 11602 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 11603 11604 String cid; 11605 String packagePath; 11606 String resourcePath; 11607 11608 /** New install */ 11609 AsecInstallArgs(InstallParams params) { 11610 super(params.origin, params.move, params.observer, params.installFlags, 11611 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11612 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11613 params.grantedRuntimePermissions, 11614 params.traceMethod, params.traceCookie); 11615 } 11616 11617 /** Existing install */ 11618 AsecInstallArgs(String fullCodePath, String[] instructionSets, 11619 boolean isExternal, boolean isForwardLocked) { 11620 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 11621 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11622 instructionSets, null, null, null, 0); 11623 // Hackily pretend we're still looking at a full code path 11624 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 11625 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 11626 } 11627 11628 // Extract cid from fullCodePath 11629 int eidx = fullCodePath.lastIndexOf("/"); 11630 String subStr1 = fullCodePath.substring(0, eidx); 11631 int sidx = subStr1.lastIndexOf("/"); 11632 cid = subStr1.substring(sidx+1, eidx); 11633 setMountPath(subStr1); 11634 } 11635 11636 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 11637 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 11638 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11639 instructionSets, null, null, null, 0); 11640 this.cid = cid; 11641 setMountPath(PackageHelper.getSdDir(cid)); 11642 } 11643 11644 void createCopyFile() { 11645 cid = mInstallerService.allocateExternalStageCidLegacy(); 11646 } 11647 11648 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11649 if (origin.staged && origin.cid != null) { 11650 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 11651 cid = origin.cid; 11652 setMountPath(PackageHelper.getSdDir(cid)); 11653 return PackageManager.INSTALL_SUCCEEDED; 11654 } 11655 11656 if (temp) { 11657 createCopyFile(); 11658 } else { 11659 /* 11660 * Pre-emptively destroy the container since it's destroyed if 11661 * copying fails due to it existing anyway. 11662 */ 11663 PackageHelper.destroySdDir(cid); 11664 } 11665 11666 final String newMountPath = imcs.copyPackageToContainer( 11667 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 11668 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 11669 11670 if (newMountPath != null) { 11671 setMountPath(newMountPath); 11672 return PackageManager.INSTALL_SUCCEEDED; 11673 } else { 11674 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11675 } 11676 } 11677 11678 @Override 11679 String getCodePath() { 11680 return packagePath; 11681 } 11682 11683 @Override 11684 String getResourcePath() { 11685 return resourcePath; 11686 } 11687 11688 int doPreInstall(int status) { 11689 if (status != PackageManager.INSTALL_SUCCEEDED) { 11690 // Destroy container 11691 PackageHelper.destroySdDir(cid); 11692 } else { 11693 boolean mounted = PackageHelper.isContainerMounted(cid); 11694 if (!mounted) { 11695 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 11696 Process.SYSTEM_UID); 11697 if (newMountPath != null) { 11698 setMountPath(newMountPath); 11699 } else { 11700 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11701 } 11702 } 11703 } 11704 return status; 11705 } 11706 11707 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11708 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 11709 String newMountPath = null; 11710 if (PackageHelper.isContainerMounted(cid)) { 11711 // Unmount the container 11712 if (!PackageHelper.unMountSdDir(cid)) { 11713 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 11714 return false; 11715 } 11716 } 11717 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11718 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 11719 " which might be stale. Will try to clean up."); 11720 // Clean up the stale container and proceed to recreate. 11721 if (!PackageHelper.destroySdDir(newCacheId)) { 11722 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 11723 return false; 11724 } 11725 // Successfully cleaned up stale container. Try to rename again. 11726 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11727 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 11728 + " inspite of cleaning it up."); 11729 return false; 11730 } 11731 } 11732 if (!PackageHelper.isContainerMounted(newCacheId)) { 11733 Slog.w(TAG, "Mounting container " + newCacheId); 11734 newMountPath = PackageHelper.mountSdDir(newCacheId, 11735 getEncryptKey(), Process.SYSTEM_UID); 11736 } else { 11737 newMountPath = PackageHelper.getSdDir(newCacheId); 11738 } 11739 if (newMountPath == null) { 11740 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 11741 return false; 11742 } 11743 Log.i(TAG, "Succesfully renamed " + cid + 11744 " to " + newCacheId + 11745 " at new path: " + newMountPath); 11746 cid = newCacheId; 11747 11748 final File beforeCodeFile = new File(packagePath); 11749 setMountPath(newMountPath); 11750 final File afterCodeFile = new File(packagePath); 11751 11752 // Reflect the rename in scanned details 11753 pkg.codePath = afterCodeFile.getAbsolutePath(); 11754 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11755 pkg.baseCodePath); 11756 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11757 pkg.splitCodePaths); 11758 11759 // Reflect the rename in app info 11760 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11761 pkg.applicationInfo.setCodePath(pkg.codePath); 11762 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11763 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11764 pkg.applicationInfo.setResourcePath(pkg.codePath); 11765 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11766 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11767 11768 return true; 11769 } 11770 11771 private void setMountPath(String mountPath) { 11772 final File mountFile = new File(mountPath); 11773 11774 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 11775 if (monolithicFile.exists()) { 11776 packagePath = monolithicFile.getAbsolutePath(); 11777 if (isFwdLocked()) { 11778 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 11779 } else { 11780 resourcePath = packagePath; 11781 } 11782 } else { 11783 packagePath = mountFile.getAbsolutePath(); 11784 resourcePath = packagePath; 11785 } 11786 } 11787 11788 int doPostInstall(int status, int uid) { 11789 if (status != PackageManager.INSTALL_SUCCEEDED) { 11790 cleanUp(); 11791 } else { 11792 final int groupOwner; 11793 final String protectedFile; 11794 if (isFwdLocked()) { 11795 groupOwner = UserHandle.getSharedAppGid(uid); 11796 protectedFile = RES_FILE_NAME; 11797 } else { 11798 groupOwner = -1; 11799 protectedFile = null; 11800 } 11801 11802 if (uid < Process.FIRST_APPLICATION_UID 11803 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 11804 Slog.e(TAG, "Failed to finalize " + cid); 11805 PackageHelper.destroySdDir(cid); 11806 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11807 } 11808 11809 boolean mounted = PackageHelper.isContainerMounted(cid); 11810 if (!mounted) { 11811 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 11812 } 11813 } 11814 return status; 11815 } 11816 11817 private void cleanUp() { 11818 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 11819 11820 // Destroy secure container 11821 PackageHelper.destroySdDir(cid); 11822 } 11823 11824 private List<String> getAllCodePaths() { 11825 final File codeFile = new File(getCodePath()); 11826 if (codeFile != null && codeFile.exists()) { 11827 try { 11828 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11829 return pkg.getAllCodePaths(); 11830 } catch (PackageParserException e) { 11831 // Ignored; we tried our best 11832 } 11833 } 11834 return Collections.EMPTY_LIST; 11835 } 11836 11837 void cleanUpResourcesLI() { 11838 // Enumerate all code paths before deleting 11839 cleanUpResourcesLI(getAllCodePaths()); 11840 } 11841 11842 private void cleanUpResourcesLI(List<String> allCodePaths) { 11843 cleanUp(); 11844 removeDexFiles(allCodePaths, instructionSets); 11845 } 11846 11847 String getPackageName() { 11848 return getAsecPackageName(cid); 11849 } 11850 11851 boolean doPostDeleteLI(boolean delete) { 11852 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 11853 final List<String> allCodePaths = getAllCodePaths(); 11854 boolean mounted = PackageHelper.isContainerMounted(cid); 11855 if (mounted) { 11856 // Unmount first 11857 if (PackageHelper.unMountSdDir(cid)) { 11858 mounted = false; 11859 } 11860 } 11861 if (!mounted && delete) { 11862 cleanUpResourcesLI(allCodePaths); 11863 } 11864 return !mounted; 11865 } 11866 11867 @Override 11868 int doPreCopy() { 11869 if (isFwdLocked()) { 11870 if (!PackageHelper.fixSdPermissions(cid, 11871 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 11872 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11873 } 11874 } 11875 11876 return PackageManager.INSTALL_SUCCEEDED; 11877 } 11878 11879 @Override 11880 int doPostCopy(int uid) { 11881 if (isFwdLocked()) { 11882 if (uid < Process.FIRST_APPLICATION_UID 11883 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 11884 RES_FILE_NAME)) { 11885 Slog.e(TAG, "Failed to finalize " + cid); 11886 PackageHelper.destroySdDir(cid); 11887 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11888 } 11889 } 11890 11891 return PackageManager.INSTALL_SUCCEEDED; 11892 } 11893 } 11894 11895 /** 11896 * Logic to handle movement of existing installed applications. 11897 */ 11898 class MoveInstallArgs extends InstallArgs { 11899 private File codeFile; 11900 private File resourceFile; 11901 11902 /** New install */ 11903 MoveInstallArgs(InstallParams params) { 11904 super(params.origin, params.move, params.observer, params.installFlags, 11905 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11906 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11907 params.grantedRuntimePermissions, 11908 params.traceMethod, params.traceCookie); 11909 } 11910 11911 int copyApk(IMediaContainerService imcs, boolean temp) { 11912 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 11913 + move.fromUuid + " to " + move.toUuid); 11914 synchronized (mInstaller) { 11915 if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName, 11916 move.dataAppName, move.appId, move.seinfo) != 0) { 11917 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11918 } 11919 } 11920 11921 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 11922 resourceFile = codeFile; 11923 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 11924 11925 return PackageManager.INSTALL_SUCCEEDED; 11926 } 11927 11928 int doPreInstall(int status) { 11929 if (status != PackageManager.INSTALL_SUCCEEDED) { 11930 cleanUp(move.toUuid); 11931 } 11932 return status; 11933 } 11934 11935 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11936 if (status != PackageManager.INSTALL_SUCCEEDED) { 11937 cleanUp(move.toUuid); 11938 return false; 11939 } 11940 11941 // Reflect the move in app info 11942 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11943 pkg.applicationInfo.setCodePath(pkg.codePath); 11944 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11945 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11946 pkg.applicationInfo.setResourcePath(pkg.codePath); 11947 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11948 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11949 11950 return true; 11951 } 11952 11953 int doPostInstall(int status, int uid) { 11954 if (status == PackageManager.INSTALL_SUCCEEDED) { 11955 cleanUp(move.fromUuid); 11956 } else { 11957 cleanUp(move.toUuid); 11958 } 11959 return status; 11960 } 11961 11962 @Override 11963 String getCodePath() { 11964 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11965 } 11966 11967 @Override 11968 String getResourcePath() { 11969 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11970 } 11971 11972 private boolean cleanUp(String volumeUuid) { 11973 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 11974 move.dataAppName); 11975 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 11976 synchronized (mInstallLock) { 11977 // Clean up both app data and code 11978 removeDataDirsLI(volumeUuid, move.packageName); 11979 if (codeFile.isDirectory()) { 11980 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11981 } else { 11982 codeFile.delete(); 11983 } 11984 } 11985 return true; 11986 } 11987 11988 void cleanUpResourcesLI() { 11989 throw new UnsupportedOperationException(); 11990 } 11991 11992 boolean doPostDeleteLI(boolean delete) { 11993 throw new UnsupportedOperationException(); 11994 } 11995 } 11996 11997 static String getAsecPackageName(String packageCid) { 11998 int idx = packageCid.lastIndexOf("-"); 11999 if (idx == -1) { 12000 return packageCid; 12001 } 12002 return packageCid.substring(0, idx); 12003 } 12004 12005 // Utility method used to create code paths based on package name and available index. 12006 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 12007 String idxStr = ""; 12008 int idx = 1; 12009 // Fall back to default value of idx=1 if prefix is not 12010 // part of oldCodePath 12011 if (oldCodePath != null) { 12012 String subStr = oldCodePath; 12013 // Drop the suffix right away 12014 if (suffix != null && subStr.endsWith(suffix)) { 12015 subStr = subStr.substring(0, subStr.length() - suffix.length()); 12016 } 12017 // If oldCodePath already contains prefix find out the 12018 // ending index to either increment or decrement. 12019 int sidx = subStr.lastIndexOf(prefix); 12020 if (sidx != -1) { 12021 subStr = subStr.substring(sidx + prefix.length()); 12022 if (subStr != null) { 12023 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 12024 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 12025 } 12026 try { 12027 idx = Integer.parseInt(subStr); 12028 if (idx <= 1) { 12029 idx++; 12030 } else { 12031 idx--; 12032 } 12033 } catch(NumberFormatException e) { 12034 } 12035 } 12036 } 12037 } 12038 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 12039 return prefix + idxStr; 12040 } 12041 12042 private File getNextCodePath(File targetDir, String packageName) { 12043 int suffix = 1; 12044 File result; 12045 do { 12046 result = new File(targetDir, packageName + "-" + suffix); 12047 suffix++; 12048 } while (result.exists()); 12049 return result; 12050 } 12051 12052 // Utility method that returns the relative package path with respect 12053 // to the installation directory. Like say for /data/data/com.test-1.apk 12054 // string com.test-1 is returned. 12055 static String deriveCodePathName(String codePath) { 12056 if (codePath == null) { 12057 return null; 12058 } 12059 final File codeFile = new File(codePath); 12060 final String name = codeFile.getName(); 12061 if (codeFile.isDirectory()) { 12062 return name; 12063 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 12064 final int lastDot = name.lastIndexOf('.'); 12065 return name.substring(0, lastDot); 12066 } else { 12067 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 12068 return null; 12069 } 12070 } 12071 12072 class PackageInstalledInfo { 12073 String name; 12074 int uid; 12075 // The set of users that originally had this package installed. 12076 int[] origUsers; 12077 // The set of users that now have this package installed. 12078 int[] newUsers; 12079 PackageParser.Package pkg; 12080 int returnCode; 12081 String returnMsg; 12082 PackageRemovedInfo removedInfo; 12083 12084 public void setError(int code, String msg) { 12085 returnCode = code; 12086 returnMsg = msg; 12087 Slog.w(TAG, msg); 12088 } 12089 12090 public void setError(String msg, PackageParserException e) { 12091 returnCode = e.error; 12092 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 12093 Slog.w(TAG, msg, e); 12094 } 12095 12096 public void setError(String msg, PackageManagerException e) { 12097 returnCode = e.error; 12098 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 12099 Slog.w(TAG, msg, e); 12100 } 12101 12102 // In some error cases we want to convey more info back to the observer 12103 String origPackage; 12104 String origPermission; 12105 } 12106 12107 /* 12108 * Install a non-existing package. 12109 */ 12110 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 12111 UserHandle user, String installerPackageName, String volumeUuid, 12112 PackageInstalledInfo res) { 12113 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 12114 12115 // Remember this for later, in case we need to rollback this install 12116 String pkgName = pkg.packageName; 12117 12118 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 12119 // TODO: b/23350563 12120 final boolean dataDirExists = Environment 12121 .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists(); 12122 12123 synchronized(mPackages) { 12124 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 12125 // A package with the same name is already installed, though 12126 // it has been renamed to an older name. The package we 12127 // are trying to install should be installed as an update to 12128 // the existing one, but that has not been requested, so bail. 12129 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 12130 + " without first uninstalling package running as " 12131 + mSettings.mRenamedPackages.get(pkgName)); 12132 return; 12133 } 12134 if (mPackages.containsKey(pkgName)) { 12135 // Don't allow installation over an existing package with the same name. 12136 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 12137 + " without first uninstalling."); 12138 return; 12139 } 12140 } 12141 12142 try { 12143 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 12144 System.currentTimeMillis(), user); 12145 12146 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 12147 // delete the partially installed application. the data directory will have to be 12148 // restored if it was already existing 12149 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12150 // remove package from internal structures. Note that we want deletePackageX to 12151 // delete the package data and cache directories that it created in 12152 // scanPackageLocked, unless those directories existed before we even tried to 12153 // install. 12154 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 12155 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 12156 res.removedInfo, true); 12157 } 12158 12159 } catch (PackageManagerException e) { 12160 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12161 } 12162 12163 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12164 } 12165 12166 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 12167 // Can't rotate keys during boot or if sharedUser. 12168 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 12169 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 12170 return false; 12171 } 12172 // app is using upgradeKeySets; make sure all are valid 12173 KeySetManagerService ksms = mSettings.mKeySetManagerService; 12174 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 12175 for (int i = 0; i < upgradeKeySets.length; i++) { 12176 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 12177 Slog.wtf(TAG, "Package " 12178 + (oldPs.name != null ? oldPs.name : "<null>") 12179 + " contains upgrade-key-set reference to unknown key-set: " 12180 + upgradeKeySets[i] 12181 + " reverting to signatures check."); 12182 return false; 12183 } 12184 } 12185 return true; 12186 } 12187 12188 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 12189 // Upgrade keysets are being used. Determine if new package has a superset of the 12190 // required keys. 12191 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 12192 KeySetManagerService ksms = mSettings.mKeySetManagerService; 12193 for (int i = 0; i < upgradeKeySets.length; i++) { 12194 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 12195 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 12196 return true; 12197 } 12198 } 12199 return false; 12200 } 12201 12202 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 12203 UserHandle user, String installerPackageName, String volumeUuid, 12204 PackageInstalledInfo res) { 12205 final PackageParser.Package oldPackage; 12206 final String pkgName = pkg.packageName; 12207 final int[] allUsers; 12208 final boolean[] perUserInstalled; 12209 12210 // First find the old package info and check signatures 12211 synchronized(mPackages) { 12212 oldPackage = mPackages.get(pkgName); 12213 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 12214 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12215 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12216 if(!checkUpgradeKeySetLP(ps, pkg)) { 12217 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 12218 "New package not signed by keys specified by upgrade-keysets: " 12219 + pkgName); 12220 return; 12221 } 12222 } else { 12223 // default to original signature matching 12224 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 12225 != PackageManager.SIGNATURE_MATCH) { 12226 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 12227 "New package has a different signature: " + pkgName); 12228 return; 12229 } 12230 } 12231 12232 // In case of rollback, remember per-user/profile install state 12233 allUsers = sUserManager.getUserIds(); 12234 perUserInstalled = new boolean[allUsers.length]; 12235 for (int i = 0; i < allUsers.length; i++) { 12236 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12237 } 12238 } 12239 12240 boolean sysPkg = (isSystemApp(oldPackage)); 12241 if (sysPkg) { 12242 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 12243 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 12244 } else { 12245 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 12246 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 12247 } 12248 } 12249 12250 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 12251 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 12252 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 12253 String volumeUuid, PackageInstalledInfo res) { 12254 String pkgName = deletedPackage.packageName; 12255 boolean deletedPkg = true; 12256 boolean updatedSettings = false; 12257 12258 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 12259 + deletedPackage); 12260 long origUpdateTime; 12261 if (pkg.mExtras != null) { 12262 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 12263 } else { 12264 origUpdateTime = 0; 12265 } 12266 12267 // First delete the existing package while retaining the data directory 12268 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 12269 res.removedInfo, true)) { 12270 // If the existing package wasn't successfully deleted 12271 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 12272 deletedPkg = false; 12273 } else { 12274 // Successfully deleted the old package; proceed with replace. 12275 12276 // If deleted package lived in a container, give users a chance to 12277 // relinquish resources before killing. 12278 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 12279 if (DEBUG_INSTALL) { 12280 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 12281 } 12282 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 12283 final ArrayList<String> pkgList = new ArrayList<String>(1); 12284 pkgList.add(deletedPackage.applicationInfo.packageName); 12285 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 12286 } 12287 12288 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 12289 try { 12290 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 12291 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 12292 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12293 perUserInstalled, res, user); 12294 updatedSettings = true; 12295 } catch (PackageManagerException e) { 12296 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12297 } 12298 } 12299 12300 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12301 // remove package from internal structures. Note that we want deletePackageX to 12302 // delete the package data and cache directories that it created in 12303 // scanPackageLocked, unless those directories existed before we even tried to 12304 // install. 12305 if(updatedSettings) { 12306 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 12307 deletePackageLI( 12308 pkgName, null, true, allUsers, perUserInstalled, 12309 PackageManager.DELETE_KEEP_DATA, 12310 res.removedInfo, true); 12311 } 12312 // Since we failed to install the new package we need to restore the old 12313 // package that we deleted. 12314 if (deletedPkg) { 12315 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 12316 File restoreFile = new File(deletedPackage.codePath); 12317 // Parse old package 12318 boolean oldExternal = isExternal(deletedPackage); 12319 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 12320 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 12321 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 12322 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 12323 try { 12324 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 12325 null); 12326 } catch (PackageManagerException e) { 12327 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 12328 + e.getMessage()); 12329 return; 12330 } 12331 // Restore of old package succeeded. Update permissions. 12332 // writer 12333 synchronized (mPackages) { 12334 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 12335 UPDATE_PERMISSIONS_ALL); 12336 // can downgrade to reader 12337 mSettings.writeLPr(); 12338 } 12339 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 12340 } 12341 } 12342 } 12343 12344 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 12345 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 12346 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 12347 String volumeUuid, PackageInstalledInfo res) { 12348 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 12349 + ", old=" + deletedPackage); 12350 boolean disabledSystem = false; 12351 boolean updatedSettings = false; 12352 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 12353 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 12354 != 0) { 12355 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12356 } 12357 String packageName = deletedPackage.packageName; 12358 if (packageName == null) { 12359 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12360 "Attempt to delete null packageName."); 12361 return; 12362 } 12363 PackageParser.Package oldPkg; 12364 PackageSetting oldPkgSetting; 12365 // reader 12366 synchronized (mPackages) { 12367 oldPkg = mPackages.get(packageName); 12368 oldPkgSetting = mSettings.mPackages.get(packageName); 12369 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 12370 (oldPkgSetting == null)) { 12371 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12372 "Couldn't find package:" + packageName + " information"); 12373 return; 12374 } 12375 } 12376 12377 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 12378 12379 res.removedInfo.uid = oldPkg.applicationInfo.uid; 12380 res.removedInfo.removedPackage = packageName; 12381 // Remove existing system package 12382 removePackageLI(oldPkgSetting, true); 12383 // writer 12384 synchronized (mPackages) { 12385 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 12386 if (!disabledSystem && deletedPackage != null) { 12387 // We didn't need to disable the .apk as a current system package, 12388 // which means we are replacing another update that is already 12389 // installed. We need to make sure to delete the older one's .apk. 12390 res.removedInfo.args = createInstallArgsForExisting(0, 12391 deletedPackage.applicationInfo.getCodePath(), 12392 deletedPackage.applicationInfo.getResourcePath(), 12393 getAppDexInstructionSets(deletedPackage.applicationInfo)); 12394 } else { 12395 res.removedInfo.args = null; 12396 } 12397 } 12398 12399 // Successfully disabled the old package. Now proceed with re-installation 12400 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 12401 12402 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12403 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 12404 12405 PackageParser.Package newPackage = null; 12406 try { 12407 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 12408 if (newPackage.mExtras != null) { 12409 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 12410 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 12411 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 12412 12413 // is the update attempting to change shared user? that isn't going to work... 12414 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 12415 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 12416 "Forbidding shared user change from " + oldPkgSetting.sharedUser 12417 + " to " + newPkgSetting.sharedUser); 12418 updatedSettings = true; 12419 } 12420 } 12421 12422 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12423 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12424 perUserInstalled, res, user); 12425 updatedSettings = true; 12426 } 12427 12428 } catch (PackageManagerException e) { 12429 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12430 } 12431 12432 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12433 // Re installation failed. Restore old information 12434 // Remove new pkg information 12435 if (newPackage != null) { 12436 removeInstalledPackageLI(newPackage, true); 12437 } 12438 // Add back the old system package 12439 try { 12440 scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 12441 } catch (PackageManagerException e) { 12442 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 12443 } 12444 // Restore the old system information in Settings 12445 synchronized (mPackages) { 12446 if (disabledSystem) { 12447 mSettings.enableSystemPackageLPw(packageName); 12448 } 12449 if (updatedSettings) { 12450 mSettings.setInstallerPackageName(packageName, 12451 oldPkgSetting.installerPackageName); 12452 } 12453 mSettings.writeLPr(); 12454 } 12455 } 12456 } 12457 12458 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 12459 // Collect all used permissions in the UID 12460 ArraySet<String> usedPermissions = new ArraySet<>(); 12461 final int packageCount = su.packages.size(); 12462 for (int i = 0; i < packageCount; i++) { 12463 PackageSetting ps = su.packages.valueAt(i); 12464 if (ps.pkg == null) { 12465 continue; 12466 } 12467 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 12468 for (int j = 0; j < requestedPermCount; j++) { 12469 String permission = ps.pkg.requestedPermissions.get(j); 12470 BasePermission bp = mSettings.mPermissions.get(permission); 12471 if (bp != null) { 12472 usedPermissions.add(permission); 12473 } 12474 } 12475 } 12476 12477 PermissionsState permissionsState = su.getPermissionsState(); 12478 // Prune install permissions 12479 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 12480 final int installPermCount = installPermStates.size(); 12481 for (int i = installPermCount - 1; i >= 0; i--) { 12482 PermissionState permissionState = installPermStates.get(i); 12483 if (!usedPermissions.contains(permissionState.getName())) { 12484 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 12485 if (bp != null) { 12486 permissionsState.revokeInstallPermission(bp); 12487 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 12488 PackageManager.MASK_PERMISSION_FLAGS, 0); 12489 } 12490 } 12491 } 12492 12493 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 12494 12495 // Prune runtime permissions 12496 for (int userId : allUserIds) { 12497 List<PermissionState> runtimePermStates = permissionsState 12498 .getRuntimePermissionStates(userId); 12499 final int runtimePermCount = runtimePermStates.size(); 12500 for (int i = runtimePermCount - 1; i >= 0; i--) { 12501 PermissionState permissionState = runtimePermStates.get(i); 12502 if (!usedPermissions.contains(permissionState.getName())) { 12503 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 12504 if (bp != null) { 12505 permissionsState.revokeRuntimePermission(bp, userId); 12506 permissionsState.updatePermissionFlags(bp, userId, 12507 PackageManager.MASK_PERMISSION_FLAGS, 0); 12508 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 12509 runtimePermissionChangedUserIds, userId); 12510 } 12511 } 12512 } 12513 } 12514 12515 return runtimePermissionChangedUserIds; 12516 } 12517 12518 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 12519 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 12520 UserHandle user) { 12521 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 12522 12523 String pkgName = newPackage.packageName; 12524 synchronized (mPackages) { 12525 //write settings. the installStatus will be incomplete at this stage. 12526 //note that the new package setting would have already been 12527 //added to mPackages. It hasn't been persisted yet. 12528 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 12529 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 12530 mSettings.writeLPr(); 12531 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12532 } 12533 12534 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 12535 synchronized (mPackages) { 12536 updatePermissionsLPw(newPackage.packageName, newPackage, 12537 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 12538 ? UPDATE_PERMISSIONS_ALL : 0)); 12539 // For system-bundled packages, we assume that installing an upgraded version 12540 // of the package implies that the user actually wants to run that new code, 12541 // so we enable the package. 12542 PackageSetting ps = mSettings.mPackages.get(pkgName); 12543 if (ps != null) { 12544 if (isSystemApp(newPackage)) { 12545 // NB: implicit assumption that system package upgrades apply to all users 12546 if (DEBUG_INSTALL) { 12547 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 12548 } 12549 if (res.origUsers != null) { 12550 for (int userHandle : res.origUsers) { 12551 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 12552 userHandle, installerPackageName); 12553 } 12554 } 12555 // Also convey the prior install/uninstall state 12556 if (allUsers != null && perUserInstalled != null) { 12557 for (int i = 0; i < allUsers.length; i++) { 12558 if (DEBUG_INSTALL) { 12559 Slog.d(TAG, " user " + allUsers[i] 12560 + " => " + perUserInstalled[i]); 12561 } 12562 ps.setInstalled(perUserInstalled[i], allUsers[i]); 12563 } 12564 // these install state changes will be persisted in the 12565 // upcoming call to mSettings.writeLPr(). 12566 } 12567 } 12568 // It's implied that when a user requests installation, they want the app to be 12569 // installed and enabled. 12570 int userId = user.getIdentifier(); 12571 if (userId != UserHandle.USER_ALL) { 12572 ps.setInstalled(true, userId); 12573 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 12574 } 12575 } 12576 res.name = pkgName; 12577 res.uid = newPackage.applicationInfo.uid; 12578 res.pkg = newPackage; 12579 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 12580 mSettings.setInstallerPackageName(pkgName, installerPackageName); 12581 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12582 //to update install status 12583 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 12584 mSettings.writeLPr(); 12585 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12586 } 12587 12588 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12589 } 12590 12591 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 12592 try { 12593 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 12594 installPackageLI(args, res); 12595 } finally { 12596 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12597 } 12598 } 12599 12600 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 12601 final int installFlags = args.installFlags; 12602 final String installerPackageName = args.installerPackageName; 12603 final String volumeUuid = args.volumeUuid; 12604 final File tmpPackageFile = new File(args.getCodePath()); 12605 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 12606 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 12607 || (args.volumeUuid != null)); 12608 final boolean quickInstall = ((installFlags & PackageManager.INSTALL_QUICK) != 0); 12609 boolean replace = false; 12610 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 12611 if (args.move != null) { 12612 // moving a complete application; perfom an initial scan on the new install location 12613 scanFlags |= SCAN_INITIAL; 12614 } 12615 // Result object to be returned 12616 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12617 12618 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 12619 12620 // Retrieve PackageSettings and parse package 12621 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 12622 | PackageParser.PARSE_ENFORCE_CODE 12623 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 12624 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 12625 | (quickInstall ? PackageParser.PARSE_SKIP_VERIFICATION : 0); 12626 PackageParser pp = new PackageParser(); 12627 pp.setSeparateProcesses(mSeparateProcesses); 12628 pp.setDisplayMetrics(mMetrics); 12629 12630 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 12631 final PackageParser.Package pkg; 12632 try { 12633 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 12634 } catch (PackageParserException e) { 12635 res.setError("Failed parse during installPackageLI", e); 12636 return; 12637 } finally { 12638 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12639 } 12640 12641 // Mark that we have an install time CPU ABI override. 12642 pkg.cpuAbiOverride = args.abiOverride; 12643 12644 String pkgName = res.name = pkg.packageName; 12645 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 12646 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 12647 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 12648 return; 12649 } 12650 } 12651 12652 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 12653 try { 12654 pp.collectCertificates(pkg, parseFlags); 12655 } catch (PackageParserException e) { 12656 res.setError("Failed collect during installPackageLI", e); 12657 return; 12658 } finally { 12659 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12660 } 12661 12662 /* If the installer passed in a manifest digest, compare it now. */ 12663 if (args.manifestDigest != null) { 12664 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectManifestDigest"); 12665 try { 12666 pp.collectManifestDigest(pkg); 12667 } catch (PackageParserException e) { 12668 res.setError("Failed collect during installPackageLI", e); 12669 return; 12670 } finally { 12671 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12672 } 12673 12674 if (DEBUG_INSTALL) { 12675 final String parsedManifest = pkg.manifestDigest == null ? "null" 12676 : pkg.manifestDigest.toString(); 12677 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 12678 + parsedManifest); 12679 } 12680 12681 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 12682 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 12683 return; 12684 } 12685 } else if (DEBUG_INSTALL) { 12686 final String parsedManifest = pkg.manifestDigest == null 12687 ? "null" : pkg.manifestDigest.toString(); 12688 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 12689 } 12690 12691 // Get rid of all references to package scan path via parser. 12692 pp = null; 12693 String oldCodePath = null; 12694 boolean systemApp = false; 12695 synchronized (mPackages) { 12696 // Check if installing already existing package 12697 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12698 String oldName = mSettings.mRenamedPackages.get(pkgName); 12699 if (pkg.mOriginalPackages != null 12700 && pkg.mOriginalPackages.contains(oldName) 12701 && mPackages.containsKey(oldName)) { 12702 // This package is derived from an original package, 12703 // and this device has been updating from that original 12704 // name. We must continue using the original name, so 12705 // rename the new package here. 12706 pkg.setPackageName(oldName); 12707 pkgName = pkg.packageName; 12708 replace = true; 12709 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 12710 + oldName + " pkgName=" + pkgName); 12711 } else if (mPackages.containsKey(pkgName)) { 12712 // This package, under its official name, already exists 12713 // on the device; we should replace it. 12714 replace = true; 12715 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 12716 } 12717 12718 // Prevent apps opting out from runtime permissions 12719 if (replace) { 12720 PackageParser.Package oldPackage = mPackages.get(pkgName); 12721 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 12722 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 12723 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 12724 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 12725 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 12726 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 12727 + " doesn't support runtime permissions but the old" 12728 + " target SDK " + oldTargetSdk + " does."); 12729 return; 12730 } 12731 } 12732 } 12733 12734 PackageSetting ps = mSettings.mPackages.get(pkgName); 12735 if (ps != null) { 12736 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 12737 12738 // Quick sanity check that we're signed correctly if updating; 12739 // we'll check this again later when scanning, but we want to 12740 // bail early here before tripping over redefined permissions. 12741 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12742 if (!checkUpgradeKeySetLP(ps, pkg)) { 12743 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 12744 + pkg.packageName + " upgrade keys do not match the " 12745 + "previously installed version"); 12746 return; 12747 } 12748 } else { 12749 try { 12750 verifySignaturesLP(ps, pkg); 12751 } catch (PackageManagerException e) { 12752 res.setError(e.error, e.getMessage()); 12753 return; 12754 } 12755 } 12756 12757 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 12758 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 12759 systemApp = (ps.pkg.applicationInfo.flags & 12760 ApplicationInfo.FLAG_SYSTEM) != 0; 12761 } 12762 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12763 } 12764 12765 // Check whether the newly-scanned package wants to define an already-defined perm 12766 int N = pkg.permissions.size(); 12767 for (int i = N-1; i >= 0; i--) { 12768 PackageParser.Permission perm = pkg.permissions.get(i); 12769 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 12770 if (bp != null) { 12771 // If the defining package is signed with our cert, it's okay. This 12772 // also includes the "updating the same package" case, of course. 12773 // "updating same package" could also involve key-rotation. 12774 final boolean sigsOk; 12775 if (bp.sourcePackage.equals(pkg.packageName) 12776 && (bp.packageSetting instanceof PackageSetting) 12777 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 12778 scanFlags))) { 12779 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 12780 } else { 12781 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 12782 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 12783 } 12784 if (!sigsOk) { 12785 // If the owning package is the system itself, we log but allow 12786 // install to proceed; we fail the install on all other permission 12787 // redefinitions. 12788 if (!bp.sourcePackage.equals("android")) { 12789 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 12790 + pkg.packageName + " attempting to redeclare permission " 12791 + perm.info.name + " already owned by " + bp.sourcePackage); 12792 res.origPermission = perm.info.name; 12793 res.origPackage = bp.sourcePackage; 12794 return; 12795 } else { 12796 Slog.w(TAG, "Package " + pkg.packageName 12797 + " attempting to redeclare system permission " 12798 + perm.info.name + "; ignoring new declaration"); 12799 pkg.permissions.remove(i); 12800 } 12801 } 12802 } 12803 } 12804 12805 } 12806 12807 if (systemApp && onExternal) { 12808 // Disable updates to system apps on sdcard 12809 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 12810 "Cannot install updates to system apps on sdcard"); 12811 return; 12812 } 12813 12814 if (args.move != null) { 12815 // We did an in-place move, so dex is ready to roll 12816 scanFlags |= SCAN_NO_DEX; 12817 scanFlags |= SCAN_MOVE; 12818 12819 synchronized (mPackages) { 12820 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12821 if (ps == null) { 12822 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 12823 "Missing settings for moved package " + pkgName); 12824 } 12825 12826 // We moved the entire application as-is, so bring over the 12827 // previously derived ABI information. 12828 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 12829 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 12830 } 12831 12832 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 12833 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 12834 scanFlags |= SCAN_NO_DEX; 12835 12836 try { 12837 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 12838 true /* extract libs */); 12839 } catch (PackageManagerException pme) { 12840 Slog.e(TAG, "Error deriving application ABI", pme); 12841 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 12842 return; 12843 } 12844 } 12845 12846 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 12847 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 12848 return; 12849 } 12850 12851 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 12852 12853 if (replace) { 12854 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 12855 installerPackageName, volumeUuid, res); 12856 } else { 12857 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 12858 args.user, installerPackageName, volumeUuid, res); 12859 } 12860 synchronized (mPackages) { 12861 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12862 if (ps != null) { 12863 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12864 } 12865 } 12866 } 12867 12868 private void startIntentFilterVerifications(int userId, boolean replacing, 12869 PackageParser.Package pkg) { 12870 if (mIntentFilterVerifierComponent == null) { 12871 Slog.w(TAG, "No IntentFilter verification will not be done as " 12872 + "there is no IntentFilterVerifier available!"); 12873 return; 12874 } 12875 12876 final int verifierUid = getPackageUid( 12877 mIntentFilterVerifierComponent.getPackageName(), 12878 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 12879 12880 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 12881 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 12882 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 12883 mHandler.sendMessage(msg); 12884 } 12885 12886 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 12887 PackageParser.Package pkg) { 12888 int size = pkg.activities.size(); 12889 if (size == 0) { 12890 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12891 "No activity, so no need to verify any IntentFilter!"); 12892 return; 12893 } 12894 12895 final boolean hasDomainURLs = hasDomainURLs(pkg); 12896 if (!hasDomainURLs) { 12897 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12898 "No domain URLs, so no need to verify any IntentFilter!"); 12899 return; 12900 } 12901 12902 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 12903 + " if any IntentFilter from the " + size 12904 + " Activities needs verification ..."); 12905 12906 int count = 0; 12907 final String packageName = pkg.packageName; 12908 12909 synchronized (mPackages) { 12910 // If this is a new install and we see that we've already run verification for this 12911 // package, we have nothing to do: it means the state was restored from backup. 12912 if (!replacing) { 12913 IntentFilterVerificationInfo ivi = 12914 mSettings.getIntentFilterVerificationLPr(packageName); 12915 if (ivi != null) { 12916 if (DEBUG_DOMAIN_VERIFICATION) { 12917 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 12918 + ivi.getStatusString()); 12919 } 12920 return; 12921 } 12922 } 12923 12924 // If any filters need to be verified, then all need to be. 12925 boolean needToVerify = false; 12926 for (PackageParser.Activity a : pkg.activities) { 12927 for (ActivityIntentInfo filter : a.intents) { 12928 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 12929 if (DEBUG_DOMAIN_VERIFICATION) { 12930 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 12931 } 12932 needToVerify = true; 12933 break; 12934 } 12935 } 12936 } 12937 12938 if (needToVerify) { 12939 final int verificationId = mIntentFilterVerificationToken++; 12940 for (PackageParser.Activity a : pkg.activities) { 12941 for (ActivityIntentInfo filter : a.intents) { 12942 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 12943 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12944 "Verification needed for IntentFilter:" + filter.toString()); 12945 mIntentFilterVerifier.addOneIntentFilterVerification( 12946 verifierUid, userId, verificationId, filter, packageName); 12947 count++; 12948 } 12949 } 12950 } 12951 } 12952 } 12953 12954 if (count > 0) { 12955 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 12956 + " IntentFilter verification" + (count > 1 ? "s" : "") 12957 + " for userId:" + userId); 12958 mIntentFilterVerifier.startVerifications(userId); 12959 } else { 12960 if (DEBUG_DOMAIN_VERIFICATION) { 12961 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 12962 } 12963 } 12964 } 12965 12966 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 12967 final ComponentName cn = filter.activity.getComponentName(); 12968 final String packageName = cn.getPackageName(); 12969 12970 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 12971 packageName); 12972 if (ivi == null) { 12973 return true; 12974 } 12975 int status = ivi.getStatus(); 12976 switch (status) { 12977 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 12978 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 12979 return true; 12980 12981 default: 12982 // Nothing to do 12983 return false; 12984 } 12985 } 12986 12987 private static boolean isMultiArch(PackageSetting ps) { 12988 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12989 } 12990 12991 private static boolean isMultiArch(ApplicationInfo info) { 12992 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12993 } 12994 12995 private static boolean isExternal(PackageParser.Package pkg) { 12996 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12997 } 12998 12999 private static boolean isExternal(PackageSetting ps) { 13000 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 13001 } 13002 13003 private static boolean isExternal(ApplicationInfo info) { 13004 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 13005 } 13006 13007 private static boolean isSystemApp(PackageParser.Package pkg) { 13008 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 13009 } 13010 13011 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 13012 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 13013 } 13014 13015 private static boolean hasDomainURLs(PackageParser.Package pkg) { 13016 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 13017 } 13018 13019 private static boolean isSystemApp(PackageSetting ps) { 13020 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 13021 } 13022 13023 private static boolean isUpdatedSystemApp(PackageSetting ps) { 13024 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 13025 } 13026 13027 private int packageFlagsToInstallFlags(PackageSetting ps) { 13028 int installFlags = 0; 13029 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 13030 // This existing package was an external ASEC install when we have 13031 // the external flag without a UUID 13032 installFlags |= PackageManager.INSTALL_EXTERNAL; 13033 } 13034 if (ps.isForwardLocked()) { 13035 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 13036 } 13037 return installFlags; 13038 } 13039 13040 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 13041 if (isExternal(pkg)) { 13042 if (TextUtils.isEmpty(pkg.volumeUuid)) { 13043 return StorageManager.UUID_PRIMARY_PHYSICAL; 13044 } else { 13045 return pkg.volumeUuid; 13046 } 13047 } else { 13048 return StorageManager.UUID_PRIVATE_INTERNAL; 13049 } 13050 } 13051 13052 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 13053 if (isExternal(pkg)) { 13054 if (TextUtils.isEmpty(pkg.volumeUuid)) { 13055 return mSettings.getExternalVersion(); 13056 } else { 13057 return mSettings.findOrCreateVersion(pkg.volumeUuid); 13058 } 13059 } else { 13060 return mSettings.getInternalVersion(); 13061 } 13062 } 13063 13064 private void deleteTempPackageFiles() { 13065 final FilenameFilter filter = new FilenameFilter() { 13066 public boolean accept(File dir, String name) { 13067 return name.startsWith("vmdl") && name.endsWith(".tmp"); 13068 } 13069 }; 13070 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 13071 file.delete(); 13072 } 13073 } 13074 13075 @Override 13076 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 13077 int flags) { 13078 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 13079 flags); 13080 } 13081 13082 @Override 13083 public void deletePackage(final String packageName, 13084 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 13085 mContext.enforceCallingOrSelfPermission( 13086 android.Manifest.permission.DELETE_PACKAGES, null); 13087 Preconditions.checkNotNull(packageName); 13088 Preconditions.checkNotNull(observer); 13089 final int uid = Binder.getCallingUid(); 13090 final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0; 13091 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 13092 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 13093 mContext.enforceCallingOrSelfPermission( 13094 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 13095 "deletePackage for user " + userId); 13096 } 13097 13098 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 13099 try { 13100 observer.onPackageDeleted(packageName, 13101 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 13102 } catch (RemoteException re) { 13103 } 13104 return; 13105 } 13106 13107 for (int currentUserId : users) { 13108 if (getBlockUninstallForUser(packageName, currentUserId)) { 13109 try { 13110 observer.onPackageDeleted(packageName, 13111 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 13112 } catch (RemoteException re) { 13113 } 13114 return; 13115 } 13116 } 13117 13118 if (DEBUG_REMOVE) { 13119 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 13120 } 13121 // Queue up an async operation since the package deletion may take a little while. 13122 mHandler.post(new Runnable() { 13123 public void run() { 13124 mHandler.removeCallbacks(this); 13125 final int returnCode = deletePackageX(packageName, userId, flags); 13126 try { 13127 observer.onPackageDeleted(packageName, returnCode, null); 13128 } catch (RemoteException e) { 13129 Log.i(TAG, "Observer no longer exists."); 13130 } //end catch 13131 } //end run 13132 }); 13133 } 13134 13135 private boolean isPackageDeviceAdmin(String packageName, int userId) { 13136 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 13137 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 13138 try { 13139 if (dpm != null) { 13140 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 13141 /* callingUserOnly =*/ false); 13142 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 13143 : deviceOwnerComponentName.getPackageName(); 13144 // Does the package contains the device owner? 13145 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 13146 // this check is probably not needed, since DO should be registered as a device 13147 // admin on some user too. (Original bug for this: b/17657954) 13148 if (packageName.equals(deviceOwnerPackageName)) { 13149 return true; 13150 } 13151 // Does it contain a device admin for any user? 13152 int[] users; 13153 if (userId == UserHandle.USER_ALL) { 13154 users = sUserManager.getUserIds(); 13155 } else { 13156 users = new int[]{userId}; 13157 } 13158 for (int i = 0; i < users.length; ++i) { 13159 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 13160 return true; 13161 } 13162 } 13163 } 13164 } catch (RemoteException e) { 13165 } 13166 return false; 13167 } 13168 13169 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 13170 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 13171 } 13172 13173 /** 13174 * This method is an internal method that could be get invoked either 13175 * to delete an installed package or to clean up a failed installation. 13176 * After deleting an installed package, a broadcast is sent to notify any 13177 * listeners that the package has been installed. For cleaning up a failed 13178 * installation, the broadcast is not necessary since the package's 13179 * installation wouldn't have sent the initial broadcast either 13180 * The key steps in deleting a package are 13181 * deleting the package information in internal structures like mPackages, 13182 * deleting the packages base directories through installd 13183 * updating mSettings to reflect current status 13184 * persisting settings for later use 13185 * sending a broadcast if necessary 13186 */ 13187 private int deletePackageX(String packageName, int userId, int flags) { 13188 final PackageRemovedInfo info = new PackageRemovedInfo(); 13189 final boolean res; 13190 13191 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 13192 ? UserHandle.ALL : new UserHandle(userId); 13193 13194 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 13195 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 13196 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 13197 } 13198 13199 boolean removedForAllUsers = false; 13200 boolean systemUpdate = false; 13201 13202 // for the uninstall-updates case and restricted profiles, remember the per- 13203 // userhandle installed state 13204 int[] allUsers; 13205 boolean[] perUserInstalled; 13206 synchronized (mPackages) { 13207 PackageSetting ps = mSettings.mPackages.get(packageName); 13208 allUsers = sUserManager.getUserIds(); 13209 perUserInstalled = new boolean[allUsers.length]; 13210 for (int i = 0; i < allUsers.length; i++) { 13211 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 13212 } 13213 } 13214 13215 synchronized (mInstallLock) { 13216 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 13217 res = deletePackageLI(packageName, removeForUser, 13218 true, allUsers, perUserInstalled, 13219 flags | REMOVE_CHATTY, info, true); 13220 systemUpdate = info.isRemovedPackageSystemUpdate; 13221 if (res && !systemUpdate && mPackages.get(packageName) == null) { 13222 removedForAllUsers = true; 13223 } 13224 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 13225 + " removedForAllUsers=" + removedForAllUsers); 13226 } 13227 13228 if (res) { 13229 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 13230 13231 // If the removed package was a system update, the old system package 13232 // was re-enabled; we need to broadcast this information 13233 if (systemUpdate) { 13234 Bundle extras = new Bundle(1); 13235 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 13236 ? info.removedAppId : info.uid); 13237 extras.putBoolean(Intent.EXTRA_REPLACING, true); 13238 13239 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 13240 extras, 0, null, null, null); 13241 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 13242 extras, 0, null, null, null); 13243 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 13244 null, 0, packageName, null, null); 13245 } 13246 } 13247 // Force a gc here. 13248 Runtime.getRuntime().gc(); 13249 // Delete the resources here after sending the broadcast to let 13250 // other processes clean up before deleting resources. 13251 if (info.args != null) { 13252 synchronized (mInstallLock) { 13253 info.args.doPostDeleteLI(true); 13254 } 13255 } 13256 13257 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 13258 } 13259 13260 class PackageRemovedInfo { 13261 String removedPackage; 13262 int uid = -1; 13263 int removedAppId = -1; 13264 int[] removedUsers = null; 13265 boolean isRemovedPackageSystemUpdate = false; 13266 // Clean up resources deleted packages. 13267 InstallArgs args = null; 13268 13269 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 13270 Bundle extras = new Bundle(1); 13271 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 13272 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 13273 if (replacing) { 13274 extras.putBoolean(Intent.EXTRA_REPLACING, true); 13275 } 13276 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 13277 if (removedPackage != null) { 13278 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 13279 extras, 0, null, null, removedUsers); 13280 if (fullRemove && !replacing) { 13281 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 13282 extras, 0, null, null, removedUsers); 13283 } 13284 } 13285 if (removedAppId >= 0) { 13286 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 13287 removedUsers); 13288 } 13289 } 13290 } 13291 13292 /* 13293 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 13294 * flag is not set, the data directory is removed as well. 13295 * make sure this flag is set for partially installed apps. If not its meaningless to 13296 * delete a partially installed application. 13297 */ 13298 private void removePackageDataLI(PackageSetting ps, 13299 int[] allUserHandles, boolean[] perUserInstalled, 13300 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 13301 String packageName = ps.name; 13302 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 13303 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 13304 // Retrieve object to delete permissions for shared user later on 13305 final PackageSetting deletedPs; 13306 // reader 13307 synchronized (mPackages) { 13308 deletedPs = mSettings.mPackages.get(packageName); 13309 if (outInfo != null) { 13310 outInfo.removedPackage = packageName; 13311 outInfo.removedUsers = deletedPs != null 13312 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 13313 : null; 13314 } 13315 } 13316 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 13317 removeDataDirsLI(ps.volumeUuid, packageName); 13318 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 13319 } 13320 // writer 13321 synchronized (mPackages) { 13322 if (deletedPs != null) { 13323 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 13324 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 13325 clearDefaultBrowserIfNeeded(packageName); 13326 if (outInfo != null) { 13327 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 13328 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 13329 } 13330 updatePermissionsLPw(deletedPs.name, null, 0); 13331 if (deletedPs.sharedUser != null) { 13332 // Remove permissions associated with package. Since runtime 13333 // permissions are per user we have to kill the removed package 13334 // or packages running under the shared user of the removed 13335 // package if revoking the permissions requested only by the removed 13336 // package is successful and this causes a change in gids. 13337 for (int userId : UserManagerService.getInstance().getUserIds()) { 13338 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 13339 userId); 13340 if (userIdToKill == UserHandle.USER_ALL 13341 || userIdToKill >= UserHandle.USER_SYSTEM) { 13342 // If gids changed for this user, kill all affected packages. 13343 mHandler.post(new Runnable() { 13344 @Override 13345 public void run() { 13346 // This has to happen with no lock held. 13347 killApplication(deletedPs.name, deletedPs.appId, 13348 KILL_APP_REASON_GIDS_CHANGED); 13349 } 13350 }); 13351 break; 13352 } 13353 } 13354 } 13355 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 13356 } 13357 // make sure to preserve per-user disabled state if this removal was just 13358 // a downgrade of a system app to the factory package 13359 if (allUserHandles != null && perUserInstalled != null) { 13360 if (DEBUG_REMOVE) { 13361 Slog.d(TAG, "Propagating install state across downgrade"); 13362 } 13363 for (int i = 0; i < allUserHandles.length; i++) { 13364 if (DEBUG_REMOVE) { 13365 Slog.d(TAG, " user " + allUserHandles[i] 13366 + " => " + perUserInstalled[i]); 13367 } 13368 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13369 } 13370 } 13371 } 13372 // can downgrade to reader 13373 if (writeSettings) { 13374 // Save settings now 13375 mSettings.writeLPr(); 13376 } 13377 } 13378 if (outInfo != null) { 13379 // A user ID was deleted here. Go through all users and remove it 13380 // from KeyStore. 13381 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 13382 } 13383 } 13384 13385 static boolean locationIsPrivileged(File path) { 13386 try { 13387 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 13388 .getCanonicalPath(); 13389 return path.getCanonicalPath().startsWith(privilegedAppDir); 13390 } catch (IOException e) { 13391 Slog.e(TAG, "Unable to access code path " + path); 13392 } 13393 return false; 13394 } 13395 13396 /* 13397 * Tries to delete system package. 13398 */ 13399 private boolean deleteSystemPackageLI(PackageSetting newPs, 13400 int[] allUserHandles, boolean[] perUserInstalled, 13401 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 13402 final boolean applyUserRestrictions 13403 = (allUserHandles != null) && (perUserInstalled != null); 13404 PackageSetting disabledPs = null; 13405 // Confirm if the system package has been updated 13406 // An updated system app can be deleted. This will also have to restore 13407 // the system pkg from system partition 13408 // reader 13409 synchronized (mPackages) { 13410 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 13411 } 13412 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 13413 + " disabledPs=" + disabledPs); 13414 if (disabledPs == null) { 13415 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 13416 return false; 13417 } else if (DEBUG_REMOVE) { 13418 Slog.d(TAG, "Deleting system pkg from data partition"); 13419 } 13420 if (DEBUG_REMOVE) { 13421 if (applyUserRestrictions) { 13422 Slog.d(TAG, "Remembering install states:"); 13423 for (int i = 0; i < allUserHandles.length; i++) { 13424 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 13425 } 13426 } 13427 } 13428 // Delete the updated package 13429 outInfo.isRemovedPackageSystemUpdate = true; 13430 if (disabledPs.versionCode < newPs.versionCode) { 13431 // Delete data for downgrades 13432 flags &= ~PackageManager.DELETE_KEEP_DATA; 13433 } else { 13434 // Preserve data by setting flag 13435 flags |= PackageManager.DELETE_KEEP_DATA; 13436 } 13437 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 13438 allUserHandles, perUserInstalled, outInfo, writeSettings); 13439 if (!ret) { 13440 return false; 13441 } 13442 // writer 13443 synchronized (mPackages) { 13444 // Reinstate the old system package 13445 mSettings.enableSystemPackageLPw(newPs.name); 13446 // Remove any native libraries from the upgraded package. 13447 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 13448 } 13449 // Install the system package 13450 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 13451 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 13452 if (locationIsPrivileged(disabledPs.codePath)) { 13453 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 13454 } 13455 13456 final PackageParser.Package newPkg; 13457 try { 13458 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 13459 } catch (PackageManagerException e) { 13460 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 13461 return false; 13462 } 13463 13464 // writer 13465 synchronized (mPackages) { 13466 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 13467 13468 // Propagate the permissions state as we do not want to drop on the floor 13469 // runtime permissions. The update permissions method below will take 13470 // care of removing obsolete permissions and grant install permissions. 13471 ps.getPermissionsState().copyFrom(newPs.getPermissionsState()); 13472 updatePermissionsLPw(newPkg.packageName, newPkg, 13473 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 13474 13475 if (applyUserRestrictions) { 13476 if (DEBUG_REMOVE) { 13477 Slog.d(TAG, "Propagating install state across reinstall"); 13478 } 13479 for (int i = 0; i < allUserHandles.length; i++) { 13480 if (DEBUG_REMOVE) { 13481 Slog.d(TAG, " user " + allUserHandles[i] 13482 + " => " + perUserInstalled[i]); 13483 } 13484 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13485 13486 mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false); 13487 } 13488 // Regardless of writeSettings we need to ensure that this restriction 13489 // state propagation is persisted 13490 mSettings.writeAllUsersPackageRestrictionsLPr(); 13491 } 13492 // can downgrade to reader here 13493 if (writeSettings) { 13494 mSettings.writeLPr(); 13495 } 13496 } 13497 return true; 13498 } 13499 13500 private boolean deleteInstalledPackageLI(PackageSetting ps, 13501 boolean deleteCodeAndResources, int flags, 13502 int[] allUserHandles, boolean[] perUserInstalled, 13503 PackageRemovedInfo outInfo, boolean writeSettings) { 13504 if (outInfo != null) { 13505 outInfo.uid = ps.appId; 13506 } 13507 13508 // Delete package data from internal structures and also remove data if flag is set 13509 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 13510 13511 // Delete application code and resources 13512 if (deleteCodeAndResources && (outInfo != null)) { 13513 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 13514 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 13515 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 13516 } 13517 return true; 13518 } 13519 13520 @Override 13521 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 13522 int userId) { 13523 mContext.enforceCallingOrSelfPermission( 13524 android.Manifest.permission.DELETE_PACKAGES, null); 13525 synchronized (mPackages) { 13526 PackageSetting ps = mSettings.mPackages.get(packageName); 13527 if (ps == null) { 13528 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 13529 return false; 13530 } 13531 if (!ps.getInstalled(userId)) { 13532 // Can't block uninstall for an app that is not installed or enabled. 13533 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 13534 return false; 13535 } 13536 ps.setBlockUninstall(blockUninstall, userId); 13537 mSettings.writePackageRestrictionsLPr(userId); 13538 } 13539 return true; 13540 } 13541 13542 @Override 13543 public boolean getBlockUninstallForUser(String packageName, int userId) { 13544 synchronized (mPackages) { 13545 PackageSetting ps = mSettings.mPackages.get(packageName); 13546 if (ps == null) { 13547 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 13548 return false; 13549 } 13550 return ps.getBlockUninstall(userId); 13551 } 13552 } 13553 13554 /* 13555 * This method handles package deletion in general 13556 */ 13557 private boolean deletePackageLI(String packageName, UserHandle user, 13558 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 13559 int flags, PackageRemovedInfo outInfo, 13560 boolean writeSettings) { 13561 if (packageName == null) { 13562 Slog.w(TAG, "Attempt to delete null packageName."); 13563 return false; 13564 } 13565 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 13566 PackageSetting ps; 13567 boolean dataOnly = false; 13568 int removeUser = -1; 13569 int appId = -1; 13570 synchronized (mPackages) { 13571 ps = mSettings.mPackages.get(packageName); 13572 if (ps == null) { 13573 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13574 return false; 13575 } 13576 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 13577 && user.getIdentifier() != UserHandle.USER_ALL) { 13578 // The caller is asking that the package only be deleted for a single 13579 // user. To do this, we just mark its uninstalled state and delete 13580 // its data. If this is a system app, we only allow this to happen if 13581 // they have set the special DELETE_SYSTEM_APP which requests different 13582 // semantics than normal for uninstalling system apps. 13583 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 13584 final int userId = user.getIdentifier(); 13585 ps.setUserState(userId, 13586 COMPONENT_ENABLED_STATE_DEFAULT, 13587 false, //installed 13588 true, //stopped 13589 true, //notLaunched 13590 false, //hidden 13591 null, null, null, 13592 false, // blockUninstall 13593 ps.readUserState(userId).domainVerificationStatus, 0); 13594 if (!isSystemApp(ps)) { 13595 // Do not uninstall the APK if an app should be cached 13596 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 13597 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 13598 // Other user still have this package installed, so all 13599 // we need to do is clear this user's data and save that 13600 // it is uninstalled. 13601 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 13602 removeUser = user.getIdentifier(); 13603 appId = ps.appId; 13604 scheduleWritePackageRestrictionsLocked(removeUser); 13605 } else { 13606 // We need to set it back to 'installed' so the uninstall 13607 // broadcasts will be sent correctly. 13608 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 13609 ps.setInstalled(true, user.getIdentifier()); 13610 } 13611 } else { 13612 // This is a system app, so we assume that the 13613 // other users still have this package installed, so all 13614 // we need to do is clear this user's data and save that 13615 // it is uninstalled. 13616 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 13617 removeUser = user.getIdentifier(); 13618 appId = ps.appId; 13619 scheduleWritePackageRestrictionsLocked(removeUser); 13620 } 13621 } 13622 } 13623 13624 if (removeUser >= 0) { 13625 // From above, we determined that we are deleting this only 13626 // for a single user. Continue the work here. 13627 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 13628 if (outInfo != null) { 13629 outInfo.removedPackage = packageName; 13630 outInfo.removedAppId = appId; 13631 outInfo.removedUsers = new int[] {removeUser}; 13632 } 13633 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 13634 removeKeystoreDataIfNeeded(removeUser, appId); 13635 schedulePackageCleaning(packageName, removeUser, false); 13636 synchronized (mPackages) { 13637 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 13638 scheduleWritePackageRestrictionsLocked(removeUser); 13639 } 13640 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser); 13641 } 13642 return true; 13643 } 13644 13645 if (dataOnly) { 13646 // Delete application data first 13647 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 13648 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 13649 return true; 13650 } 13651 13652 boolean ret = false; 13653 if (isSystemApp(ps)) { 13654 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 13655 // When an updated system application is deleted we delete the existing resources as well and 13656 // fall back to existing code in system partition 13657 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 13658 flags, outInfo, writeSettings); 13659 } else { 13660 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 13661 // Kill application pre-emptively especially for apps on sd. 13662 killApplication(packageName, ps.appId, "uninstall pkg"); 13663 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 13664 allUserHandles, perUserInstalled, 13665 outInfo, writeSettings); 13666 } 13667 13668 return ret; 13669 } 13670 13671 private final class ClearStorageConnection implements ServiceConnection { 13672 IMediaContainerService mContainerService; 13673 13674 @Override 13675 public void onServiceConnected(ComponentName name, IBinder service) { 13676 synchronized (this) { 13677 mContainerService = IMediaContainerService.Stub.asInterface(service); 13678 notifyAll(); 13679 } 13680 } 13681 13682 @Override 13683 public void onServiceDisconnected(ComponentName name) { 13684 } 13685 } 13686 13687 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 13688 final boolean mounted; 13689 if (Environment.isExternalStorageEmulated()) { 13690 mounted = true; 13691 } else { 13692 final String status = Environment.getExternalStorageState(); 13693 13694 mounted = status.equals(Environment.MEDIA_MOUNTED) 13695 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 13696 } 13697 13698 if (!mounted) { 13699 return; 13700 } 13701 13702 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 13703 int[] users; 13704 if (userId == UserHandle.USER_ALL) { 13705 users = sUserManager.getUserIds(); 13706 } else { 13707 users = new int[] { userId }; 13708 } 13709 final ClearStorageConnection conn = new ClearStorageConnection(); 13710 if (mContext.bindServiceAsUser( 13711 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 13712 try { 13713 for (int curUser : users) { 13714 long timeout = SystemClock.uptimeMillis() + 5000; 13715 synchronized (conn) { 13716 long now = SystemClock.uptimeMillis(); 13717 while (conn.mContainerService == null && now < timeout) { 13718 try { 13719 conn.wait(timeout - now); 13720 } catch (InterruptedException e) { 13721 } 13722 } 13723 } 13724 if (conn.mContainerService == null) { 13725 return; 13726 } 13727 13728 final UserEnvironment userEnv = new UserEnvironment(curUser); 13729 clearDirectory(conn.mContainerService, 13730 userEnv.buildExternalStorageAppCacheDirs(packageName)); 13731 if (allData) { 13732 clearDirectory(conn.mContainerService, 13733 userEnv.buildExternalStorageAppDataDirs(packageName)); 13734 clearDirectory(conn.mContainerService, 13735 userEnv.buildExternalStorageAppMediaDirs(packageName)); 13736 } 13737 } 13738 } finally { 13739 mContext.unbindService(conn); 13740 } 13741 } 13742 } 13743 13744 @Override 13745 public void clearApplicationUserData(final String packageName, 13746 final IPackageDataObserver observer, final int userId) { 13747 mContext.enforceCallingOrSelfPermission( 13748 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 13749 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 13750 // Queue up an async operation since the package deletion may take a little while. 13751 mHandler.post(new Runnable() { 13752 public void run() { 13753 mHandler.removeCallbacks(this); 13754 final boolean succeeded; 13755 synchronized (mInstallLock) { 13756 succeeded = clearApplicationUserDataLI(packageName, userId); 13757 } 13758 clearExternalStorageDataSync(packageName, userId, true); 13759 if (succeeded) { 13760 // invoke DeviceStorageMonitor's update method to clear any notifications 13761 DeviceStorageMonitorInternal 13762 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13763 if (dsm != null) { 13764 dsm.checkMemory(); 13765 } 13766 } 13767 if(observer != null) { 13768 try { 13769 observer.onRemoveCompleted(packageName, succeeded); 13770 } catch (RemoteException e) { 13771 Log.i(TAG, "Observer no longer exists."); 13772 } 13773 } //end if observer 13774 } //end run 13775 }); 13776 } 13777 13778 private boolean clearApplicationUserDataLI(String packageName, int userId) { 13779 if (packageName == null) { 13780 Slog.w(TAG, "Attempt to delete null packageName."); 13781 return false; 13782 } 13783 13784 // Try finding details about the requested package 13785 PackageParser.Package pkg; 13786 synchronized (mPackages) { 13787 pkg = mPackages.get(packageName); 13788 if (pkg == null) { 13789 final PackageSetting ps = mSettings.mPackages.get(packageName); 13790 if (ps != null) { 13791 pkg = ps.pkg; 13792 } 13793 } 13794 13795 if (pkg == null) { 13796 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13797 return false; 13798 } 13799 13800 PackageSetting ps = (PackageSetting) pkg.mExtras; 13801 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 13802 } 13803 13804 // Always delete data directories for package, even if we found no other 13805 // record of app. This helps users recover from UID mismatches without 13806 // resorting to a full data wipe. 13807 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 13808 if (retCode < 0) { 13809 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 13810 return false; 13811 } 13812 13813 final int appId = pkg.applicationInfo.uid; 13814 removeKeystoreDataIfNeeded(userId, appId); 13815 13816 // Create a native library symlink only if we have native libraries 13817 // and if the native libraries are 32 bit libraries. We do not provide 13818 // this symlink for 64 bit libraries. 13819 if (pkg.applicationInfo.primaryCpuAbi != null && 13820 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 13821 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 13822 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 13823 nativeLibPath, userId) < 0) { 13824 Slog.w(TAG, "Failed linking native library dir"); 13825 return false; 13826 } 13827 } 13828 13829 return true; 13830 } 13831 13832 /** 13833 * Reverts user permission state changes (permissions and flags) in 13834 * all packages for a given user. 13835 * 13836 * @param userId The device user for which to do a reset. 13837 */ 13838 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 13839 final int packageCount = mPackages.size(); 13840 for (int i = 0; i < packageCount; i++) { 13841 PackageParser.Package pkg = mPackages.valueAt(i); 13842 PackageSetting ps = (PackageSetting) pkg.mExtras; 13843 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 13844 } 13845 } 13846 13847 /** 13848 * Reverts user permission state changes (permissions and flags). 13849 * 13850 * @param ps The package for which to reset. 13851 * @param userId The device user for which to do a reset. 13852 */ 13853 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 13854 final PackageSetting ps, final int userId) { 13855 if (ps.pkg == null) { 13856 return; 13857 } 13858 13859 // These are flags that can change base on user actions. 13860 final int userSettableMask = FLAG_PERMISSION_USER_SET 13861 | FLAG_PERMISSION_USER_FIXED 13862 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 13863 | FLAG_PERMISSION_REVIEW_REQUIRED; 13864 13865 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 13866 | FLAG_PERMISSION_POLICY_FIXED; 13867 13868 boolean writeInstallPermissions = false; 13869 boolean writeRuntimePermissions = false; 13870 13871 final int permissionCount = ps.pkg.requestedPermissions.size(); 13872 for (int i = 0; i < permissionCount; i++) { 13873 String permission = ps.pkg.requestedPermissions.get(i); 13874 13875 BasePermission bp = mSettings.mPermissions.get(permission); 13876 if (bp == null) { 13877 continue; 13878 } 13879 13880 // If shared user we just reset the state to which only this app contributed. 13881 if (ps.sharedUser != null) { 13882 boolean used = false; 13883 final int packageCount = ps.sharedUser.packages.size(); 13884 for (int j = 0; j < packageCount; j++) { 13885 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 13886 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 13887 && pkg.pkg.requestedPermissions.contains(permission)) { 13888 used = true; 13889 break; 13890 } 13891 } 13892 if (used) { 13893 continue; 13894 } 13895 } 13896 13897 PermissionsState permissionsState = ps.getPermissionsState(); 13898 13899 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 13900 13901 // Always clear the user settable flags. 13902 final boolean hasInstallState = permissionsState.getInstallPermissionState( 13903 bp.name) != null; 13904 // If permission review is enabled and this is a legacy app, mark the 13905 // permission as requiring a review as this is the initial state. 13906 int flags = 0; 13907 if (Build.PERMISSIONS_REVIEW_REQUIRED 13908 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 13909 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 13910 } 13911 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 13912 if (hasInstallState) { 13913 writeInstallPermissions = true; 13914 } else { 13915 writeRuntimePermissions = true; 13916 } 13917 } 13918 13919 // Below is only runtime permission handling. 13920 if (!bp.isRuntime()) { 13921 continue; 13922 } 13923 13924 // Never clobber system or policy. 13925 if ((oldFlags & policyOrSystemFlags) != 0) { 13926 continue; 13927 } 13928 13929 // If this permission was granted by default, make sure it is. 13930 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 13931 if (permissionsState.grantRuntimePermission(bp, userId) 13932 != PERMISSION_OPERATION_FAILURE) { 13933 writeRuntimePermissions = true; 13934 } 13935 // If permission review is enabled the permissions for a legacy apps 13936 // are represented as constantly granted runtime ones, so don't revoke. 13937 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 13938 // Otherwise, reset the permission. 13939 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 13940 switch (revokeResult) { 13941 case PERMISSION_OPERATION_SUCCESS: { 13942 writeRuntimePermissions = true; 13943 } break; 13944 13945 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 13946 writeRuntimePermissions = true; 13947 final int appId = ps.appId; 13948 mHandler.post(new Runnable() { 13949 @Override 13950 public void run() { 13951 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 13952 } 13953 }); 13954 } break; 13955 } 13956 } 13957 } 13958 13959 // Synchronously write as we are taking permissions away. 13960 if (writeRuntimePermissions) { 13961 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 13962 } 13963 13964 // Synchronously write as we are taking permissions away. 13965 if (writeInstallPermissions) { 13966 mSettings.writeLPr(); 13967 } 13968 } 13969 13970 /** 13971 * Remove entries from the keystore daemon. Will only remove it if the 13972 * {@code appId} is valid. 13973 */ 13974 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 13975 if (appId < 0) { 13976 return; 13977 } 13978 13979 final KeyStore keyStore = KeyStore.getInstance(); 13980 if (keyStore != null) { 13981 if (userId == UserHandle.USER_ALL) { 13982 for (final int individual : sUserManager.getUserIds()) { 13983 keyStore.clearUid(UserHandle.getUid(individual, appId)); 13984 } 13985 } else { 13986 keyStore.clearUid(UserHandle.getUid(userId, appId)); 13987 } 13988 } else { 13989 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 13990 } 13991 } 13992 13993 @Override 13994 public void deleteApplicationCacheFiles(final String packageName, 13995 final IPackageDataObserver observer) { 13996 mContext.enforceCallingOrSelfPermission( 13997 android.Manifest.permission.DELETE_CACHE_FILES, null); 13998 // Queue up an async operation since the package deletion may take a little while. 13999 final int userId = UserHandle.getCallingUserId(); 14000 mHandler.post(new Runnable() { 14001 public void run() { 14002 mHandler.removeCallbacks(this); 14003 final boolean succeded; 14004 synchronized (mInstallLock) { 14005 succeded = deleteApplicationCacheFilesLI(packageName, userId); 14006 } 14007 clearExternalStorageDataSync(packageName, userId, false); 14008 if (observer != null) { 14009 try { 14010 observer.onRemoveCompleted(packageName, succeded); 14011 } catch (RemoteException e) { 14012 Log.i(TAG, "Observer no longer exists."); 14013 } 14014 } //end if observer 14015 } //end run 14016 }); 14017 } 14018 14019 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 14020 if (packageName == null) { 14021 Slog.w(TAG, "Attempt to delete null packageName."); 14022 return false; 14023 } 14024 PackageParser.Package p; 14025 synchronized (mPackages) { 14026 p = mPackages.get(packageName); 14027 } 14028 if (p == null) { 14029 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 14030 return false; 14031 } 14032 final ApplicationInfo applicationInfo = p.applicationInfo; 14033 if (applicationInfo == null) { 14034 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 14035 return false; 14036 } 14037 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 14038 if (retCode < 0) { 14039 Slog.w(TAG, "Couldn't remove cache files for package: " 14040 + packageName + " u" + userId); 14041 return false; 14042 } 14043 return true; 14044 } 14045 14046 @Override 14047 public void getPackageSizeInfo(final String packageName, int userHandle, 14048 final IPackageStatsObserver observer) { 14049 mContext.enforceCallingOrSelfPermission( 14050 android.Manifest.permission.GET_PACKAGE_SIZE, null); 14051 if (packageName == null) { 14052 throw new IllegalArgumentException("Attempt to get size of null packageName"); 14053 } 14054 14055 PackageStats stats = new PackageStats(packageName, userHandle); 14056 14057 /* 14058 * Queue up an async operation since the package measurement may take a 14059 * little while. 14060 */ 14061 Message msg = mHandler.obtainMessage(INIT_COPY); 14062 msg.obj = new MeasureParams(stats, observer); 14063 mHandler.sendMessage(msg); 14064 } 14065 14066 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 14067 PackageStats pStats) { 14068 if (packageName == null) { 14069 Slog.w(TAG, "Attempt to get size of null packageName."); 14070 return false; 14071 } 14072 PackageParser.Package p; 14073 boolean dataOnly = false; 14074 String libDirRoot = null; 14075 String asecPath = null; 14076 PackageSetting ps = null; 14077 synchronized (mPackages) { 14078 p = mPackages.get(packageName); 14079 ps = mSettings.mPackages.get(packageName); 14080 if(p == null) { 14081 dataOnly = true; 14082 if((ps == null) || (ps.pkg == null)) { 14083 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 14084 return false; 14085 } 14086 p = ps.pkg; 14087 } 14088 if (ps != null) { 14089 libDirRoot = ps.legacyNativeLibraryPathString; 14090 } 14091 if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) { 14092 final long token = Binder.clearCallingIdentity(); 14093 try { 14094 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 14095 if (secureContainerId != null) { 14096 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 14097 } 14098 } finally { 14099 Binder.restoreCallingIdentity(token); 14100 } 14101 } 14102 } 14103 String publicSrcDir = null; 14104 if(!dataOnly) { 14105 final ApplicationInfo applicationInfo = p.applicationInfo; 14106 if (applicationInfo == null) { 14107 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 14108 return false; 14109 } 14110 if (p.isForwardLocked()) { 14111 publicSrcDir = applicationInfo.getBaseResourcePath(); 14112 } 14113 } 14114 // TODO: extend to measure size of split APKs 14115 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 14116 // not just the first level. 14117 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 14118 // just the primary. 14119 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 14120 14121 String apkPath; 14122 File packageDir = new File(p.codePath); 14123 14124 if (packageDir.isDirectory() && p.canHaveOatDir()) { 14125 apkPath = packageDir.getAbsolutePath(); 14126 // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice 14127 if (libDirRoot != null && libDirRoot.startsWith(apkPath)) { 14128 libDirRoot = null; 14129 } 14130 } else { 14131 apkPath = p.baseCodePath; 14132 } 14133 14134 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, apkPath, 14135 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 14136 if (res < 0) { 14137 return false; 14138 } 14139 14140 // Fix-up for forward-locked applications in ASEC containers. 14141 if (!isExternal(p)) { 14142 pStats.codeSize += pStats.externalCodeSize; 14143 pStats.externalCodeSize = 0L; 14144 } 14145 14146 return true; 14147 } 14148 14149 14150 @Override 14151 public void addPackageToPreferred(String packageName) { 14152 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 14153 } 14154 14155 @Override 14156 public void removePackageFromPreferred(String packageName) { 14157 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 14158 } 14159 14160 @Override 14161 public List<PackageInfo> getPreferredPackages(int flags) { 14162 return new ArrayList<PackageInfo>(); 14163 } 14164 14165 private int getUidTargetSdkVersionLockedLPr(int uid) { 14166 Object obj = mSettings.getUserIdLPr(uid); 14167 if (obj instanceof SharedUserSetting) { 14168 final SharedUserSetting sus = (SharedUserSetting) obj; 14169 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 14170 final Iterator<PackageSetting> it = sus.packages.iterator(); 14171 while (it.hasNext()) { 14172 final PackageSetting ps = it.next(); 14173 if (ps.pkg != null) { 14174 int v = ps.pkg.applicationInfo.targetSdkVersion; 14175 if (v < vers) vers = v; 14176 } 14177 } 14178 return vers; 14179 } else if (obj instanceof PackageSetting) { 14180 final PackageSetting ps = (PackageSetting) obj; 14181 if (ps.pkg != null) { 14182 return ps.pkg.applicationInfo.targetSdkVersion; 14183 } 14184 } 14185 return Build.VERSION_CODES.CUR_DEVELOPMENT; 14186 } 14187 14188 @Override 14189 public void addPreferredActivity(IntentFilter filter, int match, 14190 ComponentName[] set, ComponentName activity, int userId) { 14191 addPreferredActivityInternal(filter, match, set, activity, true, userId, 14192 "Adding preferred"); 14193 } 14194 14195 private void addPreferredActivityInternal(IntentFilter filter, int match, 14196 ComponentName[] set, ComponentName activity, boolean always, int userId, 14197 String opname) { 14198 // writer 14199 int callingUid = Binder.getCallingUid(); 14200 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 14201 if (filter.countActions() == 0) { 14202 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 14203 return; 14204 } 14205 synchronized (mPackages) { 14206 if (mContext.checkCallingOrSelfPermission( 14207 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14208 != PackageManager.PERMISSION_GRANTED) { 14209 if (getUidTargetSdkVersionLockedLPr(callingUid) 14210 < Build.VERSION_CODES.FROYO) { 14211 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 14212 + callingUid); 14213 return; 14214 } 14215 mContext.enforceCallingOrSelfPermission( 14216 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14217 } 14218 14219 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 14220 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 14221 + userId + ":"); 14222 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14223 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 14224 scheduleWritePackageRestrictionsLocked(userId); 14225 } 14226 } 14227 14228 @Override 14229 public void replacePreferredActivity(IntentFilter filter, int match, 14230 ComponentName[] set, ComponentName activity, int userId) { 14231 if (filter.countActions() != 1) { 14232 throw new IllegalArgumentException( 14233 "replacePreferredActivity expects filter to have only 1 action."); 14234 } 14235 if (filter.countDataAuthorities() != 0 14236 || filter.countDataPaths() != 0 14237 || filter.countDataSchemes() > 1 14238 || filter.countDataTypes() != 0) { 14239 throw new IllegalArgumentException( 14240 "replacePreferredActivity expects filter to have no data authorities, " + 14241 "paths, or types; and at most one scheme."); 14242 } 14243 14244 final int callingUid = Binder.getCallingUid(); 14245 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 14246 synchronized (mPackages) { 14247 if (mContext.checkCallingOrSelfPermission( 14248 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14249 != PackageManager.PERMISSION_GRANTED) { 14250 if (getUidTargetSdkVersionLockedLPr(callingUid) 14251 < Build.VERSION_CODES.FROYO) { 14252 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 14253 + Binder.getCallingUid()); 14254 return; 14255 } 14256 mContext.enforceCallingOrSelfPermission( 14257 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14258 } 14259 14260 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 14261 if (pir != null) { 14262 // Get all of the existing entries that exactly match this filter. 14263 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 14264 if (existing != null && existing.size() == 1) { 14265 PreferredActivity cur = existing.get(0); 14266 if (DEBUG_PREFERRED) { 14267 Slog.i(TAG, "Checking replace of preferred:"); 14268 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14269 if (!cur.mPref.mAlways) { 14270 Slog.i(TAG, " -- CUR; not mAlways!"); 14271 } else { 14272 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 14273 Slog.i(TAG, " -- CUR: mSet=" 14274 + Arrays.toString(cur.mPref.mSetComponents)); 14275 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 14276 Slog.i(TAG, " -- NEW: mMatch=" 14277 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 14278 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 14279 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 14280 } 14281 } 14282 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 14283 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 14284 && cur.mPref.sameSet(set)) { 14285 // Setting the preferred activity to what it happens to be already 14286 if (DEBUG_PREFERRED) { 14287 Slog.i(TAG, "Replacing with same preferred activity " 14288 + cur.mPref.mShortComponent + " for user " 14289 + userId + ":"); 14290 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14291 } 14292 return; 14293 } 14294 } 14295 14296 if (existing != null) { 14297 if (DEBUG_PREFERRED) { 14298 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 14299 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14300 } 14301 for (int i = 0; i < existing.size(); i++) { 14302 PreferredActivity pa = existing.get(i); 14303 if (DEBUG_PREFERRED) { 14304 Slog.i(TAG, "Removing existing preferred activity " 14305 + pa.mPref.mComponent + ":"); 14306 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 14307 } 14308 pir.removeFilter(pa); 14309 } 14310 } 14311 } 14312 addPreferredActivityInternal(filter, match, set, activity, true, userId, 14313 "Replacing preferred"); 14314 } 14315 } 14316 14317 @Override 14318 public void clearPackagePreferredActivities(String packageName) { 14319 final int uid = Binder.getCallingUid(); 14320 // writer 14321 synchronized (mPackages) { 14322 PackageParser.Package pkg = mPackages.get(packageName); 14323 if (pkg == null || pkg.applicationInfo.uid != uid) { 14324 if (mContext.checkCallingOrSelfPermission( 14325 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14326 != PackageManager.PERMISSION_GRANTED) { 14327 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 14328 < Build.VERSION_CODES.FROYO) { 14329 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 14330 + Binder.getCallingUid()); 14331 return; 14332 } 14333 mContext.enforceCallingOrSelfPermission( 14334 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14335 } 14336 } 14337 14338 int user = UserHandle.getCallingUserId(); 14339 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 14340 scheduleWritePackageRestrictionsLocked(user); 14341 } 14342 } 14343 } 14344 14345 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14346 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 14347 ArrayList<PreferredActivity> removed = null; 14348 boolean changed = false; 14349 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14350 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 14351 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14352 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 14353 continue; 14354 } 14355 Iterator<PreferredActivity> it = pir.filterIterator(); 14356 while (it.hasNext()) { 14357 PreferredActivity pa = it.next(); 14358 // Mark entry for removal only if it matches the package name 14359 // and the entry is of type "always". 14360 if (packageName == null || 14361 (pa.mPref.mComponent.getPackageName().equals(packageName) 14362 && pa.mPref.mAlways)) { 14363 if (removed == null) { 14364 removed = new ArrayList<PreferredActivity>(); 14365 } 14366 removed.add(pa); 14367 } 14368 } 14369 if (removed != null) { 14370 for (int j=0; j<removed.size(); j++) { 14371 PreferredActivity pa = removed.get(j); 14372 pir.removeFilter(pa); 14373 } 14374 changed = true; 14375 } 14376 } 14377 return changed; 14378 } 14379 14380 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14381 private void clearIntentFilterVerificationsLPw(int userId) { 14382 final int packageCount = mPackages.size(); 14383 for (int i = 0; i < packageCount; i++) { 14384 PackageParser.Package pkg = mPackages.valueAt(i); 14385 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 14386 } 14387 } 14388 14389 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14390 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 14391 if (userId == UserHandle.USER_ALL) { 14392 if (mSettings.removeIntentFilterVerificationLPw(packageName, 14393 sUserManager.getUserIds())) { 14394 for (int oneUserId : sUserManager.getUserIds()) { 14395 scheduleWritePackageRestrictionsLocked(oneUserId); 14396 } 14397 } 14398 } else { 14399 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 14400 scheduleWritePackageRestrictionsLocked(userId); 14401 } 14402 } 14403 } 14404 14405 void clearDefaultBrowserIfNeeded(String packageName) { 14406 for (int oneUserId : sUserManager.getUserIds()) { 14407 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 14408 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 14409 if (packageName.equals(defaultBrowserPackageName)) { 14410 setDefaultBrowserPackageName(null, oneUserId); 14411 } 14412 } 14413 } 14414 14415 @Override 14416 public void resetApplicationPreferences(int userId) { 14417 mContext.enforceCallingOrSelfPermission( 14418 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14419 // writer 14420 synchronized (mPackages) { 14421 final long identity = Binder.clearCallingIdentity(); 14422 try { 14423 clearPackagePreferredActivitiesLPw(null, userId); 14424 mSettings.applyDefaultPreferredAppsLPw(this, userId); 14425 // TODO: We have to reset the default SMS and Phone. This requires 14426 // significant refactoring to keep all default apps in the package 14427 // manager (cleaner but more work) or have the services provide 14428 // callbacks to the package manager to request a default app reset. 14429 applyFactoryDefaultBrowserLPw(userId); 14430 clearIntentFilterVerificationsLPw(userId); 14431 primeDomainVerificationsLPw(userId); 14432 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 14433 scheduleWritePackageRestrictionsLocked(userId); 14434 } finally { 14435 Binder.restoreCallingIdentity(identity); 14436 } 14437 } 14438 } 14439 14440 @Override 14441 public int getPreferredActivities(List<IntentFilter> outFilters, 14442 List<ComponentName> outActivities, String packageName) { 14443 14444 int num = 0; 14445 final int userId = UserHandle.getCallingUserId(); 14446 // reader 14447 synchronized (mPackages) { 14448 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 14449 if (pir != null) { 14450 final Iterator<PreferredActivity> it = pir.filterIterator(); 14451 while (it.hasNext()) { 14452 final PreferredActivity pa = it.next(); 14453 if (packageName == null 14454 || (pa.mPref.mComponent.getPackageName().equals(packageName) 14455 && pa.mPref.mAlways)) { 14456 if (outFilters != null) { 14457 outFilters.add(new IntentFilter(pa)); 14458 } 14459 if (outActivities != null) { 14460 outActivities.add(pa.mPref.mComponent); 14461 } 14462 } 14463 } 14464 } 14465 } 14466 14467 return num; 14468 } 14469 14470 @Override 14471 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 14472 int userId) { 14473 int callingUid = Binder.getCallingUid(); 14474 if (callingUid != Process.SYSTEM_UID) { 14475 throw new SecurityException( 14476 "addPersistentPreferredActivity can only be run by the system"); 14477 } 14478 if (filter.countActions() == 0) { 14479 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 14480 return; 14481 } 14482 synchronized (mPackages) { 14483 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 14484 " :"); 14485 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14486 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 14487 new PersistentPreferredActivity(filter, activity)); 14488 scheduleWritePackageRestrictionsLocked(userId); 14489 } 14490 } 14491 14492 @Override 14493 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 14494 int callingUid = Binder.getCallingUid(); 14495 if (callingUid != Process.SYSTEM_UID) { 14496 throw new SecurityException( 14497 "clearPackagePersistentPreferredActivities can only be run by the system"); 14498 } 14499 ArrayList<PersistentPreferredActivity> removed = null; 14500 boolean changed = false; 14501 synchronized (mPackages) { 14502 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 14503 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 14504 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 14505 .valueAt(i); 14506 if (userId != thisUserId) { 14507 continue; 14508 } 14509 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 14510 while (it.hasNext()) { 14511 PersistentPreferredActivity ppa = it.next(); 14512 // Mark entry for removal only if it matches the package name. 14513 if (ppa.mComponent.getPackageName().equals(packageName)) { 14514 if (removed == null) { 14515 removed = new ArrayList<PersistentPreferredActivity>(); 14516 } 14517 removed.add(ppa); 14518 } 14519 } 14520 if (removed != null) { 14521 for (int j=0; j<removed.size(); j++) { 14522 PersistentPreferredActivity ppa = removed.get(j); 14523 ppir.removeFilter(ppa); 14524 } 14525 changed = true; 14526 } 14527 } 14528 14529 if (changed) { 14530 scheduleWritePackageRestrictionsLocked(userId); 14531 } 14532 } 14533 } 14534 14535 /** 14536 * Common machinery for picking apart a restored XML blob and passing 14537 * it to a caller-supplied functor to be applied to the running system. 14538 */ 14539 private void restoreFromXml(XmlPullParser parser, int userId, 14540 String expectedStartTag, BlobXmlRestorer functor) 14541 throws IOException, XmlPullParserException { 14542 int type; 14543 while ((type = parser.next()) != XmlPullParser.START_TAG 14544 && type != XmlPullParser.END_DOCUMENT) { 14545 } 14546 if (type != XmlPullParser.START_TAG) { 14547 // oops didn't find a start tag?! 14548 if (DEBUG_BACKUP) { 14549 Slog.e(TAG, "Didn't find start tag during restore"); 14550 } 14551 return; 14552 } 14553 14554 // this is supposed to be TAG_PREFERRED_BACKUP 14555 if (!expectedStartTag.equals(parser.getName())) { 14556 if (DEBUG_BACKUP) { 14557 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 14558 } 14559 return; 14560 } 14561 14562 // skip interfering stuff, then we're aligned with the backing implementation 14563 while ((type = parser.next()) == XmlPullParser.TEXT) { } 14564 functor.apply(parser, userId); 14565 } 14566 14567 private interface BlobXmlRestorer { 14568 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 14569 } 14570 14571 /** 14572 * Non-Binder method, support for the backup/restore mechanism: write the 14573 * full set of preferred activities in its canonical XML format. Returns the 14574 * XML output as a byte array, or null if there is none. 14575 */ 14576 @Override 14577 public byte[] getPreferredActivityBackup(int userId) { 14578 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14579 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 14580 } 14581 14582 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14583 try { 14584 final XmlSerializer serializer = new FastXmlSerializer(); 14585 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14586 serializer.startDocument(null, true); 14587 serializer.startTag(null, TAG_PREFERRED_BACKUP); 14588 14589 synchronized (mPackages) { 14590 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 14591 } 14592 14593 serializer.endTag(null, TAG_PREFERRED_BACKUP); 14594 serializer.endDocument(); 14595 serializer.flush(); 14596 } catch (Exception e) { 14597 if (DEBUG_BACKUP) { 14598 Slog.e(TAG, "Unable to write preferred activities for backup", e); 14599 } 14600 return null; 14601 } 14602 14603 return dataStream.toByteArray(); 14604 } 14605 14606 @Override 14607 public void restorePreferredActivities(byte[] backup, int userId) { 14608 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14609 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14610 } 14611 14612 try { 14613 final XmlPullParser parser = Xml.newPullParser(); 14614 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14615 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 14616 new BlobXmlRestorer() { 14617 @Override 14618 public void apply(XmlPullParser parser, int userId) 14619 throws XmlPullParserException, IOException { 14620 synchronized (mPackages) { 14621 mSettings.readPreferredActivitiesLPw(parser, userId); 14622 } 14623 } 14624 } ); 14625 } catch (Exception e) { 14626 if (DEBUG_BACKUP) { 14627 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14628 } 14629 } 14630 } 14631 14632 /** 14633 * Non-Binder method, support for the backup/restore mechanism: write the 14634 * default browser (etc) settings in its canonical XML format. Returns the default 14635 * browser XML representation as a byte array, or null if there is none. 14636 */ 14637 @Override 14638 public byte[] getDefaultAppsBackup(int userId) { 14639 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14640 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 14641 } 14642 14643 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14644 try { 14645 final XmlSerializer serializer = new FastXmlSerializer(); 14646 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14647 serializer.startDocument(null, true); 14648 serializer.startTag(null, TAG_DEFAULT_APPS); 14649 14650 synchronized (mPackages) { 14651 mSettings.writeDefaultAppsLPr(serializer, userId); 14652 } 14653 14654 serializer.endTag(null, TAG_DEFAULT_APPS); 14655 serializer.endDocument(); 14656 serializer.flush(); 14657 } catch (Exception e) { 14658 if (DEBUG_BACKUP) { 14659 Slog.e(TAG, "Unable to write default apps for backup", e); 14660 } 14661 return null; 14662 } 14663 14664 return dataStream.toByteArray(); 14665 } 14666 14667 @Override 14668 public void restoreDefaultApps(byte[] backup, int userId) { 14669 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14670 throw new SecurityException("Only the system may call restoreDefaultApps()"); 14671 } 14672 14673 try { 14674 final XmlPullParser parser = Xml.newPullParser(); 14675 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14676 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 14677 new BlobXmlRestorer() { 14678 @Override 14679 public void apply(XmlPullParser parser, int userId) 14680 throws XmlPullParserException, IOException { 14681 synchronized (mPackages) { 14682 mSettings.readDefaultAppsLPw(parser, userId); 14683 } 14684 } 14685 } ); 14686 } catch (Exception e) { 14687 if (DEBUG_BACKUP) { 14688 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 14689 } 14690 } 14691 } 14692 14693 @Override 14694 public byte[] getIntentFilterVerificationBackup(int userId) { 14695 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14696 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 14697 } 14698 14699 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14700 try { 14701 final XmlSerializer serializer = new FastXmlSerializer(); 14702 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14703 serializer.startDocument(null, true); 14704 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 14705 14706 synchronized (mPackages) { 14707 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 14708 } 14709 14710 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 14711 serializer.endDocument(); 14712 serializer.flush(); 14713 } catch (Exception e) { 14714 if (DEBUG_BACKUP) { 14715 Slog.e(TAG, "Unable to write default apps for backup", e); 14716 } 14717 return null; 14718 } 14719 14720 return dataStream.toByteArray(); 14721 } 14722 14723 @Override 14724 public void restoreIntentFilterVerification(byte[] backup, int userId) { 14725 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14726 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14727 } 14728 14729 try { 14730 final XmlPullParser parser = Xml.newPullParser(); 14731 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14732 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 14733 new BlobXmlRestorer() { 14734 @Override 14735 public void apply(XmlPullParser parser, int userId) 14736 throws XmlPullParserException, IOException { 14737 synchronized (mPackages) { 14738 mSettings.readAllDomainVerificationsLPr(parser, userId); 14739 mSettings.writeLPr(); 14740 } 14741 } 14742 } ); 14743 } catch (Exception e) { 14744 if (DEBUG_BACKUP) { 14745 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14746 } 14747 } 14748 } 14749 14750 @Override 14751 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 14752 int sourceUserId, int targetUserId, int flags) { 14753 mContext.enforceCallingOrSelfPermission( 14754 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14755 int callingUid = Binder.getCallingUid(); 14756 enforceOwnerRights(ownerPackage, callingUid); 14757 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14758 if (intentFilter.countActions() == 0) { 14759 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 14760 return; 14761 } 14762 synchronized (mPackages) { 14763 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 14764 ownerPackage, targetUserId, flags); 14765 CrossProfileIntentResolver resolver = 14766 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14767 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 14768 // We have all those whose filter is equal. Now checking if the rest is equal as well. 14769 if (existing != null) { 14770 int size = existing.size(); 14771 for (int i = 0; i < size; i++) { 14772 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 14773 return; 14774 } 14775 } 14776 } 14777 resolver.addFilter(newFilter); 14778 scheduleWritePackageRestrictionsLocked(sourceUserId); 14779 } 14780 } 14781 14782 @Override 14783 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 14784 mContext.enforceCallingOrSelfPermission( 14785 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14786 int callingUid = Binder.getCallingUid(); 14787 enforceOwnerRights(ownerPackage, callingUid); 14788 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14789 synchronized (mPackages) { 14790 CrossProfileIntentResolver resolver = 14791 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14792 ArraySet<CrossProfileIntentFilter> set = 14793 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 14794 for (CrossProfileIntentFilter filter : set) { 14795 if (filter.getOwnerPackage().equals(ownerPackage)) { 14796 resolver.removeFilter(filter); 14797 } 14798 } 14799 scheduleWritePackageRestrictionsLocked(sourceUserId); 14800 } 14801 } 14802 14803 // Enforcing that callingUid is owning pkg on userId 14804 private void enforceOwnerRights(String pkg, int callingUid) { 14805 // The system owns everything. 14806 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 14807 return; 14808 } 14809 int callingUserId = UserHandle.getUserId(callingUid); 14810 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 14811 if (pi == null) { 14812 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 14813 + callingUserId); 14814 } 14815 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 14816 throw new SecurityException("Calling uid " + callingUid 14817 + " does not own package " + pkg); 14818 } 14819 } 14820 14821 @Override 14822 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 14823 Intent intent = new Intent(Intent.ACTION_MAIN); 14824 intent.addCategory(Intent.CATEGORY_HOME); 14825 14826 final int callingUserId = UserHandle.getCallingUserId(); 14827 List<ResolveInfo> list = queryIntentActivities(intent, null, 14828 PackageManager.GET_META_DATA, callingUserId); 14829 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 14830 true, false, false, callingUserId); 14831 14832 allHomeCandidates.clear(); 14833 if (list != null) { 14834 for (ResolveInfo ri : list) { 14835 allHomeCandidates.add(ri); 14836 } 14837 } 14838 return (preferred == null || preferred.activityInfo == null) 14839 ? null 14840 : new ComponentName(preferred.activityInfo.packageName, 14841 preferred.activityInfo.name); 14842 } 14843 14844 @Override 14845 public void setApplicationEnabledSetting(String appPackageName, 14846 int newState, int flags, int userId, String callingPackage) { 14847 if (!sUserManager.exists(userId)) return; 14848 if (callingPackage == null) { 14849 callingPackage = Integer.toString(Binder.getCallingUid()); 14850 } 14851 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 14852 } 14853 14854 @Override 14855 public void setComponentEnabledSetting(ComponentName componentName, 14856 int newState, int flags, int userId) { 14857 if (!sUserManager.exists(userId)) return; 14858 setEnabledSetting(componentName.getPackageName(), 14859 componentName.getClassName(), newState, flags, userId, null); 14860 } 14861 14862 private void setEnabledSetting(final String packageName, String className, int newState, 14863 final int flags, int userId, String callingPackage) { 14864 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 14865 || newState == COMPONENT_ENABLED_STATE_ENABLED 14866 || newState == COMPONENT_ENABLED_STATE_DISABLED 14867 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 14868 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 14869 throw new IllegalArgumentException("Invalid new component state: " 14870 + newState); 14871 } 14872 PackageSetting pkgSetting; 14873 final int uid = Binder.getCallingUid(); 14874 final int permission = mContext.checkCallingOrSelfPermission( 14875 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14876 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 14877 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14878 boolean sendNow = false; 14879 boolean isApp = (className == null); 14880 String componentName = isApp ? packageName : className; 14881 int packageUid = -1; 14882 ArrayList<String> components; 14883 14884 // writer 14885 synchronized (mPackages) { 14886 pkgSetting = mSettings.mPackages.get(packageName); 14887 if (pkgSetting == null) { 14888 if (className == null) { 14889 throw new IllegalArgumentException( 14890 "Unknown package: " + packageName); 14891 } 14892 throw new IllegalArgumentException( 14893 "Unknown component: " + packageName 14894 + "/" + className); 14895 } 14896 // Allow root and verify that userId is not being specified by a different user 14897 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 14898 throw new SecurityException( 14899 "Permission Denial: attempt to change component state from pid=" 14900 + Binder.getCallingPid() 14901 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 14902 } 14903 if (className == null) { 14904 // We're dealing with an application/package level state change 14905 if (pkgSetting.getEnabled(userId) == newState) { 14906 // Nothing to do 14907 return; 14908 } 14909 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 14910 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 14911 // Don't care about who enables an app. 14912 callingPackage = null; 14913 } 14914 pkgSetting.setEnabled(newState, userId, callingPackage); 14915 // pkgSetting.pkg.mSetEnabled = newState; 14916 } else { 14917 // We're dealing with a component level state change 14918 // First, verify that this is a valid class name. 14919 PackageParser.Package pkg = pkgSetting.pkg; 14920 if (pkg == null || !pkg.hasComponentClassName(className)) { 14921 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 14922 throw new IllegalArgumentException("Component class " + className 14923 + " does not exist in " + packageName); 14924 } else { 14925 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 14926 + className + " does not exist in " + packageName); 14927 } 14928 } 14929 switch (newState) { 14930 case COMPONENT_ENABLED_STATE_ENABLED: 14931 if (!pkgSetting.enableComponentLPw(className, userId)) { 14932 return; 14933 } 14934 break; 14935 case COMPONENT_ENABLED_STATE_DISABLED: 14936 if (!pkgSetting.disableComponentLPw(className, userId)) { 14937 return; 14938 } 14939 break; 14940 case COMPONENT_ENABLED_STATE_DEFAULT: 14941 if (!pkgSetting.restoreComponentLPw(className, userId)) { 14942 return; 14943 } 14944 break; 14945 default: 14946 Slog.e(TAG, "Invalid new component state: " + newState); 14947 return; 14948 } 14949 } 14950 scheduleWritePackageRestrictionsLocked(userId); 14951 components = mPendingBroadcasts.get(userId, packageName); 14952 final boolean newPackage = components == null; 14953 if (newPackage) { 14954 components = new ArrayList<String>(); 14955 } 14956 if (!components.contains(componentName)) { 14957 components.add(componentName); 14958 } 14959 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 14960 sendNow = true; 14961 // Purge entry from pending broadcast list if another one exists already 14962 // since we are sending one right away. 14963 mPendingBroadcasts.remove(userId, packageName); 14964 } else { 14965 if (newPackage) { 14966 mPendingBroadcasts.put(userId, packageName, components); 14967 } 14968 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 14969 // Schedule a message 14970 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 14971 } 14972 } 14973 } 14974 14975 long callingId = Binder.clearCallingIdentity(); 14976 try { 14977 if (sendNow) { 14978 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 14979 sendPackageChangedBroadcast(packageName, 14980 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 14981 } 14982 } finally { 14983 Binder.restoreCallingIdentity(callingId); 14984 } 14985 } 14986 14987 private void sendPackageChangedBroadcast(String packageName, 14988 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 14989 if (DEBUG_INSTALL) 14990 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 14991 + componentNames); 14992 Bundle extras = new Bundle(4); 14993 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 14994 String nameList[] = new String[componentNames.size()]; 14995 componentNames.toArray(nameList); 14996 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 14997 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 14998 extras.putInt(Intent.EXTRA_UID, packageUid); 14999 // If this is not reporting a change of the overall package, then only send it 15000 // to registered receivers. We don't want to launch a swath of apps for every 15001 // little component state change. 15002 final int flags = !componentNames.contains(packageName) 15003 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 15004 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 15005 new int[] {UserHandle.getUserId(packageUid)}); 15006 } 15007 15008 @Override 15009 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 15010 if (!sUserManager.exists(userId)) return; 15011 final int uid = Binder.getCallingUid(); 15012 final int permission = mContext.checkCallingOrSelfPermission( 15013 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 15014 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 15015 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 15016 // writer 15017 synchronized (mPackages) { 15018 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 15019 allowedByPermission, uid, userId)) { 15020 scheduleWritePackageRestrictionsLocked(userId); 15021 } 15022 } 15023 } 15024 15025 @Override 15026 public String getInstallerPackageName(String packageName) { 15027 // reader 15028 synchronized (mPackages) { 15029 return mSettings.getInstallerPackageNameLPr(packageName); 15030 } 15031 } 15032 15033 @Override 15034 public int getApplicationEnabledSetting(String packageName, int userId) { 15035 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 15036 int uid = Binder.getCallingUid(); 15037 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 15038 // reader 15039 synchronized (mPackages) { 15040 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 15041 } 15042 } 15043 15044 @Override 15045 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 15046 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 15047 int uid = Binder.getCallingUid(); 15048 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 15049 // reader 15050 synchronized (mPackages) { 15051 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 15052 } 15053 } 15054 15055 @Override 15056 public void enterSafeMode() { 15057 enforceSystemOrRoot("Only the system can request entering safe mode"); 15058 15059 if (!mSystemReady) { 15060 mSafeMode = true; 15061 } 15062 } 15063 15064 @Override 15065 public void systemReady() { 15066 mSystemReady = true; 15067 15068 // Read the compatibilty setting when the system is ready. 15069 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 15070 mContext.getContentResolver(), 15071 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 15072 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 15073 if (DEBUG_SETTINGS) { 15074 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 15075 } 15076 15077 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 15078 15079 synchronized (mPackages) { 15080 // Verify that all of the preferred activity components actually 15081 // exist. It is possible for applications to be updated and at 15082 // that point remove a previously declared activity component that 15083 // had been set as a preferred activity. We try to clean this up 15084 // the next time we encounter that preferred activity, but it is 15085 // possible for the user flow to never be able to return to that 15086 // situation so here we do a sanity check to make sure we haven't 15087 // left any junk around. 15088 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 15089 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 15090 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 15091 removed.clear(); 15092 for (PreferredActivity pa : pir.filterSet()) { 15093 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 15094 removed.add(pa); 15095 } 15096 } 15097 if (removed.size() > 0) { 15098 for (int r=0; r<removed.size(); r++) { 15099 PreferredActivity pa = removed.get(r); 15100 Slog.w(TAG, "Removing dangling preferred activity: " 15101 + pa.mPref.mComponent); 15102 pir.removeFilter(pa); 15103 } 15104 mSettings.writePackageRestrictionsLPr( 15105 mSettings.mPreferredActivities.keyAt(i)); 15106 } 15107 } 15108 15109 for (int userId : UserManagerService.getInstance().getUserIds()) { 15110 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 15111 grantPermissionsUserIds = ArrayUtils.appendInt( 15112 grantPermissionsUserIds, userId); 15113 } 15114 } 15115 } 15116 sUserManager.systemReady(); 15117 15118 // If we upgraded grant all default permissions before kicking off. 15119 for (int userId : grantPermissionsUserIds) { 15120 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 15121 } 15122 15123 // Kick off any messages waiting for system ready 15124 if (mPostSystemReadyMessages != null) { 15125 for (Message msg : mPostSystemReadyMessages) { 15126 msg.sendToTarget(); 15127 } 15128 mPostSystemReadyMessages = null; 15129 } 15130 15131 // Watch for external volumes that come and go over time 15132 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15133 storage.registerListener(mStorageListener); 15134 15135 mInstallerService.systemReady(); 15136 mPackageDexOptimizer.systemReady(); 15137 15138 MountServiceInternal mountServiceInternal = LocalServices.getService( 15139 MountServiceInternal.class); 15140 mountServiceInternal.addExternalStoragePolicy( 15141 new MountServiceInternal.ExternalStorageMountPolicy() { 15142 @Override 15143 public int getMountMode(int uid, String packageName) { 15144 if (Process.isIsolated(uid)) { 15145 return Zygote.MOUNT_EXTERNAL_NONE; 15146 } 15147 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 15148 return Zygote.MOUNT_EXTERNAL_DEFAULT; 15149 } 15150 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 15151 return Zygote.MOUNT_EXTERNAL_DEFAULT; 15152 } 15153 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 15154 return Zygote.MOUNT_EXTERNAL_READ; 15155 } 15156 return Zygote.MOUNT_EXTERNAL_WRITE; 15157 } 15158 15159 @Override 15160 public boolean hasExternalStorage(int uid, String packageName) { 15161 return true; 15162 } 15163 }); 15164 } 15165 15166 @Override 15167 public boolean isSafeMode() { 15168 return mSafeMode; 15169 } 15170 15171 @Override 15172 public boolean hasSystemUidErrors() { 15173 return mHasSystemUidErrors; 15174 } 15175 15176 static String arrayToString(int[] array) { 15177 StringBuffer buf = new StringBuffer(128); 15178 buf.append('['); 15179 if (array != null) { 15180 for (int i=0; i<array.length; i++) { 15181 if (i > 0) buf.append(", "); 15182 buf.append(array[i]); 15183 } 15184 } 15185 buf.append(']'); 15186 return buf.toString(); 15187 } 15188 15189 static class DumpState { 15190 public static final int DUMP_LIBS = 1 << 0; 15191 public static final int DUMP_FEATURES = 1 << 1; 15192 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 15193 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 15194 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 15195 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 15196 public static final int DUMP_PERMISSIONS = 1 << 6; 15197 public static final int DUMP_PACKAGES = 1 << 7; 15198 public static final int DUMP_SHARED_USERS = 1 << 8; 15199 public static final int DUMP_MESSAGES = 1 << 9; 15200 public static final int DUMP_PROVIDERS = 1 << 10; 15201 public static final int DUMP_VERIFIERS = 1 << 11; 15202 public static final int DUMP_PREFERRED = 1 << 12; 15203 public static final int DUMP_PREFERRED_XML = 1 << 13; 15204 public static final int DUMP_KEYSETS = 1 << 14; 15205 public static final int DUMP_VERSION = 1 << 15; 15206 public static final int DUMP_INSTALLS = 1 << 16; 15207 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 15208 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 15209 15210 public static final int OPTION_SHOW_FILTERS = 1 << 0; 15211 15212 private int mTypes; 15213 15214 private int mOptions; 15215 15216 private boolean mTitlePrinted; 15217 15218 private SharedUserSetting mSharedUser; 15219 15220 public boolean isDumping(int type) { 15221 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 15222 return true; 15223 } 15224 15225 return (mTypes & type) != 0; 15226 } 15227 15228 public void setDump(int type) { 15229 mTypes |= type; 15230 } 15231 15232 public boolean isOptionEnabled(int option) { 15233 return (mOptions & option) != 0; 15234 } 15235 15236 public void setOptionEnabled(int option) { 15237 mOptions |= option; 15238 } 15239 15240 public boolean onTitlePrinted() { 15241 final boolean printed = mTitlePrinted; 15242 mTitlePrinted = true; 15243 return printed; 15244 } 15245 15246 public boolean getTitlePrinted() { 15247 return mTitlePrinted; 15248 } 15249 15250 public void setTitlePrinted(boolean enabled) { 15251 mTitlePrinted = enabled; 15252 } 15253 15254 public SharedUserSetting getSharedUser() { 15255 return mSharedUser; 15256 } 15257 15258 public void setSharedUser(SharedUserSetting user) { 15259 mSharedUser = user; 15260 } 15261 } 15262 15263 @Override 15264 public void onShellCommand(FileDescriptor in, FileDescriptor out, 15265 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 15266 (new PackageManagerShellCommand(this)).exec( 15267 this, in, out, err, args, resultReceiver); 15268 } 15269 15270 @Override 15271 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 15272 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 15273 != PackageManager.PERMISSION_GRANTED) { 15274 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 15275 + Binder.getCallingPid() 15276 + ", uid=" + Binder.getCallingUid() 15277 + " without permission " 15278 + android.Manifest.permission.DUMP); 15279 return; 15280 } 15281 15282 DumpState dumpState = new DumpState(); 15283 boolean fullPreferred = false; 15284 boolean checkin = false; 15285 15286 String packageName = null; 15287 ArraySet<String> permissionNames = null; 15288 15289 int opti = 0; 15290 while (opti < args.length) { 15291 String opt = args[opti]; 15292 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 15293 break; 15294 } 15295 opti++; 15296 15297 if ("-a".equals(opt)) { 15298 // Right now we only know how to print all. 15299 } else if ("-h".equals(opt)) { 15300 pw.println("Package manager dump options:"); 15301 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 15302 pw.println(" --checkin: dump for a checkin"); 15303 pw.println(" -f: print details of intent filters"); 15304 pw.println(" -h: print this help"); 15305 pw.println(" cmd may be one of:"); 15306 pw.println(" l[ibraries]: list known shared libraries"); 15307 pw.println(" f[eatures]: list device features"); 15308 pw.println(" k[eysets]: print known keysets"); 15309 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 15310 pw.println(" perm[issions]: dump permissions"); 15311 pw.println(" permission [name ...]: dump declaration and use of given permission"); 15312 pw.println(" pref[erred]: print preferred package settings"); 15313 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 15314 pw.println(" prov[iders]: dump content providers"); 15315 pw.println(" p[ackages]: dump installed packages"); 15316 pw.println(" s[hared-users]: dump shared user IDs"); 15317 pw.println(" m[essages]: print collected runtime messages"); 15318 pw.println(" v[erifiers]: print package verifier info"); 15319 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 15320 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 15321 pw.println(" version: print database version info"); 15322 pw.println(" write: write current settings now"); 15323 pw.println(" installs: details about install sessions"); 15324 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 15325 pw.println(" <package.name>: info about given package"); 15326 return; 15327 } else if ("--checkin".equals(opt)) { 15328 checkin = true; 15329 } else if ("-f".equals(opt)) { 15330 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 15331 } else { 15332 pw.println("Unknown argument: " + opt + "; use -h for help"); 15333 } 15334 } 15335 15336 // Is the caller requesting to dump a particular piece of data? 15337 if (opti < args.length) { 15338 String cmd = args[opti]; 15339 opti++; 15340 // Is this a package name? 15341 if ("android".equals(cmd) || cmd.contains(".")) { 15342 packageName = cmd; 15343 // When dumping a single package, we always dump all of its 15344 // filter information since the amount of data will be reasonable. 15345 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 15346 } else if ("check-permission".equals(cmd)) { 15347 if (opti >= args.length) { 15348 pw.println("Error: check-permission missing permission argument"); 15349 return; 15350 } 15351 String perm = args[opti]; 15352 opti++; 15353 if (opti >= args.length) { 15354 pw.println("Error: check-permission missing package argument"); 15355 return; 15356 } 15357 String pkg = args[opti]; 15358 opti++; 15359 int user = UserHandle.getUserId(Binder.getCallingUid()); 15360 if (opti < args.length) { 15361 try { 15362 user = Integer.parseInt(args[opti]); 15363 } catch (NumberFormatException e) { 15364 pw.println("Error: check-permission user argument is not a number: " 15365 + args[opti]); 15366 return; 15367 } 15368 } 15369 pw.println(checkPermission(perm, pkg, user)); 15370 return; 15371 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 15372 dumpState.setDump(DumpState.DUMP_LIBS); 15373 } else if ("f".equals(cmd) || "features".equals(cmd)) { 15374 dumpState.setDump(DumpState.DUMP_FEATURES); 15375 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 15376 if (opti >= args.length) { 15377 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 15378 | DumpState.DUMP_SERVICE_RESOLVERS 15379 | DumpState.DUMP_RECEIVER_RESOLVERS 15380 | DumpState.DUMP_CONTENT_RESOLVERS); 15381 } else { 15382 while (opti < args.length) { 15383 String name = args[opti]; 15384 if ("a".equals(name) || "activity".equals(name)) { 15385 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 15386 } else if ("s".equals(name) || "service".equals(name)) { 15387 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 15388 } else if ("r".equals(name) || "receiver".equals(name)) { 15389 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 15390 } else if ("c".equals(name) || "content".equals(name)) { 15391 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 15392 } else { 15393 pw.println("Error: unknown resolver table type: " + name); 15394 return; 15395 } 15396 opti++; 15397 } 15398 } 15399 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 15400 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 15401 } else if ("permission".equals(cmd)) { 15402 if (opti >= args.length) { 15403 pw.println("Error: permission requires permission name"); 15404 return; 15405 } 15406 permissionNames = new ArraySet<>(); 15407 while (opti < args.length) { 15408 permissionNames.add(args[opti]); 15409 opti++; 15410 } 15411 dumpState.setDump(DumpState.DUMP_PERMISSIONS 15412 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 15413 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 15414 dumpState.setDump(DumpState.DUMP_PREFERRED); 15415 } else if ("preferred-xml".equals(cmd)) { 15416 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 15417 if (opti < args.length && "--full".equals(args[opti])) { 15418 fullPreferred = true; 15419 opti++; 15420 } 15421 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 15422 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 15423 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 15424 dumpState.setDump(DumpState.DUMP_PACKAGES); 15425 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 15426 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 15427 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 15428 dumpState.setDump(DumpState.DUMP_PROVIDERS); 15429 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 15430 dumpState.setDump(DumpState.DUMP_MESSAGES); 15431 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 15432 dumpState.setDump(DumpState.DUMP_VERIFIERS); 15433 } else if ("i".equals(cmd) || "ifv".equals(cmd) 15434 || "intent-filter-verifiers".equals(cmd)) { 15435 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 15436 } else if ("version".equals(cmd)) { 15437 dumpState.setDump(DumpState.DUMP_VERSION); 15438 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 15439 dumpState.setDump(DumpState.DUMP_KEYSETS); 15440 } else if ("installs".equals(cmd)) { 15441 dumpState.setDump(DumpState.DUMP_INSTALLS); 15442 } else if ("write".equals(cmd)) { 15443 synchronized (mPackages) { 15444 mSettings.writeLPr(); 15445 pw.println("Settings written."); 15446 return; 15447 } 15448 } 15449 } 15450 15451 if (checkin) { 15452 pw.println("vers,1"); 15453 } 15454 15455 // reader 15456 synchronized (mPackages) { 15457 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 15458 if (!checkin) { 15459 if (dumpState.onTitlePrinted()) 15460 pw.println(); 15461 pw.println("Database versions:"); 15462 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 15463 } 15464 } 15465 15466 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 15467 if (!checkin) { 15468 if (dumpState.onTitlePrinted()) 15469 pw.println(); 15470 pw.println("Verifiers:"); 15471 pw.print(" Required: "); 15472 pw.print(mRequiredVerifierPackage); 15473 pw.print(" (uid="); 15474 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 15475 pw.println(")"); 15476 } else if (mRequiredVerifierPackage != null) { 15477 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 15478 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 15479 } 15480 } 15481 15482 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 15483 packageName == null) { 15484 if (mIntentFilterVerifierComponent != null) { 15485 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 15486 if (!checkin) { 15487 if (dumpState.onTitlePrinted()) 15488 pw.println(); 15489 pw.println("Intent Filter Verifier:"); 15490 pw.print(" Using: "); 15491 pw.print(verifierPackageName); 15492 pw.print(" (uid="); 15493 pw.print(getPackageUid(verifierPackageName, 0)); 15494 pw.println(")"); 15495 } else if (verifierPackageName != null) { 15496 pw.print("ifv,"); pw.print(verifierPackageName); 15497 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 15498 } 15499 } else { 15500 pw.println(); 15501 pw.println("No Intent Filter Verifier available!"); 15502 } 15503 } 15504 15505 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 15506 boolean printedHeader = false; 15507 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 15508 while (it.hasNext()) { 15509 String name = it.next(); 15510 SharedLibraryEntry ent = mSharedLibraries.get(name); 15511 if (!checkin) { 15512 if (!printedHeader) { 15513 if (dumpState.onTitlePrinted()) 15514 pw.println(); 15515 pw.println("Libraries:"); 15516 printedHeader = true; 15517 } 15518 pw.print(" "); 15519 } else { 15520 pw.print("lib,"); 15521 } 15522 pw.print(name); 15523 if (!checkin) { 15524 pw.print(" -> "); 15525 } 15526 if (ent.path != null) { 15527 if (!checkin) { 15528 pw.print("(jar) "); 15529 pw.print(ent.path); 15530 } else { 15531 pw.print(",jar,"); 15532 pw.print(ent.path); 15533 } 15534 } else { 15535 if (!checkin) { 15536 pw.print("(apk) "); 15537 pw.print(ent.apk); 15538 } else { 15539 pw.print(",apk,"); 15540 pw.print(ent.apk); 15541 } 15542 } 15543 pw.println(); 15544 } 15545 } 15546 15547 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 15548 if (dumpState.onTitlePrinted()) 15549 pw.println(); 15550 if (!checkin) { 15551 pw.println("Features:"); 15552 } 15553 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 15554 while (it.hasNext()) { 15555 String name = it.next(); 15556 if (!checkin) { 15557 pw.print(" "); 15558 } else { 15559 pw.print("feat,"); 15560 } 15561 pw.println(name); 15562 } 15563 } 15564 15565 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 15566 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 15567 : "Activity Resolver Table:", " ", packageName, 15568 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15569 dumpState.setTitlePrinted(true); 15570 } 15571 } 15572 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 15573 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 15574 : "Receiver Resolver Table:", " ", packageName, 15575 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15576 dumpState.setTitlePrinted(true); 15577 } 15578 } 15579 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 15580 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 15581 : "Service Resolver Table:", " ", packageName, 15582 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15583 dumpState.setTitlePrinted(true); 15584 } 15585 } 15586 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 15587 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 15588 : "Provider Resolver Table:", " ", packageName, 15589 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15590 dumpState.setTitlePrinted(true); 15591 } 15592 } 15593 15594 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 15595 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 15596 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 15597 int user = mSettings.mPreferredActivities.keyAt(i); 15598 if (pir.dump(pw, 15599 dumpState.getTitlePrinted() 15600 ? "\nPreferred Activities User " + user + ":" 15601 : "Preferred Activities User " + user + ":", " ", 15602 packageName, true, false)) { 15603 dumpState.setTitlePrinted(true); 15604 } 15605 } 15606 } 15607 15608 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 15609 pw.flush(); 15610 FileOutputStream fout = new FileOutputStream(fd); 15611 BufferedOutputStream str = new BufferedOutputStream(fout); 15612 XmlSerializer serializer = new FastXmlSerializer(); 15613 try { 15614 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 15615 serializer.startDocument(null, true); 15616 serializer.setFeature( 15617 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 15618 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 15619 serializer.endDocument(); 15620 serializer.flush(); 15621 } catch (IllegalArgumentException e) { 15622 pw.println("Failed writing: " + e); 15623 } catch (IllegalStateException e) { 15624 pw.println("Failed writing: " + e); 15625 } catch (IOException e) { 15626 pw.println("Failed writing: " + e); 15627 } 15628 } 15629 15630 if (!checkin 15631 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 15632 && packageName == null) { 15633 pw.println(); 15634 int count = mSettings.mPackages.size(); 15635 if (count == 0) { 15636 pw.println("No applications!"); 15637 pw.println(); 15638 } else { 15639 final String prefix = " "; 15640 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 15641 if (allPackageSettings.size() == 0) { 15642 pw.println("No domain preferred apps!"); 15643 pw.println(); 15644 } else { 15645 pw.println("App verification status:"); 15646 pw.println(); 15647 count = 0; 15648 for (PackageSetting ps : allPackageSettings) { 15649 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 15650 if (ivi == null || ivi.getPackageName() == null) continue; 15651 pw.println(prefix + "Package: " + ivi.getPackageName()); 15652 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 15653 pw.println(prefix + "Status: " + ivi.getStatusString()); 15654 pw.println(); 15655 count++; 15656 } 15657 if (count == 0) { 15658 pw.println(prefix + "No app verification established."); 15659 pw.println(); 15660 } 15661 for (int userId : sUserManager.getUserIds()) { 15662 pw.println("App linkages for user " + userId + ":"); 15663 pw.println(); 15664 count = 0; 15665 for (PackageSetting ps : allPackageSettings) { 15666 final long status = ps.getDomainVerificationStatusForUser(userId); 15667 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 15668 continue; 15669 } 15670 pw.println(prefix + "Package: " + ps.name); 15671 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 15672 String statusStr = IntentFilterVerificationInfo. 15673 getStatusStringFromValue(status); 15674 pw.println(prefix + "Status: " + statusStr); 15675 pw.println(); 15676 count++; 15677 } 15678 if (count == 0) { 15679 pw.println(prefix + "No configured app linkages."); 15680 pw.println(); 15681 } 15682 } 15683 } 15684 } 15685 } 15686 15687 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 15688 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 15689 if (packageName == null && permissionNames == null) { 15690 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 15691 if (iperm == 0) { 15692 if (dumpState.onTitlePrinted()) 15693 pw.println(); 15694 pw.println("AppOp Permissions:"); 15695 } 15696 pw.print(" AppOp Permission "); 15697 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 15698 pw.println(":"); 15699 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 15700 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 15701 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 15702 } 15703 } 15704 } 15705 } 15706 15707 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 15708 boolean printedSomething = false; 15709 for (PackageParser.Provider p : mProviders.mProviders.values()) { 15710 if (packageName != null && !packageName.equals(p.info.packageName)) { 15711 continue; 15712 } 15713 if (!printedSomething) { 15714 if (dumpState.onTitlePrinted()) 15715 pw.println(); 15716 pw.println("Registered ContentProviders:"); 15717 printedSomething = true; 15718 } 15719 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 15720 pw.print(" "); pw.println(p.toString()); 15721 } 15722 printedSomething = false; 15723 for (Map.Entry<String, PackageParser.Provider> entry : 15724 mProvidersByAuthority.entrySet()) { 15725 PackageParser.Provider p = entry.getValue(); 15726 if (packageName != null && !packageName.equals(p.info.packageName)) { 15727 continue; 15728 } 15729 if (!printedSomething) { 15730 if (dumpState.onTitlePrinted()) 15731 pw.println(); 15732 pw.println("ContentProvider Authorities:"); 15733 printedSomething = true; 15734 } 15735 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 15736 pw.print(" "); pw.println(p.toString()); 15737 if (p.info != null && p.info.applicationInfo != null) { 15738 final String appInfo = p.info.applicationInfo.toString(); 15739 pw.print(" applicationInfo="); pw.println(appInfo); 15740 } 15741 } 15742 } 15743 15744 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 15745 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 15746 } 15747 15748 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 15749 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 15750 } 15751 15752 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 15753 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 15754 } 15755 15756 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 15757 // XXX should handle packageName != null by dumping only install data that 15758 // the given package is involved with. 15759 if (dumpState.onTitlePrinted()) pw.println(); 15760 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 15761 } 15762 15763 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 15764 if (dumpState.onTitlePrinted()) pw.println(); 15765 mSettings.dumpReadMessagesLPr(pw, dumpState); 15766 15767 pw.println(); 15768 pw.println("Package warning messages:"); 15769 BufferedReader in = null; 15770 String line = null; 15771 try { 15772 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15773 while ((line = in.readLine()) != null) { 15774 if (line.contains("ignored: updated version")) continue; 15775 pw.println(line); 15776 } 15777 } catch (IOException ignored) { 15778 } finally { 15779 IoUtils.closeQuietly(in); 15780 } 15781 } 15782 15783 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 15784 BufferedReader in = null; 15785 String line = null; 15786 try { 15787 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15788 while ((line = in.readLine()) != null) { 15789 if (line.contains("ignored: updated version")) continue; 15790 pw.print("msg,"); 15791 pw.println(line); 15792 } 15793 } catch (IOException ignored) { 15794 } finally { 15795 IoUtils.closeQuietly(in); 15796 } 15797 } 15798 } 15799 } 15800 15801 private String dumpDomainString(String packageName) { 15802 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName); 15803 List<IntentFilter> filters = getAllIntentFilters(packageName); 15804 15805 ArraySet<String> result = new ArraySet<>(); 15806 if (iviList.size() > 0) { 15807 for (IntentFilterVerificationInfo ivi : iviList) { 15808 for (String host : ivi.getDomains()) { 15809 result.add(host); 15810 } 15811 } 15812 } 15813 if (filters != null && filters.size() > 0) { 15814 for (IntentFilter filter : filters) { 15815 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 15816 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 15817 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 15818 result.addAll(filter.getHostsList()); 15819 } 15820 } 15821 } 15822 15823 StringBuilder sb = new StringBuilder(result.size() * 16); 15824 for (String domain : result) { 15825 if (sb.length() > 0) sb.append(" "); 15826 sb.append(domain); 15827 } 15828 return sb.toString(); 15829 } 15830 15831 // ------- apps on sdcard specific code ------- 15832 static final boolean DEBUG_SD_INSTALL = false; 15833 15834 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 15835 15836 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 15837 15838 private boolean mMediaMounted = false; 15839 15840 static String getEncryptKey() { 15841 try { 15842 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 15843 SD_ENCRYPTION_KEYSTORE_NAME); 15844 if (sdEncKey == null) { 15845 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 15846 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 15847 if (sdEncKey == null) { 15848 Slog.e(TAG, "Failed to create encryption keys"); 15849 return null; 15850 } 15851 } 15852 return sdEncKey; 15853 } catch (NoSuchAlgorithmException nsae) { 15854 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 15855 return null; 15856 } catch (IOException ioe) { 15857 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 15858 return null; 15859 } 15860 } 15861 15862 /* 15863 * Update media status on PackageManager. 15864 */ 15865 @Override 15866 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 15867 int callingUid = Binder.getCallingUid(); 15868 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 15869 throw new SecurityException("Media status can only be updated by the system"); 15870 } 15871 // reader; this apparently protects mMediaMounted, but should probably 15872 // be a different lock in that case. 15873 synchronized (mPackages) { 15874 Log.i(TAG, "Updating external media status from " 15875 + (mMediaMounted ? "mounted" : "unmounted") + " to " 15876 + (mediaStatus ? "mounted" : "unmounted")); 15877 if (DEBUG_SD_INSTALL) 15878 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 15879 + ", mMediaMounted=" + mMediaMounted); 15880 if (mediaStatus == mMediaMounted) { 15881 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 15882 : 0, -1); 15883 mHandler.sendMessage(msg); 15884 return; 15885 } 15886 mMediaMounted = mediaStatus; 15887 } 15888 // Queue up an async operation since the package installation may take a 15889 // little while. 15890 mHandler.post(new Runnable() { 15891 public void run() { 15892 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 15893 } 15894 }); 15895 } 15896 15897 /** 15898 * Called by MountService when the initial ASECs to scan are available. 15899 * Should block until all the ASEC containers are finished being scanned. 15900 */ 15901 public void scanAvailableAsecs() { 15902 updateExternalMediaStatusInner(true, false, false); 15903 if (mShouldRestoreconData) { 15904 SELinuxMMAC.setRestoreconDone(); 15905 mShouldRestoreconData = false; 15906 } 15907 } 15908 15909 /* 15910 * Collect information of applications on external media, map them against 15911 * existing containers and update information based on current mount status. 15912 * Please note that we always have to report status if reportStatus has been 15913 * set to true especially when unloading packages. 15914 */ 15915 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 15916 boolean externalStorage) { 15917 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 15918 int[] uidArr = EmptyArray.INT; 15919 15920 final String[] list = PackageHelper.getSecureContainerList(); 15921 if (ArrayUtils.isEmpty(list)) { 15922 Log.i(TAG, "No secure containers found"); 15923 } else { 15924 // Process list of secure containers and categorize them 15925 // as active or stale based on their package internal state. 15926 15927 // reader 15928 synchronized (mPackages) { 15929 for (String cid : list) { 15930 // Leave stages untouched for now; installer service owns them 15931 if (PackageInstallerService.isStageName(cid)) continue; 15932 15933 if (DEBUG_SD_INSTALL) 15934 Log.i(TAG, "Processing container " + cid); 15935 String pkgName = getAsecPackageName(cid); 15936 if (pkgName == null) { 15937 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 15938 continue; 15939 } 15940 if (DEBUG_SD_INSTALL) 15941 Log.i(TAG, "Looking for pkg : " + pkgName); 15942 15943 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15944 if (ps == null) { 15945 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 15946 continue; 15947 } 15948 15949 /* 15950 * Skip packages that are not external if we're unmounting 15951 * external storage. 15952 */ 15953 if (externalStorage && !isMounted && !isExternal(ps)) { 15954 continue; 15955 } 15956 15957 final AsecInstallArgs args = new AsecInstallArgs(cid, 15958 getAppDexInstructionSets(ps), ps.isForwardLocked()); 15959 // The package status is changed only if the code path 15960 // matches between settings and the container id. 15961 if (ps.codePathString != null 15962 && ps.codePathString.startsWith(args.getCodePath())) { 15963 if (DEBUG_SD_INSTALL) { 15964 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 15965 + " at code path: " + ps.codePathString); 15966 } 15967 15968 // We do have a valid package installed on sdcard 15969 processCids.put(args, ps.codePathString); 15970 final int uid = ps.appId; 15971 if (uid != -1) { 15972 uidArr = ArrayUtils.appendInt(uidArr, uid); 15973 } 15974 } else { 15975 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 15976 + ps.codePathString); 15977 } 15978 } 15979 } 15980 15981 Arrays.sort(uidArr); 15982 } 15983 15984 // Process packages with valid entries. 15985 if (isMounted) { 15986 if (DEBUG_SD_INSTALL) 15987 Log.i(TAG, "Loading packages"); 15988 loadMediaPackages(processCids, uidArr, externalStorage); 15989 startCleaningPackages(); 15990 mInstallerService.onSecureContainersAvailable(); 15991 } else { 15992 if (DEBUG_SD_INSTALL) 15993 Log.i(TAG, "Unloading packages"); 15994 unloadMediaPackages(processCids, uidArr, reportStatus); 15995 } 15996 } 15997 15998 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15999 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 16000 final int size = infos.size(); 16001 final String[] packageNames = new String[size]; 16002 final int[] packageUids = new int[size]; 16003 for (int i = 0; i < size; i++) { 16004 final ApplicationInfo info = infos.get(i); 16005 packageNames[i] = info.packageName; 16006 packageUids[i] = info.uid; 16007 } 16008 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 16009 finishedReceiver); 16010 } 16011 16012 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 16013 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 16014 sendResourcesChangedBroadcast(mediaStatus, replacing, 16015 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 16016 } 16017 16018 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 16019 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 16020 int size = pkgList.length; 16021 if (size > 0) { 16022 // Send broadcasts here 16023 Bundle extras = new Bundle(); 16024 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 16025 if (uidArr != null) { 16026 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 16027 } 16028 if (replacing) { 16029 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 16030 } 16031 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 16032 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 16033 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 16034 } 16035 } 16036 16037 /* 16038 * Look at potentially valid container ids from processCids If package 16039 * information doesn't match the one on record or package scanning fails, 16040 * the cid is added to list of removeCids. We currently don't delete stale 16041 * containers. 16042 */ 16043 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 16044 boolean externalStorage) { 16045 ArrayList<String> pkgList = new ArrayList<String>(); 16046 Set<AsecInstallArgs> keys = processCids.keySet(); 16047 16048 for (AsecInstallArgs args : keys) { 16049 String codePath = processCids.get(args); 16050 if (DEBUG_SD_INSTALL) 16051 Log.i(TAG, "Loading container : " + args.cid); 16052 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 16053 try { 16054 // Make sure there are no container errors first. 16055 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 16056 Slog.e(TAG, "Failed to mount cid : " + args.cid 16057 + " when installing from sdcard"); 16058 continue; 16059 } 16060 // Check code path here. 16061 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 16062 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 16063 + " does not match one in settings " + codePath); 16064 continue; 16065 } 16066 // Parse package 16067 int parseFlags = mDefParseFlags; 16068 if (args.isExternalAsec()) { 16069 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 16070 } 16071 if (args.isFwdLocked()) { 16072 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 16073 } 16074 16075 synchronized (mInstallLock) { 16076 PackageParser.Package pkg = null; 16077 try { 16078 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null); 16079 } catch (PackageManagerException e) { 16080 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 16081 } 16082 // Scan the package 16083 if (pkg != null) { 16084 /* 16085 * TODO why is the lock being held? doPostInstall is 16086 * called in other places without the lock. This needs 16087 * to be straightened out. 16088 */ 16089 // writer 16090 synchronized (mPackages) { 16091 retCode = PackageManager.INSTALL_SUCCEEDED; 16092 pkgList.add(pkg.packageName); 16093 // Post process args 16094 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 16095 pkg.applicationInfo.uid); 16096 } 16097 } else { 16098 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 16099 } 16100 } 16101 16102 } finally { 16103 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 16104 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 16105 } 16106 } 16107 } 16108 // writer 16109 synchronized (mPackages) { 16110 // If the platform SDK has changed since the last time we booted, 16111 // we need to re-grant app permission to catch any new ones that 16112 // appear. This is really a hack, and means that apps can in some 16113 // cases get permissions that the user didn't initially explicitly 16114 // allow... it would be nice to have some better way to handle 16115 // this situation. 16116 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 16117 : mSettings.getInternalVersion(); 16118 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 16119 : StorageManager.UUID_PRIVATE_INTERNAL; 16120 16121 int updateFlags = UPDATE_PERMISSIONS_ALL; 16122 if (ver.sdkVersion != mSdkVersion) { 16123 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 16124 + mSdkVersion + "; regranting permissions for external"); 16125 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 16126 } 16127 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 16128 16129 // Yay, everything is now upgraded 16130 ver.forceCurrent(); 16131 16132 // can downgrade to reader 16133 // Persist settings 16134 mSettings.writeLPr(); 16135 } 16136 // Send a broadcast to let everyone know we are done processing 16137 if (pkgList.size() > 0) { 16138 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 16139 } 16140 } 16141 16142 /* 16143 * Utility method to unload a list of specified containers 16144 */ 16145 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 16146 // Just unmount all valid containers. 16147 for (AsecInstallArgs arg : cidArgs) { 16148 synchronized (mInstallLock) { 16149 arg.doPostDeleteLI(false); 16150 } 16151 } 16152 } 16153 16154 /* 16155 * Unload packages mounted on external media. This involves deleting package 16156 * data from internal structures, sending broadcasts about diabled packages, 16157 * gc'ing to free up references, unmounting all secure containers 16158 * corresponding to packages on external media, and posting a 16159 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 16160 * that we always have to post this message if status has been requested no 16161 * matter what. 16162 */ 16163 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 16164 final boolean reportStatus) { 16165 if (DEBUG_SD_INSTALL) 16166 Log.i(TAG, "unloading media packages"); 16167 ArrayList<String> pkgList = new ArrayList<String>(); 16168 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 16169 final Set<AsecInstallArgs> keys = processCids.keySet(); 16170 for (AsecInstallArgs args : keys) { 16171 String pkgName = args.getPackageName(); 16172 if (DEBUG_SD_INSTALL) 16173 Log.i(TAG, "Trying to unload pkg : " + pkgName); 16174 // Delete package internally 16175 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 16176 synchronized (mInstallLock) { 16177 boolean res = deletePackageLI(pkgName, null, false, null, null, 16178 PackageManager.DELETE_KEEP_DATA, outInfo, false); 16179 if (res) { 16180 pkgList.add(pkgName); 16181 } else { 16182 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 16183 failedList.add(args); 16184 } 16185 } 16186 } 16187 16188 // reader 16189 synchronized (mPackages) { 16190 // We didn't update the settings after removing each package; 16191 // write them now for all packages. 16192 mSettings.writeLPr(); 16193 } 16194 16195 // We have to absolutely send UPDATED_MEDIA_STATUS only 16196 // after confirming that all the receivers processed the ordered 16197 // broadcast when packages get disabled, force a gc to clean things up. 16198 // and unload all the containers. 16199 if (pkgList.size() > 0) { 16200 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 16201 new IIntentReceiver.Stub() { 16202 public void performReceive(Intent intent, int resultCode, String data, 16203 Bundle extras, boolean ordered, boolean sticky, 16204 int sendingUser) throws RemoteException { 16205 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 16206 reportStatus ? 1 : 0, 1, keys); 16207 mHandler.sendMessage(msg); 16208 } 16209 }); 16210 } else { 16211 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 16212 keys); 16213 mHandler.sendMessage(msg); 16214 } 16215 } 16216 16217 private void loadPrivatePackages(final VolumeInfo vol) { 16218 mHandler.post(new Runnable() { 16219 @Override 16220 public void run() { 16221 loadPrivatePackagesInner(vol); 16222 } 16223 }); 16224 } 16225 16226 private void loadPrivatePackagesInner(VolumeInfo vol) { 16227 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 16228 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 16229 16230 final VersionInfo ver; 16231 final List<PackageSetting> packages; 16232 synchronized (mPackages) { 16233 ver = mSettings.findOrCreateVersion(vol.fsUuid); 16234 packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 16235 } 16236 16237 for (PackageSetting ps : packages) { 16238 synchronized (mInstallLock) { 16239 final PackageParser.Package pkg; 16240 try { 16241 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 16242 loaded.add(pkg.applicationInfo); 16243 } catch (PackageManagerException e) { 16244 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 16245 } 16246 16247 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 16248 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 16249 } 16250 } 16251 } 16252 16253 synchronized (mPackages) { 16254 int updateFlags = UPDATE_PERMISSIONS_ALL; 16255 if (ver.sdkVersion != mSdkVersion) { 16256 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 16257 + mSdkVersion + "; regranting permissions for " + vol.fsUuid); 16258 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 16259 } 16260 updatePermissionsLPw(null, null, vol.fsUuid, updateFlags); 16261 16262 // Yay, everything is now upgraded 16263 ver.forceCurrent(); 16264 16265 mSettings.writeLPr(); 16266 } 16267 16268 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 16269 sendResourcesChangedBroadcast(true, false, loaded, null); 16270 } 16271 16272 private void unloadPrivatePackages(final VolumeInfo vol) { 16273 mHandler.post(new Runnable() { 16274 @Override 16275 public void run() { 16276 unloadPrivatePackagesInner(vol); 16277 } 16278 }); 16279 } 16280 16281 private void unloadPrivatePackagesInner(VolumeInfo vol) { 16282 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 16283 synchronized (mInstallLock) { 16284 synchronized (mPackages) { 16285 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 16286 for (PackageSetting ps : packages) { 16287 if (ps.pkg == null) continue; 16288 16289 final ApplicationInfo info = ps.pkg.applicationInfo; 16290 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 16291 if (deletePackageLI(ps.name, null, false, null, null, 16292 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 16293 unloaded.add(info); 16294 } else { 16295 Slog.w(TAG, "Failed to unload " + ps.codePath); 16296 } 16297 } 16298 16299 mSettings.writeLPr(); 16300 } 16301 } 16302 16303 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 16304 sendResourcesChangedBroadcast(false, false, unloaded, null); 16305 } 16306 16307 /** 16308 * Examine all users present on given mounted volume, and destroy data 16309 * belonging to users that are no longer valid, or whose user ID has been 16310 * recycled. 16311 */ 16312 private void reconcileUsers(String volumeUuid) { 16313 final File[] files = FileUtils 16314 .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid)); 16315 for (File file : files) { 16316 if (!file.isDirectory()) continue; 16317 16318 final int userId; 16319 final UserInfo info; 16320 try { 16321 userId = Integer.parseInt(file.getName()); 16322 info = sUserManager.getUserInfo(userId); 16323 } catch (NumberFormatException e) { 16324 Slog.w(TAG, "Invalid user directory " + file); 16325 continue; 16326 } 16327 16328 boolean destroyUser = false; 16329 if (info == null) { 16330 logCriticalInfo(Log.WARN, "Destroying user directory " + file 16331 + " because no matching user was found"); 16332 destroyUser = true; 16333 } else { 16334 try { 16335 UserManagerService.enforceSerialNumber(file, info.serialNumber); 16336 } catch (IOException e) { 16337 logCriticalInfo(Log.WARN, "Destroying user directory " + file 16338 + " because we failed to enforce serial number: " + e); 16339 destroyUser = true; 16340 } 16341 } 16342 16343 if (destroyUser) { 16344 synchronized (mInstallLock) { 16345 mInstaller.removeUserDataDirs(volumeUuid, userId); 16346 } 16347 } 16348 } 16349 16350 final StorageManager sm = mContext.getSystemService(StorageManager.class); 16351 final UserManager um = mContext.getSystemService(UserManager.class); 16352 for (UserInfo user : um.getUsers()) { 16353 final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id); 16354 if (userDir.exists()) continue; 16355 16356 try { 16357 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber); 16358 UserManagerService.enforceSerialNumber(userDir, user.serialNumber); 16359 } catch (IOException e) { 16360 Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e); 16361 } 16362 } 16363 } 16364 16365 /** 16366 * Examine all apps present on given mounted volume, and destroy apps that 16367 * aren't expected, either due to uninstallation or reinstallation on 16368 * another volume. 16369 */ 16370 private void reconcileApps(String volumeUuid) { 16371 final File[] files = FileUtils 16372 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 16373 for (File file : files) { 16374 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 16375 && !PackageInstallerService.isStageName(file.getName()); 16376 if (!isPackage) { 16377 // Ignore entries which are not packages 16378 continue; 16379 } 16380 16381 boolean destroyApp = false; 16382 String packageName = null; 16383 try { 16384 final PackageLite pkg = PackageParser.parsePackageLite(file, 16385 PackageParser.PARSE_MUST_BE_APK); 16386 packageName = pkg.packageName; 16387 16388 synchronized (mPackages) { 16389 final PackageSetting ps = mSettings.mPackages.get(packageName); 16390 if (ps == null) { 16391 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + " 16392 + volumeUuid + " because we found no install record"); 16393 destroyApp = true; 16394 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 16395 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on " 16396 + volumeUuid + " because we expected it on " + ps.volumeUuid); 16397 destroyApp = true; 16398 } 16399 } 16400 16401 } catch (PackageParserException e) { 16402 logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e); 16403 destroyApp = true; 16404 } 16405 16406 if (destroyApp) { 16407 synchronized (mInstallLock) { 16408 if (packageName != null) { 16409 removeDataDirsLI(volumeUuid, packageName); 16410 } 16411 if (file.isDirectory()) { 16412 mInstaller.rmPackageDir(file.getAbsolutePath()); 16413 } else { 16414 file.delete(); 16415 } 16416 } 16417 } 16418 } 16419 } 16420 16421 private void unfreezePackage(String packageName) { 16422 synchronized (mPackages) { 16423 final PackageSetting ps = mSettings.mPackages.get(packageName); 16424 if (ps != null) { 16425 ps.frozen = false; 16426 } 16427 } 16428 } 16429 16430 @Override 16431 public int movePackage(final String packageName, final String volumeUuid) { 16432 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 16433 16434 final int moveId = mNextMoveId.getAndIncrement(); 16435 mHandler.post(new Runnable() { 16436 @Override 16437 public void run() { 16438 try { 16439 movePackageInternal(packageName, volumeUuid, moveId); 16440 } catch (PackageManagerException e) { 16441 Slog.w(TAG, "Failed to move " + packageName, e); 16442 mMoveCallbacks.notifyStatusChanged(moveId, 16443 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 16444 } 16445 } 16446 }); 16447 return moveId; 16448 } 16449 16450 private void movePackageInternal(final String packageName, final String volumeUuid, 16451 final int moveId) throws PackageManagerException { 16452 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 16453 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16454 final PackageManager pm = mContext.getPackageManager(); 16455 16456 final boolean currentAsec; 16457 final String currentVolumeUuid; 16458 final File codeFile; 16459 final String installerPackageName; 16460 final String packageAbiOverride; 16461 final int appId; 16462 final String seinfo; 16463 final String label; 16464 16465 // reader 16466 synchronized (mPackages) { 16467 final PackageParser.Package pkg = mPackages.get(packageName); 16468 final PackageSetting ps = mSettings.mPackages.get(packageName); 16469 if (pkg == null || ps == null) { 16470 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 16471 } 16472 16473 if (pkg.applicationInfo.isSystemApp()) { 16474 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 16475 "Cannot move system application"); 16476 } 16477 16478 if (pkg.applicationInfo.isExternalAsec()) { 16479 currentAsec = true; 16480 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 16481 } else if (pkg.applicationInfo.isForwardLocked()) { 16482 currentAsec = true; 16483 currentVolumeUuid = "forward_locked"; 16484 } else { 16485 currentAsec = false; 16486 currentVolumeUuid = ps.volumeUuid; 16487 16488 final File probe = new File(pkg.codePath); 16489 final File probeOat = new File(probe, "oat"); 16490 if (!probe.isDirectory() || !probeOat.isDirectory()) { 16491 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16492 "Move only supported for modern cluster style installs"); 16493 } 16494 } 16495 16496 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 16497 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16498 "Package already moved to " + volumeUuid); 16499 } 16500 16501 if (ps.frozen) { 16502 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 16503 "Failed to move already frozen package"); 16504 } 16505 ps.frozen = true; 16506 16507 codeFile = new File(pkg.codePath); 16508 installerPackageName = ps.installerPackageName; 16509 packageAbiOverride = ps.cpuAbiOverrideString; 16510 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16511 seinfo = pkg.applicationInfo.seinfo; 16512 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 16513 } 16514 16515 // Now that we're guarded by frozen state, kill app during move 16516 final long token = Binder.clearCallingIdentity(); 16517 try { 16518 killApplication(packageName, appId, "move pkg"); 16519 } finally { 16520 Binder.restoreCallingIdentity(token); 16521 } 16522 16523 final Bundle extras = new Bundle(); 16524 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 16525 extras.putString(Intent.EXTRA_TITLE, label); 16526 mMoveCallbacks.notifyCreated(moveId, extras); 16527 16528 int installFlags; 16529 final boolean moveCompleteApp; 16530 final File measurePath; 16531 16532 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 16533 installFlags = INSTALL_INTERNAL; 16534 moveCompleteApp = !currentAsec; 16535 measurePath = Environment.getDataAppDirectory(volumeUuid); 16536 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 16537 installFlags = INSTALL_EXTERNAL; 16538 moveCompleteApp = false; 16539 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 16540 } else { 16541 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 16542 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 16543 || !volume.isMountedWritable()) { 16544 unfreezePackage(packageName); 16545 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16546 "Move location not mounted private volume"); 16547 } 16548 16549 Preconditions.checkState(!currentAsec); 16550 16551 installFlags = INSTALL_INTERNAL; 16552 moveCompleteApp = true; 16553 measurePath = Environment.getDataAppDirectory(volumeUuid); 16554 } 16555 16556 final PackageStats stats = new PackageStats(null, -1); 16557 synchronized (mInstaller) { 16558 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 16559 unfreezePackage(packageName); 16560 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16561 "Failed to measure package size"); 16562 } 16563 } 16564 16565 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 16566 + stats.dataSize); 16567 16568 final long startFreeBytes = measurePath.getFreeSpace(); 16569 final long sizeBytes; 16570 if (moveCompleteApp) { 16571 sizeBytes = stats.codeSize + stats.dataSize; 16572 } else { 16573 sizeBytes = stats.codeSize; 16574 } 16575 16576 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 16577 unfreezePackage(packageName); 16578 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16579 "Not enough free space to move"); 16580 } 16581 16582 mMoveCallbacks.notifyStatusChanged(moveId, 10); 16583 16584 final CountDownLatch installedLatch = new CountDownLatch(1); 16585 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 16586 @Override 16587 public void onUserActionRequired(Intent intent) throws RemoteException { 16588 throw new IllegalStateException(); 16589 } 16590 16591 @Override 16592 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 16593 Bundle extras) throws RemoteException { 16594 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 16595 + PackageManager.installStatusToString(returnCode, msg)); 16596 16597 installedLatch.countDown(); 16598 16599 // Regardless of success or failure of the move operation, 16600 // always unfreeze the package 16601 unfreezePackage(packageName); 16602 16603 final int status = PackageManager.installStatusToPublicStatus(returnCode); 16604 switch (status) { 16605 case PackageInstaller.STATUS_SUCCESS: 16606 mMoveCallbacks.notifyStatusChanged(moveId, 16607 PackageManager.MOVE_SUCCEEDED); 16608 break; 16609 case PackageInstaller.STATUS_FAILURE_STORAGE: 16610 mMoveCallbacks.notifyStatusChanged(moveId, 16611 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 16612 break; 16613 default: 16614 mMoveCallbacks.notifyStatusChanged(moveId, 16615 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 16616 break; 16617 } 16618 } 16619 }; 16620 16621 final MoveInfo move; 16622 if (moveCompleteApp) { 16623 // Kick off a thread to report progress estimates 16624 new Thread() { 16625 @Override 16626 public void run() { 16627 while (true) { 16628 try { 16629 if (installedLatch.await(1, TimeUnit.SECONDS)) { 16630 break; 16631 } 16632 } catch (InterruptedException ignored) { 16633 } 16634 16635 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 16636 final int progress = 10 + (int) MathUtils.constrain( 16637 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 16638 mMoveCallbacks.notifyStatusChanged(moveId, progress); 16639 } 16640 } 16641 }.start(); 16642 16643 final String dataAppName = codeFile.getName(); 16644 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 16645 dataAppName, appId, seinfo); 16646 } else { 16647 move = null; 16648 } 16649 16650 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 16651 16652 final Message msg = mHandler.obtainMessage(INIT_COPY); 16653 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 16654 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 16655 installerPackageName, volumeUuid, null, user, packageAbiOverride, null); 16656 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 16657 msg.obj = params; 16658 16659 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 16660 System.identityHashCode(msg.obj)); 16661 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 16662 System.identityHashCode(msg.obj)); 16663 16664 mHandler.sendMessage(msg); 16665 } 16666 16667 @Override 16668 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 16669 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 16670 16671 final int realMoveId = mNextMoveId.getAndIncrement(); 16672 final Bundle extras = new Bundle(); 16673 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 16674 mMoveCallbacks.notifyCreated(realMoveId, extras); 16675 16676 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 16677 @Override 16678 public void onCreated(int moveId, Bundle extras) { 16679 // Ignored 16680 } 16681 16682 @Override 16683 public void onStatusChanged(int moveId, int status, long estMillis) { 16684 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 16685 } 16686 }; 16687 16688 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16689 storage.setPrimaryStorageUuid(volumeUuid, callback); 16690 return realMoveId; 16691 } 16692 16693 @Override 16694 public int getMoveStatus(int moveId) { 16695 mContext.enforceCallingOrSelfPermission( 16696 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16697 return mMoveCallbacks.mLastStatus.get(moveId); 16698 } 16699 16700 @Override 16701 public void registerMoveCallback(IPackageMoveObserver callback) { 16702 mContext.enforceCallingOrSelfPermission( 16703 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16704 mMoveCallbacks.register(callback); 16705 } 16706 16707 @Override 16708 public void unregisterMoveCallback(IPackageMoveObserver callback) { 16709 mContext.enforceCallingOrSelfPermission( 16710 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16711 mMoveCallbacks.unregister(callback); 16712 } 16713 16714 @Override 16715 public boolean setInstallLocation(int loc) { 16716 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 16717 null); 16718 if (getInstallLocation() == loc) { 16719 return true; 16720 } 16721 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 16722 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 16723 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 16724 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 16725 return true; 16726 } 16727 return false; 16728 } 16729 16730 @Override 16731 public int getInstallLocation() { 16732 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 16733 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 16734 PackageHelper.APP_INSTALL_AUTO); 16735 } 16736 16737 /** Called by UserManagerService */ 16738 void cleanUpUser(UserManagerService userManager, int userHandle) { 16739 synchronized (mPackages) { 16740 mDirtyUsers.remove(userHandle); 16741 mUserNeedsBadging.delete(userHandle); 16742 mSettings.removeUserLPw(userHandle); 16743 mPendingBroadcasts.remove(userHandle); 16744 } 16745 synchronized (mInstallLock) { 16746 if (mInstaller != null) { 16747 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16748 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 16749 final String volumeUuid = vol.getFsUuid(); 16750 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 16751 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 16752 } 16753 } 16754 synchronized (mPackages) { 16755 removeUnusedPackagesLILPw(userManager, userHandle); 16756 } 16757 } 16758 } 16759 16760 /** 16761 * We're removing userHandle and would like to remove any downloaded packages 16762 * that are no longer in use by any other user. 16763 * @param userHandle the user being removed 16764 */ 16765 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 16766 final boolean DEBUG_CLEAN_APKS = false; 16767 int [] users = userManager.getUserIds(); 16768 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 16769 while (psit.hasNext()) { 16770 PackageSetting ps = psit.next(); 16771 if (ps.pkg == null) { 16772 continue; 16773 } 16774 final String packageName = ps.pkg.packageName; 16775 // Skip over if system app 16776 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 16777 continue; 16778 } 16779 if (DEBUG_CLEAN_APKS) { 16780 Slog.i(TAG, "Checking package " + packageName); 16781 } 16782 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 16783 if (keep) { 16784 if (DEBUG_CLEAN_APKS) { 16785 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 16786 } 16787 } else { 16788 for (int i = 0; i < users.length; i++) { 16789 if (users[i] != userHandle && ps.getInstalled(users[i])) { 16790 keep = true; 16791 if (DEBUG_CLEAN_APKS) { 16792 Slog.i(TAG, " Keeping package " + packageName + " for user " 16793 + users[i]); 16794 } 16795 break; 16796 } 16797 } 16798 } 16799 if (!keep) { 16800 if (DEBUG_CLEAN_APKS) { 16801 Slog.i(TAG, " Removing package " + packageName); 16802 } 16803 mHandler.post(new Runnable() { 16804 public void run() { 16805 deletePackageX(packageName, userHandle, 0); 16806 } //end run 16807 }); 16808 } 16809 } 16810 } 16811 16812 /** Called by UserManagerService */ 16813 void createNewUser(int userHandle) { 16814 if (mInstaller != null) { 16815 synchronized (mInstallLock) { 16816 synchronized (mPackages) { 16817 mInstaller.createUserConfig(userHandle); 16818 mSettings.createNewUserLILPw(this, mInstaller, userHandle); 16819 } 16820 } 16821 synchronized (mPackages) { 16822 applyFactoryDefaultBrowserLPw(userHandle); 16823 primeDomainVerificationsLPw(userHandle); 16824 } 16825 } 16826 } 16827 16828 void newUserCreated(final int userHandle) { 16829 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 16830 // If permission review for legacy apps is required, we represent 16831 // dagerous permissions for such apps as always granted runtime 16832 // permissions to keep per user flag state whether review is needed. 16833 // Hence, if a new user is added we have to propagate dangerous 16834 // permission grants for these legacy apps. 16835 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 16836 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 16837 | UPDATE_PERMISSIONS_REPLACE_ALL); 16838 } 16839 } 16840 16841 @Override 16842 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 16843 mContext.enforceCallingOrSelfPermission( 16844 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 16845 "Only package verification agents can read the verifier device identity"); 16846 16847 synchronized (mPackages) { 16848 return mSettings.getVerifierDeviceIdentityLPw(); 16849 } 16850 } 16851 16852 @Override 16853 public void setPermissionEnforced(String permission, boolean enforced) { 16854 // TODO: Now that we no longer change GID for storage, this should to away. 16855 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 16856 "setPermissionEnforced"); 16857 if (READ_EXTERNAL_STORAGE.equals(permission)) { 16858 synchronized (mPackages) { 16859 if (mSettings.mReadExternalStorageEnforced == null 16860 || mSettings.mReadExternalStorageEnforced != enforced) { 16861 mSettings.mReadExternalStorageEnforced = enforced; 16862 mSettings.writeLPr(); 16863 } 16864 } 16865 // kill any non-foreground processes so we restart them and 16866 // grant/revoke the GID. 16867 final IActivityManager am = ActivityManagerNative.getDefault(); 16868 if (am != null) { 16869 final long token = Binder.clearCallingIdentity(); 16870 try { 16871 am.killProcessesBelowForeground("setPermissionEnforcement"); 16872 } catch (RemoteException e) { 16873 } finally { 16874 Binder.restoreCallingIdentity(token); 16875 } 16876 } 16877 } else { 16878 throw new IllegalArgumentException("No selective enforcement for " + permission); 16879 } 16880 } 16881 16882 @Override 16883 @Deprecated 16884 public boolean isPermissionEnforced(String permission) { 16885 return true; 16886 } 16887 16888 @Override 16889 public boolean isStorageLow() { 16890 final long token = Binder.clearCallingIdentity(); 16891 try { 16892 final DeviceStorageMonitorInternal 16893 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 16894 if (dsm != null) { 16895 return dsm.isMemoryLow(); 16896 } else { 16897 return false; 16898 } 16899 } finally { 16900 Binder.restoreCallingIdentity(token); 16901 } 16902 } 16903 16904 @Override 16905 public IPackageInstaller getPackageInstaller() { 16906 return mInstallerService; 16907 } 16908 16909 private boolean userNeedsBadging(int userId) { 16910 int index = mUserNeedsBadging.indexOfKey(userId); 16911 if (index < 0) { 16912 final UserInfo userInfo; 16913 final long token = Binder.clearCallingIdentity(); 16914 try { 16915 userInfo = sUserManager.getUserInfo(userId); 16916 } finally { 16917 Binder.restoreCallingIdentity(token); 16918 } 16919 final boolean b; 16920 if (userInfo != null && userInfo.isManagedProfile()) { 16921 b = true; 16922 } else { 16923 b = false; 16924 } 16925 mUserNeedsBadging.put(userId, b); 16926 return b; 16927 } 16928 return mUserNeedsBadging.valueAt(index); 16929 } 16930 16931 @Override 16932 public KeySet getKeySetByAlias(String packageName, String alias) { 16933 if (packageName == null || alias == null) { 16934 return null; 16935 } 16936 synchronized(mPackages) { 16937 final PackageParser.Package pkg = mPackages.get(packageName); 16938 if (pkg == null) { 16939 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16940 throw new IllegalArgumentException("Unknown package: " + packageName); 16941 } 16942 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16943 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 16944 } 16945 } 16946 16947 @Override 16948 public KeySet getSigningKeySet(String packageName) { 16949 if (packageName == null) { 16950 return null; 16951 } 16952 synchronized(mPackages) { 16953 final PackageParser.Package pkg = mPackages.get(packageName); 16954 if (pkg == null) { 16955 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16956 throw new IllegalArgumentException("Unknown package: " + packageName); 16957 } 16958 if (pkg.applicationInfo.uid != Binder.getCallingUid() 16959 && Process.SYSTEM_UID != Binder.getCallingUid()) { 16960 throw new SecurityException("May not access signing KeySet of other apps."); 16961 } 16962 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16963 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 16964 } 16965 } 16966 16967 @Override 16968 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 16969 if (packageName == null || ks == null) { 16970 return false; 16971 } 16972 synchronized(mPackages) { 16973 final PackageParser.Package pkg = mPackages.get(packageName); 16974 if (pkg == null) { 16975 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16976 throw new IllegalArgumentException("Unknown package: " + packageName); 16977 } 16978 IBinder ksh = ks.getToken(); 16979 if (ksh instanceof KeySetHandle) { 16980 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16981 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 16982 } 16983 return false; 16984 } 16985 } 16986 16987 @Override 16988 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 16989 if (packageName == null || ks == null) { 16990 return false; 16991 } 16992 synchronized(mPackages) { 16993 final PackageParser.Package pkg = mPackages.get(packageName); 16994 if (pkg == null) { 16995 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16996 throw new IllegalArgumentException("Unknown package: " + packageName); 16997 } 16998 IBinder ksh = ks.getToken(); 16999 if (ksh instanceof KeySetHandle) { 17000 KeySetManagerService ksms = mSettings.mKeySetManagerService; 17001 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 17002 } 17003 return false; 17004 } 17005 } 17006 17007 private void deletePackageIfUnusedLPr(final String packageName) { 17008 PackageSetting ps = mSettings.mPackages.get(packageName); 17009 if (ps == null) { 17010 return; 17011 } 17012 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 17013 // TODO Implement atomic delete if package is unused 17014 // It is currently possible that the package will be deleted even if it is installed 17015 // after this method returns. 17016 mHandler.post(new Runnable() { 17017 public void run() { 17018 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 17019 } 17020 }); 17021 } 17022 } 17023 17024 /** 17025 * Check and throw if the given before/after packages would be considered a 17026 * downgrade. 17027 */ 17028 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 17029 throws PackageManagerException { 17030 if (after.versionCode < before.mVersionCode) { 17031 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 17032 "Update version code " + after.versionCode + " is older than current " 17033 + before.mVersionCode); 17034 } else if (after.versionCode == before.mVersionCode) { 17035 if (after.baseRevisionCode < before.baseRevisionCode) { 17036 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 17037 "Update base revision code " + after.baseRevisionCode 17038 + " is older than current " + before.baseRevisionCode); 17039 } 17040 17041 if (!ArrayUtils.isEmpty(after.splitNames)) { 17042 for (int i = 0; i < after.splitNames.length; i++) { 17043 final String splitName = after.splitNames[i]; 17044 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 17045 if (j != -1) { 17046 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 17047 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 17048 "Update split " + splitName + " revision code " 17049 + after.splitRevisionCodes[i] + " is older than current " 17050 + before.splitRevisionCodes[j]); 17051 } 17052 } 17053 } 17054 } 17055 } 17056 } 17057 17058 private static class MoveCallbacks extends Handler { 17059 private static final int MSG_CREATED = 1; 17060 private static final int MSG_STATUS_CHANGED = 2; 17061 17062 private final RemoteCallbackList<IPackageMoveObserver> 17063 mCallbacks = new RemoteCallbackList<>(); 17064 17065 private final SparseIntArray mLastStatus = new SparseIntArray(); 17066 17067 public MoveCallbacks(Looper looper) { 17068 super(looper); 17069 } 17070 17071 public void register(IPackageMoveObserver callback) { 17072 mCallbacks.register(callback); 17073 } 17074 17075 public void unregister(IPackageMoveObserver callback) { 17076 mCallbacks.unregister(callback); 17077 } 17078 17079 @Override 17080 public void handleMessage(Message msg) { 17081 final SomeArgs args = (SomeArgs) msg.obj; 17082 final int n = mCallbacks.beginBroadcast(); 17083 for (int i = 0; i < n; i++) { 17084 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 17085 try { 17086 invokeCallback(callback, msg.what, args); 17087 } catch (RemoteException ignored) { 17088 } 17089 } 17090 mCallbacks.finishBroadcast(); 17091 args.recycle(); 17092 } 17093 17094 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 17095 throws RemoteException { 17096 switch (what) { 17097 case MSG_CREATED: { 17098 callback.onCreated(args.argi1, (Bundle) args.arg2); 17099 break; 17100 } 17101 case MSG_STATUS_CHANGED: { 17102 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 17103 break; 17104 } 17105 } 17106 } 17107 17108 private void notifyCreated(int moveId, Bundle extras) { 17109 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 17110 17111 final SomeArgs args = SomeArgs.obtain(); 17112 args.argi1 = moveId; 17113 args.arg2 = extras; 17114 obtainMessage(MSG_CREATED, args).sendToTarget(); 17115 } 17116 17117 private void notifyStatusChanged(int moveId, int status) { 17118 notifyStatusChanged(moveId, status, -1); 17119 } 17120 17121 private void notifyStatusChanged(int moveId, int status, long estMillis) { 17122 Slog.v(TAG, "Move " + moveId + " status " + status); 17123 17124 final SomeArgs args = SomeArgs.obtain(); 17125 args.argi1 = moveId; 17126 args.argi2 = status; 17127 args.arg3 = estMillis; 17128 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 17129 17130 synchronized (mLastStatus) { 17131 mLastStatus.put(moveId, status); 17132 } 17133 } 17134 } 17135 17136 private final class OnPermissionChangeListeners extends Handler { 17137 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 17138 17139 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 17140 new RemoteCallbackList<>(); 17141 17142 public OnPermissionChangeListeners(Looper looper) { 17143 super(looper); 17144 } 17145 17146 @Override 17147 public void handleMessage(Message msg) { 17148 switch (msg.what) { 17149 case MSG_ON_PERMISSIONS_CHANGED: { 17150 final int uid = msg.arg1; 17151 handleOnPermissionsChanged(uid); 17152 } break; 17153 } 17154 } 17155 17156 public void addListenerLocked(IOnPermissionsChangeListener listener) { 17157 mPermissionListeners.register(listener); 17158 17159 } 17160 17161 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 17162 mPermissionListeners.unregister(listener); 17163 } 17164 17165 public void onPermissionsChanged(int uid) { 17166 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 17167 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 17168 } 17169 } 17170 17171 private void handleOnPermissionsChanged(int uid) { 17172 final int count = mPermissionListeners.beginBroadcast(); 17173 try { 17174 for (int i = 0; i < count; i++) { 17175 IOnPermissionsChangeListener callback = mPermissionListeners 17176 .getBroadcastItem(i); 17177 try { 17178 callback.onPermissionsChanged(uid); 17179 } catch (RemoteException e) { 17180 Log.e(TAG, "Permission listener is dead", e); 17181 } 17182 } 17183 } finally { 17184 mPermissionListeners.finishBroadcast(); 17185 } 17186 } 17187 } 17188 17189 private class PackageManagerInternalImpl extends PackageManagerInternal { 17190 @Override 17191 public void setLocationPackagesProvider(PackagesProvider provider) { 17192 synchronized (mPackages) { 17193 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 17194 } 17195 } 17196 17197 @Override 17198 public void setImePackagesProvider(PackagesProvider provider) { 17199 synchronized (mPackages) { 17200 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 17201 } 17202 } 17203 17204 @Override 17205 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 17206 synchronized (mPackages) { 17207 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 17208 } 17209 } 17210 17211 @Override 17212 public void setSmsAppPackagesProvider(PackagesProvider provider) { 17213 synchronized (mPackages) { 17214 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 17215 } 17216 } 17217 17218 @Override 17219 public void setDialerAppPackagesProvider(PackagesProvider provider) { 17220 synchronized (mPackages) { 17221 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 17222 } 17223 } 17224 17225 @Override 17226 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 17227 synchronized (mPackages) { 17228 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 17229 } 17230 } 17231 17232 @Override 17233 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 17234 synchronized (mPackages) { 17235 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 17236 } 17237 } 17238 17239 @Override 17240 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 17241 synchronized (mPackages) { 17242 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 17243 packageName, userId); 17244 } 17245 } 17246 17247 @Override 17248 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 17249 synchronized (mPackages) { 17250 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 17251 packageName, userId); 17252 } 17253 } 17254 17255 @Override 17256 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 17257 synchronized (mPackages) { 17258 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 17259 packageName, userId); 17260 } 17261 } 17262 17263 @Override 17264 public void setKeepUninstalledPackages(final List<String> packageList) { 17265 Preconditions.checkNotNull(packageList); 17266 List<String> removedFromList = null; 17267 synchronized (mPackages) { 17268 if (mKeepUninstalledPackages != null) { 17269 final int packagesCount = mKeepUninstalledPackages.size(); 17270 for (int i = 0; i < packagesCount; i++) { 17271 String oldPackage = mKeepUninstalledPackages.get(i); 17272 if (packageList != null && packageList.contains(oldPackage)) { 17273 continue; 17274 } 17275 if (removedFromList == null) { 17276 removedFromList = new ArrayList<>(); 17277 } 17278 removedFromList.add(oldPackage); 17279 } 17280 } 17281 mKeepUninstalledPackages = new ArrayList<>(packageList); 17282 if (removedFromList != null) { 17283 final int removedCount = removedFromList.size(); 17284 for (int i = 0; i < removedCount; i++) { 17285 deletePackageIfUnusedLPr(removedFromList.get(i)); 17286 } 17287 } 17288 } 17289 } 17290 17291 @Override 17292 public boolean isPermissionsReviewRequired(String packageName, int userId) { 17293 synchronized (mPackages) { 17294 // If we do not support permission review, done. 17295 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 17296 return false; 17297 } 17298 17299 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 17300 if (packageSetting == null) { 17301 return false; 17302 } 17303 17304 // Permission review applies only to apps not supporting the new permission model. 17305 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 17306 return false; 17307 } 17308 17309 // Legacy apps have the permission and get user consent on launch. 17310 PermissionsState permissionsState = packageSetting.getPermissionsState(); 17311 return permissionsState.isPermissionReviewRequired(userId); 17312 } 17313 } 17314 } 17315 17316 @Override 17317 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 17318 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 17319 synchronized (mPackages) { 17320 final long identity = Binder.clearCallingIdentity(); 17321 try { 17322 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 17323 packageNames, userId); 17324 } finally { 17325 Binder.restoreCallingIdentity(identity); 17326 } 17327 } 17328 } 17329 17330 private static void enforceSystemOrPhoneCaller(String tag) { 17331 int callingUid = Binder.getCallingUid(); 17332 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 17333 throw new SecurityException( 17334 "Cannot call " + tag + " from UID " + callingUid); 17335 } 17336 } 17337} 17338