PackageManagerService.java revision c72b3101ee368d2a9943e4436ede679acfa38f92
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 21import static android.Manifest.permission.WRITE_MEDIA_STORAGE; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 27import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 28import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 29import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 31import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 32import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 34import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 35import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 36import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 37import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 40import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 41import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 42import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 43import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 45import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 46import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 47import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 48import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 49import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 50import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED; 51import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 52import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 53import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 54import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 55import static android.content.pm.PackageManager.INSTALL_INTERNAL; 56import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 62import static android.content.pm.PackageManager.MATCH_ALL; 63import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 64import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 65import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 66import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 67import static android.content.pm.PackageManager.PERMISSION_DENIED; 68import static android.content.pm.PackageManager.PERMISSION_GRANTED; 69import static android.content.pm.PackageParser.isApkFile; 70import static android.os.Process.PACKAGE_INFO_GID; 71import static android.os.Process.SYSTEM_UID; 72import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 73import static android.system.OsConstants.O_CREAT; 74import static android.system.OsConstants.O_RDWR; 75import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 76import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 77import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 78import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 79import static com.android.internal.util.ArrayUtils.appendInt; 80import static com.android.server.pm.Installer.DEXOPT_PUBLIC; 81import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 82import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 83import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 84import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 85import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 86import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 87import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 88import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 89 90import android.Manifest; 91import android.app.ActivityManager; 92import android.app.ActivityManagerNative; 93import android.app.AppGlobals; 94import android.app.IActivityManager; 95import android.app.admin.IDevicePolicyManager; 96import android.app.backup.IBackupManager; 97import android.app.usage.UsageStats; 98import android.app.usage.UsageStatsManager; 99import android.content.BroadcastReceiver; 100import android.content.ComponentName; 101import android.content.Context; 102import android.content.IIntentReceiver; 103import android.content.Intent; 104import android.content.IntentFilter; 105import android.content.IntentSender; 106import android.content.IntentSender.SendIntentException; 107import android.content.ServiceConnection; 108import android.content.pm.ActivityInfo; 109import android.content.pm.ApplicationInfo; 110import android.content.pm.AppsQueryHelper; 111import android.content.pm.FeatureInfo; 112import android.content.pm.IOnPermissionsChangeListener; 113import android.content.pm.IPackageDataObserver; 114import android.content.pm.IPackageDeleteObserver; 115import android.content.pm.IPackageDeleteObserver2; 116import android.content.pm.IPackageInstallObserver2; 117import android.content.pm.IPackageInstaller; 118import android.content.pm.IPackageManager; 119import android.content.pm.IPackageMoveObserver; 120import android.content.pm.IPackageStatsObserver; 121import android.content.pm.InstrumentationInfo; 122import android.content.pm.IntentFilterVerificationInfo; 123import android.content.pm.KeySet; 124import android.content.pm.ManifestDigest; 125import android.content.pm.PackageCleanItem; 126import android.content.pm.PackageInfo; 127import android.content.pm.PackageInfoLite; 128import android.content.pm.PackageInstaller; 129import android.content.pm.PackageManager; 130import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 131import android.content.pm.PackageManagerInternal; 132import android.content.pm.PackageParser; 133import android.content.pm.PackageParser.ActivityIntentInfo; 134import android.content.pm.PackageParser.PackageLite; 135import android.content.pm.PackageParser.PackageParserException; 136import android.content.pm.PackageStats; 137import android.content.pm.PackageUserState; 138import android.content.pm.ParceledListSlice; 139import android.content.pm.PermissionGroupInfo; 140import android.content.pm.PermissionInfo; 141import android.content.pm.ProviderInfo; 142import android.content.pm.ResolveInfo; 143import android.content.pm.ServiceInfo; 144import android.content.pm.Signature; 145import android.content.pm.UserInfo; 146import android.content.pm.VerificationParams; 147import android.content.pm.VerifierDeviceIdentity; 148import android.content.pm.VerifierInfo; 149import android.content.res.Resources; 150import android.hardware.display.DisplayManager; 151import android.net.Uri; 152import android.os.Debug; 153import android.os.Binder; 154import android.os.Build; 155import android.os.Bundle; 156import android.os.Environment; 157import android.os.Environment.UserEnvironment; 158import android.os.FileUtils; 159import android.os.Handler; 160import android.os.IBinder; 161import android.os.Looper; 162import android.os.Message; 163import android.os.Parcel; 164import android.os.ParcelFileDescriptor; 165import android.os.Process; 166import android.os.RemoteCallbackList; 167import android.os.RemoteException; 168import android.os.ResultReceiver; 169import android.os.SELinux; 170import android.os.ServiceManager; 171import android.os.SystemClock; 172import android.os.SystemProperties; 173import android.os.Trace; 174import android.os.UserHandle; 175import android.os.UserManager; 176import android.os.storage.IMountService; 177import android.os.storage.MountServiceInternal; 178import android.os.storage.StorageEventListener; 179import android.os.storage.StorageManager; 180import android.os.storage.VolumeInfo; 181import android.os.storage.VolumeRecord; 182import android.security.KeyStore; 183import android.security.SystemKeyStore; 184import android.system.ErrnoException; 185import android.system.Os; 186import android.system.StructStat; 187import android.text.TextUtils; 188import android.text.format.DateUtils; 189import android.util.ArrayMap; 190import android.util.ArraySet; 191import android.util.AtomicFile; 192import android.util.DisplayMetrics; 193import android.util.EventLog; 194import android.util.ExceptionUtils; 195import android.util.Log; 196import android.util.LogPrinter; 197import android.util.MathUtils; 198import android.util.PrintStreamPrinter; 199import android.util.Slog; 200import android.util.SparseArray; 201import android.util.SparseBooleanArray; 202import android.util.SparseIntArray; 203import android.util.Xml; 204import android.view.Display; 205 206import dalvik.system.DexFile; 207import dalvik.system.VMRuntime; 208 209import libcore.io.IoUtils; 210import libcore.util.EmptyArray; 211 212import com.android.internal.R; 213import com.android.internal.annotations.GuardedBy; 214import com.android.internal.app.EphemeralResolveInfo; 215import com.android.internal.app.IMediaContainerService; 216import com.android.internal.app.ResolverActivity; 217import com.android.internal.content.NativeLibraryHelper; 218import com.android.internal.content.PackageHelper; 219import com.android.internal.os.IParcelFileDescriptorFactory; 220import com.android.internal.os.SomeArgs; 221import com.android.internal.os.Zygote; 222import com.android.internal.util.ArrayUtils; 223import com.android.internal.util.FastPrintWriter; 224import com.android.internal.util.FastXmlSerializer; 225import com.android.internal.util.IndentingPrintWriter; 226import com.android.internal.util.Preconditions; 227import com.android.server.EventLogTags; 228import com.android.server.FgThread; 229import com.android.server.IntentResolver; 230import com.android.server.LocalServices; 231import com.android.server.ServiceThread; 232import com.android.server.SystemConfig; 233import com.android.server.Watchdog; 234import com.android.server.pm.PermissionsState.PermissionState; 235import com.android.server.pm.Settings.DatabaseVersion; 236import com.android.server.pm.Settings.VersionInfo; 237import com.android.server.storage.DeviceStorageMonitorInternal; 238 239import org.xmlpull.v1.XmlPullParser; 240import org.xmlpull.v1.XmlPullParserException; 241import org.xmlpull.v1.XmlSerializer; 242 243import java.io.BufferedInputStream; 244import java.io.BufferedOutputStream; 245import java.io.BufferedReader; 246import java.io.ByteArrayInputStream; 247import java.io.ByteArrayOutputStream; 248import java.io.File; 249import java.io.FileDescriptor; 250import java.io.FileNotFoundException; 251import java.io.FileOutputStream; 252import java.io.FileReader; 253import java.io.FilenameFilter; 254import java.io.IOException; 255import java.io.InputStream; 256import java.io.PrintWriter; 257import java.nio.charset.StandardCharsets; 258import java.security.MessageDigest; 259import java.security.NoSuchAlgorithmException; 260import java.security.PublicKey; 261import java.security.cert.CertificateEncodingException; 262import java.security.cert.CertificateException; 263import java.text.SimpleDateFormat; 264import java.util.ArrayList; 265import java.util.Arrays; 266import java.util.Collection; 267import java.util.Collections; 268import java.util.Comparator; 269import java.util.Date; 270import java.util.Iterator; 271import java.util.List; 272import java.util.Map; 273import java.util.Objects; 274import java.util.Set; 275import java.util.concurrent.CountDownLatch; 276import java.util.concurrent.TimeUnit; 277import java.util.concurrent.atomic.AtomicBoolean; 278import java.util.concurrent.atomic.AtomicInteger; 279import java.util.concurrent.atomic.AtomicLong; 280 281/** 282 * Keep track of all those .apks everywhere. 283 * 284 * This is very central to the platform's security; please run the unit 285 * tests whenever making modifications here: 286 * 287runtest -c android.content.pm.PackageManagerTests frameworks-core 288 * 289 * {@hide} 290 */ 291public class PackageManagerService extends IPackageManager.Stub { 292 static final String TAG = "PackageManager"; 293 static final boolean DEBUG_SETTINGS = false; 294 static final boolean DEBUG_PREFERRED = false; 295 static final boolean DEBUG_UPGRADE = false; 296 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 297 private static final boolean DEBUG_BACKUP = false; 298 private static final boolean DEBUG_INSTALL = false; 299 private static final boolean DEBUG_REMOVE = false; 300 private static final boolean DEBUG_BROADCASTS = false; 301 private static final boolean DEBUG_SHOW_INFO = false; 302 private static final boolean DEBUG_PACKAGE_INFO = false; 303 private static final boolean DEBUG_INTENT_MATCHING = false; 304 private static final boolean DEBUG_PACKAGE_SCANNING = false; 305 private static final boolean DEBUG_VERIFY = false; 306 private static final boolean DEBUG_DEXOPT = false; 307 private static final boolean DEBUG_ABI_SELECTION = false; 308 private static final boolean DEBUG_EPHEMERAL = false; 309 310 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 311 312 private static final int RADIO_UID = Process.PHONE_UID; 313 private static final int LOG_UID = Process.LOG_UID; 314 private static final int NFC_UID = Process.NFC_UID; 315 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 316 private static final int SHELL_UID = Process.SHELL_UID; 317 318 // Cap the size of permission trees that 3rd party apps can define 319 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 320 321 // Suffix used during package installation when copying/moving 322 // package apks to install directory. 323 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 324 325 static final int SCAN_NO_DEX = 1<<1; 326 static final int SCAN_FORCE_DEX = 1<<2; 327 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 328 static final int SCAN_NEW_INSTALL = 1<<4; 329 static final int SCAN_NO_PATHS = 1<<5; 330 static final int SCAN_UPDATE_TIME = 1<<6; 331 static final int SCAN_DEFER_DEX = 1<<7; 332 static final int SCAN_BOOTING = 1<<8; 333 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 334 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 335 static final int SCAN_REPLACING = 1<<11; 336 static final int SCAN_REQUIRE_KNOWN = 1<<12; 337 static final int SCAN_MOVE = 1<<13; 338 static final int SCAN_INITIAL = 1<<14; 339 340 static final int REMOVE_CHATTY = 1<<16; 341 342 private static final int[] EMPTY_INT_ARRAY = new int[0]; 343 344 /** 345 * Timeout (in milliseconds) after which the watchdog should declare that 346 * our handler thread is wedged. The usual default for such things is one 347 * minute but we sometimes do very lengthy I/O operations on this thread, 348 * such as installing multi-gigabyte applications, so ours needs to be longer. 349 */ 350 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 351 352 /** 353 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 354 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 355 * settings entry if available, otherwise we use the hardcoded default. If it's been 356 * more than this long since the last fstrim, we force one during the boot sequence. 357 * 358 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 359 * one gets run at the next available charging+idle time. This final mandatory 360 * no-fstrim check kicks in only of the other scheduling criteria is never met. 361 */ 362 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 363 364 /** 365 * Whether verification is enabled by default. 366 */ 367 private static final boolean DEFAULT_VERIFY_ENABLE = true; 368 369 /** 370 * The default maximum time to wait for the verification agent to return in 371 * milliseconds. 372 */ 373 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 374 375 /** 376 * The default response for package verification timeout. 377 * 378 * This can be either PackageManager.VERIFICATION_ALLOW or 379 * PackageManager.VERIFICATION_REJECT. 380 */ 381 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 382 383 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 384 385 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 386 DEFAULT_CONTAINER_PACKAGE, 387 "com.android.defcontainer.DefaultContainerService"); 388 389 private static final String KILL_APP_REASON_GIDS_CHANGED = 390 "permission grant or revoke changed gids"; 391 392 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 393 "permissions revoked"; 394 395 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 396 397 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 398 399 /** Permission grant: not grant the permission. */ 400 private static final int GRANT_DENIED = 1; 401 402 /** Permission grant: grant the permission as an install permission. */ 403 private static final int GRANT_INSTALL = 2; 404 405 /** Permission grant: grant the permission as a runtime one. */ 406 private static final int GRANT_RUNTIME = 3; 407 408 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 409 private static final int GRANT_UPGRADE = 4; 410 411 /** Canonical intent used to identify what counts as a "web browser" app */ 412 private static final Intent sBrowserIntent; 413 static { 414 sBrowserIntent = new Intent(); 415 sBrowserIntent.setAction(Intent.ACTION_VIEW); 416 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 417 sBrowserIntent.setData(Uri.parse("http:")); 418 } 419 420 final ServiceThread mHandlerThread; 421 422 final PackageHandler mHandler; 423 424 /** 425 * Messages for {@link #mHandler} that need to wait for system ready before 426 * being dispatched. 427 */ 428 private ArrayList<Message> mPostSystemReadyMessages; 429 430 final int mSdkVersion = Build.VERSION.SDK_INT; 431 432 final Context mContext; 433 final boolean mFactoryTest; 434 final boolean mOnlyCore; 435 final DisplayMetrics mMetrics; 436 final int mDefParseFlags; 437 final String[] mSeparateProcesses; 438 final boolean mIsUpgrade; 439 440 // This is where all application persistent data goes. 441 final File mAppDataDir; 442 443 // This is where all application persistent data goes for secondary users. 444 final File mUserAppDataDir; 445 446 /** The location for ASEC container files on internal storage. */ 447 final String mAsecInternalPath; 448 449 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 450 // LOCK HELD. Can be called with mInstallLock held. 451 @GuardedBy("mInstallLock") 452 final Installer mInstaller; 453 454 /** Directory where installed third-party apps stored */ 455 final File mAppInstallDir; 456 final File mEphemeralInstallDir; 457 458 /** 459 * Directory to which applications installed internally have their 460 * 32 bit native libraries copied. 461 */ 462 private File mAppLib32InstallDir; 463 464 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 465 // apps. 466 final File mDrmAppPrivateInstallDir; 467 468 // ---------------------------------------------------------------- 469 470 // Lock for state used when installing and doing other long running 471 // operations. Methods that must be called with this lock held have 472 // the suffix "LI". 473 final Object mInstallLock = new Object(); 474 475 // ---------------------------------------------------------------- 476 477 // Keys are String (package name), values are Package. This also serves 478 // as the lock for the global state. Methods that must be called with 479 // this lock held have the prefix "LP". 480 @GuardedBy("mPackages") 481 final ArrayMap<String, PackageParser.Package> mPackages = 482 new ArrayMap<String, PackageParser.Package>(); 483 484 // Tracks available target package names -> overlay package paths. 485 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 486 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 487 488 /** 489 * Tracks new system packages [received in an OTA] that we expect to 490 * find updated user-installed versions. Keys are package name, values 491 * are package location. 492 */ 493 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 494 495 /** 496 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 497 */ 498 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 499 /** 500 * Whether or not system app permissions should be promoted from install to runtime. 501 */ 502 boolean mPromoteSystemApps; 503 504 final Settings mSettings; 505 boolean mRestoredSettings; 506 507 // System configuration read by SystemConfig. 508 final int[] mGlobalGids; 509 final SparseArray<ArraySet<String>> mSystemPermissions; 510 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 511 512 // If mac_permissions.xml was found for seinfo labeling. 513 boolean mFoundPolicyFile; 514 515 // If a recursive restorecon of /data/data/<pkg> is needed. 516 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 517 518 public static final class SharedLibraryEntry { 519 public final String path; 520 public final String apk; 521 522 SharedLibraryEntry(String _path, String _apk) { 523 path = _path; 524 apk = _apk; 525 } 526 } 527 528 // Currently known shared libraries. 529 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 530 new ArrayMap<String, SharedLibraryEntry>(); 531 532 // All available activities, for your resolving pleasure. 533 final ActivityIntentResolver mActivities = 534 new ActivityIntentResolver(); 535 536 // All available receivers, for your resolving pleasure. 537 final ActivityIntentResolver mReceivers = 538 new ActivityIntentResolver(); 539 540 // All available services, for your resolving pleasure. 541 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 542 543 // All available providers, for your resolving pleasure. 544 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 545 546 // Mapping from provider base names (first directory in content URI codePath) 547 // to the provider information. 548 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 549 new ArrayMap<String, PackageParser.Provider>(); 550 551 // Mapping from instrumentation class names to info about them. 552 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 553 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 554 555 // Mapping from permission names to info about them. 556 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 557 new ArrayMap<String, PackageParser.PermissionGroup>(); 558 559 // Packages whose data we have transfered into another package, thus 560 // should no longer exist. 561 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 562 563 // Broadcast actions that are only available to the system. 564 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 565 566 /** List of packages waiting for verification. */ 567 final SparseArray<PackageVerificationState> mPendingVerification 568 = new SparseArray<PackageVerificationState>(); 569 570 /** Set of packages associated with each app op permission. */ 571 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 572 573 final PackageInstallerService mInstallerService; 574 575 private final PackageDexOptimizer mPackageDexOptimizer; 576 577 private AtomicInteger mNextMoveId = new AtomicInteger(); 578 private final MoveCallbacks mMoveCallbacks; 579 580 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 581 582 // Cache of users who need badging. 583 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 584 585 /** Token for keys in mPendingVerification. */ 586 private int mPendingVerificationToken = 0; 587 588 volatile boolean mSystemReady; 589 volatile boolean mSafeMode; 590 volatile boolean mHasSystemUidErrors; 591 592 ApplicationInfo mAndroidApplication; 593 final ActivityInfo mResolveActivity = new ActivityInfo(); 594 final ResolveInfo mResolveInfo = new ResolveInfo(); 595 ComponentName mResolveComponentName; 596 PackageParser.Package mPlatformPackage; 597 ComponentName mCustomResolverComponentName; 598 599 boolean mResolverReplaced = false; 600 601 private final ComponentName mIntentFilterVerifierComponent; 602 private int mIntentFilterVerificationToken = 0; 603 604 /** Component that knows whether or not an ephemeral application exists */ 605 final ComponentName mEphemeralResolverComponent; 606 /** The service connection to the ephemeral resolver */ 607 final EphemeralResolverConnection mEphemeralResolverConnection; 608 609 /** Component used to install ephemeral applications */ 610 final ComponentName mEphemeralInstallerComponent; 611 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 612 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 613 614 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 615 = new SparseArray<IntentFilterVerificationState>(); 616 617 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 618 new DefaultPermissionGrantPolicy(this); 619 620 // List of packages names to keep cached, even if they are uninstalled for all users 621 private List<String> mKeepUninstalledPackages; 622 623 private static class IFVerificationParams { 624 PackageParser.Package pkg; 625 boolean replacing; 626 int userId; 627 int verifierUid; 628 629 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 630 int _userId, int _verifierUid) { 631 pkg = _pkg; 632 replacing = _replacing; 633 userId = _userId; 634 replacing = _replacing; 635 verifierUid = _verifierUid; 636 } 637 } 638 639 private interface IntentFilterVerifier<T extends IntentFilter> { 640 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 641 T filter, String packageName); 642 void startVerifications(int userId); 643 void receiveVerificationResponse(int verificationId); 644 } 645 646 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 647 private Context mContext; 648 private ComponentName mIntentFilterVerifierComponent; 649 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 650 651 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 652 mContext = context; 653 mIntentFilterVerifierComponent = verifierComponent; 654 } 655 656 private String getDefaultScheme() { 657 return IntentFilter.SCHEME_HTTPS; 658 } 659 660 @Override 661 public void startVerifications(int userId) { 662 // Launch verifications requests 663 int count = mCurrentIntentFilterVerifications.size(); 664 for (int n=0; n<count; n++) { 665 int verificationId = mCurrentIntentFilterVerifications.get(n); 666 final IntentFilterVerificationState ivs = 667 mIntentFilterVerificationStates.get(verificationId); 668 669 String packageName = ivs.getPackageName(); 670 671 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 672 final int filterCount = filters.size(); 673 ArraySet<String> domainsSet = new ArraySet<>(); 674 for (int m=0; m<filterCount; m++) { 675 PackageParser.ActivityIntentInfo filter = filters.get(m); 676 domainsSet.addAll(filter.getHostsList()); 677 } 678 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 679 synchronized (mPackages) { 680 if (mSettings.createIntentFilterVerificationIfNeededLPw( 681 packageName, domainsList) != null) { 682 scheduleWriteSettingsLocked(); 683 } 684 } 685 sendVerificationRequest(userId, verificationId, ivs); 686 } 687 mCurrentIntentFilterVerifications.clear(); 688 } 689 690 private void sendVerificationRequest(int userId, int verificationId, 691 IntentFilterVerificationState ivs) { 692 693 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 694 verificationIntent.putExtra( 695 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 696 verificationId); 697 verificationIntent.putExtra( 698 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 699 getDefaultScheme()); 700 verificationIntent.putExtra( 701 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 702 ivs.getHostsString()); 703 verificationIntent.putExtra( 704 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 705 ivs.getPackageName()); 706 verificationIntent.setComponent(mIntentFilterVerifierComponent); 707 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 708 709 UserHandle user = new UserHandle(userId); 710 mContext.sendBroadcastAsUser(verificationIntent, user); 711 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 712 "Sending IntentFilter verification broadcast"); 713 } 714 715 public void receiveVerificationResponse(int verificationId) { 716 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 717 718 final boolean verified = ivs.isVerified(); 719 720 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 721 final int count = filters.size(); 722 if (DEBUG_DOMAIN_VERIFICATION) { 723 Slog.i(TAG, "Received verification response " + verificationId 724 + " for " + count + " filters, verified=" + verified); 725 } 726 for (int n=0; n<count; n++) { 727 PackageParser.ActivityIntentInfo filter = filters.get(n); 728 filter.setVerified(verified); 729 730 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 731 + " verified with result:" + verified + " and hosts:" 732 + ivs.getHostsString()); 733 } 734 735 mIntentFilterVerificationStates.remove(verificationId); 736 737 final String packageName = ivs.getPackageName(); 738 IntentFilterVerificationInfo ivi = null; 739 740 synchronized (mPackages) { 741 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 742 } 743 if (ivi == null) { 744 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 745 + verificationId + " packageName:" + packageName); 746 return; 747 } 748 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 749 "Updating IntentFilterVerificationInfo for package " + packageName 750 +" verificationId:" + verificationId); 751 752 synchronized (mPackages) { 753 if (verified) { 754 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 755 } else { 756 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 757 } 758 scheduleWriteSettingsLocked(); 759 760 final int userId = ivs.getUserId(); 761 if (userId != UserHandle.USER_ALL) { 762 final int userStatus = 763 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 764 765 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 766 boolean needUpdate = false; 767 768 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 769 // already been set by the User thru the Disambiguation dialog 770 switch (userStatus) { 771 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 772 if (verified) { 773 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 774 } else { 775 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 776 } 777 needUpdate = true; 778 break; 779 780 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 781 if (verified) { 782 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 783 needUpdate = true; 784 } 785 break; 786 787 default: 788 // Nothing to do 789 } 790 791 if (needUpdate) { 792 mSettings.updateIntentFilterVerificationStatusLPw( 793 packageName, updatedStatus, userId); 794 scheduleWritePackageRestrictionsLocked(userId); 795 } 796 } 797 } 798 } 799 800 @Override 801 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 802 ActivityIntentInfo filter, String packageName) { 803 if (!hasValidDomains(filter)) { 804 return false; 805 } 806 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 807 if (ivs == null) { 808 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 809 packageName); 810 } 811 if (DEBUG_DOMAIN_VERIFICATION) { 812 Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter); 813 } 814 ivs.addFilter(filter); 815 return true; 816 } 817 818 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 819 int userId, int verificationId, String packageName) { 820 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 821 verifierUid, userId, packageName); 822 ivs.setPendingState(); 823 synchronized (mPackages) { 824 mIntentFilterVerificationStates.append(verificationId, ivs); 825 mCurrentIntentFilterVerifications.add(verificationId); 826 } 827 return ivs; 828 } 829 } 830 831 private static boolean hasValidDomains(ActivityIntentInfo filter) { 832 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 833 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 834 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 835 } 836 837 private IntentFilterVerifier mIntentFilterVerifier; 838 839 // Set of pending broadcasts for aggregating enable/disable of components. 840 static class PendingPackageBroadcasts { 841 // for each user id, a map of <package name -> components within that package> 842 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 843 844 public PendingPackageBroadcasts() { 845 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 846 } 847 848 public ArrayList<String> get(int userId, String packageName) { 849 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 850 return packages.get(packageName); 851 } 852 853 public void put(int userId, String packageName, ArrayList<String> components) { 854 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 855 packages.put(packageName, components); 856 } 857 858 public void remove(int userId, String packageName) { 859 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 860 if (packages != null) { 861 packages.remove(packageName); 862 } 863 } 864 865 public void remove(int userId) { 866 mUidMap.remove(userId); 867 } 868 869 public int userIdCount() { 870 return mUidMap.size(); 871 } 872 873 public int userIdAt(int n) { 874 return mUidMap.keyAt(n); 875 } 876 877 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 878 return mUidMap.get(userId); 879 } 880 881 public int size() { 882 // total number of pending broadcast entries across all userIds 883 int num = 0; 884 for (int i = 0; i< mUidMap.size(); i++) { 885 num += mUidMap.valueAt(i).size(); 886 } 887 return num; 888 } 889 890 public void clear() { 891 mUidMap.clear(); 892 } 893 894 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 895 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 896 if (map == null) { 897 map = new ArrayMap<String, ArrayList<String>>(); 898 mUidMap.put(userId, map); 899 } 900 return map; 901 } 902 } 903 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 904 905 // Service Connection to remote media container service to copy 906 // package uri's from external media onto secure containers 907 // or internal storage. 908 private IMediaContainerService mContainerService = null; 909 910 static final int SEND_PENDING_BROADCAST = 1; 911 static final int MCS_BOUND = 3; 912 static final int END_COPY = 4; 913 static final int INIT_COPY = 5; 914 static final int MCS_UNBIND = 6; 915 static final int START_CLEANING_PACKAGE = 7; 916 static final int FIND_INSTALL_LOC = 8; 917 static final int POST_INSTALL = 9; 918 static final int MCS_RECONNECT = 10; 919 static final int MCS_GIVE_UP = 11; 920 static final int UPDATED_MEDIA_STATUS = 12; 921 static final int WRITE_SETTINGS = 13; 922 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 923 static final int PACKAGE_VERIFIED = 15; 924 static final int CHECK_PENDING_VERIFICATION = 16; 925 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 926 static final int INTENT_FILTER_VERIFIED = 18; 927 928 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 929 930 // Delay time in millisecs 931 static final int BROADCAST_DELAY = 10 * 1000; 932 933 static UserManagerService sUserManager; 934 935 // Stores a list of users whose package restrictions file needs to be updated 936 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 937 938 final private DefaultContainerConnection mDefContainerConn = 939 new DefaultContainerConnection(); 940 class DefaultContainerConnection implements ServiceConnection { 941 public void onServiceConnected(ComponentName name, IBinder service) { 942 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 943 IMediaContainerService imcs = 944 IMediaContainerService.Stub.asInterface(service); 945 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 946 } 947 948 public void onServiceDisconnected(ComponentName name) { 949 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 950 } 951 } 952 953 // Recordkeeping of restore-after-install operations that are currently in flight 954 // between the Package Manager and the Backup Manager 955 class PostInstallData { 956 public InstallArgs args; 957 public PackageInstalledInfo res; 958 959 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 960 args = _a; 961 res = _r; 962 } 963 } 964 965 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 966 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 967 968 // XML tags for backup/restore of various bits of state 969 private static final String TAG_PREFERRED_BACKUP = "pa"; 970 private static final String TAG_DEFAULT_APPS = "da"; 971 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 972 973 final String mRequiredVerifierPackage; 974 final String mRequiredInstallerPackage; 975 976 private final PackageUsage mPackageUsage = new PackageUsage(); 977 978 private class PackageUsage { 979 private static final int WRITE_INTERVAL 980 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 981 982 private final Object mFileLock = new Object(); 983 private final AtomicLong mLastWritten = new AtomicLong(0); 984 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 985 986 private boolean mIsHistoricalPackageUsageAvailable = true; 987 988 boolean isHistoricalPackageUsageAvailable() { 989 return mIsHistoricalPackageUsageAvailable; 990 } 991 992 void write(boolean force) { 993 if (force) { 994 writeInternal(); 995 return; 996 } 997 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 998 && !DEBUG_DEXOPT) { 999 return; 1000 } 1001 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 1002 new Thread("PackageUsage_DiskWriter") { 1003 @Override 1004 public void run() { 1005 try { 1006 writeInternal(); 1007 } finally { 1008 mBackgroundWriteRunning.set(false); 1009 } 1010 } 1011 }.start(); 1012 } 1013 } 1014 1015 private void writeInternal() { 1016 synchronized (mPackages) { 1017 synchronized (mFileLock) { 1018 AtomicFile file = getFile(); 1019 FileOutputStream f = null; 1020 try { 1021 f = file.startWrite(); 1022 BufferedOutputStream out = new BufferedOutputStream(f); 1023 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1024 StringBuilder sb = new StringBuilder(); 1025 for (PackageParser.Package pkg : mPackages.values()) { 1026 if (pkg.mLastPackageUsageTimeInMills == 0) { 1027 continue; 1028 } 1029 sb.setLength(0); 1030 sb.append(pkg.packageName); 1031 sb.append(' '); 1032 sb.append((long)pkg.mLastPackageUsageTimeInMills); 1033 sb.append('\n'); 1034 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1035 } 1036 out.flush(); 1037 file.finishWrite(f); 1038 } catch (IOException e) { 1039 if (f != null) { 1040 file.failWrite(f); 1041 } 1042 Log.e(TAG, "Failed to write package usage times", e); 1043 } 1044 } 1045 } 1046 mLastWritten.set(SystemClock.elapsedRealtime()); 1047 } 1048 1049 void readLP() { 1050 synchronized (mFileLock) { 1051 AtomicFile file = getFile(); 1052 BufferedInputStream in = null; 1053 try { 1054 in = new BufferedInputStream(file.openRead()); 1055 StringBuffer sb = new StringBuffer(); 1056 while (true) { 1057 String packageName = readToken(in, sb, ' '); 1058 if (packageName == null) { 1059 break; 1060 } 1061 String timeInMillisString = readToken(in, sb, '\n'); 1062 if (timeInMillisString == null) { 1063 throw new IOException("Failed to find last usage time for package " 1064 + packageName); 1065 } 1066 PackageParser.Package pkg = mPackages.get(packageName); 1067 if (pkg == null) { 1068 continue; 1069 } 1070 long timeInMillis; 1071 try { 1072 timeInMillis = Long.parseLong(timeInMillisString.toString()); 1073 } catch (NumberFormatException e) { 1074 throw new IOException("Failed to parse " + timeInMillisString 1075 + " as a long.", e); 1076 } 1077 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1078 } 1079 } catch (FileNotFoundException expected) { 1080 mIsHistoricalPackageUsageAvailable = false; 1081 } catch (IOException e) { 1082 Log.w(TAG, "Failed to read package usage times", e); 1083 } finally { 1084 IoUtils.closeQuietly(in); 1085 } 1086 } 1087 mLastWritten.set(SystemClock.elapsedRealtime()); 1088 } 1089 1090 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1091 throws IOException { 1092 sb.setLength(0); 1093 while (true) { 1094 int ch = in.read(); 1095 if (ch == -1) { 1096 if (sb.length() == 0) { 1097 return null; 1098 } 1099 throw new IOException("Unexpected EOF"); 1100 } 1101 if (ch == endOfToken) { 1102 return sb.toString(); 1103 } 1104 sb.append((char)ch); 1105 } 1106 } 1107 1108 private AtomicFile getFile() { 1109 File dataDir = Environment.getDataDirectory(); 1110 File systemDir = new File(dataDir, "system"); 1111 File fname = new File(systemDir, "package-usage.list"); 1112 return new AtomicFile(fname); 1113 } 1114 } 1115 1116 class PackageHandler extends Handler { 1117 private boolean mBound = false; 1118 final ArrayList<HandlerParams> mPendingInstalls = 1119 new ArrayList<HandlerParams>(); 1120 1121 private boolean connectToService() { 1122 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1123 " DefaultContainerService"); 1124 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1125 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1126 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1127 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1128 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1129 mBound = true; 1130 return true; 1131 } 1132 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1133 return false; 1134 } 1135 1136 private void disconnectService() { 1137 mContainerService = null; 1138 mBound = false; 1139 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1140 mContext.unbindService(mDefContainerConn); 1141 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1142 } 1143 1144 PackageHandler(Looper looper) { 1145 super(looper); 1146 } 1147 1148 public void handleMessage(Message msg) { 1149 try { 1150 doHandleMessage(msg); 1151 } finally { 1152 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1153 } 1154 } 1155 1156 void doHandleMessage(Message msg) { 1157 switch (msg.what) { 1158 case INIT_COPY: { 1159 HandlerParams params = (HandlerParams) msg.obj; 1160 int idx = mPendingInstalls.size(); 1161 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1162 // If a bind was already initiated we dont really 1163 // need to do anything. The pending install 1164 // will be processed later on. 1165 if (!mBound) { 1166 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1167 System.identityHashCode(mHandler)); 1168 // If this is the only one pending we might 1169 // have to bind to the service again. 1170 if (!connectToService()) { 1171 Slog.e(TAG, "Failed to bind to media container service"); 1172 params.serviceError(); 1173 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1174 System.identityHashCode(mHandler)); 1175 if (params.traceMethod != null) { 1176 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1177 params.traceCookie); 1178 } 1179 return; 1180 } else { 1181 // Once we bind to the service, the first 1182 // pending request will be processed. 1183 mPendingInstalls.add(idx, params); 1184 } 1185 } else { 1186 mPendingInstalls.add(idx, params); 1187 // Already bound to the service. Just make 1188 // sure we trigger off processing the first request. 1189 if (idx == 0) { 1190 mHandler.sendEmptyMessage(MCS_BOUND); 1191 } 1192 } 1193 break; 1194 } 1195 case MCS_BOUND: { 1196 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1197 if (msg.obj != null) { 1198 mContainerService = (IMediaContainerService) msg.obj; 1199 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1200 System.identityHashCode(mHandler)); 1201 } 1202 if (mContainerService == null) { 1203 if (!mBound) { 1204 // Something seriously wrong since we are not bound and we are not 1205 // waiting for connection. Bail out. 1206 Slog.e(TAG, "Cannot bind to media container service"); 1207 for (HandlerParams params : mPendingInstalls) { 1208 // Indicate service bind error 1209 params.serviceError(); 1210 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1211 System.identityHashCode(params)); 1212 if (params.traceMethod != null) { 1213 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1214 params.traceMethod, params.traceCookie); 1215 } 1216 return; 1217 } 1218 mPendingInstalls.clear(); 1219 } else { 1220 Slog.w(TAG, "Waiting to connect to media container service"); 1221 } 1222 } else if (mPendingInstalls.size() > 0) { 1223 HandlerParams params = mPendingInstalls.get(0); 1224 if (params != null) { 1225 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1226 System.identityHashCode(params)); 1227 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1228 if (params.startCopy()) { 1229 // We are done... look for more work or to 1230 // go idle. 1231 if (DEBUG_SD_INSTALL) Log.i(TAG, 1232 "Checking for more work or unbind..."); 1233 // Delete pending install 1234 if (mPendingInstalls.size() > 0) { 1235 mPendingInstalls.remove(0); 1236 } 1237 if (mPendingInstalls.size() == 0) { 1238 if (mBound) { 1239 if (DEBUG_SD_INSTALL) Log.i(TAG, 1240 "Posting delayed MCS_UNBIND"); 1241 removeMessages(MCS_UNBIND); 1242 Message ubmsg = obtainMessage(MCS_UNBIND); 1243 // Unbind after a little delay, to avoid 1244 // continual thrashing. 1245 sendMessageDelayed(ubmsg, 10000); 1246 } 1247 } else { 1248 // There are more pending requests in queue. 1249 // Just post MCS_BOUND message to trigger processing 1250 // of next pending install. 1251 if (DEBUG_SD_INSTALL) Log.i(TAG, 1252 "Posting MCS_BOUND for next work"); 1253 mHandler.sendEmptyMessage(MCS_BOUND); 1254 } 1255 } 1256 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1257 } 1258 } else { 1259 // Should never happen ideally. 1260 Slog.w(TAG, "Empty queue"); 1261 } 1262 break; 1263 } 1264 case MCS_RECONNECT: { 1265 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1266 if (mPendingInstalls.size() > 0) { 1267 if (mBound) { 1268 disconnectService(); 1269 } 1270 if (!connectToService()) { 1271 Slog.e(TAG, "Failed to bind to media container service"); 1272 for (HandlerParams params : mPendingInstalls) { 1273 // Indicate service bind error 1274 params.serviceError(); 1275 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1276 System.identityHashCode(params)); 1277 } 1278 mPendingInstalls.clear(); 1279 } 1280 } 1281 break; 1282 } 1283 case MCS_UNBIND: { 1284 // If there is no actual work left, then time to unbind. 1285 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1286 1287 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1288 if (mBound) { 1289 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1290 1291 disconnectService(); 1292 } 1293 } else if (mPendingInstalls.size() > 0) { 1294 // There are more pending requests in queue. 1295 // Just post MCS_BOUND message to trigger processing 1296 // of next pending install. 1297 mHandler.sendEmptyMessage(MCS_BOUND); 1298 } 1299 1300 break; 1301 } 1302 case MCS_GIVE_UP: { 1303 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1304 HandlerParams params = mPendingInstalls.remove(0); 1305 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1306 System.identityHashCode(params)); 1307 break; 1308 } 1309 case SEND_PENDING_BROADCAST: { 1310 String packages[]; 1311 ArrayList<String> components[]; 1312 int size = 0; 1313 int uids[]; 1314 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1315 synchronized (mPackages) { 1316 if (mPendingBroadcasts == null) { 1317 return; 1318 } 1319 size = mPendingBroadcasts.size(); 1320 if (size <= 0) { 1321 // Nothing to be done. Just return 1322 return; 1323 } 1324 packages = new String[size]; 1325 components = new ArrayList[size]; 1326 uids = new int[size]; 1327 int i = 0; // filling out the above arrays 1328 1329 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1330 int packageUserId = mPendingBroadcasts.userIdAt(n); 1331 Iterator<Map.Entry<String, ArrayList<String>>> it 1332 = mPendingBroadcasts.packagesForUserId(packageUserId) 1333 .entrySet().iterator(); 1334 while (it.hasNext() && i < size) { 1335 Map.Entry<String, ArrayList<String>> ent = it.next(); 1336 packages[i] = ent.getKey(); 1337 components[i] = ent.getValue(); 1338 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1339 uids[i] = (ps != null) 1340 ? UserHandle.getUid(packageUserId, ps.appId) 1341 : -1; 1342 i++; 1343 } 1344 } 1345 size = i; 1346 mPendingBroadcasts.clear(); 1347 } 1348 // Send broadcasts 1349 for (int i = 0; i < size; i++) { 1350 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1351 } 1352 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1353 break; 1354 } 1355 case START_CLEANING_PACKAGE: { 1356 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1357 final String packageName = (String)msg.obj; 1358 final int userId = msg.arg1; 1359 final boolean andCode = msg.arg2 != 0; 1360 synchronized (mPackages) { 1361 if (userId == UserHandle.USER_ALL) { 1362 int[] users = sUserManager.getUserIds(); 1363 for (int user : users) { 1364 mSettings.addPackageToCleanLPw( 1365 new PackageCleanItem(user, packageName, andCode)); 1366 } 1367 } else { 1368 mSettings.addPackageToCleanLPw( 1369 new PackageCleanItem(userId, packageName, andCode)); 1370 } 1371 } 1372 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1373 startCleaningPackages(); 1374 } break; 1375 case POST_INSTALL: { 1376 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1377 1378 PostInstallData data = mRunningInstalls.get(msg.arg1); 1379 mRunningInstalls.delete(msg.arg1); 1380 boolean deleteOld = false; 1381 1382 if (data != null) { 1383 InstallArgs args = data.args; 1384 PackageInstalledInfo res = data.res; 1385 1386 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1387 final String packageName = res.pkg.applicationInfo.packageName; 1388 res.removedInfo.sendBroadcast(false, true, false); 1389 Bundle extras = new Bundle(1); 1390 extras.putInt(Intent.EXTRA_UID, res.uid); 1391 1392 // Now that we successfully installed the package, grant runtime 1393 // permissions if requested before broadcasting the install. 1394 if ((args.installFlags 1395 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 1396 && res.pkg.applicationInfo.targetSdkVersion 1397 >= Build.VERSION_CODES.M) { 1398 grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(), 1399 args.installGrantPermissions); 1400 } 1401 1402 // Determine the set of users who are adding this 1403 // package for the first time vs. those who are seeing 1404 // an update. 1405 int[] firstUsers; 1406 int[] updateUsers = new int[0]; 1407 if (res.origUsers == null || res.origUsers.length == 0) { 1408 firstUsers = res.newUsers; 1409 } else { 1410 firstUsers = new int[0]; 1411 for (int i=0; i<res.newUsers.length; i++) { 1412 int user = res.newUsers[i]; 1413 boolean isNew = true; 1414 for (int j=0; j<res.origUsers.length; j++) { 1415 if (res.origUsers[j] == user) { 1416 isNew = false; 1417 break; 1418 } 1419 } 1420 if (isNew) { 1421 int[] newFirst = new int[firstUsers.length+1]; 1422 System.arraycopy(firstUsers, 0, newFirst, 0, 1423 firstUsers.length); 1424 newFirst[firstUsers.length] = user; 1425 firstUsers = newFirst; 1426 } else { 1427 int[] newUpdate = new int[updateUsers.length+1]; 1428 System.arraycopy(updateUsers, 0, newUpdate, 0, 1429 updateUsers.length); 1430 newUpdate[updateUsers.length] = user; 1431 updateUsers = newUpdate; 1432 } 1433 } 1434 } 1435 // don't broadcast for ephemeral installs/updates 1436 final boolean isEphemeral = isEphemeral(res.pkg); 1437 if (!isEphemeral) { 1438 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1439 extras, 0 /*flags*/, null /*targetPackage*/, 1440 null /*finishedReceiver*/, firstUsers); 1441 } 1442 final boolean update = res.removedInfo.removedPackage != null; 1443 if (update) { 1444 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1445 } 1446 if (!isEphemeral) { 1447 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1448 extras, 0 /*flags*/, null /*targetPackage*/, 1449 null /*finishedReceiver*/, updateUsers); 1450 } 1451 if (update) { 1452 if (!isEphemeral) { 1453 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1454 packageName, extras, 0 /*flags*/, 1455 null /*targetPackage*/, null /*finishedReceiver*/, 1456 updateUsers); 1457 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1458 null /*package*/, null /*extras*/, 0 /*flags*/, 1459 packageName /*targetPackage*/, 1460 null /*finishedReceiver*/, updateUsers); 1461 } 1462 1463 // treat asec-hosted packages like removable media on upgrade 1464 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1465 if (DEBUG_INSTALL) { 1466 Slog.i(TAG, "upgrading pkg " + res.pkg 1467 + " is ASEC-hosted -> AVAILABLE"); 1468 } 1469 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1470 ArrayList<String> pkgList = new ArrayList<String>(1); 1471 pkgList.add(packageName); 1472 sendResourcesChangedBroadcast(true, true, 1473 pkgList,uidArray, null); 1474 } 1475 } 1476 if (res.removedInfo.args != null) { 1477 // Remove the replaced package's older resources safely now 1478 deleteOld = true; 1479 } 1480 1481 // If this app is a browser and it's newly-installed for some 1482 // users, clear any default-browser state in those users 1483 if (firstUsers.length > 0) { 1484 // the app's nature doesn't depend on the user, so we can just 1485 // check its browser nature in any user and generalize. 1486 if (packageIsBrowser(packageName, firstUsers[0])) { 1487 synchronized (mPackages) { 1488 for (int userId : firstUsers) { 1489 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1490 } 1491 } 1492 } 1493 } 1494 // Log current value of "unknown sources" setting 1495 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1496 getUnknownSourcesSettings()); 1497 } 1498 // Force a gc to clear up things 1499 Runtime.getRuntime().gc(); 1500 // We delete after a gc for applications on sdcard. 1501 if (deleteOld) { 1502 synchronized (mInstallLock) { 1503 res.removedInfo.args.doPostDeleteLI(true); 1504 } 1505 } 1506 if (args.observer != null) { 1507 try { 1508 Bundle extras = extrasForInstallResult(res); 1509 args.observer.onPackageInstalled(res.name, res.returnCode, 1510 res.returnMsg, extras); 1511 } catch (RemoteException e) { 1512 Slog.i(TAG, "Observer no longer exists."); 1513 } 1514 } 1515 if (args.traceMethod != null) { 1516 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1517 args.traceCookie); 1518 } 1519 return; 1520 } else { 1521 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1522 } 1523 1524 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1525 } break; 1526 case UPDATED_MEDIA_STATUS: { 1527 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1528 boolean reportStatus = msg.arg1 == 1; 1529 boolean doGc = msg.arg2 == 1; 1530 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1531 if (doGc) { 1532 // Force a gc to clear up stale containers. 1533 Runtime.getRuntime().gc(); 1534 } 1535 if (msg.obj != null) { 1536 @SuppressWarnings("unchecked") 1537 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1538 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1539 // Unload containers 1540 unloadAllContainers(args); 1541 } 1542 if (reportStatus) { 1543 try { 1544 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1545 PackageHelper.getMountService().finishMediaUpdate(); 1546 } catch (RemoteException e) { 1547 Log.e(TAG, "MountService not running?"); 1548 } 1549 } 1550 } break; 1551 case WRITE_SETTINGS: { 1552 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1553 synchronized (mPackages) { 1554 removeMessages(WRITE_SETTINGS); 1555 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1556 mSettings.writeLPr(); 1557 mDirtyUsers.clear(); 1558 } 1559 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1560 } break; 1561 case WRITE_PACKAGE_RESTRICTIONS: { 1562 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1563 synchronized (mPackages) { 1564 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1565 for (int userId : mDirtyUsers) { 1566 mSettings.writePackageRestrictionsLPr(userId); 1567 } 1568 mDirtyUsers.clear(); 1569 } 1570 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1571 } break; 1572 case CHECK_PENDING_VERIFICATION: { 1573 final int verificationId = msg.arg1; 1574 final PackageVerificationState state = mPendingVerification.get(verificationId); 1575 1576 if ((state != null) && !state.timeoutExtended()) { 1577 final InstallArgs args = state.getInstallArgs(); 1578 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1579 1580 Slog.i(TAG, "Verification timed out for " + originUri); 1581 mPendingVerification.remove(verificationId); 1582 1583 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1584 1585 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1586 Slog.i(TAG, "Continuing with installation of " + originUri); 1587 state.setVerifierResponse(Binder.getCallingUid(), 1588 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1589 broadcastPackageVerified(verificationId, originUri, 1590 PackageManager.VERIFICATION_ALLOW, 1591 state.getInstallArgs().getUser()); 1592 try { 1593 ret = args.copyApk(mContainerService, true); 1594 } catch (RemoteException e) { 1595 Slog.e(TAG, "Could not contact the ContainerService"); 1596 } 1597 } else { 1598 broadcastPackageVerified(verificationId, originUri, 1599 PackageManager.VERIFICATION_REJECT, 1600 state.getInstallArgs().getUser()); 1601 } 1602 1603 Trace.asyncTraceEnd( 1604 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1605 1606 processPendingInstall(args, ret); 1607 mHandler.sendEmptyMessage(MCS_UNBIND); 1608 } 1609 break; 1610 } 1611 case PACKAGE_VERIFIED: { 1612 final int verificationId = msg.arg1; 1613 1614 final PackageVerificationState state = mPendingVerification.get(verificationId); 1615 if (state == null) { 1616 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1617 break; 1618 } 1619 1620 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1621 1622 state.setVerifierResponse(response.callerUid, response.code); 1623 1624 if (state.isVerificationComplete()) { 1625 mPendingVerification.remove(verificationId); 1626 1627 final InstallArgs args = state.getInstallArgs(); 1628 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1629 1630 int ret; 1631 if (state.isInstallAllowed()) { 1632 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1633 broadcastPackageVerified(verificationId, originUri, 1634 response.code, state.getInstallArgs().getUser()); 1635 try { 1636 ret = args.copyApk(mContainerService, true); 1637 } catch (RemoteException e) { 1638 Slog.e(TAG, "Could not contact the ContainerService"); 1639 } 1640 } else { 1641 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1642 } 1643 1644 Trace.asyncTraceEnd( 1645 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1646 1647 processPendingInstall(args, ret); 1648 mHandler.sendEmptyMessage(MCS_UNBIND); 1649 } 1650 1651 break; 1652 } 1653 case START_INTENT_FILTER_VERIFICATIONS: { 1654 IFVerificationParams params = (IFVerificationParams) msg.obj; 1655 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1656 params.replacing, params.pkg); 1657 break; 1658 } 1659 case INTENT_FILTER_VERIFIED: { 1660 final int verificationId = msg.arg1; 1661 1662 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1663 verificationId); 1664 if (state == null) { 1665 Slog.w(TAG, "Invalid IntentFilter verification token " 1666 + verificationId + " received"); 1667 break; 1668 } 1669 1670 final int userId = state.getUserId(); 1671 1672 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1673 "Processing IntentFilter verification with token:" 1674 + verificationId + " and userId:" + userId); 1675 1676 final IntentFilterVerificationResponse response = 1677 (IntentFilterVerificationResponse) msg.obj; 1678 1679 state.setVerifierResponse(response.callerUid, response.code); 1680 1681 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1682 "IntentFilter verification with token:" + verificationId 1683 + " and userId:" + userId 1684 + " is settings verifier response with response code:" 1685 + response.code); 1686 1687 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1688 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1689 + response.getFailedDomainsString()); 1690 } 1691 1692 if (state.isVerificationComplete()) { 1693 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1694 } else { 1695 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1696 "IntentFilter verification with token:" + verificationId 1697 + " was not said to be complete"); 1698 } 1699 1700 break; 1701 } 1702 } 1703 } 1704 } 1705 1706 private StorageEventListener mStorageListener = new StorageEventListener() { 1707 @Override 1708 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1709 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1710 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1711 final String volumeUuid = vol.getFsUuid(); 1712 1713 // Clean up any users or apps that were removed or recreated 1714 // while this volume was missing 1715 reconcileUsers(volumeUuid); 1716 reconcileApps(volumeUuid); 1717 1718 // Clean up any install sessions that expired or were 1719 // cancelled while this volume was missing 1720 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1721 1722 loadPrivatePackages(vol); 1723 1724 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1725 unloadPrivatePackages(vol); 1726 } 1727 } 1728 1729 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1730 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1731 updateExternalMediaStatus(true, false); 1732 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1733 updateExternalMediaStatus(false, false); 1734 } 1735 } 1736 } 1737 1738 @Override 1739 public void onVolumeForgotten(String fsUuid) { 1740 if (TextUtils.isEmpty(fsUuid)) { 1741 Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1742 return; 1743 } 1744 1745 // Remove any apps installed on the forgotten volume 1746 synchronized (mPackages) { 1747 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1748 for (PackageSetting ps : packages) { 1749 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1750 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1751 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1752 } 1753 1754 mSettings.onVolumeForgotten(fsUuid); 1755 mSettings.writeLPr(); 1756 } 1757 } 1758 }; 1759 1760 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId, 1761 String[] grantedPermissions) { 1762 if (userId >= UserHandle.USER_SYSTEM) { 1763 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1764 } else if (userId == UserHandle.USER_ALL) { 1765 final int[] userIds; 1766 synchronized (mPackages) { 1767 userIds = UserManagerService.getInstance().getUserIds(); 1768 } 1769 for (int someUserId : userIds) { 1770 grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions); 1771 } 1772 } 1773 1774 // We could have touched GID membership, so flush out packages.list 1775 synchronized (mPackages) { 1776 mSettings.writePackageListLPr(); 1777 } 1778 } 1779 1780 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1781 String[] grantedPermissions) { 1782 SettingBase sb = (SettingBase) pkg.mExtras; 1783 if (sb == null) { 1784 return; 1785 } 1786 1787 PermissionsState permissionsState = sb.getPermissionsState(); 1788 1789 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 1790 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 1791 1792 synchronized (mPackages) { 1793 for (String permission : pkg.requestedPermissions) { 1794 BasePermission bp = mSettings.mPermissions.get(permission); 1795 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 1796 && (grantedPermissions == null 1797 || ArrayUtils.contains(grantedPermissions, permission))) { 1798 final int flags = permissionsState.getPermissionFlags(permission, userId); 1799 // Installer cannot change immutable permissions. 1800 if ((flags & immutableFlags) == 0) { 1801 grantRuntimePermission(pkg.packageName, permission, userId); 1802 } 1803 } 1804 } 1805 } 1806 } 1807 1808 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1809 Bundle extras = null; 1810 switch (res.returnCode) { 1811 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1812 extras = new Bundle(); 1813 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1814 res.origPermission); 1815 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1816 res.origPackage); 1817 break; 1818 } 1819 case PackageManager.INSTALL_SUCCEEDED: { 1820 extras = new Bundle(); 1821 extras.putBoolean(Intent.EXTRA_REPLACING, 1822 res.removedInfo != null && res.removedInfo.removedPackage != null); 1823 break; 1824 } 1825 } 1826 return extras; 1827 } 1828 1829 void scheduleWriteSettingsLocked() { 1830 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1831 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1832 } 1833 } 1834 1835 void scheduleWritePackageRestrictionsLocked(int userId) { 1836 if (!sUserManager.exists(userId)) return; 1837 mDirtyUsers.add(userId); 1838 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1839 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1840 } 1841 } 1842 1843 public static PackageManagerService main(Context context, Installer installer, 1844 boolean factoryTest, boolean onlyCore) { 1845 PackageManagerService m = new PackageManagerService(context, installer, 1846 factoryTest, onlyCore); 1847 m.enableSystemUserApps(); 1848 ServiceManager.addService("package", m); 1849 return m; 1850 } 1851 1852 private void enableSystemUserApps() { 1853 if (!UserManager.isSplitSystemUser()) { 1854 return; 1855 } 1856 // For system user, enable apps based on the following conditions: 1857 // - app is whitelisted or belong to one of these groups: 1858 // -- system app which has no launcher icons 1859 // -- system app which has INTERACT_ACROSS_USERS permission 1860 // -- system IME app 1861 // - app is not in the blacklist 1862 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 1863 Set<String> enableApps = new ArraySet<>(); 1864 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 1865 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 1866 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 1867 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 1868 enableApps.addAll(wlApps); 1869 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 1870 enableApps.removeAll(blApps); 1871 1872 List<String> systemApps = queryHelper.queryApps(0, /* systemAppsOnly */ true, 1873 UserHandle.SYSTEM); 1874 final int systemAppsSize = systemApps.size(); 1875 synchronized (mPackages) { 1876 for (int i = 0; i < systemAppsSize; i++) { 1877 String pName = systemApps.get(i); 1878 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 1879 // Should not happen, but we shouldn't be failing if it does 1880 if (pkgSetting == null) { 1881 continue; 1882 } 1883 boolean installed = enableApps.contains(pName); 1884 pkgSetting.setInstalled(installed, UserHandle.USER_SYSTEM); 1885 } 1886 } 1887 } 1888 1889 static String[] splitString(String str, char sep) { 1890 int count = 1; 1891 int i = 0; 1892 while ((i=str.indexOf(sep, i)) >= 0) { 1893 count++; 1894 i++; 1895 } 1896 1897 String[] res = new String[count]; 1898 i=0; 1899 count = 0; 1900 int lastI=0; 1901 while ((i=str.indexOf(sep, i)) >= 0) { 1902 res[count] = str.substring(lastI, i); 1903 count++; 1904 i++; 1905 lastI = i; 1906 } 1907 res[count] = str.substring(lastI, str.length()); 1908 return res; 1909 } 1910 1911 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1912 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1913 Context.DISPLAY_SERVICE); 1914 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1915 } 1916 1917 public PackageManagerService(Context context, Installer installer, 1918 boolean factoryTest, boolean onlyCore) { 1919 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1920 SystemClock.uptimeMillis()); 1921 1922 if (mSdkVersion <= 0) { 1923 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1924 } 1925 1926 mContext = context; 1927 mFactoryTest = factoryTest; 1928 mOnlyCore = onlyCore; 1929 mMetrics = new DisplayMetrics(); 1930 mSettings = new Settings(mPackages); 1931 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1932 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1933 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1934 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1935 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1936 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1937 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1938 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1939 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1940 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1941 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1942 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1943 1944 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1945 if (separateProcesses != null && separateProcesses.length() > 0) { 1946 if ("*".equals(separateProcesses)) { 1947 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1948 mSeparateProcesses = null; 1949 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1950 } else { 1951 mDefParseFlags = 0; 1952 mSeparateProcesses = separateProcesses.split(","); 1953 Slog.w(TAG, "Running with debug.separate_processes: " 1954 + separateProcesses); 1955 } 1956 } else { 1957 mDefParseFlags = 0; 1958 mSeparateProcesses = null; 1959 } 1960 1961 mInstaller = installer; 1962 mPackageDexOptimizer = new PackageDexOptimizer(this); 1963 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1964 1965 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 1966 FgThread.get().getLooper()); 1967 1968 getDefaultDisplayMetrics(context, mMetrics); 1969 1970 SystemConfig systemConfig = SystemConfig.getInstance(); 1971 mGlobalGids = systemConfig.getGlobalGids(); 1972 mSystemPermissions = systemConfig.getSystemPermissions(); 1973 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1974 1975 synchronized (mInstallLock) { 1976 // writer 1977 synchronized (mPackages) { 1978 mHandlerThread = new ServiceThread(TAG, 1979 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1980 mHandlerThread.start(); 1981 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1982 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1983 1984 File dataDir = Environment.getDataDirectory(); 1985 mAppDataDir = new File(dataDir, "data"); 1986 mAppInstallDir = new File(dataDir, "app"); 1987 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1988 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 1989 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1990 mUserAppDataDir = new File(dataDir, "user"); 1991 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1992 1993 sUserManager = new UserManagerService(context, this, mPackages); 1994 1995 // Propagate permission configuration in to package manager. 1996 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1997 = systemConfig.getPermissions(); 1998 for (int i=0; i<permConfig.size(); i++) { 1999 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2000 BasePermission bp = mSettings.mPermissions.get(perm.name); 2001 if (bp == null) { 2002 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2003 mSettings.mPermissions.put(perm.name, bp); 2004 } 2005 if (perm.gids != null) { 2006 bp.setGids(perm.gids, perm.perUser); 2007 } 2008 } 2009 2010 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2011 for (int i=0; i<libConfig.size(); i++) { 2012 mSharedLibraries.put(libConfig.keyAt(i), 2013 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2014 } 2015 2016 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2017 2018 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 2019 2020 String customResolverActivity = Resources.getSystem().getString( 2021 R.string.config_customResolverActivity); 2022 if (TextUtils.isEmpty(customResolverActivity)) { 2023 customResolverActivity = null; 2024 } else { 2025 mCustomResolverComponentName = ComponentName.unflattenFromString( 2026 customResolverActivity); 2027 } 2028 2029 long startTime = SystemClock.uptimeMillis(); 2030 2031 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2032 startTime); 2033 2034 // Set flag to monitor and not change apk file paths when 2035 // scanning install directories. 2036 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2037 2038 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2039 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2040 2041 if (bootClassPath == null) { 2042 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2043 } 2044 2045 if (systemServerClassPath == null) { 2046 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2047 } 2048 2049 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2050 final String[] dexCodeInstructionSets = 2051 getDexCodeInstructionSets( 2052 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2053 2054 /** 2055 * Ensure all external libraries have had dexopt run on them. 2056 */ 2057 if (mSharedLibraries.size() > 0) { 2058 // NOTE: For now, we're compiling these system "shared libraries" 2059 // (and framework jars) into all available architectures. It's possible 2060 // to compile them only when we come across an app that uses them (there's 2061 // already logic for that in scanPackageLI) but that adds some complexity. 2062 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2063 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2064 final String lib = libEntry.path; 2065 if (lib == null) { 2066 continue; 2067 } 2068 2069 try { 2070 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 2071 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2072 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2073 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/); 2074 } 2075 } catch (FileNotFoundException e) { 2076 Slog.w(TAG, "Library not found: " + lib); 2077 } catch (IOException e) { 2078 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2079 + e.getMessage()); 2080 } 2081 } 2082 } 2083 } 2084 2085 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2086 2087 final VersionInfo ver = mSettings.getInternalVersion(); 2088 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2089 // when upgrading from pre-M, promote system app permissions from install to runtime 2090 mPromoteSystemApps = 2091 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2092 2093 // save off the names of pre-existing system packages prior to scanning; we don't 2094 // want to automatically grant runtime permissions for new system apps 2095 if (mPromoteSystemApps) { 2096 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2097 while (pkgSettingIter.hasNext()) { 2098 PackageSetting ps = pkgSettingIter.next(); 2099 if (isSystemApp(ps)) { 2100 mExistingSystemPackages.add(ps.name); 2101 } 2102 } 2103 } 2104 2105 // Collect vendor overlay packages. 2106 // (Do this before scanning any apps.) 2107 // For security and version matching reason, only consider 2108 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2109 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2110 scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2111 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2112 2113 // Find base frameworks (resource packages without code). 2114 scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2115 | PackageParser.PARSE_IS_SYSTEM_DIR 2116 | PackageParser.PARSE_IS_PRIVILEGED, 2117 scanFlags | SCAN_NO_DEX, 0); 2118 2119 // Collected privileged system packages. 2120 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2121 scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2122 | PackageParser.PARSE_IS_SYSTEM_DIR 2123 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2124 2125 // Collect ordinary system packages. 2126 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2127 scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2128 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2129 2130 // Collect all vendor packages. 2131 File vendorAppDir = new File("/vendor/app"); 2132 try { 2133 vendorAppDir = vendorAppDir.getCanonicalFile(); 2134 } catch (IOException e) { 2135 // failed to look up canonical path, continue with original one 2136 } 2137 scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2138 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2139 2140 // Collect all OEM packages. 2141 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2142 scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2143 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2144 2145 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 2146 mInstaller.moveFiles(); 2147 2148 // Prune any system packages that no longer exist. 2149 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2150 if (!mOnlyCore) { 2151 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2152 while (psit.hasNext()) { 2153 PackageSetting ps = psit.next(); 2154 2155 /* 2156 * If this is not a system app, it can't be a 2157 * disable system app. 2158 */ 2159 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2160 continue; 2161 } 2162 2163 /* 2164 * If the package is scanned, it's not erased. 2165 */ 2166 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2167 if (scannedPkg != null) { 2168 /* 2169 * If the system app is both scanned and in the 2170 * disabled packages list, then it must have been 2171 * added via OTA. Remove it from the currently 2172 * scanned package so the previously user-installed 2173 * application can be scanned. 2174 */ 2175 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2176 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2177 + ps.name + "; removing system app. Last known codePath=" 2178 + ps.codePathString + ", installStatus=" + ps.installStatus 2179 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2180 + scannedPkg.mVersionCode); 2181 removePackageLI(ps, true); 2182 mExpectingBetter.put(ps.name, ps.codePath); 2183 } 2184 2185 continue; 2186 } 2187 2188 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2189 psit.remove(); 2190 logCriticalInfo(Log.WARN, "System package " + ps.name 2191 + " no longer exists; wiping its data"); 2192 removeDataDirsLI(null, ps.name); 2193 } else { 2194 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2195 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2196 possiblyDeletedUpdatedSystemApps.add(ps.name); 2197 } 2198 } 2199 } 2200 } 2201 2202 //look for any incomplete package installations 2203 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2204 //clean up list 2205 for(int i = 0; i < deletePkgsList.size(); i++) { 2206 //clean up here 2207 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2208 } 2209 //delete tmp files 2210 deleteTempPackageFiles(); 2211 2212 // Remove any shared userIDs that have no associated packages 2213 mSettings.pruneSharedUsersLPw(); 2214 2215 if (!mOnlyCore) { 2216 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2217 SystemClock.uptimeMillis()); 2218 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2219 2220 scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2221 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2222 2223 scanDirLI(mEphemeralInstallDir, PackageParser.PARSE_IS_EPHEMERAL, 2224 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2225 2226 /** 2227 * Remove disable package settings for any updated system 2228 * apps that were removed via an OTA. If they're not a 2229 * previously-updated app, remove them completely. 2230 * Otherwise, just revoke their system-level permissions. 2231 */ 2232 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2233 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2234 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2235 2236 String msg; 2237 if (deletedPkg == null) { 2238 msg = "Updated system package " + deletedAppName 2239 + " no longer exists; wiping its data"; 2240 removeDataDirsLI(null, deletedAppName); 2241 } else { 2242 msg = "Updated system app + " + deletedAppName 2243 + " no longer present; removing system privileges for " 2244 + deletedAppName; 2245 2246 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2247 2248 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2249 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2250 } 2251 logCriticalInfo(Log.WARN, msg); 2252 } 2253 2254 /** 2255 * Make sure all system apps that we expected to appear on 2256 * the userdata partition actually showed up. If they never 2257 * appeared, crawl back and revive the system version. 2258 */ 2259 for (int i = 0; i < mExpectingBetter.size(); i++) { 2260 final String packageName = mExpectingBetter.keyAt(i); 2261 if (!mPackages.containsKey(packageName)) { 2262 final File scanFile = mExpectingBetter.valueAt(i); 2263 2264 logCriticalInfo(Log.WARN, "Expected better " + packageName 2265 + " but never showed up; reverting to system"); 2266 2267 final int reparseFlags; 2268 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2269 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2270 | PackageParser.PARSE_IS_SYSTEM_DIR 2271 | PackageParser.PARSE_IS_PRIVILEGED; 2272 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2273 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2274 | PackageParser.PARSE_IS_SYSTEM_DIR; 2275 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2276 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2277 | PackageParser.PARSE_IS_SYSTEM_DIR; 2278 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2279 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2280 | PackageParser.PARSE_IS_SYSTEM_DIR; 2281 } else { 2282 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2283 continue; 2284 } 2285 2286 mSettings.enableSystemPackageLPw(packageName); 2287 2288 try { 2289 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2290 } catch (PackageManagerException e) { 2291 Slog.e(TAG, "Failed to parse original system package: " 2292 + e.getMessage()); 2293 } 2294 } 2295 } 2296 } 2297 mExpectingBetter.clear(); 2298 2299 // Now that we know all of the shared libraries, update all clients to have 2300 // the correct library paths. 2301 updateAllSharedLibrariesLPw(); 2302 2303 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2304 // NOTE: We ignore potential failures here during a system scan (like 2305 // the rest of the commands above) because there's precious little we 2306 // can do about it. A settings error is reported, though. 2307 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2308 false /* boot complete */); 2309 } 2310 2311 // Now that we know all the packages we are keeping, 2312 // read and update their last usage times. 2313 mPackageUsage.readLP(); 2314 2315 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2316 SystemClock.uptimeMillis()); 2317 Slog.i(TAG, "Time to scan packages: " 2318 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2319 + " seconds"); 2320 2321 // If the platform SDK has changed since the last time we booted, 2322 // we need to re-grant app permission to catch any new ones that 2323 // appear. This is really a hack, and means that apps can in some 2324 // cases get permissions that the user didn't initially explicitly 2325 // allow... it would be nice to have some better way to handle 2326 // this situation. 2327 int updateFlags = UPDATE_PERMISSIONS_ALL; 2328 if (ver.sdkVersion != mSdkVersion) { 2329 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2330 + mSdkVersion + "; regranting permissions for internal storage"); 2331 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2332 } 2333 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2334 ver.sdkVersion = mSdkVersion; 2335 2336 // If this is the first boot or an update from pre-M, and it is a normal 2337 // boot, then we need to initialize the default preferred apps across 2338 // all defined users. 2339 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2340 for (UserInfo user : sUserManager.getUsers(true)) { 2341 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2342 applyFactoryDefaultBrowserLPw(user.id); 2343 primeDomainVerificationsLPw(user.id); 2344 } 2345 } 2346 2347 // If this is first boot after an OTA, and a normal boot, then 2348 // we need to clear code cache directories. 2349 if (mIsUpgrade && !onlyCore) { 2350 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2351 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2352 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2353 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2354 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2355 } 2356 } 2357 ver.fingerprint = Build.FINGERPRINT; 2358 } 2359 2360 checkDefaultBrowser(); 2361 2362 // clear only after permissions and other defaults have been updated 2363 mExistingSystemPackages.clear(); 2364 mPromoteSystemApps = false; 2365 2366 // All the changes are done during package scanning. 2367 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2368 2369 // can downgrade to reader 2370 mSettings.writeLPr(); 2371 2372 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2373 SystemClock.uptimeMillis()); 2374 2375 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2376 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2377 2378 mInstallerService = new PackageInstallerService(context, this); 2379 2380 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2381 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2382 mIntentFilterVerifierComponent); 2383 2384 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2385 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2386 // both the installer and resolver must be present to enable ephemeral 2387 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2388 if (DEBUG_EPHEMERAL) { 2389 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2390 + " installer:" + ephemeralInstallerComponent); 2391 } 2392 mEphemeralResolverComponent = ephemeralResolverComponent; 2393 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2394 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2395 mEphemeralResolverConnection = 2396 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2397 } else { 2398 if (DEBUG_EPHEMERAL) { 2399 final String missingComponent = 2400 (ephemeralResolverComponent == null) 2401 ? (ephemeralInstallerComponent == null) 2402 ? "resolver and installer" 2403 : "resolver" 2404 : "installer"; 2405 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2406 } 2407 mEphemeralResolverComponent = null; 2408 mEphemeralInstallerComponent = null; 2409 mEphemeralResolverConnection = null; 2410 } 2411 } // synchronized (mPackages) 2412 } // synchronized (mInstallLock) 2413 2414 // Now after opening every single application zip, make sure they 2415 // are all flushed. Not really needed, but keeps things nice and 2416 // tidy. 2417 Runtime.getRuntime().gc(); 2418 2419 // The initial scanning above does many calls into installd while 2420 // holding the mPackages lock, but we're mostly interested in yelling 2421 // once we have a booted system. 2422 mInstaller.setWarnIfHeld(mPackages); 2423 2424 // Expose private service for system components to use. 2425 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2426 } 2427 2428 @Override 2429 public boolean isFirstBoot() { 2430 return !mRestoredSettings; 2431 } 2432 2433 @Override 2434 public boolean isOnlyCoreApps() { 2435 return mOnlyCore; 2436 } 2437 2438 @Override 2439 public boolean isUpgrade() { 2440 return mIsUpgrade; 2441 } 2442 2443 private String getRequiredVerifierLPr() { 2444 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2445 // We only care about verifier that's installed under system user. 2446 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2447 PackageManager.GET_DISABLED_COMPONENTS, UserHandle.USER_SYSTEM); 2448 2449 String requiredVerifier = null; 2450 2451 final int N = receivers.size(); 2452 for (int i = 0; i < N; i++) { 2453 final ResolveInfo info = receivers.get(i); 2454 2455 if (info.activityInfo == null) { 2456 continue; 2457 } 2458 2459 final String packageName = info.activityInfo.packageName; 2460 2461 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2462 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2463 continue; 2464 } 2465 2466 if (requiredVerifier != null) { 2467 throw new RuntimeException("There can be only one required verifier"); 2468 } 2469 2470 requiredVerifier = packageName; 2471 } 2472 2473 return requiredVerifier; 2474 } 2475 2476 private String getRequiredInstallerLPr() { 2477 Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2478 installerIntent.addCategory(Intent.CATEGORY_DEFAULT); 2479 installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2480 2481 final List<ResolveInfo> installers = queryIntentActivities(installerIntent, 2482 PACKAGE_MIME_TYPE, 0, UserHandle.USER_SYSTEM); 2483 2484 String requiredInstaller = null; 2485 2486 final int N = installers.size(); 2487 for (int i = 0; i < N; i++) { 2488 final ResolveInfo info = installers.get(i); 2489 final String packageName = info.activityInfo.packageName; 2490 2491 if (!info.activityInfo.applicationInfo.isSystemApp()) { 2492 continue; 2493 } 2494 2495 if (requiredInstaller != null) { 2496 throw new RuntimeException("There must be one required installer"); 2497 } 2498 2499 requiredInstaller = packageName; 2500 } 2501 2502 if (requiredInstaller == null) { 2503 throw new RuntimeException("There must be one required installer"); 2504 } 2505 2506 return requiredInstaller; 2507 } 2508 2509 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2510 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2511 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2512 PackageManager.GET_DISABLED_COMPONENTS, UserHandle.USER_SYSTEM); 2513 2514 ComponentName verifierComponentName = null; 2515 2516 int priority = -1000; 2517 final int N = receivers.size(); 2518 for (int i = 0; i < N; i++) { 2519 final ResolveInfo info = receivers.get(i); 2520 2521 if (info.activityInfo == null) { 2522 continue; 2523 } 2524 2525 final String packageName = info.activityInfo.packageName; 2526 2527 final PackageSetting ps = mSettings.mPackages.get(packageName); 2528 if (ps == null) { 2529 continue; 2530 } 2531 2532 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2533 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2534 continue; 2535 } 2536 2537 // Select the IntentFilterVerifier with the highest priority 2538 if (priority < info.priority) { 2539 priority = info.priority; 2540 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2541 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: " 2542 + verifierComponentName + " with priority: " + info.priority); 2543 } 2544 } 2545 2546 return verifierComponentName; 2547 } 2548 2549 private ComponentName getEphemeralResolverLPr() { 2550 final String[] packageArray = 2551 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2552 if (packageArray.length == 0) { 2553 if (DEBUG_EPHEMERAL) { 2554 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2555 } 2556 return null; 2557 } 2558 2559 Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2560 final List<ResolveInfo> resolvers = queryIntentServices(resolverIntent, 2561 null /*resolvedType*/, 0 /*flags*/, UserHandle.USER_SYSTEM); 2562 2563 final int N = resolvers.size(); 2564 if (N == 0) { 2565 if (DEBUG_EPHEMERAL) { 2566 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2567 } 2568 return null; 2569 } 2570 2571 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2572 for (int i = 0; i < N; i++) { 2573 final ResolveInfo info = resolvers.get(i); 2574 2575 if (info.serviceInfo == null) { 2576 continue; 2577 } 2578 2579 final String packageName = info.serviceInfo.packageName; 2580 if (!possiblePackages.contains(packageName)) { 2581 if (DEBUG_EPHEMERAL) { 2582 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2583 + " pkg: " + packageName + ", info:" + info); 2584 } 2585 continue; 2586 } 2587 2588 if (DEBUG_EPHEMERAL) { 2589 Slog.v(TAG, "Ephemeral resolver found;" 2590 + " pkg: " + packageName + ", info:" + info); 2591 } 2592 return new ComponentName(packageName, info.serviceInfo.name); 2593 } 2594 if (DEBUG_EPHEMERAL) { 2595 Slog.v(TAG, "Ephemeral resolver NOT found"); 2596 } 2597 return null; 2598 } 2599 2600 private ComponentName getEphemeralInstallerLPr() { 2601 Intent installerIntent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2602 installerIntent.addCategory(Intent.CATEGORY_DEFAULT); 2603 installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2604 final List<ResolveInfo> installers = queryIntentActivities(installerIntent, 2605 PACKAGE_MIME_TYPE, 0 /*flags*/, 0 /*userId*/); 2606 2607 ComponentName ephemeralInstaller = null; 2608 2609 final int N = installers.size(); 2610 for (int i = 0; i < N; i++) { 2611 final ResolveInfo info = installers.get(i); 2612 final String packageName = info.activityInfo.packageName; 2613 2614 if (!info.activityInfo.applicationInfo.isSystemApp()) { 2615 if (DEBUG_EPHEMERAL) { 2616 Slog.d(TAG, "Ephemeral installer is not system app;" 2617 + " pkg: " + packageName + ", info:" + info); 2618 } 2619 continue; 2620 } 2621 2622 if (ephemeralInstaller != null) { 2623 throw new RuntimeException("There must only be one ephemeral installer"); 2624 } 2625 2626 ephemeralInstaller = new ComponentName(packageName, info.activityInfo.name); 2627 } 2628 2629 return ephemeralInstaller; 2630 } 2631 2632 private void primeDomainVerificationsLPw(int userId) { 2633 if (DEBUG_DOMAIN_VERIFICATION) { 2634 Slog.d(TAG, "Priming domain verifications in user " + userId); 2635 } 2636 2637 SystemConfig systemConfig = SystemConfig.getInstance(); 2638 ArraySet<String> packages = systemConfig.getLinkedApps(); 2639 ArraySet<String> domains = new ArraySet<String>(); 2640 2641 for (String packageName : packages) { 2642 PackageParser.Package pkg = mPackages.get(packageName); 2643 if (pkg != null) { 2644 if (!pkg.isSystemApp()) { 2645 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2646 continue; 2647 } 2648 2649 domains.clear(); 2650 for (PackageParser.Activity a : pkg.activities) { 2651 for (ActivityIntentInfo filter : a.intents) { 2652 if (hasValidDomains(filter)) { 2653 domains.addAll(filter.getHostsList()); 2654 } 2655 } 2656 } 2657 2658 if (domains.size() > 0) { 2659 if (DEBUG_DOMAIN_VERIFICATION) { 2660 Slog.v(TAG, " + " + packageName); 2661 } 2662 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2663 // state w.r.t. the formal app-linkage "no verification attempted" state; 2664 // and then 'always' in the per-user state actually used for intent resolution. 2665 final IntentFilterVerificationInfo ivi; 2666 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2667 new ArrayList<String>(domains)); 2668 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2669 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2670 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2671 } else { 2672 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2673 + "' does not handle web links"); 2674 } 2675 } else { 2676 Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>"); 2677 } 2678 } 2679 2680 scheduleWritePackageRestrictionsLocked(userId); 2681 scheduleWriteSettingsLocked(); 2682 } 2683 2684 private void applyFactoryDefaultBrowserLPw(int userId) { 2685 // The default browser app's package name is stored in a string resource, 2686 // with a product-specific overlay used for vendor customization. 2687 String browserPkg = mContext.getResources().getString( 2688 com.android.internal.R.string.default_browser); 2689 if (!TextUtils.isEmpty(browserPkg)) { 2690 // non-empty string => required to be a known package 2691 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2692 if (ps == null) { 2693 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2694 browserPkg = null; 2695 } else { 2696 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2697 } 2698 } 2699 2700 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2701 // default. If there's more than one, just leave everything alone. 2702 if (browserPkg == null) { 2703 calculateDefaultBrowserLPw(userId); 2704 } 2705 } 2706 2707 private void calculateDefaultBrowserLPw(int userId) { 2708 List<String> allBrowsers = resolveAllBrowserApps(userId); 2709 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2710 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2711 } 2712 2713 private List<String> resolveAllBrowserApps(int userId) { 2714 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2715 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2716 PackageManager.MATCH_ALL, userId); 2717 2718 final int count = list.size(); 2719 List<String> result = new ArrayList<String>(count); 2720 for (int i=0; i<count; i++) { 2721 ResolveInfo info = list.get(i); 2722 if (info.activityInfo == null 2723 || !info.handleAllWebDataURI 2724 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2725 || result.contains(info.activityInfo.packageName)) { 2726 continue; 2727 } 2728 result.add(info.activityInfo.packageName); 2729 } 2730 2731 return result; 2732 } 2733 2734 private boolean packageIsBrowser(String packageName, int userId) { 2735 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2736 PackageManager.MATCH_ALL, userId); 2737 final int N = list.size(); 2738 for (int i = 0; i < N; i++) { 2739 ResolveInfo info = list.get(i); 2740 if (packageName.equals(info.activityInfo.packageName)) { 2741 return true; 2742 } 2743 } 2744 return false; 2745 } 2746 2747 private void checkDefaultBrowser() { 2748 final int myUserId = UserHandle.myUserId(); 2749 final String packageName = getDefaultBrowserPackageName(myUserId); 2750 if (packageName != null) { 2751 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2752 if (info == null) { 2753 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2754 synchronized (mPackages) { 2755 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2756 } 2757 } 2758 } 2759 } 2760 2761 @Override 2762 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2763 throws RemoteException { 2764 try { 2765 return super.onTransact(code, data, reply, flags); 2766 } catch (RuntimeException e) { 2767 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2768 Slog.wtf(TAG, "Package Manager Crash", e); 2769 } 2770 throw e; 2771 } 2772 } 2773 2774 void cleanupInstallFailedPackage(PackageSetting ps) { 2775 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2776 2777 removeDataDirsLI(ps.volumeUuid, ps.name); 2778 if (ps.codePath != null) { 2779 if (ps.codePath.isDirectory()) { 2780 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2781 } else { 2782 ps.codePath.delete(); 2783 } 2784 } 2785 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2786 if (ps.resourcePath.isDirectory()) { 2787 FileUtils.deleteContents(ps.resourcePath); 2788 } 2789 ps.resourcePath.delete(); 2790 } 2791 mSettings.removePackageLPw(ps.name); 2792 } 2793 2794 static int[] appendInts(int[] cur, int[] add) { 2795 if (add == null) return cur; 2796 if (cur == null) return add; 2797 final int N = add.length; 2798 for (int i=0; i<N; i++) { 2799 cur = appendInt(cur, add[i]); 2800 } 2801 return cur; 2802 } 2803 2804 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2805 if (!sUserManager.exists(userId)) return null; 2806 final PackageSetting ps = (PackageSetting) p.mExtras; 2807 if (ps == null) { 2808 return null; 2809 } 2810 2811 final PermissionsState permissionsState = ps.getPermissionsState(); 2812 2813 final int[] gids = permissionsState.computeGids(userId); 2814 final Set<String> permissions = permissionsState.getPermissions(userId); 2815 final PackageUserState state = ps.readUserState(userId); 2816 2817 return PackageParser.generatePackageInfo(p, gids, flags, 2818 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2819 } 2820 2821 @Override 2822 public void checkPackageStartable(String packageName, int userId) { 2823 final boolean userKeyUnlocked = isUserKeyUnlocked(userId); 2824 2825 synchronized (mPackages) { 2826 final PackageSetting ps = mSettings.mPackages.get(packageName); 2827 if (ps == null) { 2828 throw new SecurityException("Package " + packageName + " was not found!"); 2829 } 2830 2831 if (ps.frozen) { 2832 throw new SecurityException("Package " + packageName + " is currently frozen!"); 2833 } 2834 2835 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isEncryptionAware() 2836 || ps.pkg.applicationInfo.isPartiallyEncryptionAware())) { 2837 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 2838 } 2839 } 2840 } 2841 2842 @Override 2843 public boolean isPackageAvailable(String packageName, int userId) { 2844 if (!sUserManager.exists(userId)) return false; 2845 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2846 synchronized (mPackages) { 2847 PackageParser.Package p = mPackages.get(packageName); 2848 if (p != null) { 2849 final PackageSetting ps = (PackageSetting) p.mExtras; 2850 if (ps != null) { 2851 final PackageUserState state = ps.readUserState(userId); 2852 if (state != null) { 2853 return PackageParser.isAvailable(state); 2854 } 2855 } 2856 } 2857 } 2858 return false; 2859 } 2860 2861 @Override 2862 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2863 if (!sUserManager.exists(userId)) return null; 2864 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2865 // reader 2866 synchronized (mPackages) { 2867 PackageParser.Package p = mPackages.get(packageName); 2868 if (DEBUG_PACKAGE_INFO) 2869 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2870 if (p != null) { 2871 return generatePackageInfo(p, flags, userId); 2872 } 2873 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2874 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2875 } 2876 } 2877 return null; 2878 } 2879 2880 @Override 2881 public String[] currentToCanonicalPackageNames(String[] names) { 2882 String[] out = new String[names.length]; 2883 // reader 2884 synchronized (mPackages) { 2885 for (int i=names.length-1; i>=0; i--) { 2886 PackageSetting ps = mSettings.mPackages.get(names[i]); 2887 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2888 } 2889 } 2890 return out; 2891 } 2892 2893 @Override 2894 public String[] canonicalToCurrentPackageNames(String[] names) { 2895 String[] out = new String[names.length]; 2896 // reader 2897 synchronized (mPackages) { 2898 for (int i=names.length-1; i>=0; i--) { 2899 String cur = mSettings.mRenamedPackages.get(names[i]); 2900 out[i] = cur != null ? cur : names[i]; 2901 } 2902 } 2903 return out; 2904 } 2905 2906 @Override 2907 public int getPackageUid(String packageName, int userId) { 2908 return getPackageUidEtc(packageName, 0, userId); 2909 } 2910 2911 @Override 2912 public int getPackageUidEtc(String packageName, int flags, int userId) { 2913 if (!sUserManager.exists(userId)) return -1; 2914 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2915 2916 // reader 2917 synchronized (mPackages) { 2918 final PackageParser.Package p = mPackages.get(packageName); 2919 if (p != null) { 2920 return UserHandle.getUid(userId, p.applicationInfo.uid); 2921 } 2922 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2923 final PackageSetting ps = mSettings.mPackages.get(packageName); 2924 if (ps != null) { 2925 return UserHandle.getUid(userId, ps.appId); 2926 } 2927 } 2928 } 2929 2930 return -1; 2931 } 2932 2933 @Override 2934 public int[] getPackageGids(String packageName, int userId) { 2935 return getPackageGidsEtc(packageName, 0, userId); 2936 } 2937 2938 @Override 2939 public int[] getPackageGidsEtc(String packageName, int flags, int userId) { 2940 if (!sUserManager.exists(userId)) { 2941 return null; 2942 } 2943 2944 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2945 "getPackageGids"); 2946 2947 // reader 2948 synchronized (mPackages) { 2949 final PackageParser.Package p = mPackages.get(packageName); 2950 if (p != null) { 2951 PackageSetting ps = (PackageSetting) p.mExtras; 2952 return ps.getPermissionsState().computeGids(userId); 2953 } 2954 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2955 final PackageSetting ps = mSettings.mPackages.get(packageName); 2956 if (ps != null) { 2957 return ps.getPermissionsState().computeGids(userId); 2958 } 2959 } 2960 } 2961 2962 return null; 2963 } 2964 2965 static PermissionInfo generatePermissionInfo( 2966 BasePermission bp, int flags) { 2967 if (bp.perm != null) { 2968 return PackageParser.generatePermissionInfo(bp.perm, flags); 2969 } 2970 PermissionInfo pi = new PermissionInfo(); 2971 pi.name = bp.name; 2972 pi.packageName = bp.sourcePackage; 2973 pi.nonLocalizedLabel = bp.name; 2974 pi.protectionLevel = bp.protectionLevel; 2975 return pi; 2976 } 2977 2978 @Override 2979 public PermissionInfo getPermissionInfo(String name, int flags) { 2980 // reader 2981 synchronized (mPackages) { 2982 final BasePermission p = mSettings.mPermissions.get(name); 2983 if (p != null) { 2984 return generatePermissionInfo(p, flags); 2985 } 2986 return null; 2987 } 2988 } 2989 2990 @Override 2991 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2992 // reader 2993 synchronized (mPackages) { 2994 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2995 for (BasePermission p : mSettings.mPermissions.values()) { 2996 if (group == null) { 2997 if (p.perm == null || p.perm.info.group == null) { 2998 out.add(generatePermissionInfo(p, flags)); 2999 } 3000 } else { 3001 if (p.perm != null && group.equals(p.perm.info.group)) { 3002 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3003 } 3004 } 3005 } 3006 3007 if (out.size() > 0) { 3008 return out; 3009 } 3010 return mPermissionGroups.containsKey(group) ? out : null; 3011 } 3012 } 3013 3014 @Override 3015 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3016 // reader 3017 synchronized (mPackages) { 3018 return PackageParser.generatePermissionGroupInfo( 3019 mPermissionGroups.get(name), flags); 3020 } 3021 } 3022 3023 @Override 3024 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3025 // reader 3026 synchronized (mPackages) { 3027 final int N = mPermissionGroups.size(); 3028 ArrayList<PermissionGroupInfo> out 3029 = new ArrayList<PermissionGroupInfo>(N); 3030 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3031 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3032 } 3033 return out; 3034 } 3035 } 3036 3037 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3038 int userId) { 3039 if (!sUserManager.exists(userId)) return null; 3040 PackageSetting ps = mSettings.mPackages.get(packageName); 3041 if (ps != null) { 3042 if (ps.pkg == null) { 3043 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 3044 flags, userId); 3045 if (pInfo != null) { 3046 return pInfo.applicationInfo; 3047 } 3048 return null; 3049 } 3050 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3051 ps.readUserState(userId), userId); 3052 } 3053 return null; 3054 } 3055 3056 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 3057 int userId) { 3058 if (!sUserManager.exists(userId)) return null; 3059 PackageSetting ps = mSettings.mPackages.get(packageName); 3060 if (ps != null) { 3061 PackageParser.Package pkg = ps.pkg; 3062 if (pkg == null) { 3063 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 3064 return null; 3065 } 3066 // Only data remains, so we aren't worried about code paths 3067 pkg = new PackageParser.Package(packageName); 3068 pkg.applicationInfo.packageName = packageName; 3069 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 3070 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 3071 pkg.applicationInfo.uid = ps.appId; 3072 pkg.applicationInfo.initForUser(userId); 3073 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 3074 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 3075 } 3076 return generatePackageInfo(pkg, flags, userId); 3077 } 3078 return null; 3079 } 3080 3081 @Override 3082 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3083 if (!sUserManager.exists(userId)) return null; 3084 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 3085 // writer 3086 synchronized (mPackages) { 3087 PackageParser.Package p = mPackages.get(packageName); 3088 if (DEBUG_PACKAGE_INFO) Log.v( 3089 TAG, "getApplicationInfo " + packageName 3090 + ": " + p); 3091 if (p != null) { 3092 PackageSetting ps = mSettings.mPackages.get(packageName); 3093 if (ps == null) return null; 3094 // Note: isEnabledLP() does not apply here - always return info 3095 return PackageParser.generateApplicationInfo( 3096 p, flags, ps.readUserState(userId), userId); 3097 } 3098 if ("android".equals(packageName)||"system".equals(packageName)) { 3099 return mAndroidApplication; 3100 } 3101 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 3102 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3103 } 3104 } 3105 return null; 3106 } 3107 3108 @Override 3109 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3110 final IPackageDataObserver observer) { 3111 mContext.enforceCallingOrSelfPermission( 3112 android.Manifest.permission.CLEAR_APP_CACHE, null); 3113 // Queue up an async operation since clearing cache may take a little while. 3114 mHandler.post(new Runnable() { 3115 public void run() { 3116 mHandler.removeCallbacks(this); 3117 int retCode = -1; 3118 synchronized (mInstallLock) { 3119 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 3120 if (retCode < 0) { 3121 Slog.w(TAG, "Couldn't clear application caches"); 3122 } 3123 } 3124 if (observer != null) { 3125 try { 3126 observer.onRemoveCompleted(null, (retCode >= 0)); 3127 } catch (RemoteException e) { 3128 Slog.w(TAG, "RemoveException when invoking call back"); 3129 } 3130 } 3131 } 3132 }); 3133 } 3134 3135 @Override 3136 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3137 final IntentSender pi) { 3138 mContext.enforceCallingOrSelfPermission( 3139 android.Manifest.permission.CLEAR_APP_CACHE, null); 3140 // Queue up an async operation since clearing cache may take a little while. 3141 mHandler.post(new Runnable() { 3142 public void run() { 3143 mHandler.removeCallbacks(this); 3144 int retCode = -1; 3145 synchronized (mInstallLock) { 3146 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 3147 if (retCode < 0) { 3148 Slog.w(TAG, "Couldn't clear application caches"); 3149 } 3150 } 3151 if(pi != null) { 3152 try { 3153 // Callback via pending intent 3154 int code = (retCode >= 0) ? 1 : 0; 3155 pi.sendIntent(null, code, null, 3156 null, null); 3157 } catch (SendIntentException e1) { 3158 Slog.i(TAG, "Failed to send pending intent"); 3159 } 3160 } 3161 } 3162 }); 3163 } 3164 3165 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3166 synchronized (mInstallLock) { 3167 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 3168 throw new IOException("Failed to free enough space"); 3169 } 3170 } 3171 } 3172 3173 /** 3174 * Return if the user key is currently unlocked. 3175 */ 3176 private boolean isUserKeyUnlocked(int userId) { 3177 if (StorageManager.isFileBasedEncryptionEnabled()) { 3178 final IMountService mount = IMountService.Stub 3179 .asInterface(ServiceManager.getService("mount")); 3180 if (mount == null) { 3181 Slog.w(TAG, "Early during boot, assuming locked"); 3182 return false; 3183 } 3184 final long token = Binder.clearCallingIdentity(); 3185 try { 3186 return mount.isUserKeyUnlocked(userId); 3187 } catch (RemoteException e) { 3188 throw e.rethrowAsRuntimeException(); 3189 } finally { 3190 Binder.restoreCallingIdentity(token); 3191 } 3192 } else { 3193 return true; 3194 } 3195 } 3196 3197 /** 3198 * Augment the given flags depending on current user running state. This is 3199 * purposefully done before acquiring {@link #mPackages} lock. 3200 */ 3201 private int augmentFlagsForUser(int flags, int userId) { 3202 if (!isUserKeyUnlocked(userId)) { 3203 flags |= PackageManager.MATCH_ENCRYPTION_AWARE_ONLY; 3204 } 3205 return flags; 3206 } 3207 3208 @Override 3209 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3210 if (!sUserManager.exists(userId)) return null; 3211 flags = augmentFlagsForUser(flags, userId); 3212 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 3213 synchronized (mPackages) { 3214 PackageParser.Activity a = mActivities.mActivities.get(component); 3215 3216 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3217 if (a != null && mSettings.isEnabledAndVisibleLPr(a.info, flags, userId)) { 3218 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3219 if (ps == null) return null; 3220 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3221 userId); 3222 } 3223 if (mResolveComponentName.equals(component)) { 3224 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3225 new PackageUserState(), userId); 3226 } 3227 } 3228 return null; 3229 } 3230 3231 @Override 3232 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3233 String resolvedType) { 3234 synchronized (mPackages) { 3235 if (component.equals(mResolveComponentName)) { 3236 // The resolver supports EVERYTHING! 3237 return true; 3238 } 3239 PackageParser.Activity a = mActivities.mActivities.get(component); 3240 if (a == null) { 3241 return false; 3242 } 3243 for (int i=0; i<a.intents.size(); i++) { 3244 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3245 intent.getData(), intent.getCategories(), TAG) >= 0) { 3246 return true; 3247 } 3248 } 3249 return false; 3250 } 3251 } 3252 3253 @Override 3254 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3255 if (!sUserManager.exists(userId)) return null; 3256 flags = augmentFlagsForUser(flags, userId); 3257 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 3258 synchronized (mPackages) { 3259 PackageParser.Activity a = mReceivers.mActivities.get(component); 3260 if (DEBUG_PACKAGE_INFO) Log.v( 3261 TAG, "getReceiverInfo " + component + ": " + a); 3262 if (a != null && mSettings.isEnabledAndVisibleLPr(a.info, flags, userId)) { 3263 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3264 if (ps == null) return null; 3265 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3266 userId); 3267 } 3268 } 3269 return null; 3270 } 3271 3272 @Override 3273 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3274 if (!sUserManager.exists(userId)) return null; 3275 flags = augmentFlagsForUser(flags, userId); 3276 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 3277 synchronized (mPackages) { 3278 PackageParser.Service s = mServices.mServices.get(component); 3279 if (DEBUG_PACKAGE_INFO) Log.v( 3280 TAG, "getServiceInfo " + component + ": " + s); 3281 if (s != null && mSettings.isEnabledAndVisibleLPr(s.info, flags, userId)) { 3282 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3283 if (ps == null) return null; 3284 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3285 userId); 3286 } 3287 } 3288 return null; 3289 } 3290 3291 @Override 3292 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3293 if (!sUserManager.exists(userId)) return null; 3294 flags = augmentFlagsForUser(flags, userId); 3295 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 3296 synchronized (mPackages) { 3297 PackageParser.Provider p = mProviders.mProviders.get(component); 3298 if (DEBUG_PACKAGE_INFO) Log.v( 3299 TAG, "getProviderInfo " + component + ": " + p); 3300 if (p != null && mSettings.isEnabledAndVisibleLPr(p.info, flags, userId)) { 3301 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3302 if (ps == null) return null; 3303 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3304 userId); 3305 } 3306 } 3307 return null; 3308 } 3309 3310 @Override 3311 public String[] getSystemSharedLibraryNames() { 3312 Set<String> libSet; 3313 synchronized (mPackages) { 3314 libSet = mSharedLibraries.keySet(); 3315 int size = libSet.size(); 3316 if (size > 0) { 3317 String[] libs = new String[size]; 3318 libSet.toArray(libs); 3319 return libs; 3320 } 3321 } 3322 return null; 3323 } 3324 3325 /** 3326 * @hide 3327 */ 3328 PackageParser.Package findSharedNonSystemLibrary(String libName) { 3329 synchronized (mPackages) { 3330 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 3331 if (lib != null && lib.apk != null) { 3332 return mPackages.get(lib.apk); 3333 } 3334 } 3335 return null; 3336 } 3337 3338 @Override 3339 public FeatureInfo[] getSystemAvailableFeatures() { 3340 Collection<FeatureInfo> featSet; 3341 synchronized (mPackages) { 3342 featSet = mAvailableFeatures.values(); 3343 int size = featSet.size(); 3344 if (size > 0) { 3345 FeatureInfo[] features = new FeatureInfo[size+1]; 3346 featSet.toArray(features); 3347 FeatureInfo fi = new FeatureInfo(); 3348 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3349 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3350 features[size] = fi; 3351 return features; 3352 } 3353 } 3354 return null; 3355 } 3356 3357 @Override 3358 public boolean hasSystemFeature(String name) { 3359 synchronized (mPackages) { 3360 return mAvailableFeatures.containsKey(name); 3361 } 3362 } 3363 3364 private void checkValidCaller(int uid, int userId) { 3365 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 3366 return; 3367 3368 throw new SecurityException("Caller uid=" + uid 3369 + " is not privileged to communicate with user=" + userId); 3370 } 3371 3372 @Override 3373 public int checkPermission(String permName, String pkgName, int userId) { 3374 if (!sUserManager.exists(userId)) { 3375 return PackageManager.PERMISSION_DENIED; 3376 } 3377 3378 synchronized (mPackages) { 3379 final PackageParser.Package p = mPackages.get(pkgName); 3380 if (p != null && p.mExtras != null) { 3381 final PackageSetting ps = (PackageSetting) p.mExtras; 3382 final PermissionsState permissionsState = ps.getPermissionsState(); 3383 if (permissionsState.hasPermission(permName, userId)) { 3384 return PackageManager.PERMISSION_GRANTED; 3385 } 3386 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3387 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3388 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3389 return PackageManager.PERMISSION_GRANTED; 3390 } 3391 } 3392 } 3393 3394 return PackageManager.PERMISSION_DENIED; 3395 } 3396 3397 @Override 3398 public int checkUidPermission(String permName, int uid) { 3399 final int userId = UserHandle.getUserId(uid); 3400 3401 if (!sUserManager.exists(userId)) { 3402 return PackageManager.PERMISSION_DENIED; 3403 } 3404 3405 synchronized (mPackages) { 3406 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3407 if (obj != null) { 3408 final SettingBase ps = (SettingBase) obj; 3409 final PermissionsState permissionsState = ps.getPermissionsState(); 3410 if (permissionsState.hasPermission(permName, userId)) { 3411 return PackageManager.PERMISSION_GRANTED; 3412 } 3413 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3414 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3415 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3416 return PackageManager.PERMISSION_GRANTED; 3417 } 3418 } else { 3419 ArraySet<String> perms = mSystemPermissions.get(uid); 3420 if (perms != null) { 3421 if (perms.contains(permName)) { 3422 return PackageManager.PERMISSION_GRANTED; 3423 } 3424 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3425 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3426 return PackageManager.PERMISSION_GRANTED; 3427 } 3428 } 3429 } 3430 } 3431 3432 return PackageManager.PERMISSION_DENIED; 3433 } 3434 3435 @Override 3436 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3437 if (UserHandle.getCallingUserId() != userId) { 3438 mContext.enforceCallingPermission( 3439 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3440 "isPermissionRevokedByPolicy for user " + userId); 3441 } 3442 3443 if (checkPermission(permission, packageName, userId) 3444 == PackageManager.PERMISSION_GRANTED) { 3445 return false; 3446 } 3447 3448 final long identity = Binder.clearCallingIdentity(); 3449 try { 3450 final int flags = getPermissionFlags(permission, packageName, userId); 3451 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3452 } finally { 3453 Binder.restoreCallingIdentity(identity); 3454 } 3455 } 3456 3457 @Override 3458 public String getPermissionControllerPackageName() { 3459 synchronized (mPackages) { 3460 return mRequiredInstallerPackage; 3461 } 3462 } 3463 3464 /** 3465 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3466 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3467 * @param checkShell TODO(yamasani): 3468 * @param message the message to log on security exception 3469 */ 3470 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3471 boolean checkShell, String message) { 3472 if (userId < 0) { 3473 throw new IllegalArgumentException("Invalid userId " + userId); 3474 } 3475 if (checkShell) { 3476 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3477 } 3478 if (userId == UserHandle.getUserId(callingUid)) return; 3479 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3480 if (requireFullPermission) { 3481 mContext.enforceCallingOrSelfPermission( 3482 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3483 } else { 3484 try { 3485 mContext.enforceCallingOrSelfPermission( 3486 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3487 } catch (SecurityException se) { 3488 mContext.enforceCallingOrSelfPermission( 3489 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3490 } 3491 } 3492 } 3493 } 3494 3495 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3496 if (callingUid == Process.SHELL_UID) { 3497 if (userHandle >= 0 3498 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3499 throw new SecurityException("Shell does not have permission to access user " 3500 + userHandle); 3501 } else if (userHandle < 0) { 3502 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3503 + Debug.getCallers(3)); 3504 } 3505 } 3506 } 3507 3508 private BasePermission findPermissionTreeLP(String permName) { 3509 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3510 if (permName.startsWith(bp.name) && 3511 permName.length() > bp.name.length() && 3512 permName.charAt(bp.name.length()) == '.') { 3513 return bp; 3514 } 3515 } 3516 return null; 3517 } 3518 3519 private BasePermission checkPermissionTreeLP(String permName) { 3520 if (permName != null) { 3521 BasePermission bp = findPermissionTreeLP(permName); 3522 if (bp != null) { 3523 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3524 return bp; 3525 } 3526 throw new SecurityException("Calling uid " 3527 + Binder.getCallingUid() 3528 + " is not allowed to add to permission tree " 3529 + bp.name + " owned by uid " + bp.uid); 3530 } 3531 } 3532 throw new SecurityException("No permission tree found for " + permName); 3533 } 3534 3535 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3536 if (s1 == null) { 3537 return s2 == null; 3538 } 3539 if (s2 == null) { 3540 return false; 3541 } 3542 if (s1.getClass() != s2.getClass()) { 3543 return false; 3544 } 3545 return s1.equals(s2); 3546 } 3547 3548 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3549 if (pi1.icon != pi2.icon) return false; 3550 if (pi1.logo != pi2.logo) return false; 3551 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3552 if (!compareStrings(pi1.name, pi2.name)) return false; 3553 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3554 // We'll take care of setting this one. 3555 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3556 // These are not currently stored in settings. 3557 //if (!compareStrings(pi1.group, pi2.group)) return false; 3558 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3559 //if (pi1.labelRes != pi2.labelRes) return false; 3560 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3561 return true; 3562 } 3563 3564 int permissionInfoFootprint(PermissionInfo info) { 3565 int size = info.name.length(); 3566 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3567 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3568 return size; 3569 } 3570 3571 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3572 int size = 0; 3573 for (BasePermission perm : mSettings.mPermissions.values()) { 3574 if (perm.uid == tree.uid) { 3575 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3576 } 3577 } 3578 return size; 3579 } 3580 3581 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3582 // We calculate the max size of permissions defined by this uid and throw 3583 // if that plus the size of 'info' would exceed our stated maximum. 3584 if (tree.uid != Process.SYSTEM_UID) { 3585 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3586 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3587 throw new SecurityException("Permission tree size cap exceeded"); 3588 } 3589 } 3590 } 3591 3592 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3593 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3594 throw new SecurityException("Label must be specified in permission"); 3595 } 3596 BasePermission tree = checkPermissionTreeLP(info.name); 3597 BasePermission bp = mSettings.mPermissions.get(info.name); 3598 boolean added = bp == null; 3599 boolean changed = true; 3600 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3601 if (added) { 3602 enforcePermissionCapLocked(info, tree); 3603 bp = new BasePermission(info.name, tree.sourcePackage, 3604 BasePermission.TYPE_DYNAMIC); 3605 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3606 throw new SecurityException( 3607 "Not allowed to modify non-dynamic permission " 3608 + info.name); 3609 } else { 3610 if (bp.protectionLevel == fixedLevel 3611 && bp.perm.owner.equals(tree.perm.owner) 3612 && bp.uid == tree.uid 3613 && comparePermissionInfos(bp.perm.info, info)) { 3614 changed = false; 3615 } 3616 } 3617 bp.protectionLevel = fixedLevel; 3618 info = new PermissionInfo(info); 3619 info.protectionLevel = fixedLevel; 3620 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3621 bp.perm.info.packageName = tree.perm.info.packageName; 3622 bp.uid = tree.uid; 3623 if (added) { 3624 mSettings.mPermissions.put(info.name, bp); 3625 } 3626 if (changed) { 3627 if (!async) { 3628 mSettings.writeLPr(); 3629 } else { 3630 scheduleWriteSettingsLocked(); 3631 } 3632 } 3633 return added; 3634 } 3635 3636 @Override 3637 public boolean addPermission(PermissionInfo info) { 3638 synchronized (mPackages) { 3639 return addPermissionLocked(info, false); 3640 } 3641 } 3642 3643 @Override 3644 public boolean addPermissionAsync(PermissionInfo info) { 3645 synchronized (mPackages) { 3646 return addPermissionLocked(info, true); 3647 } 3648 } 3649 3650 @Override 3651 public void removePermission(String name) { 3652 synchronized (mPackages) { 3653 checkPermissionTreeLP(name); 3654 BasePermission bp = mSettings.mPermissions.get(name); 3655 if (bp != null) { 3656 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3657 throw new SecurityException( 3658 "Not allowed to modify non-dynamic permission " 3659 + name); 3660 } 3661 mSettings.mPermissions.remove(name); 3662 mSettings.writeLPr(); 3663 } 3664 } 3665 } 3666 3667 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 3668 BasePermission bp) { 3669 int index = pkg.requestedPermissions.indexOf(bp.name); 3670 if (index == -1) { 3671 throw new SecurityException("Package " + pkg.packageName 3672 + " has not requested permission " + bp.name); 3673 } 3674 if (!bp.isRuntime() && !bp.isDevelopment()) { 3675 throw new SecurityException("Permission " + bp.name 3676 + " is not a changeable permission type"); 3677 } 3678 } 3679 3680 @Override 3681 public void grantRuntimePermission(String packageName, String name, final int userId) { 3682 if (!sUserManager.exists(userId)) { 3683 Log.e(TAG, "No such user:" + userId); 3684 return; 3685 } 3686 3687 mContext.enforceCallingOrSelfPermission( 3688 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3689 "grantRuntimePermission"); 3690 3691 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3692 "grantRuntimePermission"); 3693 3694 final int uid; 3695 final SettingBase sb; 3696 3697 synchronized (mPackages) { 3698 final PackageParser.Package pkg = mPackages.get(packageName); 3699 if (pkg == null) { 3700 throw new IllegalArgumentException("Unknown package: " + packageName); 3701 } 3702 3703 final BasePermission bp = mSettings.mPermissions.get(name); 3704 if (bp == null) { 3705 throw new IllegalArgumentException("Unknown permission: " + name); 3706 } 3707 3708 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3709 3710 // If a permission review is required for legacy apps we represent 3711 // their permissions as always granted runtime ones since we need 3712 // to keep the review required permission flag per user while an 3713 // install permission's state is shared across all users. 3714 if (Build.PERMISSIONS_REVIEW_REQUIRED 3715 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 3716 && bp.isRuntime()) { 3717 return; 3718 } 3719 3720 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3721 sb = (SettingBase) pkg.mExtras; 3722 if (sb == null) { 3723 throw new IllegalArgumentException("Unknown package: " + packageName); 3724 } 3725 3726 final PermissionsState permissionsState = sb.getPermissionsState(); 3727 3728 final int flags = permissionsState.getPermissionFlags(name, userId); 3729 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3730 throw new SecurityException("Cannot grant system fixed permission: " 3731 + name + " for package: " + packageName); 3732 } 3733 3734 if (bp.isDevelopment()) { 3735 // Development permissions must be handled specially, since they are not 3736 // normal runtime permissions. For now they apply to all users. 3737 if (permissionsState.grantInstallPermission(bp) != 3738 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3739 scheduleWriteSettingsLocked(); 3740 } 3741 return; 3742 } 3743 3744 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 3745 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 3746 return; 3747 } 3748 3749 final int result = permissionsState.grantRuntimePermission(bp, userId); 3750 switch (result) { 3751 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3752 return; 3753 } 3754 3755 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3756 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3757 mHandler.post(new Runnable() { 3758 @Override 3759 public void run() { 3760 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 3761 } 3762 }); 3763 } 3764 break; 3765 } 3766 3767 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3768 3769 // Not critical if that is lost - app has to request again. 3770 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3771 } 3772 3773 // Only need to do this if user is initialized. Otherwise it's a new user 3774 // and there are no processes running as the user yet and there's no need 3775 // to make an expensive call to remount processes for the changed permissions. 3776 if (READ_EXTERNAL_STORAGE.equals(name) 3777 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3778 final long token = Binder.clearCallingIdentity(); 3779 try { 3780 if (sUserManager.isInitialized(userId)) { 3781 MountServiceInternal mountServiceInternal = LocalServices.getService( 3782 MountServiceInternal.class); 3783 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 3784 } 3785 } finally { 3786 Binder.restoreCallingIdentity(token); 3787 } 3788 } 3789 } 3790 3791 @Override 3792 public void revokeRuntimePermission(String packageName, String name, int userId) { 3793 if (!sUserManager.exists(userId)) { 3794 Log.e(TAG, "No such user:" + userId); 3795 return; 3796 } 3797 3798 mContext.enforceCallingOrSelfPermission( 3799 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3800 "revokeRuntimePermission"); 3801 3802 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3803 "revokeRuntimePermission"); 3804 3805 final int appId; 3806 3807 synchronized (mPackages) { 3808 final PackageParser.Package pkg = mPackages.get(packageName); 3809 if (pkg == null) { 3810 throw new IllegalArgumentException("Unknown package: " + packageName); 3811 } 3812 3813 final BasePermission bp = mSettings.mPermissions.get(name); 3814 if (bp == null) { 3815 throw new IllegalArgumentException("Unknown permission: " + name); 3816 } 3817 3818 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3819 3820 // If a permission review is required for legacy apps we represent 3821 // their permissions as always granted runtime ones since we need 3822 // to keep the review required permission flag per user while an 3823 // install permission's state is shared across all users. 3824 if (Build.PERMISSIONS_REVIEW_REQUIRED 3825 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 3826 && bp.isRuntime()) { 3827 return; 3828 } 3829 3830 SettingBase sb = (SettingBase) pkg.mExtras; 3831 if (sb == null) { 3832 throw new IllegalArgumentException("Unknown package: " + packageName); 3833 } 3834 3835 final PermissionsState permissionsState = sb.getPermissionsState(); 3836 3837 final int flags = permissionsState.getPermissionFlags(name, userId); 3838 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3839 throw new SecurityException("Cannot revoke system fixed permission: " 3840 + name + " for package: " + packageName); 3841 } 3842 3843 if (bp.isDevelopment()) { 3844 // Development permissions must be handled specially, since they are not 3845 // normal runtime permissions. For now they apply to all users. 3846 if (permissionsState.revokeInstallPermission(bp) != 3847 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3848 scheduleWriteSettingsLocked(); 3849 } 3850 return; 3851 } 3852 3853 if (permissionsState.revokeRuntimePermission(bp, userId) == 3854 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3855 return; 3856 } 3857 3858 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3859 3860 // Critical, after this call app should never have the permission. 3861 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3862 3863 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3864 } 3865 3866 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3867 } 3868 3869 @Override 3870 public void resetRuntimePermissions() { 3871 mContext.enforceCallingOrSelfPermission( 3872 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3873 "revokeRuntimePermission"); 3874 3875 int callingUid = Binder.getCallingUid(); 3876 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3877 mContext.enforceCallingOrSelfPermission( 3878 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3879 "resetRuntimePermissions"); 3880 } 3881 3882 synchronized (mPackages) { 3883 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 3884 for (int userId : UserManagerService.getInstance().getUserIds()) { 3885 final int packageCount = mPackages.size(); 3886 for (int i = 0; i < packageCount; i++) { 3887 PackageParser.Package pkg = mPackages.valueAt(i); 3888 if (!(pkg.mExtras instanceof PackageSetting)) { 3889 continue; 3890 } 3891 PackageSetting ps = (PackageSetting) pkg.mExtras; 3892 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 3893 } 3894 } 3895 } 3896 } 3897 3898 @Override 3899 public int getPermissionFlags(String name, String packageName, int userId) { 3900 if (!sUserManager.exists(userId)) { 3901 return 0; 3902 } 3903 3904 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 3905 3906 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3907 "getPermissionFlags"); 3908 3909 synchronized (mPackages) { 3910 final PackageParser.Package pkg = mPackages.get(packageName); 3911 if (pkg == null) { 3912 throw new IllegalArgumentException("Unknown package: " + packageName); 3913 } 3914 3915 final BasePermission bp = mSettings.mPermissions.get(name); 3916 if (bp == null) { 3917 throw new IllegalArgumentException("Unknown permission: " + name); 3918 } 3919 3920 SettingBase sb = (SettingBase) pkg.mExtras; 3921 if (sb == null) { 3922 throw new IllegalArgumentException("Unknown package: " + packageName); 3923 } 3924 3925 PermissionsState permissionsState = sb.getPermissionsState(); 3926 return permissionsState.getPermissionFlags(name, userId); 3927 } 3928 } 3929 3930 @Override 3931 public void updatePermissionFlags(String name, String packageName, int flagMask, 3932 int flagValues, int userId) { 3933 if (!sUserManager.exists(userId)) { 3934 return; 3935 } 3936 3937 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 3938 3939 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3940 "updatePermissionFlags"); 3941 3942 // Only the system can change these flags and nothing else. 3943 if (getCallingUid() != Process.SYSTEM_UID) { 3944 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3945 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3946 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3947 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3948 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 3949 } 3950 3951 synchronized (mPackages) { 3952 final PackageParser.Package pkg = mPackages.get(packageName); 3953 if (pkg == null) { 3954 throw new IllegalArgumentException("Unknown package: " + packageName); 3955 } 3956 3957 final BasePermission bp = mSettings.mPermissions.get(name); 3958 if (bp == null) { 3959 throw new IllegalArgumentException("Unknown permission: " + name); 3960 } 3961 3962 SettingBase sb = (SettingBase) pkg.mExtras; 3963 if (sb == null) { 3964 throw new IllegalArgumentException("Unknown package: " + packageName); 3965 } 3966 3967 PermissionsState permissionsState = sb.getPermissionsState(); 3968 3969 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 3970 3971 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3972 // Install and runtime permissions are stored in different places, 3973 // so figure out what permission changed and persist the change. 3974 if (permissionsState.getInstallPermissionState(name) != null) { 3975 scheduleWriteSettingsLocked(); 3976 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 3977 || hadState) { 3978 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3979 } 3980 } 3981 } 3982 } 3983 3984 /** 3985 * Update the permission flags for all packages and runtime permissions of a user in order 3986 * to allow device or profile owner to remove POLICY_FIXED. 3987 */ 3988 @Override 3989 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 3990 if (!sUserManager.exists(userId)) { 3991 return; 3992 } 3993 3994 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 3995 3996 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3997 "updatePermissionFlagsForAllApps"); 3998 3999 // Only the system can change system fixed flags. 4000 if (getCallingUid() != Process.SYSTEM_UID) { 4001 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4002 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4003 } 4004 4005 synchronized (mPackages) { 4006 boolean changed = false; 4007 final int packageCount = mPackages.size(); 4008 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4009 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4010 SettingBase sb = (SettingBase) pkg.mExtras; 4011 if (sb == null) { 4012 continue; 4013 } 4014 PermissionsState permissionsState = sb.getPermissionsState(); 4015 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4016 userId, flagMask, flagValues); 4017 } 4018 if (changed) { 4019 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4020 } 4021 } 4022 } 4023 4024 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4025 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4026 != PackageManager.PERMISSION_GRANTED 4027 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4028 != PackageManager.PERMISSION_GRANTED) { 4029 throw new SecurityException(message + " requires " 4030 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4031 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4032 } 4033 } 4034 4035 @Override 4036 public boolean shouldShowRequestPermissionRationale(String permissionName, 4037 String packageName, int userId) { 4038 if (UserHandle.getCallingUserId() != userId) { 4039 mContext.enforceCallingPermission( 4040 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4041 "canShowRequestPermissionRationale for user " + userId); 4042 } 4043 4044 final int uid = getPackageUid(packageName, userId); 4045 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4046 return false; 4047 } 4048 4049 if (checkPermission(permissionName, packageName, userId) 4050 == PackageManager.PERMISSION_GRANTED) { 4051 return false; 4052 } 4053 4054 final int flags; 4055 4056 final long identity = Binder.clearCallingIdentity(); 4057 try { 4058 flags = getPermissionFlags(permissionName, 4059 packageName, userId); 4060 } finally { 4061 Binder.restoreCallingIdentity(identity); 4062 } 4063 4064 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4065 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4066 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4067 4068 if ((flags & fixedFlags) != 0) { 4069 return false; 4070 } 4071 4072 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4073 } 4074 4075 @Override 4076 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4077 mContext.enforceCallingOrSelfPermission( 4078 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4079 "addOnPermissionsChangeListener"); 4080 4081 synchronized (mPackages) { 4082 mOnPermissionChangeListeners.addListenerLocked(listener); 4083 } 4084 } 4085 4086 @Override 4087 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4088 synchronized (mPackages) { 4089 mOnPermissionChangeListeners.removeListenerLocked(listener); 4090 } 4091 } 4092 4093 @Override 4094 public boolean isProtectedBroadcast(String actionName) { 4095 synchronized (mPackages) { 4096 return mProtectedBroadcasts.contains(actionName); 4097 } 4098 } 4099 4100 @Override 4101 public int checkSignatures(String pkg1, String pkg2) { 4102 synchronized (mPackages) { 4103 final PackageParser.Package p1 = mPackages.get(pkg1); 4104 final PackageParser.Package p2 = mPackages.get(pkg2); 4105 if (p1 == null || p1.mExtras == null 4106 || p2 == null || p2.mExtras == null) { 4107 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4108 } 4109 return compareSignatures(p1.mSignatures, p2.mSignatures); 4110 } 4111 } 4112 4113 @Override 4114 public int checkUidSignatures(int uid1, int uid2) { 4115 // Map to base uids. 4116 uid1 = UserHandle.getAppId(uid1); 4117 uid2 = UserHandle.getAppId(uid2); 4118 // reader 4119 synchronized (mPackages) { 4120 Signature[] s1; 4121 Signature[] s2; 4122 Object obj = mSettings.getUserIdLPr(uid1); 4123 if (obj != null) { 4124 if (obj instanceof SharedUserSetting) { 4125 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4126 } else if (obj instanceof PackageSetting) { 4127 s1 = ((PackageSetting)obj).signatures.mSignatures; 4128 } else { 4129 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4130 } 4131 } else { 4132 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4133 } 4134 obj = mSettings.getUserIdLPr(uid2); 4135 if (obj != null) { 4136 if (obj instanceof SharedUserSetting) { 4137 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4138 } else if (obj instanceof PackageSetting) { 4139 s2 = ((PackageSetting)obj).signatures.mSignatures; 4140 } else { 4141 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4142 } 4143 } else { 4144 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4145 } 4146 return compareSignatures(s1, s2); 4147 } 4148 } 4149 4150 private void killUid(int appId, int userId, String reason) { 4151 final long identity = Binder.clearCallingIdentity(); 4152 try { 4153 IActivityManager am = ActivityManagerNative.getDefault(); 4154 if (am != null) { 4155 try { 4156 am.killUid(appId, userId, reason); 4157 } catch (RemoteException e) { 4158 /* ignore - same process */ 4159 } 4160 } 4161 } finally { 4162 Binder.restoreCallingIdentity(identity); 4163 } 4164 } 4165 4166 /** 4167 * Compares two sets of signatures. Returns: 4168 * <br /> 4169 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4170 * <br /> 4171 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4172 * <br /> 4173 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4174 * <br /> 4175 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4176 * <br /> 4177 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4178 */ 4179 static int compareSignatures(Signature[] s1, Signature[] s2) { 4180 if (s1 == null) { 4181 return s2 == null 4182 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4183 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4184 } 4185 4186 if (s2 == null) { 4187 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4188 } 4189 4190 if (s1.length != s2.length) { 4191 return PackageManager.SIGNATURE_NO_MATCH; 4192 } 4193 4194 // Since both signature sets are of size 1, we can compare without HashSets. 4195 if (s1.length == 1) { 4196 return s1[0].equals(s2[0]) ? 4197 PackageManager.SIGNATURE_MATCH : 4198 PackageManager.SIGNATURE_NO_MATCH; 4199 } 4200 4201 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4202 for (Signature sig : s1) { 4203 set1.add(sig); 4204 } 4205 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4206 for (Signature sig : s2) { 4207 set2.add(sig); 4208 } 4209 // Make sure s2 contains all signatures in s1. 4210 if (set1.equals(set2)) { 4211 return PackageManager.SIGNATURE_MATCH; 4212 } 4213 return PackageManager.SIGNATURE_NO_MATCH; 4214 } 4215 4216 /** 4217 * If the database version for this type of package (internal storage or 4218 * external storage) is less than the version where package signatures 4219 * were updated, return true. 4220 */ 4221 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4222 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4223 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4224 } 4225 4226 /** 4227 * Used for backward compatibility to make sure any packages with 4228 * certificate chains get upgraded to the new style. {@code existingSigs} 4229 * will be in the old format (since they were stored on disk from before the 4230 * system upgrade) and {@code scannedSigs} will be in the newer format. 4231 */ 4232 private int compareSignaturesCompat(PackageSignatures existingSigs, 4233 PackageParser.Package scannedPkg) { 4234 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4235 return PackageManager.SIGNATURE_NO_MATCH; 4236 } 4237 4238 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4239 for (Signature sig : existingSigs.mSignatures) { 4240 existingSet.add(sig); 4241 } 4242 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4243 for (Signature sig : scannedPkg.mSignatures) { 4244 try { 4245 Signature[] chainSignatures = sig.getChainSignatures(); 4246 for (Signature chainSig : chainSignatures) { 4247 scannedCompatSet.add(chainSig); 4248 } 4249 } catch (CertificateEncodingException e) { 4250 scannedCompatSet.add(sig); 4251 } 4252 } 4253 /* 4254 * Make sure the expanded scanned set contains all signatures in the 4255 * existing one. 4256 */ 4257 if (scannedCompatSet.equals(existingSet)) { 4258 // Migrate the old signatures to the new scheme. 4259 existingSigs.assignSignatures(scannedPkg.mSignatures); 4260 // The new KeySets will be re-added later in the scanning process. 4261 synchronized (mPackages) { 4262 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4263 } 4264 return PackageManager.SIGNATURE_MATCH; 4265 } 4266 return PackageManager.SIGNATURE_NO_MATCH; 4267 } 4268 4269 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4270 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4271 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4272 } 4273 4274 private int compareSignaturesRecover(PackageSignatures existingSigs, 4275 PackageParser.Package scannedPkg) { 4276 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4277 return PackageManager.SIGNATURE_NO_MATCH; 4278 } 4279 4280 String msg = null; 4281 try { 4282 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4283 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4284 + scannedPkg.packageName); 4285 return PackageManager.SIGNATURE_MATCH; 4286 } 4287 } catch (CertificateException e) { 4288 msg = e.getMessage(); 4289 } 4290 4291 logCriticalInfo(Log.INFO, 4292 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4293 return PackageManager.SIGNATURE_NO_MATCH; 4294 } 4295 4296 @Override 4297 public String[] getPackagesForUid(int uid) { 4298 uid = UserHandle.getAppId(uid); 4299 // reader 4300 synchronized (mPackages) { 4301 Object obj = mSettings.getUserIdLPr(uid); 4302 if (obj instanceof SharedUserSetting) { 4303 final SharedUserSetting sus = (SharedUserSetting) obj; 4304 final int N = sus.packages.size(); 4305 final String[] res = new String[N]; 4306 final Iterator<PackageSetting> it = sus.packages.iterator(); 4307 int i = 0; 4308 while (it.hasNext()) { 4309 res[i++] = it.next().name; 4310 } 4311 return res; 4312 } else if (obj instanceof PackageSetting) { 4313 final PackageSetting ps = (PackageSetting) obj; 4314 return new String[] { ps.name }; 4315 } 4316 } 4317 return null; 4318 } 4319 4320 @Override 4321 public String getNameForUid(int uid) { 4322 // reader 4323 synchronized (mPackages) { 4324 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4325 if (obj instanceof SharedUserSetting) { 4326 final SharedUserSetting sus = (SharedUserSetting) obj; 4327 return sus.name + ":" + sus.userId; 4328 } else if (obj instanceof PackageSetting) { 4329 final PackageSetting ps = (PackageSetting) obj; 4330 return ps.name; 4331 } 4332 } 4333 return null; 4334 } 4335 4336 @Override 4337 public int getUidForSharedUser(String sharedUserName) { 4338 if(sharedUserName == null) { 4339 return -1; 4340 } 4341 // reader 4342 synchronized (mPackages) { 4343 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4344 if (suid == null) { 4345 return -1; 4346 } 4347 return suid.userId; 4348 } 4349 } 4350 4351 @Override 4352 public int getFlagsForUid(int uid) { 4353 synchronized (mPackages) { 4354 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4355 if (obj instanceof SharedUserSetting) { 4356 final SharedUserSetting sus = (SharedUserSetting) obj; 4357 return sus.pkgFlags; 4358 } else if (obj instanceof PackageSetting) { 4359 final PackageSetting ps = (PackageSetting) obj; 4360 return ps.pkgFlags; 4361 } 4362 } 4363 return 0; 4364 } 4365 4366 @Override 4367 public int getPrivateFlagsForUid(int uid) { 4368 synchronized (mPackages) { 4369 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4370 if (obj instanceof SharedUserSetting) { 4371 final SharedUserSetting sus = (SharedUserSetting) obj; 4372 return sus.pkgPrivateFlags; 4373 } else if (obj instanceof PackageSetting) { 4374 final PackageSetting ps = (PackageSetting) obj; 4375 return ps.pkgPrivateFlags; 4376 } 4377 } 4378 return 0; 4379 } 4380 4381 @Override 4382 public boolean isUidPrivileged(int uid) { 4383 uid = UserHandle.getAppId(uid); 4384 // reader 4385 synchronized (mPackages) { 4386 Object obj = mSettings.getUserIdLPr(uid); 4387 if (obj instanceof SharedUserSetting) { 4388 final SharedUserSetting sus = (SharedUserSetting) obj; 4389 final Iterator<PackageSetting> it = sus.packages.iterator(); 4390 while (it.hasNext()) { 4391 if (it.next().isPrivileged()) { 4392 return true; 4393 } 4394 } 4395 } else if (obj instanceof PackageSetting) { 4396 final PackageSetting ps = (PackageSetting) obj; 4397 return ps.isPrivileged(); 4398 } 4399 } 4400 return false; 4401 } 4402 4403 @Override 4404 public String[] getAppOpPermissionPackages(String permissionName) { 4405 synchronized (mPackages) { 4406 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4407 if (pkgs == null) { 4408 return null; 4409 } 4410 return pkgs.toArray(new String[pkgs.size()]); 4411 } 4412 } 4413 4414 @Override 4415 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4416 int flags, int userId) { 4417 if (!sUserManager.exists(userId)) return null; 4418 flags = augmentFlagsForUser(flags, userId); 4419 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 4420 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4421 return chooseBestActivity(intent, resolvedType, flags, query, userId); 4422 } 4423 4424 @Override 4425 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4426 IntentFilter filter, int match, ComponentName activity) { 4427 final int userId = UserHandle.getCallingUserId(); 4428 if (DEBUG_PREFERRED) { 4429 Log.v(TAG, "setLastChosenActivity intent=" + intent 4430 + " resolvedType=" + resolvedType 4431 + " flags=" + flags 4432 + " filter=" + filter 4433 + " match=" + match 4434 + " activity=" + activity); 4435 filter.dump(new PrintStreamPrinter(System.out), " "); 4436 } 4437 intent.setComponent(null); 4438 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4439 // Find any earlier preferred or last chosen entries and nuke them 4440 findPreferredActivity(intent, resolvedType, 4441 flags, query, 0, false, true, false, userId); 4442 // Add the new activity as the last chosen for this filter 4443 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4444 "Setting last chosen"); 4445 } 4446 4447 @Override 4448 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4449 final int userId = UserHandle.getCallingUserId(); 4450 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4451 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4452 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4453 false, false, false, userId); 4454 } 4455 4456 private boolean isEphemeralAvailable(Intent intent, String resolvedType, int userId) { 4457 MessageDigest digest = null; 4458 try { 4459 digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM); 4460 } catch (NoSuchAlgorithmException e) { 4461 // If we can't create a digest, ignore ephemeral apps. 4462 return false; 4463 } 4464 4465 final byte[] hostBytes = intent.getData().getHost().getBytes(); 4466 final byte[] digestBytes = digest.digest(hostBytes); 4467 int shaPrefix = 4468 digestBytes[0] << 24 4469 | digestBytes[1] << 16 4470 | digestBytes[2] << 8 4471 | digestBytes[3] << 0; 4472 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4473 mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix); 4474 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4475 // No hash prefix match; there are no ephemeral apps for this domain. 4476 return false; 4477 } 4478 for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) { 4479 EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i); 4480 if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) { 4481 continue; 4482 } 4483 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4484 // No filters; this should never happen. 4485 if (filters.isEmpty()) { 4486 continue; 4487 } 4488 // We have a domain match; resolve the filters to see if anything matches. 4489 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4490 for (int j = filters.size() - 1; j >= 0; --j) { 4491 ephemeralResolver.addFilter(filters.get(j)); 4492 } 4493 List<ResolveInfo> ephemeralResolveList = ephemeralResolver.queryIntent( 4494 intent, resolvedType, false /*defaultOnly*/, userId); 4495 return !ephemeralResolveList.isEmpty(); 4496 } 4497 // Hash or filter mis-match; no ephemeral apps for this domain. 4498 return false; 4499 } 4500 4501 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4502 int flags, List<ResolveInfo> query, int userId) { 4503 final boolean isWebUri = hasWebURI(intent); 4504 // Check whether or not an ephemeral app exists to handle the URI. 4505 if (isWebUri && mEphemeralResolverConnection != null) { 4506 // Deny ephemeral apps if the user choose _ALWAYS or _ALWAYS_ASK for intent resolution. 4507 boolean hasAlwaysHandler = false; 4508 synchronized (mPackages) { 4509 final int count = query.size(); 4510 for (int n=0; n<count; n++) { 4511 ResolveInfo info = query.get(n); 4512 String packageName = info.activityInfo.packageName; 4513 PackageSetting ps = mSettings.mPackages.get(packageName); 4514 if (ps != null) { 4515 // Try to get the status from User settings first 4516 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4517 int status = (int) (packedStatus >> 32); 4518 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4519 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4520 hasAlwaysHandler = true; 4521 break; 4522 } 4523 } 4524 } 4525 } 4526 4527 // Only consider installing an ephemeral app if there isn't already a verified handler. 4528 // We've determined that there's an ephemeral app available for the URI, ignore any 4529 // ResolveInfo's and just return the ephemeral installer 4530 if (!hasAlwaysHandler && isEphemeralAvailable(intent, resolvedType, userId)) { 4531 if (DEBUG_EPHEMERAL) { 4532 Slog.v(TAG, "Resolving to the ephemeral installer"); 4533 } 4534 // ditch the result and return a ResolveInfo to launch the ephemeral installer 4535 ResolveInfo ri = new ResolveInfo(mEphemeralInstallerInfo); 4536 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4537 // make a deep copy of the applicationInfo 4538 ri.activityInfo.applicationInfo = new ApplicationInfo( 4539 ri.activityInfo.applicationInfo); 4540 if (userId != 0) { 4541 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4542 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4543 } 4544 return ri; 4545 } 4546 } 4547 if (query != null) { 4548 final int N = query.size(); 4549 if (N == 1) { 4550 return query.get(0); 4551 } else if (N > 1) { 4552 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4553 // If there is more than one activity with the same priority, 4554 // then let the user decide between them. 4555 ResolveInfo r0 = query.get(0); 4556 ResolveInfo r1 = query.get(1); 4557 if (DEBUG_INTENT_MATCHING || debug) { 4558 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4559 + r1.activityInfo.name + "=" + r1.priority); 4560 } 4561 // If the first activity has a higher priority, or a different 4562 // default, then it is always desireable to pick it. 4563 if (r0.priority != r1.priority 4564 || r0.preferredOrder != r1.preferredOrder 4565 || r0.isDefault != r1.isDefault) { 4566 return query.get(0); 4567 } 4568 // If we have saved a preference for a preferred activity for 4569 // this Intent, use that. 4570 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4571 flags, query, r0.priority, true, false, debug, userId); 4572 if (ri != null) { 4573 return ri; 4574 } 4575 ri = new ResolveInfo(mResolveInfo); 4576 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4577 ri.activityInfo.applicationInfo = new ApplicationInfo( 4578 ri.activityInfo.applicationInfo); 4579 if (userId != 0) { 4580 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4581 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4582 } 4583 // Make sure that the resolver is displayable in car mode 4584 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 4585 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 4586 return ri; 4587 } 4588 } 4589 return null; 4590 } 4591 4592 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4593 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4594 final int N = query.size(); 4595 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4596 .get(userId); 4597 // Get the list of persistent preferred activities that handle the intent 4598 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4599 List<PersistentPreferredActivity> pprefs = ppir != null 4600 ? ppir.queryIntent(intent, resolvedType, 4601 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4602 : null; 4603 if (pprefs != null && pprefs.size() > 0) { 4604 final int M = pprefs.size(); 4605 for (int i=0; i<M; i++) { 4606 final PersistentPreferredActivity ppa = pprefs.get(i); 4607 if (DEBUG_PREFERRED || debug) { 4608 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4609 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4610 + "\n component=" + ppa.mComponent); 4611 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4612 } 4613 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4614 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4615 if (DEBUG_PREFERRED || debug) { 4616 Slog.v(TAG, "Found persistent preferred activity:"); 4617 if (ai != null) { 4618 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4619 } else { 4620 Slog.v(TAG, " null"); 4621 } 4622 } 4623 if (ai == null) { 4624 // This previously registered persistent preferred activity 4625 // component is no longer known. Ignore it and do NOT remove it. 4626 continue; 4627 } 4628 for (int j=0; j<N; j++) { 4629 final ResolveInfo ri = query.get(j); 4630 if (!ri.activityInfo.applicationInfo.packageName 4631 .equals(ai.applicationInfo.packageName)) { 4632 continue; 4633 } 4634 if (!ri.activityInfo.name.equals(ai.name)) { 4635 continue; 4636 } 4637 // Found a persistent preference that can handle the intent. 4638 if (DEBUG_PREFERRED || debug) { 4639 Slog.v(TAG, "Returning persistent preferred activity: " + 4640 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4641 } 4642 return ri; 4643 } 4644 } 4645 } 4646 return null; 4647 } 4648 4649 // TODO: handle preferred activities missing while user has amnesia 4650 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4651 List<ResolveInfo> query, int priority, boolean always, 4652 boolean removeMatches, boolean debug, int userId) { 4653 if (!sUserManager.exists(userId)) return null; 4654 flags = augmentFlagsForUser(flags, userId); 4655 // writer 4656 synchronized (mPackages) { 4657 if (intent.getSelector() != null) { 4658 intent = intent.getSelector(); 4659 } 4660 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4661 4662 // Try to find a matching persistent preferred activity. 4663 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4664 debug, userId); 4665 4666 // If a persistent preferred activity matched, use it. 4667 if (pri != null) { 4668 return pri; 4669 } 4670 4671 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4672 // Get the list of preferred activities that handle the intent 4673 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4674 List<PreferredActivity> prefs = pir != null 4675 ? pir.queryIntent(intent, resolvedType, 4676 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4677 : null; 4678 if (prefs != null && prefs.size() > 0) { 4679 boolean changed = false; 4680 try { 4681 // First figure out how good the original match set is. 4682 // We will only allow preferred activities that came 4683 // from the same match quality. 4684 int match = 0; 4685 4686 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4687 4688 final int N = query.size(); 4689 for (int j=0; j<N; j++) { 4690 final ResolveInfo ri = query.get(j); 4691 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4692 + ": 0x" + Integer.toHexString(match)); 4693 if (ri.match > match) { 4694 match = ri.match; 4695 } 4696 } 4697 4698 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4699 + Integer.toHexString(match)); 4700 4701 match &= IntentFilter.MATCH_CATEGORY_MASK; 4702 final int M = prefs.size(); 4703 for (int i=0; i<M; i++) { 4704 final PreferredActivity pa = prefs.get(i); 4705 if (DEBUG_PREFERRED || debug) { 4706 Slog.v(TAG, "Checking PreferredActivity ds=" 4707 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4708 + "\n component=" + pa.mPref.mComponent); 4709 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4710 } 4711 if (pa.mPref.mMatch != match) { 4712 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4713 + Integer.toHexString(pa.mPref.mMatch)); 4714 continue; 4715 } 4716 // If it's not an "always" type preferred activity and that's what we're 4717 // looking for, skip it. 4718 if (always && !pa.mPref.mAlways) { 4719 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4720 continue; 4721 } 4722 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4723 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4724 if (DEBUG_PREFERRED || debug) { 4725 Slog.v(TAG, "Found preferred activity:"); 4726 if (ai != null) { 4727 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4728 } else { 4729 Slog.v(TAG, " null"); 4730 } 4731 } 4732 if (ai == null) { 4733 // This previously registered preferred activity 4734 // component is no longer known. Most likely an update 4735 // to the app was installed and in the new version this 4736 // component no longer exists. Clean it up by removing 4737 // it from the preferred activities list, and skip it. 4738 Slog.w(TAG, "Removing dangling preferred activity: " 4739 + pa.mPref.mComponent); 4740 pir.removeFilter(pa); 4741 changed = true; 4742 continue; 4743 } 4744 for (int j=0; j<N; j++) { 4745 final ResolveInfo ri = query.get(j); 4746 if (!ri.activityInfo.applicationInfo.packageName 4747 .equals(ai.applicationInfo.packageName)) { 4748 continue; 4749 } 4750 if (!ri.activityInfo.name.equals(ai.name)) { 4751 continue; 4752 } 4753 4754 if (removeMatches) { 4755 pir.removeFilter(pa); 4756 changed = true; 4757 if (DEBUG_PREFERRED) { 4758 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4759 } 4760 break; 4761 } 4762 4763 // Okay we found a previously set preferred or last chosen app. 4764 // If the result set is different from when this 4765 // was created, we need to clear it and re-ask the 4766 // user their preference, if we're looking for an "always" type entry. 4767 if (always && !pa.mPref.sameSet(query)) { 4768 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4769 + intent + " type " + resolvedType); 4770 if (DEBUG_PREFERRED) { 4771 Slog.v(TAG, "Removing preferred activity since set changed " 4772 + pa.mPref.mComponent); 4773 } 4774 pir.removeFilter(pa); 4775 // Re-add the filter as a "last chosen" entry (!always) 4776 PreferredActivity lastChosen = new PreferredActivity( 4777 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4778 pir.addFilter(lastChosen); 4779 changed = true; 4780 return null; 4781 } 4782 4783 // Yay! Either the set matched or we're looking for the last chosen 4784 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4785 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4786 return ri; 4787 } 4788 } 4789 } finally { 4790 if (changed) { 4791 if (DEBUG_PREFERRED) { 4792 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4793 } 4794 scheduleWritePackageRestrictionsLocked(userId); 4795 } 4796 } 4797 } 4798 } 4799 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4800 return null; 4801 } 4802 4803 /* 4804 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4805 */ 4806 @Override 4807 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4808 int targetUserId) { 4809 mContext.enforceCallingOrSelfPermission( 4810 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4811 List<CrossProfileIntentFilter> matches = 4812 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4813 if (matches != null) { 4814 int size = matches.size(); 4815 for (int i = 0; i < size; i++) { 4816 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4817 } 4818 } 4819 if (hasWebURI(intent)) { 4820 // cross-profile app linking works only towards the parent. 4821 final UserInfo parent = getProfileParent(sourceUserId); 4822 synchronized(mPackages) { 4823 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 4824 intent, resolvedType, 0, sourceUserId, parent.id); 4825 return xpDomainInfo != null; 4826 } 4827 } 4828 return false; 4829 } 4830 4831 private UserInfo getProfileParent(int userId) { 4832 final long identity = Binder.clearCallingIdentity(); 4833 try { 4834 return sUserManager.getProfileParent(userId); 4835 } finally { 4836 Binder.restoreCallingIdentity(identity); 4837 } 4838 } 4839 4840 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4841 String resolvedType, int userId) { 4842 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4843 if (resolver != null) { 4844 return resolver.queryIntent(intent, resolvedType, false, userId); 4845 } 4846 return null; 4847 } 4848 4849 @Override 4850 public List<ResolveInfo> queryIntentActivities(Intent intent, 4851 String resolvedType, int flags, int userId) { 4852 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4853 flags = augmentFlagsForUser(flags, userId); 4854 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4855 ComponentName comp = intent.getComponent(); 4856 if (comp == null) { 4857 if (intent.getSelector() != null) { 4858 intent = intent.getSelector(); 4859 comp = intent.getComponent(); 4860 } 4861 } 4862 4863 if (comp != null) { 4864 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4865 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4866 if (ai != null) { 4867 final ResolveInfo ri = new ResolveInfo(); 4868 ri.activityInfo = ai; 4869 list.add(ri); 4870 } 4871 return list; 4872 } 4873 4874 // reader 4875 synchronized (mPackages) { 4876 final String pkgName = intent.getPackage(); 4877 if (pkgName == null) { 4878 List<CrossProfileIntentFilter> matchingFilters = 4879 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4880 // Check for results that need to skip the current profile. 4881 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4882 resolvedType, flags, userId); 4883 if (xpResolveInfo != null) { 4884 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4885 result.add(xpResolveInfo); 4886 return filterIfNotSystemUser(result, userId); 4887 } 4888 4889 // Check for results in the current profile. 4890 List<ResolveInfo> result = mActivities.queryIntent( 4891 intent, resolvedType, flags, userId); 4892 result = filterIfNotSystemUser(result, userId); 4893 4894 // Check for cross profile results. 4895 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 4896 xpResolveInfo = queryCrossProfileIntents( 4897 matchingFilters, intent, resolvedType, flags, userId, 4898 hasNonNegativePriorityResult); 4899 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4900 boolean isVisibleToUser = filterIfNotSystemUser( 4901 Collections.singletonList(xpResolveInfo), userId).size() > 0; 4902 if (isVisibleToUser) { 4903 result.add(xpResolveInfo); 4904 Collections.sort(result, mResolvePrioritySorter); 4905 } 4906 } 4907 if (hasWebURI(intent)) { 4908 CrossProfileDomainInfo xpDomainInfo = null; 4909 final UserInfo parent = getProfileParent(userId); 4910 if (parent != null) { 4911 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 4912 flags, userId, parent.id); 4913 } 4914 if (xpDomainInfo != null) { 4915 if (xpResolveInfo != null) { 4916 // If we didn't remove it, the cross-profile ResolveInfo would be twice 4917 // in the result. 4918 result.remove(xpResolveInfo); 4919 } 4920 if (result.size() == 0) { 4921 result.add(xpDomainInfo.resolveInfo); 4922 return result; 4923 } 4924 } else if (result.size() <= 1) { 4925 return result; 4926 } 4927 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 4928 xpDomainInfo, userId); 4929 Collections.sort(result, mResolvePrioritySorter); 4930 } 4931 return result; 4932 } 4933 final PackageParser.Package pkg = mPackages.get(pkgName); 4934 if (pkg != null) { 4935 return filterIfNotSystemUser( 4936 mActivities.queryIntentForPackage( 4937 intent, resolvedType, flags, pkg.activities, userId), 4938 userId); 4939 } 4940 return new ArrayList<ResolveInfo>(); 4941 } 4942 } 4943 4944 private static class CrossProfileDomainInfo { 4945 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 4946 ResolveInfo resolveInfo; 4947 /* Best domain verification status of the activities found in the other profile */ 4948 int bestDomainVerificationStatus; 4949 } 4950 4951 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 4952 String resolvedType, int flags, int sourceUserId, int parentUserId) { 4953 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 4954 sourceUserId)) { 4955 return null; 4956 } 4957 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4958 resolvedType, flags, parentUserId); 4959 4960 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 4961 return null; 4962 } 4963 CrossProfileDomainInfo result = null; 4964 int size = resultTargetUser.size(); 4965 for (int i = 0; i < size; i++) { 4966 ResolveInfo riTargetUser = resultTargetUser.get(i); 4967 // Intent filter verification is only for filters that specify a host. So don't return 4968 // those that handle all web uris. 4969 if (riTargetUser.handleAllWebDataURI) { 4970 continue; 4971 } 4972 String packageName = riTargetUser.activityInfo.packageName; 4973 PackageSetting ps = mSettings.mPackages.get(packageName); 4974 if (ps == null) { 4975 continue; 4976 } 4977 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 4978 int status = (int)(verificationState >> 32); 4979 if (result == null) { 4980 result = new CrossProfileDomainInfo(); 4981 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 4982 sourceUserId, parentUserId); 4983 result.bestDomainVerificationStatus = status; 4984 } else { 4985 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 4986 result.bestDomainVerificationStatus); 4987 } 4988 } 4989 // Don't consider matches with status NEVER across profiles. 4990 if (result != null && result.bestDomainVerificationStatus 4991 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4992 return null; 4993 } 4994 return result; 4995 } 4996 4997 /** 4998 * Verification statuses are ordered from the worse to the best, except for 4999 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5000 */ 5001 private int bestDomainVerificationStatus(int status1, int status2) { 5002 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5003 return status2; 5004 } 5005 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5006 return status1; 5007 } 5008 return (int) MathUtils.max(status1, status2); 5009 } 5010 5011 private boolean isUserEnabled(int userId) { 5012 long callingId = Binder.clearCallingIdentity(); 5013 try { 5014 UserInfo userInfo = sUserManager.getUserInfo(userId); 5015 return userInfo != null && userInfo.isEnabled(); 5016 } finally { 5017 Binder.restoreCallingIdentity(callingId); 5018 } 5019 } 5020 5021 /** 5022 * Filter out activities with systemUserOnly flag set, when current user is not System. 5023 * 5024 * @return filtered list 5025 */ 5026 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5027 if (userId == UserHandle.USER_SYSTEM) { 5028 return resolveInfos; 5029 } 5030 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5031 ResolveInfo info = resolveInfos.get(i); 5032 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5033 resolveInfos.remove(i); 5034 } 5035 } 5036 return resolveInfos; 5037 } 5038 5039 /** 5040 * @param resolveInfos list of resolve infos in descending priority order 5041 * @return if the list contains a resolve info with non-negative priority 5042 */ 5043 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5044 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5045 } 5046 5047 private static boolean hasWebURI(Intent intent) { 5048 if (intent.getData() == null) { 5049 return false; 5050 } 5051 final String scheme = intent.getScheme(); 5052 if (TextUtils.isEmpty(scheme)) { 5053 return false; 5054 } 5055 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5056 } 5057 5058 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5059 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5060 int userId) { 5061 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5062 5063 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5064 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5065 candidates.size()); 5066 } 5067 5068 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5069 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5070 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5071 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5072 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5073 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5074 5075 synchronized (mPackages) { 5076 final int count = candidates.size(); 5077 // First, try to use linked apps. Partition the candidates into four lists: 5078 // one for the final results, one for the "do not use ever", one for "undefined status" 5079 // and finally one for "browser app type". 5080 for (int n=0; n<count; n++) { 5081 ResolveInfo info = candidates.get(n); 5082 String packageName = info.activityInfo.packageName; 5083 PackageSetting ps = mSettings.mPackages.get(packageName); 5084 if (ps != null) { 5085 // Add to the special match all list (Browser use case) 5086 if (info.handleAllWebDataURI) { 5087 matchAllList.add(info); 5088 continue; 5089 } 5090 // Try to get the status from User settings first 5091 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5092 int status = (int)(packedStatus >> 32); 5093 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5094 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5095 if (DEBUG_DOMAIN_VERIFICATION) { 5096 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5097 + " : linkgen=" + linkGeneration); 5098 } 5099 // Use link-enabled generation as preferredOrder, i.e. 5100 // prefer newly-enabled over earlier-enabled. 5101 info.preferredOrder = linkGeneration; 5102 alwaysList.add(info); 5103 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5104 if (DEBUG_DOMAIN_VERIFICATION) { 5105 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5106 } 5107 neverList.add(info); 5108 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5109 if (DEBUG_DOMAIN_VERIFICATION) { 5110 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5111 } 5112 alwaysAskList.add(info); 5113 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5114 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5115 if (DEBUG_DOMAIN_VERIFICATION) { 5116 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5117 } 5118 undefinedList.add(info); 5119 } 5120 } 5121 } 5122 5123 // We'll want to include browser possibilities in a few cases 5124 boolean includeBrowser = false; 5125 5126 // First try to add the "always" resolution(s) for the current user, if any 5127 if (alwaysList.size() > 0) { 5128 result.addAll(alwaysList); 5129 } else { 5130 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5131 result.addAll(undefinedList); 5132 // Maybe add one for the other profile. 5133 if (xpDomainInfo != null && ( 5134 xpDomainInfo.bestDomainVerificationStatus 5135 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5136 result.add(xpDomainInfo.resolveInfo); 5137 } 5138 includeBrowser = true; 5139 } 5140 5141 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5142 // If there were 'always' entries their preferred order has been set, so we also 5143 // back that off to make the alternatives equivalent 5144 if (alwaysAskList.size() > 0) { 5145 for (ResolveInfo i : result) { 5146 i.preferredOrder = 0; 5147 } 5148 result.addAll(alwaysAskList); 5149 includeBrowser = true; 5150 } 5151 5152 if (includeBrowser) { 5153 // Also add browsers (all of them or only the default one) 5154 if (DEBUG_DOMAIN_VERIFICATION) { 5155 Slog.v(TAG, " ...including browsers in candidate set"); 5156 } 5157 if ((matchFlags & MATCH_ALL) != 0) { 5158 result.addAll(matchAllList); 5159 } else { 5160 // Browser/generic handling case. If there's a default browser, go straight 5161 // to that (but only if there is no other higher-priority match). 5162 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5163 int maxMatchPrio = 0; 5164 ResolveInfo defaultBrowserMatch = null; 5165 final int numCandidates = matchAllList.size(); 5166 for (int n = 0; n < numCandidates; n++) { 5167 ResolveInfo info = matchAllList.get(n); 5168 // track the highest overall match priority... 5169 if (info.priority > maxMatchPrio) { 5170 maxMatchPrio = info.priority; 5171 } 5172 // ...and the highest-priority default browser match 5173 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5174 if (defaultBrowserMatch == null 5175 || (defaultBrowserMatch.priority < info.priority)) { 5176 if (debug) { 5177 Slog.v(TAG, "Considering default browser match " + info); 5178 } 5179 defaultBrowserMatch = info; 5180 } 5181 } 5182 } 5183 if (defaultBrowserMatch != null 5184 && defaultBrowserMatch.priority >= maxMatchPrio 5185 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5186 { 5187 if (debug) { 5188 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5189 } 5190 result.add(defaultBrowserMatch); 5191 } else { 5192 result.addAll(matchAllList); 5193 } 5194 } 5195 5196 // If there is nothing selected, add all candidates and remove the ones that the user 5197 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5198 if (result.size() == 0) { 5199 result.addAll(candidates); 5200 result.removeAll(neverList); 5201 } 5202 } 5203 } 5204 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5205 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5206 result.size()); 5207 for (ResolveInfo info : result) { 5208 Slog.v(TAG, " + " + info.activityInfo); 5209 } 5210 } 5211 return result; 5212 } 5213 5214 // Returns a packed value as a long: 5215 // 5216 // high 'int'-sized word: link status: undefined/ask/never/always. 5217 // low 'int'-sized word: relative priority among 'always' results. 5218 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5219 long result = ps.getDomainVerificationStatusForUser(userId); 5220 // if none available, get the master status 5221 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5222 if (ps.getIntentFilterVerificationInfo() != null) { 5223 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5224 } 5225 } 5226 return result; 5227 } 5228 5229 private ResolveInfo querySkipCurrentProfileIntents( 5230 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5231 int flags, int sourceUserId) { 5232 if (matchingFilters != null) { 5233 int size = matchingFilters.size(); 5234 for (int i = 0; i < size; i ++) { 5235 CrossProfileIntentFilter filter = matchingFilters.get(i); 5236 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5237 // Checking if there are activities in the target user that can handle the 5238 // intent. 5239 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5240 resolvedType, flags, sourceUserId); 5241 if (resolveInfo != null) { 5242 return resolveInfo; 5243 } 5244 } 5245 } 5246 } 5247 return null; 5248 } 5249 5250 // Return matching ResolveInfo in target user if any. 5251 private ResolveInfo queryCrossProfileIntents( 5252 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5253 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5254 if (matchingFilters != null) { 5255 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5256 // match the same intent. For performance reasons, it is better not to 5257 // run queryIntent twice for the same userId 5258 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5259 int size = matchingFilters.size(); 5260 for (int i = 0; i < size; i++) { 5261 CrossProfileIntentFilter filter = matchingFilters.get(i); 5262 int targetUserId = filter.getTargetUserId(); 5263 boolean skipCurrentProfile = 5264 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5265 boolean skipCurrentProfileIfNoMatchFound = 5266 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5267 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5268 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5269 // Checking if there are activities in the target user that can handle the 5270 // intent. 5271 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5272 resolvedType, flags, sourceUserId); 5273 if (resolveInfo != null) return resolveInfo; 5274 alreadyTriedUserIds.put(targetUserId, true); 5275 } 5276 } 5277 } 5278 return null; 5279 } 5280 5281 /** 5282 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5283 * will forward the intent to the filter's target user. 5284 * Otherwise, returns null. 5285 */ 5286 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5287 String resolvedType, int flags, int sourceUserId) { 5288 int targetUserId = filter.getTargetUserId(); 5289 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5290 resolvedType, flags, targetUserId); 5291 if (resultTargetUser != null && !resultTargetUser.isEmpty() 5292 && isUserEnabled(targetUserId)) { 5293 return createForwardingResolveInfoUnchecked(filter, sourceUserId, targetUserId); 5294 } 5295 return null; 5296 } 5297 5298 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5299 int sourceUserId, int targetUserId) { 5300 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5301 long ident = Binder.clearCallingIdentity(); 5302 boolean targetIsProfile; 5303 try { 5304 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5305 } finally { 5306 Binder.restoreCallingIdentity(ident); 5307 } 5308 String className; 5309 if (targetIsProfile) { 5310 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5311 } else { 5312 className = FORWARD_INTENT_TO_PARENT; 5313 } 5314 ComponentName forwardingActivityComponentName = new ComponentName( 5315 mAndroidApplication.packageName, className); 5316 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5317 sourceUserId); 5318 if (!targetIsProfile) { 5319 forwardingActivityInfo.showUserIcon = targetUserId; 5320 forwardingResolveInfo.noResourceId = true; 5321 } 5322 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5323 forwardingResolveInfo.priority = 0; 5324 forwardingResolveInfo.preferredOrder = 0; 5325 forwardingResolveInfo.match = 0; 5326 forwardingResolveInfo.isDefault = true; 5327 forwardingResolveInfo.filter = filter; 5328 forwardingResolveInfo.targetUserId = targetUserId; 5329 return forwardingResolveInfo; 5330 } 5331 5332 @Override 5333 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5334 Intent[] specifics, String[] specificTypes, Intent intent, 5335 String resolvedType, int flags, int userId) { 5336 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5337 flags = augmentFlagsForUser(flags, userId); 5338 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 5339 false, "query intent activity options"); 5340 final String resultsAction = intent.getAction(); 5341 5342 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 5343 | PackageManager.GET_RESOLVED_FILTER, userId); 5344 5345 if (DEBUG_INTENT_MATCHING) { 5346 Log.v(TAG, "Query " + intent + ": " + results); 5347 } 5348 5349 int specificsPos = 0; 5350 int N; 5351 5352 // todo: note that the algorithm used here is O(N^2). This 5353 // isn't a problem in our current environment, but if we start running 5354 // into situations where we have more than 5 or 10 matches then this 5355 // should probably be changed to something smarter... 5356 5357 // First we go through and resolve each of the specific items 5358 // that were supplied, taking care of removing any corresponding 5359 // duplicate items in the generic resolve list. 5360 if (specifics != null) { 5361 for (int i=0; i<specifics.length; i++) { 5362 final Intent sintent = specifics[i]; 5363 if (sintent == null) { 5364 continue; 5365 } 5366 5367 if (DEBUG_INTENT_MATCHING) { 5368 Log.v(TAG, "Specific #" + i + ": " + sintent); 5369 } 5370 5371 String action = sintent.getAction(); 5372 if (resultsAction != null && resultsAction.equals(action)) { 5373 // If this action was explicitly requested, then don't 5374 // remove things that have it. 5375 action = null; 5376 } 5377 5378 ResolveInfo ri = null; 5379 ActivityInfo ai = null; 5380 5381 ComponentName comp = sintent.getComponent(); 5382 if (comp == null) { 5383 ri = resolveIntent( 5384 sintent, 5385 specificTypes != null ? specificTypes[i] : null, 5386 flags, userId); 5387 if (ri == null) { 5388 continue; 5389 } 5390 if (ri == mResolveInfo) { 5391 // ACK! Must do something better with this. 5392 } 5393 ai = ri.activityInfo; 5394 comp = new ComponentName(ai.applicationInfo.packageName, 5395 ai.name); 5396 } else { 5397 ai = getActivityInfo(comp, flags, userId); 5398 if (ai == null) { 5399 continue; 5400 } 5401 } 5402 5403 // Look for any generic query activities that are duplicates 5404 // of this specific one, and remove them from the results. 5405 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5406 N = results.size(); 5407 int j; 5408 for (j=specificsPos; j<N; j++) { 5409 ResolveInfo sri = results.get(j); 5410 if ((sri.activityInfo.name.equals(comp.getClassName()) 5411 && sri.activityInfo.applicationInfo.packageName.equals( 5412 comp.getPackageName())) 5413 || (action != null && sri.filter.matchAction(action))) { 5414 results.remove(j); 5415 if (DEBUG_INTENT_MATCHING) Log.v( 5416 TAG, "Removing duplicate item from " + j 5417 + " due to specific " + specificsPos); 5418 if (ri == null) { 5419 ri = sri; 5420 } 5421 j--; 5422 N--; 5423 } 5424 } 5425 5426 // Add this specific item to its proper place. 5427 if (ri == null) { 5428 ri = new ResolveInfo(); 5429 ri.activityInfo = ai; 5430 } 5431 results.add(specificsPos, ri); 5432 ri.specificIndex = i; 5433 specificsPos++; 5434 } 5435 } 5436 5437 // Now we go through the remaining generic results and remove any 5438 // duplicate actions that are found here. 5439 N = results.size(); 5440 for (int i=specificsPos; i<N-1; i++) { 5441 final ResolveInfo rii = results.get(i); 5442 if (rii.filter == null) { 5443 continue; 5444 } 5445 5446 // Iterate over all of the actions of this result's intent 5447 // filter... typically this should be just one. 5448 final Iterator<String> it = rii.filter.actionsIterator(); 5449 if (it == null) { 5450 continue; 5451 } 5452 while (it.hasNext()) { 5453 final String action = it.next(); 5454 if (resultsAction != null && resultsAction.equals(action)) { 5455 // If this action was explicitly requested, then don't 5456 // remove things that have it. 5457 continue; 5458 } 5459 for (int j=i+1; j<N; j++) { 5460 final ResolveInfo rij = results.get(j); 5461 if (rij.filter != null && rij.filter.hasAction(action)) { 5462 results.remove(j); 5463 if (DEBUG_INTENT_MATCHING) Log.v( 5464 TAG, "Removing duplicate item from " + j 5465 + " due to action " + action + " at " + i); 5466 j--; 5467 N--; 5468 } 5469 } 5470 } 5471 5472 // If the caller didn't request filter information, drop it now 5473 // so we don't have to marshall/unmarshall it. 5474 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5475 rii.filter = null; 5476 } 5477 } 5478 5479 // Filter out the caller activity if so requested. 5480 if (caller != null) { 5481 N = results.size(); 5482 for (int i=0; i<N; i++) { 5483 ActivityInfo ainfo = results.get(i).activityInfo; 5484 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5485 && caller.getClassName().equals(ainfo.name)) { 5486 results.remove(i); 5487 break; 5488 } 5489 } 5490 } 5491 5492 // If the caller didn't request filter information, 5493 // drop them now so we don't have to 5494 // marshall/unmarshall it. 5495 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5496 N = results.size(); 5497 for (int i=0; i<N; i++) { 5498 results.get(i).filter = null; 5499 } 5500 } 5501 5502 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5503 return results; 5504 } 5505 5506 @Override 5507 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 5508 int userId) { 5509 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5510 flags = augmentFlagsForUser(flags, userId); 5511 ComponentName comp = intent.getComponent(); 5512 if (comp == null) { 5513 if (intent.getSelector() != null) { 5514 intent = intent.getSelector(); 5515 comp = intent.getComponent(); 5516 } 5517 } 5518 if (comp != null) { 5519 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5520 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5521 if (ai != null) { 5522 ResolveInfo ri = new ResolveInfo(); 5523 ri.activityInfo = ai; 5524 list.add(ri); 5525 } 5526 return list; 5527 } 5528 5529 // reader 5530 synchronized (mPackages) { 5531 String pkgName = intent.getPackage(); 5532 if (pkgName == null) { 5533 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5534 } 5535 final PackageParser.Package pkg = mPackages.get(pkgName); 5536 if (pkg != null) { 5537 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5538 userId); 5539 } 5540 return null; 5541 } 5542 } 5543 5544 @Override 5545 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5546 if (!sUserManager.exists(userId)) return null; 5547 flags = augmentFlagsForUser(flags, userId); 5548 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 5549 if (query != null) { 5550 if (query.size() >= 1) { 5551 // If there is more than one service with the same priority, 5552 // just arbitrarily pick the first one. 5553 return query.get(0); 5554 } 5555 } 5556 return null; 5557 } 5558 5559 @Override 5560 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 5561 int userId) { 5562 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5563 flags = augmentFlagsForUser(flags, userId); 5564 ComponentName comp = intent.getComponent(); 5565 if (comp == null) { 5566 if (intent.getSelector() != null) { 5567 intent = intent.getSelector(); 5568 comp = intent.getComponent(); 5569 } 5570 } 5571 if (comp != null) { 5572 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5573 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5574 if (si != null) { 5575 final ResolveInfo ri = new ResolveInfo(); 5576 ri.serviceInfo = si; 5577 list.add(ri); 5578 } 5579 return list; 5580 } 5581 5582 // reader 5583 synchronized (mPackages) { 5584 String pkgName = intent.getPackage(); 5585 if (pkgName == null) { 5586 return mServices.queryIntent(intent, resolvedType, flags, userId); 5587 } 5588 final PackageParser.Package pkg = mPackages.get(pkgName); 5589 if (pkg != null) { 5590 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5591 userId); 5592 } 5593 return null; 5594 } 5595 } 5596 5597 @Override 5598 public List<ResolveInfo> queryIntentContentProviders( 5599 Intent intent, String resolvedType, int flags, int userId) { 5600 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5601 flags = augmentFlagsForUser(flags, userId); 5602 ComponentName comp = intent.getComponent(); 5603 if (comp == null) { 5604 if (intent.getSelector() != null) { 5605 intent = intent.getSelector(); 5606 comp = intent.getComponent(); 5607 } 5608 } 5609 if (comp != null) { 5610 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5611 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5612 if (pi != null) { 5613 final ResolveInfo ri = new ResolveInfo(); 5614 ri.providerInfo = pi; 5615 list.add(ri); 5616 } 5617 return list; 5618 } 5619 5620 // reader 5621 synchronized (mPackages) { 5622 String pkgName = intent.getPackage(); 5623 if (pkgName == null) { 5624 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5625 } 5626 final PackageParser.Package pkg = mPackages.get(pkgName); 5627 if (pkg != null) { 5628 return mProviders.queryIntentForPackage( 5629 intent, resolvedType, flags, pkg.providers, userId); 5630 } 5631 return null; 5632 } 5633 } 5634 5635 @Override 5636 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5637 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5638 5639 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 5640 5641 // writer 5642 synchronized (mPackages) { 5643 ArrayList<PackageInfo> list; 5644 if (listUninstalled) { 5645 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5646 for (PackageSetting ps : mSettings.mPackages.values()) { 5647 PackageInfo pi; 5648 if (ps.pkg != null) { 5649 pi = generatePackageInfo(ps.pkg, flags, userId); 5650 } else { 5651 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5652 } 5653 if (pi != null) { 5654 list.add(pi); 5655 } 5656 } 5657 } else { 5658 list = new ArrayList<PackageInfo>(mPackages.size()); 5659 for (PackageParser.Package p : mPackages.values()) { 5660 PackageInfo pi = generatePackageInfo(p, flags, userId); 5661 if (pi != null) { 5662 list.add(pi); 5663 } 5664 } 5665 } 5666 5667 return new ParceledListSlice<PackageInfo>(list); 5668 } 5669 } 5670 5671 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5672 String[] permissions, boolean[] tmp, int flags, int userId) { 5673 int numMatch = 0; 5674 final PermissionsState permissionsState = ps.getPermissionsState(); 5675 for (int i=0; i<permissions.length; i++) { 5676 final String permission = permissions[i]; 5677 if (permissionsState.hasPermission(permission, userId)) { 5678 tmp[i] = true; 5679 numMatch++; 5680 } else { 5681 tmp[i] = false; 5682 } 5683 } 5684 if (numMatch == 0) { 5685 return; 5686 } 5687 PackageInfo pi; 5688 if (ps.pkg != null) { 5689 pi = generatePackageInfo(ps.pkg, flags, userId); 5690 } else { 5691 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5692 } 5693 // The above might return null in cases of uninstalled apps or install-state 5694 // skew across users/profiles. 5695 if (pi != null) { 5696 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5697 if (numMatch == permissions.length) { 5698 pi.requestedPermissions = permissions; 5699 } else { 5700 pi.requestedPermissions = new String[numMatch]; 5701 numMatch = 0; 5702 for (int i=0; i<permissions.length; i++) { 5703 if (tmp[i]) { 5704 pi.requestedPermissions[numMatch] = permissions[i]; 5705 numMatch++; 5706 } 5707 } 5708 } 5709 } 5710 list.add(pi); 5711 } 5712 } 5713 5714 @Override 5715 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5716 String[] permissions, int flags, int userId) { 5717 if (!sUserManager.exists(userId)) return null; 5718 flags = augmentFlagsForUser(flags, userId); 5719 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5720 5721 // writer 5722 synchronized (mPackages) { 5723 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5724 boolean[] tmpBools = new boolean[permissions.length]; 5725 if (listUninstalled) { 5726 for (PackageSetting ps : mSettings.mPackages.values()) { 5727 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5728 } 5729 } else { 5730 for (PackageParser.Package pkg : mPackages.values()) { 5731 PackageSetting ps = (PackageSetting)pkg.mExtras; 5732 if (ps != null) { 5733 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5734 userId); 5735 } 5736 } 5737 } 5738 5739 return new ParceledListSlice<PackageInfo>(list); 5740 } 5741 } 5742 5743 @Override 5744 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5745 if (!sUserManager.exists(userId)) return null; 5746 flags = augmentFlagsForUser(flags, userId); 5747 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5748 5749 // writer 5750 synchronized (mPackages) { 5751 ArrayList<ApplicationInfo> list; 5752 if (listUninstalled) { 5753 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5754 for (PackageSetting ps : mSettings.mPackages.values()) { 5755 ApplicationInfo ai; 5756 if (ps.pkg != null) { 5757 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5758 ps.readUserState(userId), userId); 5759 } else { 5760 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5761 } 5762 if (ai != null) { 5763 list.add(ai); 5764 } 5765 } 5766 } else { 5767 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5768 for (PackageParser.Package p : mPackages.values()) { 5769 if (p.mExtras != null) { 5770 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5771 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5772 if (ai != null) { 5773 list.add(ai); 5774 } 5775 } 5776 } 5777 } 5778 5779 return new ParceledListSlice<ApplicationInfo>(list); 5780 } 5781 } 5782 5783 public List<ApplicationInfo> getPersistentApplications(int flags) { 5784 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 5785 5786 // reader 5787 synchronized (mPackages) { 5788 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 5789 final int userId = UserHandle.getCallingUserId(); 5790 while (i.hasNext()) { 5791 final PackageParser.Package p = i.next(); 5792 if (p.applicationInfo != null 5793 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 5794 && (!mSafeMode || isSystemApp(p))) { 5795 PackageSetting ps = mSettings.mPackages.get(p.packageName); 5796 if (ps != null) { 5797 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5798 ps.readUserState(userId), userId); 5799 if (ai != null) { 5800 finalList.add(ai); 5801 } 5802 } 5803 } 5804 } 5805 } 5806 5807 return finalList; 5808 } 5809 5810 @Override 5811 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 5812 if (!sUserManager.exists(userId)) return null; 5813 flags = augmentFlagsForUser(flags, userId); 5814 // reader 5815 synchronized (mPackages) { 5816 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 5817 PackageSetting ps = provider != null 5818 ? mSettings.mPackages.get(provider.owner.packageName) 5819 : null; 5820 return ps != null 5821 && mSettings.isEnabledAndVisibleLPr(provider.info, flags, userId) 5822 && (!mSafeMode || (provider.info.applicationInfo.flags 5823 &ApplicationInfo.FLAG_SYSTEM) != 0) 5824 ? PackageParser.generateProviderInfo(provider, flags, 5825 ps.readUserState(userId), userId) 5826 : null; 5827 } 5828 } 5829 5830 /** 5831 * @deprecated 5832 */ 5833 @Deprecated 5834 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 5835 // reader 5836 synchronized (mPackages) { 5837 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 5838 .entrySet().iterator(); 5839 final int userId = UserHandle.getCallingUserId(); 5840 while (i.hasNext()) { 5841 Map.Entry<String, PackageParser.Provider> entry = i.next(); 5842 PackageParser.Provider p = entry.getValue(); 5843 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5844 5845 if (ps != null && p.syncable 5846 && (!mSafeMode || (p.info.applicationInfo.flags 5847 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 5848 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 5849 ps.readUserState(userId), userId); 5850 if (info != null) { 5851 outNames.add(entry.getKey()); 5852 outInfo.add(info); 5853 } 5854 } 5855 } 5856 } 5857 } 5858 5859 @Override 5860 public ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 5861 int uid, int flags) { 5862 final int userId = processName != null ? UserHandle.getUserId(uid) 5863 : UserHandle.getCallingUserId(); 5864 if (!sUserManager.exists(userId)) return null; 5865 flags = augmentFlagsForUser(flags, userId); 5866 5867 ArrayList<ProviderInfo> finalList = null; 5868 // reader 5869 synchronized (mPackages) { 5870 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 5871 while (i.hasNext()) { 5872 final PackageParser.Provider p = i.next(); 5873 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5874 if (ps != null && p.info.authority != null 5875 && (processName == null 5876 || (p.info.processName.equals(processName) 5877 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 5878 && mSettings.isEnabledAndVisibleLPr(p.info, flags, userId) 5879 && (!mSafeMode 5880 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 5881 if (finalList == null) { 5882 finalList = new ArrayList<ProviderInfo>(3); 5883 } 5884 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 5885 ps.readUserState(userId), userId); 5886 if (info != null) { 5887 finalList.add(info); 5888 } 5889 } 5890 } 5891 } 5892 5893 if (finalList != null) { 5894 Collections.sort(finalList, mProviderInitOrderSorter); 5895 return new ParceledListSlice<ProviderInfo>(finalList); 5896 } 5897 5898 return null; 5899 } 5900 5901 @Override 5902 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 5903 int flags) { 5904 // reader 5905 synchronized (mPackages) { 5906 final PackageParser.Instrumentation i = mInstrumentation.get(name); 5907 return PackageParser.generateInstrumentationInfo(i, flags); 5908 } 5909 } 5910 5911 @Override 5912 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 5913 int flags) { 5914 ArrayList<InstrumentationInfo> finalList = 5915 new ArrayList<InstrumentationInfo>(); 5916 5917 // reader 5918 synchronized (mPackages) { 5919 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 5920 while (i.hasNext()) { 5921 final PackageParser.Instrumentation p = i.next(); 5922 if (targetPackage == null 5923 || targetPackage.equals(p.info.targetPackage)) { 5924 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 5925 flags); 5926 if (ii != null) { 5927 finalList.add(ii); 5928 } 5929 } 5930 } 5931 } 5932 5933 return finalList; 5934 } 5935 5936 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 5937 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 5938 if (overlays == null) { 5939 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 5940 return; 5941 } 5942 for (PackageParser.Package opkg : overlays.values()) { 5943 // Not much to do if idmap fails: we already logged the error 5944 // and we certainly don't want to abort installation of pkg simply 5945 // because an overlay didn't fit properly. For these reasons, 5946 // ignore the return value of createIdmapForPackagePairLI. 5947 createIdmapForPackagePairLI(pkg, opkg); 5948 } 5949 } 5950 5951 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 5952 PackageParser.Package opkg) { 5953 if (!opkg.mTrustedOverlay) { 5954 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 5955 opkg.baseCodePath + ": overlay not trusted"); 5956 return false; 5957 } 5958 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 5959 if (overlaySet == null) { 5960 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 5961 opkg.baseCodePath + " but target package has no known overlays"); 5962 return false; 5963 } 5964 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 5965 // TODO: generate idmap for split APKs 5966 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 5967 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 5968 + opkg.baseCodePath); 5969 return false; 5970 } 5971 PackageParser.Package[] overlayArray = 5972 overlaySet.values().toArray(new PackageParser.Package[0]); 5973 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 5974 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 5975 return p1.mOverlayPriority - p2.mOverlayPriority; 5976 } 5977 }; 5978 Arrays.sort(overlayArray, cmp); 5979 5980 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 5981 int i = 0; 5982 for (PackageParser.Package p : overlayArray) { 5983 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 5984 } 5985 return true; 5986 } 5987 5988 private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5989 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 5990 try { 5991 scanDirLI(dir, parseFlags, scanFlags, currentTime); 5992 } finally { 5993 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5994 } 5995 } 5996 5997 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5998 final File[] files = dir.listFiles(); 5999 if (ArrayUtils.isEmpty(files)) { 6000 Log.d(TAG, "No files in app dir " + dir); 6001 return; 6002 } 6003 6004 if (DEBUG_PACKAGE_SCANNING) { 6005 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6006 + " flags=0x" + Integer.toHexString(parseFlags)); 6007 } 6008 6009 for (File file : files) { 6010 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6011 && !PackageInstallerService.isStageName(file.getName()); 6012 if (!isPackage) { 6013 // Ignore entries which are not packages 6014 continue; 6015 } 6016 try { 6017 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6018 scanFlags, currentTime, null); 6019 } catch (PackageManagerException e) { 6020 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6021 6022 // Delete invalid userdata apps 6023 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6024 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6025 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6026 if (file.isDirectory()) { 6027 mInstaller.rmPackageDir(file.getAbsolutePath()); 6028 } else { 6029 file.delete(); 6030 } 6031 } 6032 } 6033 } 6034 } 6035 6036 private static File getSettingsProblemFile() { 6037 File dataDir = Environment.getDataDirectory(); 6038 File systemDir = new File(dataDir, "system"); 6039 File fname = new File(systemDir, "uiderrors.txt"); 6040 return fname; 6041 } 6042 6043 static void reportSettingsProblem(int priority, String msg) { 6044 logCriticalInfo(priority, msg); 6045 } 6046 6047 static void logCriticalInfo(int priority, String msg) { 6048 Slog.println(priority, TAG, msg); 6049 EventLogTags.writePmCriticalInfo(msg); 6050 try { 6051 File fname = getSettingsProblemFile(); 6052 FileOutputStream out = new FileOutputStream(fname, true); 6053 PrintWriter pw = new FastPrintWriter(out); 6054 SimpleDateFormat formatter = new SimpleDateFormat(); 6055 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6056 pw.println(dateString + ": " + msg); 6057 pw.close(); 6058 FileUtils.setPermissions( 6059 fname.toString(), 6060 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6061 -1, -1); 6062 } catch (java.io.IOException e) { 6063 } 6064 } 6065 6066 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 6067 PackageParser.Package pkg, File srcFile, int parseFlags) 6068 throws PackageManagerException { 6069 if (ps != null 6070 && ps.codePath.equals(srcFile) 6071 && ps.timeStamp == srcFile.lastModified() 6072 && !isCompatSignatureUpdateNeeded(pkg) 6073 && !isRecoverSignatureUpdateNeeded(pkg)) { 6074 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6075 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6076 ArraySet<PublicKey> signingKs; 6077 synchronized (mPackages) { 6078 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6079 } 6080 if (ps.signatures.mSignatures != null 6081 && ps.signatures.mSignatures.length != 0 6082 && signingKs != null) { 6083 // Optimization: reuse the existing cached certificates 6084 // if the package appears to be unchanged. 6085 pkg.mSignatures = ps.signatures.mSignatures; 6086 pkg.mSigningKeys = signingKs; 6087 return; 6088 } 6089 6090 Slog.w(TAG, "PackageSetting for " + ps.name 6091 + " is missing signatures. Collecting certs again to recover them."); 6092 } else { 6093 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6094 } 6095 6096 try { 6097 pp.collectCertificates(pkg, parseFlags); 6098 pp.collectManifestDigest(pkg); 6099 } catch (PackageParserException e) { 6100 throw PackageManagerException.from(e); 6101 } 6102 } 6103 6104 /** 6105 * Traces a package scan. 6106 * @see #scanPackageLI(File, int, int, long, UserHandle) 6107 */ 6108 private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags, 6109 long currentTime, UserHandle user) throws PackageManagerException { 6110 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6111 try { 6112 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6113 } finally { 6114 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6115 } 6116 } 6117 6118 /** 6119 * Scans a package and returns the newly parsed package. 6120 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6121 */ 6122 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6123 long currentTime, UserHandle user) throws PackageManagerException { 6124 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6125 parseFlags |= mDefParseFlags; 6126 PackageParser pp = new PackageParser(); 6127 pp.setSeparateProcesses(mSeparateProcesses); 6128 pp.setOnlyCoreApps(mOnlyCore); 6129 pp.setDisplayMetrics(mMetrics); 6130 6131 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6132 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6133 } 6134 6135 final PackageParser.Package pkg; 6136 try { 6137 pkg = pp.parsePackage(scanFile, parseFlags); 6138 } catch (PackageParserException e) { 6139 throw PackageManagerException.from(e); 6140 } 6141 6142 PackageSetting ps = null; 6143 PackageSetting updatedPkg; 6144 // reader 6145 synchronized (mPackages) { 6146 // Look to see if we already know about this package. 6147 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6148 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6149 // This package has been renamed to its original name. Let's 6150 // use that. 6151 ps = mSettings.peekPackageLPr(oldName); 6152 } 6153 // If there was no original package, see one for the real package name. 6154 if (ps == null) { 6155 ps = mSettings.peekPackageLPr(pkg.packageName); 6156 } 6157 // Check to see if this package could be hiding/updating a system 6158 // package. Must look for it either under the original or real 6159 // package name depending on our state. 6160 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6161 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6162 } 6163 boolean updatedPkgBetter = false; 6164 // First check if this is a system package that may involve an update 6165 if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6166 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6167 // it needs to drop FLAG_PRIVILEGED. 6168 if (locationIsPrivileged(scanFile)) { 6169 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6170 } else { 6171 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6172 } 6173 6174 if (ps != null && !ps.codePath.equals(scanFile)) { 6175 // The path has changed from what was last scanned... check the 6176 // version of the new path against what we have stored to determine 6177 // what to do. 6178 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6179 if (pkg.mVersionCode <= ps.versionCode) { 6180 // The system package has been updated and the code path does not match 6181 // Ignore entry. Skip it. 6182 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6183 + " ignored: updated version " + ps.versionCode 6184 + " better than this " + pkg.mVersionCode); 6185 if (!updatedPkg.codePath.equals(scanFile)) { 6186 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 6187 + ps.name + " changing from " + updatedPkg.codePathString 6188 + " to " + scanFile); 6189 updatedPkg.codePath = scanFile; 6190 updatedPkg.codePathString = scanFile.toString(); 6191 updatedPkg.resourcePath = scanFile; 6192 updatedPkg.resourcePathString = scanFile.toString(); 6193 } 6194 updatedPkg.pkg = pkg; 6195 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6196 "Package " + ps.name + " at " + scanFile 6197 + " ignored: updated version " + ps.versionCode 6198 + " better than this " + pkg.mVersionCode); 6199 } else { 6200 // The current app on the system partition is better than 6201 // what we have updated to on the data partition; switch 6202 // back to the system partition version. 6203 // At this point, its safely assumed that package installation for 6204 // apps in system partition will go through. If not there won't be a working 6205 // version of the app 6206 // writer 6207 synchronized (mPackages) { 6208 // Just remove the loaded entries from package lists. 6209 mPackages.remove(ps.name); 6210 } 6211 6212 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6213 + " reverting from " + ps.codePathString 6214 + ": new version " + pkg.mVersionCode 6215 + " better than installed " + ps.versionCode); 6216 6217 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6218 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6219 synchronized (mInstallLock) { 6220 args.cleanUpResourcesLI(); 6221 } 6222 synchronized (mPackages) { 6223 mSettings.enableSystemPackageLPw(ps.name); 6224 } 6225 updatedPkgBetter = true; 6226 } 6227 } 6228 } 6229 6230 if (updatedPkg != null) { 6231 // An updated system app will not have the PARSE_IS_SYSTEM flag set 6232 // initially 6233 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 6234 6235 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 6236 // flag set initially 6237 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 6238 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 6239 } 6240 } 6241 6242 // Verify certificates against what was last scanned 6243 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 6244 6245 /* 6246 * A new system app appeared, but we already had a non-system one of the 6247 * same name installed earlier. 6248 */ 6249 boolean shouldHideSystemApp = false; 6250 if (updatedPkg == null && ps != null 6251 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 6252 /* 6253 * Check to make sure the signatures match first. If they don't, 6254 * wipe the installed application and its data. 6255 */ 6256 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 6257 != PackageManager.SIGNATURE_MATCH) { 6258 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 6259 + " signatures don't match existing userdata copy; removing"); 6260 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 6261 ps = null; 6262 } else { 6263 /* 6264 * If the newly-added system app is an older version than the 6265 * already installed version, hide it. It will be scanned later 6266 * and re-added like an update. 6267 */ 6268 if (pkg.mVersionCode <= ps.versionCode) { 6269 shouldHideSystemApp = true; 6270 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 6271 + " but new version " + pkg.mVersionCode + " better than installed " 6272 + ps.versionCode + "; hiding system"); 6273 } else { 6274 /* 6275 * The newly found system app is a newer version that the 6276 * one previously installed. Simply remove the 6277 * already-installed application and replace it with our own 6278 * while keeping the application data. 6279 */ 6280 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6281 + " reverting from " + ps.codePathString + ": new version " 6282 + pkg.mVersionCode + " better than installed " + ps.versionCode); 6283 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6284 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6285 synchronized (mInstallLock) { 6286 args.cleanUpResourcesLI(); 6287 } 6288 } 6289 } 6290 } 6291 6292 // The apk is forward locked (not public) if its code and resources 6293 // are kept in different files. (except for app in either system or 6294 // vendor path). 6295 // TODO grab this value from PackageSettings 6296 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6297 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 6298 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 6299 } 6300 } 6301 6302 // TODO: extend to support forward-locked splits 6303 String resourcePath = null; 6304 String baseResourcePath = null; 6305 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 6306 if (ps != null && ps.resourcePathString != null) { 6307 resourcePath = ps.resourcePathString; 6308 baseResourcePath = ps.resourcePathString; 6309 } else { 6310 // Should not happen at all. Just log an error. 6311 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 6312 } 6313 } else { 6314 resourcePath = pkg.codePath; 6315 baseResourcePath = pkg.baseCodePath; 6316 } 6317 6318 // Set application objects path explicitly. 6319 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 6320 pkg.applicationInfo.setCodePath(pkg.codePath); 6321 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 6322 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 6323 pkg.applicationInfo.setResourcePath(resourcePath); 6324 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 6325 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 6326 6327 // Note that we invoke the following method only if we are about to unpack an application 6328 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 6329 | SCAN_UPDATE_SIGNATURE, currentTime, user); 6330 6331 /* 6332 * If the system app should be overridden by a previously installed 6333 * data, hide the system app now and let the /data/app scan pick it up 6334 * again. 6335 */ 6336 if (shouldHideSystemApp) { 6337 synchronized (mPackages) { 6338 mSettings.disableSystemPackageLPw(pkg.packageName); 6339 } 6340 } 6341 6342 return scannedPkg; 6343 } 6344 6345 private static String fixProcessName(String defProcessName, 6346 String processName, int uid) { 6347 if (processName == null) { 6348 return defProcessName; 6349 } 6350 return processName; 6351 } 6352 6353 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 6354 throws PackageManagerException { 6355 if (pkgSetting.signatures.mSignatures != null) { 6356 // Already existing package. Make sure signatures match 6357 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 6358 == PackageManager.SIGNATURE_MATCH; 6359 if (!match) { 6360 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 6361 == PackageManager.SIGNATURE_MATCH; 6362 } 6363 if (!match) { 6364 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 6365 == PackageManager.SIGNATURE_MATCH; 6366 } 6367 if (!match) { 6368 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 6369 + pkg.packageName + " signatures do not match the " 6370 + "previously installed version; ignoring!"); 6371 } 6372 } 6373 6374 // Check for shared user signatures 6375 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 6376 // Already existing package. Make sure signatures match 6377 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6378 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 6379 if (!match) { 6380 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 6381 == PackageManager.SIGNATURE_MATCH; 6382 } 6383 if (!match) { 6384 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 6385 == PackageManager.SIGNATURE_MATCH; 6386 } 6387 if (!match) { 6388 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 6389 "Package " + pkg.packageName 6390 + " has no signatures that match those in shared user " 6391 + pkgSetting.sharedUser.name + "; ignoring!"); 6392 } 6393 } 6394 } 6395 6396 /** 6397 * Enforces that only the system UID or root's UID can call a method exposed 6398 * via Binder. 6399 * 6400 * @param message used as message if SecurityException is thrown 6401 * @throws SecurityException if the caller is not system or root 6402 */ 6403 private static final void enforceSystemOrRoot(String message) { 6404 final int uid = Binder.getCallingUid(); 6405 if (uid != Process.SYSTEM_UID && uid != 0) { 6406 throw new SecurityException(message); 6407 } 6408 } 6409 6410 @Override 6411 public void performFstrimIfNeeded() { 6412 enforceSystemOrRoot("Only the system can request fstrim"); 6413 6414 // Before everything else, see whether we need to fstrim. 6415 try { 6416 IMountService ms = PackageHelper.getMountService(); 6417 if (ms != null) { 6418 final boolean isUpgrade = isUpgrade(); 6419 boolean doTrim = isUpgrade; 6420 if (doTrim) { 6421 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 6422 } else { 6423 final long interval = android.provider.Settings.Global.getLong( 6424 mContext.getContentResolver(), 6425 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 6426 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 6427 if (interval > 0) { 6428 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 6429 if (timeSinceLast > interval) { 6430 doTrim = true; 6431 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 6432 + "; running immediately"); 6433 } 6434 } 6435 } 6436 if (doTrim) { 6437 if (!isFirstBoot()) { 6438 try { 6439 ActivityManagerNative.getDefault().showBootMessage( 6440 mContext.getResources().getString( 6441 R.string.android_upgrading_fstrim), true); 6442 } catch (RemoteException e) { 6443 } 6444 } 6445 ms.runMaintenance(); 6446 } 6447 } else { 6448 Slog.e(TAG, "Mount service unavailable!"); 6449 } 6450 } catch (RemoteException e) { 6451 // Can't happen; MountService is local 6452 } 6453 } 6454 6455 private ArraySet<String> getPackageNamesForIntent(Intent intent, int userId) { 6456 List<ResolveInfo> ris = null; 6457 try { 6458 ris = AppGlobals.getPackageManager().queryIntentReceivers( 6459 intent, null, 0, userId); 6460 } catch (RemoteException e) { 6461 } 6462 ArraySet<String> pkgNames = new ArraySet<String>(); 6463 if (ris != null) { 6464 for (ResolveInfo ri : ris) { 6465 pkgNames.add(ri.activityInfo.packageName); 6466 } 6467 } 6468 return pkgNames; 6469 } 6470 6471 @Override 6472 public void notifyPackageUse(String packageName) { 6473 synchronized (mPackages) { 6474 PackageParser.Package p = mPackages.get(packageName); 6475 if (p == null) { 6476 return; 6477 } 6478 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6479 } 6480 } 6481 6482 @Override 6483 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6484 return performDexOptTraced(packageName, instructionSet); 6485 } 6486 6487 public boolean performDexOpt(String packageName, String instructionSet) { 6488 return performDexOptTraced(packageName, instructionSet); 6489 } 6490 6491 private boolean performDexOptTraced(String packageName, String instructionSet) { 6492 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 6493 try { 6494 return performDexOptInternal(packageName, instructionSet); 6495 } finally { 6496 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6497 } 6498 } 6499 6500 private boolean performDexOptInternal(String packageName, String instructionSet) { 6501 PackageParser.Package p; 6502 final String targetInstructionSet; 6503 synchronized (mPackages) { 6504 p = mPackages.get(packageName); 6505 if (p == null) { 6506 return false; 6507 } 6508 mPackageUsage.write(false); 6509 6510 targetInstructionSet = instructionSet != null ? instructionSet : 6511 getPrimaryInstructionSet(p.applicationInfo); 6512 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 6513 return false; 6514 } 6515 } 6516 long callingId = Binder.clearCallingIdentity(); 6517 try { 6518 synchronized (mInstallLock) { 6519 final String[] instructionSets = new String[] { targetInstructionSet }; 6520 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 6521 true /* inclDependencies */); 6522 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6523 } 6524 } finally { 6525 Binder.restoreCallingIdentity(callingId); 6526 } 6527 } 6528 6529 public ArraySet<String> getPackagesThatNeedDexOpt() { 6530 ArraySet<String> pkgs = null; 6531 synchronized (mPackages) { 6532 for (PackageParser.Package p : mPackages.values()) { 6533 if (DEBUG_DEXOPT) { 6534 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 6535 } 6536 if (!p.mDexOptPerformed.isEmpty()) { 6537 continue; 6538 } 6539 if (pkgs == null) { 6540 pkgs = new ArraySet<String>(); 6541 } 6542 pkgs.add(p.packageName); 6543 } 6544 } 6545 return pkgs; 6546 } 6547 6548 public void shutdown() { 6549 mPackageUsage.write(true); 6550 } 6551 6552 @Override 6553 public void forceDexOpt(String packageName) { 6554 enforceSystemOrRoot("forceDexOpt"); 6555 6556 PackageParser.Package pkg; 6557 synchronized (mPackages) { 6558 pkg = mPackages.get(packageName); 6559 if (pkg == null) { 6560 throw new IllegalArgumentException("Missing package: " + packageName); 6561 } 6562 } 6563 6564 synchronized (mInstallLock) { 6565 final String[] instructionSets = new String[] { 6566 getPrimaryInstructionSet(pkg.applicationInfo) }; 6567 6568 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 6569 6570 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 6571 true /* inclDependencies */); 6572 6573 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6574 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 6575 throw new IllegalStateException("Failed to dexopt: " + res); 6576 } 6577 } 6578 } 6579 6580 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 6581 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 6582 Slog.w(TAG, "Unable to update from " + oldPkg.name 6583 + " to " + newPkg.packageName 6584 + ": old package not in system partition"); 6585 return false; 6586 } else if (mPackages.get(oldPkg.name) != null) { 6587 Slog.w(TAG, "Unable to update from " + oldPkg.name 6588 + " to " + newPkg.packageName 6589 + ": old package still exists"); 6590 return false; 6591 } 6592 return true; 6593 } 6594 6595 private void createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) 6596 throws PackageManagerException { 6597 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 6598 if (res != 0) { 6599 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6600 "Failed to install " + packageName + ": " + res); 6601 } 6602 6603 final int[] users = sUserManager.getUserIds(); 6604 for (int user : users) { 6605 if (user != 0) { 6606 res = mInstaller.createUserData(volumeUuid, packageName, 6607 UserHandle.getUid(user, uid), user, seinfo); 6608 if (res != 0) { 6609 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6610 "Failed to createUserData " + packageName + ": " + res); 6611 } 6612 } 6613 } 6614 } 6615 6616 private int removeDataDirsLI(String volumeUuid, String packageName) { 6617 int[] users = sUserManager.getUserIds(); 6618 int res = 0; 6619 for (int user : users) { 6620 int resInner = mInstaller.remove(volumeUuid, packageName, user); 6621 if (resInner < 0) { 6622 res = resInner; 6623 } 6624 } 6625 6626 return res; 6627 } 6628 6629 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 6630 int[] users = sUserManager.getUserIds(); 6631 int res = 0; 6632 for (int user : users) { 6633 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 6634 if (resInner < 0) { 6635 res = resInner; 6636 } 6637 } 6638 return res; 6639 } 6640 6641 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 6642 PackageParser.Package changingLib) { 6643 if (file.path != null) { 6644 usesLibraryFiles.add(file.path); 6645 return; 6646 } 6647 PackageParser.Package p = mPackages.get(file.apk); 6648 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 6649 // If we are doing this while in the middle of updating a library apk, 6650 // then we need to make sure to use that new apk for determining the 6651 // dependencies here. (We haven't yet finished committing the new apk 6652 // to the package manager state.) 6653 if (p == null || p.packageName.equals(changingLib.packageName)) { 6654 p = changingLib; 6655 } 6656 } 6657 if (p != null) { 6658 usesLibraryFiles.addAll(p.getAllCodePaths()); 6659 } 6660 } 6661 6662 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 6663 PackageParser.Package changingLib) throws PackageManagerException { 6664 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 6665 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 6666 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 6667 for (int i=0; i<N; i++) { 6668 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 6669 if (file == null) { 6670 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 6671 "Package " + pkg.packageName + " requires unavailable shared library " 6672 + pkg.usesLibraries.get(i) + "; failing!"); 6673 } 6674 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6675 } 6676 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 6677 for (int i=0; i<N; i++) { 6678 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 6679 if (file == null) { 6680 Slog.w(TAG, "Package " + pkg.packageName 6681 + " desires unavailable shared library " 6682 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 6683 } else { 6684 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6685 } 6686 } 6687 N = usesLibraryFiles.size(); 6688 if (N > 0) { 6689 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 6690 } else { 6691 pkg.usesLibraryFiles = null; 6692 } 6693 } 6694 } 6695 6696 private static boolean hasString(List<String> list, List<String> which) { 6697 if (list == null) { 6698 return false; 6699 } 6700 for (int i=list.size()-1; i>=0; i--) { 6701 for (int j=which.size()-1; j>=0; j--) { 6702 if (which.get(j).equals(list.get(i))) { 6703 return true; 6704 } 6705 } 6706 } 6707 return false; 6708 } 6709 6710 private void updateAllSharedLibrariesLPw() { 6711 for (PackageParser.Package pkg : mPackages.values()) { 6712 try { 6713 updateSharedLibrariesLPw(pkg, null); 6714 } catch (PackageManagerException e) { 6715 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6716 } 6717 } 6718 } 6719 6720 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 6721 PackageParser.Package changingPkg) { 6722 ArrayList<PackageParser.Package> res = null; 6723 for (PackageParser.Package pkg : mPackages.values()) { 6724 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 6725 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 6726 if (res == null) { 6727 res = new ArrayList<PackageParser.Package>(); 6728 } 6729 res.add(pkg); 6730 try { 6731 updateSharedLibrariesLPw(pkg, changingPkg); 6732 } catch (PackageManagerException e) { 6733 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6734 } 6735 } 6736 } 6737 return res; 6738 } 6739 6740 /** 6741 * Derive the value of the {@code cpuAbiOverride} based on the provided 6742 * value and an optional stored value from the package settings. 6743 */ 6744 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 6745 String cpuAbiOverride = null; 6746 6747 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 6748 cpuAbiOverride = null; 6749 } else if (abiOverride != null) { 6750 cpuAbiOverride = abiOverride; 6751 } else if (settings != null) { 6752 cpuAbiOverride = settings.cpuAbiOverrideString; 6753 } 6754 6755 return cpuAbiOverride; 6756 } 6757 6758 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags, 6759 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6760 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6761 try { 6762 return scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user); 6763 } finally { 6764 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6765 } 6766 } 6767 6768 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 6769 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6770 boolean success = false; 6771 try { 6772 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 6773 currentTime, user); 6774 success = true; 6775 return res; 6776 } finally { 6777 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 6778 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 6779 } 6780 } 6781 } 6782 6783 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 6784 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6785 final File scanFile = new File(pkg.codePath); 6786 if (pkg.applicationInfo.getCodePath() == null || 6787 pkg.applicationInfo.getResourcePath() == null) { 6788 // Bail out. The resource and code paths haven't been set. 6789 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 6790 "Code and resource paths haven't been set correctly"); 6791 } 6792 6793 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 6794 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 6795 } else { 6796 // Only allow system apps to be flagged as core apps. 6797 pkg.coreApp = false; 6798 } 6799 6800 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 6801 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6802 } 6803 6804 if (mCustomResolverComponentName != null && 6805 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 6806 setUpCustomResolverActivity(pkg); 6807 } 6808 6809 if (pkg.packageName.equals("android")) { 6810 synchronized (mPackages) { 6811 if (mAndroidApplication != null) { 6812 Slog.w(TAG, "*************************************************"); 6813 Slog.w(TAG, "Core android package being redefined. Skipping."); 6814 Slog.w(TAG, " file=" + scanFile); 6815 Slog.w(TAG, "*************************************************"); 6816 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6817 "Core android package being redefined. Skipping."); 6818 } 6819 6820 // Set up information for our fall-back user intent resolution activity. 6821 mPlatformPackage = pkg; 6822 pkg.mVersionCode = mSdkVersion; 6823 mAndroidApplication = pkg.applicationInfo; 6824 6825 if (!mResolverReplaced) { 6826 mResolveActivity.applicationInfo = mAndroidApplication; 6827 mResolveActivity.name = ResolverActivity.class.getName(); 6828 mResolveActivity.packageName = mAndroidApplication.packageName; 6829 mResolveActivity.processName = "system:ui"; 6830 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6831 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 6832 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 6833 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 6834 mResolveActivity.exported = true; 6835 mResolveActivity.enabled = true; 6836 mResolveInfo.activityInfo = mResolveActivity; 6837 mResolveInfo.priority = 0; 6838 mResolveInfo.preferredOrder = 0; 6839 mResolveInfo.match = 0; 6840 mResolveComponentName = new ComponentName( 6841 mAndroidApplication.packageName, mResolveActivity.name); 6842 } 6843 } 6844 } 6845 6846 if (DEBUG_PACKAGE_SCANNING) { 6847 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6848 Log.d(TAG, "Scanning package " + pkg.packageName); 6849 } 6850 6851 if (mPackages.containsKey(pkg.packageName) 6852 || mSharedLibraries.containsKey(pkg.packageName)) { 6853 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6854 "Application package " + pkg.packageName 6855 + " already installed. Skipping duplicate."); 6856 } 6857 6858 // If we're only installing presumed-existing packages, require that the 6859 // scanned APK is both already known and at the path previously established 6860 // for it. Previously unknown packages we pick up normally, but if we have an 6861 // a priori expectation about this package's install presence, enforce it. 6862 // With a singular exception for new system packages. When an OTA contains 6863 // a new system package, we allow the codepath to change from a system location 6864 // to the user-installed location. If we don't allow this change, any newer, 6865 // user-installed version of the application will be ignored. 6866 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 6867 if (mExpectingBetter.containsKey(pkg.packageName)) { 6868 logCriticalInfo(Log.WARN, 6869 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 6870 } else { 6871 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 6872 if (known != null) { 6873 if (DEBUG_PACKAGE_SCANNING) { 6874 Log.d(TAG, "Examining " + pkg.codePath 6875 + " and requiring known paths " + known.codePathString 6876 + " & " + known.resourcePathString); 6877 } 6878 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6879 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6880 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6881 "Application package " + pkg.packageName 6882 + " found at " + pkg.applicationInfo.getCodePath() 6883 + " but expected at " + known.codePathString + "; ignoring."); 6884 } 6885 } 6886 } 6887 } 6888 6889 // Initialize package source and resource directories 6890 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6891 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6892 6893 SharedUserSetting suid = null; 6894 PackageSetting pkgSetting = null; 6895 6896 if (!isSystemApp(pkg)) { 6897 // Only system apps can use these features. 6898 pkg.mOriginalPackages = null; 6899 pkg.mRealPackage = null; 6900 pkg.mAdoptPermissions = null; 6901 } 6902 6903 // writer 6904 synchronized (mPackages) { 6905 if (pkg.mSharedUserId != null) { 6906 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 6907 if (suid == null) { 6908 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6909 "Creating application package " + pkg.packageName 6910 + " for shared user failed"); 6911 } 6912 if (DEBUG_PACKAGE_SCANNING) { 6913 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6914 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 6915 + "): packages=" + suid.packages); 6916 } 6917 } 6918 6919 // Check if we are renaming from an original package name. 6920 PackageSetting origPackage = null; 6921 String realName = null; 6922 if (pkg.mOriginalPackages != null) { 6923 // This package may need to be renamed to a previously 6924 // installed name. Let's check on that... 6925 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 6926 if (pkg.mOriginalPackages.contains(renamed)) { 6927 // This package had originally been installed as the 6928 // original name, and we have already taken care of 6929 // transitioning to the new one. Just update the new 6930 // one to continue using the old name. 6931 realName = pkg.mRealPackage; 6932 if (!pkg.packageName.equals(renamed)) { 6933 // Callers into this function may have already taken 6934 // care of renaming the package; only do it here if 6935 // it is not already done. 6936 pkg.setPackageName(renamed); 6937 } 6938 6939 } else { 6940 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 6941 if ((origPackage = mSettings.peekPackageLPr( 6942 pkg.mOriginalPackages.get(i))) != null) { 6943 // We do have the package already installed under its 6944 // original name... should we use it? 6945 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 6946 // New package is not compatible with original. 6947 origPackage = null; 6948 continue; 6949 } else if (origPackage.sharedUser != null) { 6950 // Make sure uid is compatible between packages. 6951 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 6952 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 6953 + " to " + pkg.packageName + ": old uid " 6954 + origPackage.sharedUser.name 6955 + " differs from " + pkg.mSharedUserId); 6956 origPackage = null; 6957 continue; 6958 } 6959 } else { 6960 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6961 + pkg.packageName + " to old name " + origPackage.name); 6962 } 6963 break; 6964 } 6965 } 6966 } 6967 } 6968 6969 if (mTransferedPackages.contains(pkg.packageName)) { 6970 Slog.w(TAG, "Package " + pkg.packageName 6971 + " was transferred to another, but its .apk remains"); 6972 } 6973 6974 // Just create the setting, don't add it yet. For already existing packages 6975 // the PkgSetting exists already and doesn't have to be created. 6976 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6977 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6978 pkg.applicationInfo.primaryCpuAbi, 6979 pkg.applicationInfo.secondaryCpuAbi, 6980 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6981 user, false); 6982 if (pkgSetting == null) { 6983 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6984 "Creating application package " + pkg.packageName + " failed"); 6985 } 6986 6987 if (pkgSetting.origPackage != null) { 6988 // If we are first transitioning from an original package, 6989 // fix up the new package's name now. We need to do this after 6990 // looking up the package under its new name, so getPackageLP 6991 // can take care of fiddling things correctly. 6992 pkg.setPackageName(origPackage.name); 6993 6994 // File a report about this. 6995 String msg = "New package " + pkgSetting.realName 6996 + " renamed to replace old package " + pkgSetting.name; 6997 reportSettingsProblem(Log.WARN, msg); 6998 6999 // Make a note of it. 7000 mTransferedPackages.add(origPackage.name); 7001 7002 // No longer need to retain this. 7003 pkgSetting.origPackage = null; 7004 } 7005 7006 if (realName != null) { 7007 // Make a note of it. 7008 mTransferedPackages.add(pkg.packageName); 7009 } 7010 7011 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 7012 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 7013 } 7014 7015 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7016 // Check all shared libraries and map to their actual file path. 7017 // We only do this here for apps not on a system dir, because those 7018 // are the only ones that can fail an install due to this. We 7019 // will take care of the system apps by updating all of their 7020 // library paths after the scan is done. 7021 updateSharedLibrariesLPw(pkg, null); 7022 } 7023 7024 if (mFoundPolicyFile) { 7025 SELinuxMMAC.assignSeinfoValue(pkg); 7026 } 7027 7028 pkg.applicationInfo.uid = pkgSetting.appId; 7029 pkg.mExtras = pkgSetting; 7030 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 7031 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 7032 // We just determined the app is signed correctly, so bring 7033 // over the latest parsed certs. 7034 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7035 } else { 7036 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7037 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7038 "Package " + pkg.packageName + " upgrade keys do not match the " 7039 + "previously installed version"); 7040 } else { 7041 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7042 String msg = "System package " + pkg.packageName 7043 + " signature changed; retaining data."; 7044 reportSettingsProblem(Log.WARN, msg); 7045 } 7046 } 7047 } else { 7048 try { 7049 verifySignaturesLP(pkgSetting, pkg); 7050 // We just determined the app is signed correctly, so bring 7051 // over the latest parsed certs. 7052 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7053 } catch (PackageManagerException e) { 7054 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7055 throw e; 7056 } 7057 // The signature has changed, but this package is in the system 7058 // image... let's recover! 7059 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7060 // However... if this package is part of a shared user, but it 7061 // doesn't match the signature of the shared user, let's fail. 7062 // What this means is that you can't change the signatures 7063 // associated with an overall shared user, which doesn't seem all 7064 // that unreasonable. 7065 if (pkgSetting.sharedUser != null) { 7066 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7067 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 7068 throw new PackageManagerException( 7069 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 7070 "Signature mismatch for shared user : " 7071 + pkgSetting.sharedUser); 7072 } 7073 } 7074 // File a report about this. 7075 String msg = "System package " + pkg.packageName 7076 + " signature changed; retaining data."; 7077 reportSettingsProblem(Log.WARN, msg); 7078 } 7079 } 7080 // Verify that this new package doesn't have any content providers 7081 // that conflict with existing packages. Only do this if the 7082 // package isn't already installed, since we don't want to break 7083 // things that are installed. 7084 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 7085 final int N = pkg.providers.size(); 7086 int i; 7087 for (i=0; i<N; i++) { 7088 PackageParser.Provider p = pkg.providers.get(i); 7089 if (p.info.authority != null) { 7090 String names[] = p.info.authority.split(";"); 7091 for (int j = 0; j < names.length; j++) { 7092 if (mProvidersByAuthority.containsKey(names[j])) { 7093 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7094 final String otherPackageName = 7095 ((other != null && other.getComponentName() != null) ? 7096 other.getComponentName().getPackageName() : "?"); 7097 throw new PackageManagerException( 7098 INSTALL_FAILED_CONFLICTING_PROVIDER, 7099 "Can't install because provider name " + names[j] 7100 + " (in package " + pkg.applicationInfo.packageName 7101 + ") is already used by " + otherPackageName); 7102 } 7103 } 7104 } 7105 } 7106 } 7107 7108 if (pkg.mAdoptPermissions != null) { 7109 // This package wants to adopt ownership of permissions from 7110 // another package. 7111 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 7112 final String origName = pkg.mAdoptPermissions.get(i); 7113 final PackageSetting orig = mSettings.peekPackageLPr(origName); 7114 if (orig != null) { 7115 if (verifyPackageUpdateLPr(orig, pkg)) { 7116 Slog.i(TAG, "Adopting permissions from " + origName + " to " 7117 + pkg.packageName); 7118 mSettings.transferPermissionsLPw(origName, pkg.packageName); 7119 } 7120 } 7121 } 7122 } 7123 } 7124 7125 final String pkgName = pkg.packageName; 7126 7127 final long scanFileTime = scanFile.lastModified(); 7128 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 7129 pkg.applicationInfo.processName = fixProcessName( 7130 pkg.applicationInfo.packageName, 7131 pkg.applicationInfo.processName, 7132 pkg.applicationInfo.uid); 7133 7134 if (pkg != mPlatformPackage) { 7135 // This is a normal package, need to make its data directory. 7136 final File dataPath = Environment.getDataUserCredentialEncryptedPackageDirectory( 7137 pkg.volumeUuid, UserHandle.USER_SYSTEM, pkg.packageName); 7138 7139 boolean uidError = false; 7140 if (dataPath.exists()) { 7141 int currentUid = 0; 7142 try { 7143 StructStat stat = Os.stat(dataPath.getPath()); 7144 currentUid = stat.st_uid; 7145 } catch (ErrnoException e) { 7146 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 7147 } 7148 7149 // If we have mismatched owners for the data path, we have a problem. 7150 if (currentUid != pkg.applicationInfo.uid) { 7151 boolean recovered = false; 7152 if (currentUid == 0) { 7153 // The directory somehow became owned by root. Wow. 7154 // This is probably because the system was stopped while 7155 // installd was in the middle of messing with its libs 7156 // directory. Ask installd to fix that. 7157 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 7158 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 7159 if (ret >= 0) { 7160 recovered = true; 7161 String msg = "Package " + pkg.packageName 7162 + " unexpectedly changed to uid 0; recovered to " + 7163 + pkg.applicationInfo.uid; 7164 reportSettingsProblem(Log.WARN, msg); 7165 } 7166 } 7167 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 7168 || (scanFlags&SCAN_BOOTING) != 0)) { 7169 // If this is a system app, we can at least delete its 7170 // current data so the application will still work. 7171 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 7172 if (ret >= 0) { 7173 // TODO: Kill the processes first 7174 // Old data gone! 7175 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 7176 ? "System package " : "Third party package "; 7177 String msg = prefix + pkg.packageName 7178 + " has changed from uid: " 7179 + currentUid + " to " 7180 + pkg.applicationInfo.uid + "; old data erased"; 7181 reportSettingsProblem(Log.WARN, msg); 7182 recovered = true; 7183 } 7184 if (!recovered) { 7185 mHasSystemUidErrors = true; 7186 } 7187 } else if (!recovered) { 7188 // If we allow this install to proceed, we will be broken. 7189 // Abort, abort! 7190 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 7191 "scanPackageLI"); 7192 } 7193 if (!recovered) { 7194 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 7195 + pkg.applicationInfo.uid + "/fs_" 7196 + currentUid; 7197 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 7198 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 7199 String msg = "Package " + pkg.packageName 7200 + " has mismatched uid: " 7201 + currentUid + " on disk, " 7202 + pkg.applicationInfo.uid + " in settings"; 7203 // writer 7204 synchronized (mPackages) { 7205 mSettings.mReadMessages.append(msg); 7206 mSettings.mReadMessages.append('\n'); 7207 uidError = true; 7208 if (!pkgSetting.uidError) { 7209 reportSettingsProblem(Log.ERROR, msg); 7210 } 7211 } 7212 } 7213 } 7214 7215 // Ensure that directories are prepared 7216 createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 7217 pkg.applicationInfo.seinfo); 7218 7219 if (mShouldRestoreconData) { 7220 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 7221 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 7222 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 7223 } 7224 } else { 7225 if (DEBUG_PACKAGE_SCANNING) { 7226 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7227 Log.v(TAG, "Want this data dir: " + dataPath); 7228 } 7229 createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 7230 pkg.applicationInfo.seinfo); 7231 } 7232 7233 // Get all of our default paths setup 7234 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 7235 7236 pkgSetting.uidError = uidError; 7237 } 7238 7239 final String path = scanFile.getPath(); 7240 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 7241 7242 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 7243 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 7244 7245 // Some system apps still use directory structure for native libraries 7246 // in which case we might end up not detecting abi solely based on apk 7247 // structure. Try to detect abi based on directory structure. 7248 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 7249 pkg.applicationInfo.primaryCpuAbi == null) { 7250 setBundledAppAbisAndRoots(pkg, pkgSetting); 7251 setNativeLibraryPaths(pkg); 7252 } 7253 7254 } else { 7255 if ((scanFlags & SCAN_MOVE) != 0) { 7256 // We haven't run dex-opt for this move (since we've moved the compiled output too) 7257 // but we already have this packages package info in the PackageSetting. We just 7258 // use that and derive the native library path based on the new codepath. 7259 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 7260 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 7261 } 7262 7263 // Set native library paths again. For moves, the path will be updated based on the 7264 // ABIs we've determined above. For non-moves, the path will be updated based on the 7265 // ABIs we determined during compilation, but the path will depend on the final 7266 // package path (after the rename away from the stage path). 7267 setNativeLibraryPaths(pkg); 7268 } 7269 7270 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 7271 final int[] userIds = sUserManager.getUserIds(); 7272 synchronized (mInstallLock) { 7273 // Make sure all user data directories are ready to roll; we're okay 7274 // if they already exist 7275 if (!TextUtils.isEmpty(pkg.volumeUuid)) { 7276 for (int userId : userIds) { 7277 if (userId != UserHandle.USER_SYSTEM) { 7278 mInstaller.createUserData(pkg.volumeUuid, pkg.packageName, 7279 UserHandle.getUid(userId, pkg.applicationInfo.uid), userId, 7280 pkg.applicationInfo.seinfo); 7281 } 7282 } 7283 } 7284 7285 // Create a native library symlink only if we have native libraries 7286 // and if the native libraries are 32 bit libraries. We do not provide 7287 // this symlink for 64 bit libraries. 7288 if (pkg.applicationInfo.primaryCpuAbi != null && 7289 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 7290 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "linkNativeLib"); 7291 try { 7292 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 7293 for (int userId : userIds) { 7294 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 7295 nativeLibPath, userId) < 0) { 7296 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7297 "Failed linking native library dir (user=" + userId + ")"); 7298 } 7299 } 7300 } finally { 7301 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7302 } 7303 } 7304 } 7305 7306 // This is a special case for the "system" package, where the ABI is 7307 // dictated by the zygote configuration (and init.rc). We should keep track 7308 // of this ABI so that we can deal with "normal" applications that run under 7309 // the same UID correctly. 7310 if (mPlatformPackage == pkg) { 7311 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 7312 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 7313 } 7314 7315 // If there's a mismatch between the abi-override in the package setting 7316 // and the abiOverride specified for the install. Warn about this because we 7317 // would've already compiled the app without taking the package setting into 7318 // account. 7319 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 7320 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 7321 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 7322 " for package: " + pkg.packageName); 7323 } 7324 } 7325 7326 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7327 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7328 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 7329 7330 // Copy the derived override back to the parsed package, so that we can 7331 // update the package settings accordingly. 7332 pkg.cpuAbiOverride = cpuAbiOverride; 7333 7334 if (DEBUG_ABI_SELECTION) { 7335 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 7336 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 7337 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 7338 } 7339 7340 // Push the derived path down into PackageSettings so we know what to 7341 // clean up at uninstall time. 7342 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 7343 7344 if (DEBUG_ABI_SELECTION) { 7345 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 7346 " primary=" + pkg.applicationInfo.primaryCpuAbi + 7347 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 7348 } 7349 7350 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 7351 // We don't do this here during boot because we can do it all 7352 // at once after scanning all existing packages. 7353 // 7354 // We also do this *before* we perform dexopt on this package, so that 7355 // we can avoid redundant dexopts, and also to make sure we've got the 7356 // code and package path correct. 7357 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 7358 pkg, true /* boot complete */); 7359 } 7360 7361 if (mFactoryTest && pkg.requestedPermissions.contains( 7362 android.Manifest.permission.FACTORY_TEST)) { 7363 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 7364 } 7365 7366 ArrayList<PackageParser.Package> clientLibPkgs = null; 7367 7368 // writer 7369 synchronized (mPackages) { 7370 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7371 // Only system apps can add new shared libraries. 7372 if (pkg.libraryNames != null) { 7373 for (int i=0; i<pkg.libraryNames.size(); i++) { 7374 String name = pkg.libraryNames.get(i); 7375 boolean allowed = false; 7376 if (pkg.isUpdatedSystemApp()) { 7377 // New library entries can only be added through the 7378 // system image. This is important to get rid of a lot 7379 // of nasty edge cases: for example if we allowed a non- 7380 // system update of the app to add a library, then uninstalling 7381 // the update would make the library go away, and assumptions 7382 // we made such as through app install filtering would now 7383 // have allowed apps on the device which aren't compatible 7384 // with it. Better to just have the restriction here, be 7385 // conservative, and create many fewer cases that can negatively 7386 // impact the user experience. 7387 final PackageSetting sysPs = mSettings 7388 .getDisabledSystemPkgLPr(pkg.packageName); 7389 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 7390 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 7391 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 7392 allowed = true; 7393 break; 7394 } 7395 } 7396 } 7397 } else { 7398 allowed = true; 7399 } 7400 if (allowed) { 7401 if (!mSharedLibraries.containsKey(name)) { 7402 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 7403 } else if (!name.equals(pkg.packageName)) { 7404 Slog.w(TAG, "Package " + pkg.packageName + " library " 7405 + name + " already exists; skipping"); 7406 } 7407 } else { 7408 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 7409 + name + " that is not declared on system image; skipping"); 7410 } 7411 } 7412 if ((scanFlags & SCAN_BOOTING) == 0) { 7413 // If we are not booting, we need to update any applications 7414 // that are clients of our shared library. If we are booting, 7415 // this will all be done once the scan is complete. 7416 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 7417 } 7418 } 7419 } 7420 } 7421 7422 // Request the ActivityManager to kill the process(only for existing packages) 7423 // so that we do not end up in a confused state while the user is still using the older 7424 // version of the application while the new one gets installed. 7425 if ((scanFlags & SCAN_REPLACING) != 0) { 7426 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication"); 7427 7428 killApplication(pkg.applicationInfo.packageName, 7429 pkg.applicationInfo.uid, "replace pkg"); 7430 7431 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7432 } 7433 7434 // Also need to kill any apps that are dependent on the library. 7435 if (clientLibPkgs != null) { 7436 for (int i=0; i<clientLibPkgs.size(); i++) { 7437 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7438 killApplication(clientPkg.applicationInfo.packageName, 7439 clientPkg.applicationInfo.uid, "update lib"); 7440 } 7441 } 7442 7443 // Make sure we're not adding any bogus keyset info 7444 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7445 ksms.assertScannedPackageValid(pkg); 7446 7447 // writer 7448 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 7449 7450 boolean createIdmapFailed = false; 7451 synchronized (mPackages) { 7452 // We don't expect installation to fail beyond this point 7453 7454 // Add the new setting to mSettings 7455 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 7456 // Add the new setting to mPackages 7457 mPackages.put(pkg.applicationInfo.packageName, pkg); 7458 // Make sure we don't accidentally delete its data. 7459 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 7460 while (iter.hasNext()) { 7461 PackageCleanItem item = iter.next(); 7462 if (pkgName.equals(item.packageName)) { 7463 iter.remove(); 7464 } 7465 } 7466 7467 // Take care of first install / last update times. 7468 if (currentTime != 0) { 7469 if (pkgSetting.firstInstallTime == 0) { 7470 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7471 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7472 pkgSetting.lastUpdateTime = currentTime; 7473 } 7474 } else if (pkgSetting.firstInstallTime == 0) { 7475 // We need *something*. Take time time stamp of the file. 7476 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7477 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7478 if (scanFileTime != pkgSetting.timeStamp) { 7479 // A package on the system image has changed; consider this 7480 // to be an update. 7481 pkgSetting.lastUpdateTime = scanFileTime; 7482 } 7483 } 7484 7485 // Add the package's KeySets to the global KeySetManagerService 7486 ksms.addScannedPackageLPw(pkg); 7487 7488 int N = pkg.providers.size(); 7489 StringBuilder r = null; 7490 int i; 7491 for (i=0; i<N; i++) { 7492 PackageParser.Provider p = pkg.providers.get(i); 7493 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7494 p.info.processName, pkg.applicationInfo.uid); 7495 mProviders.addProvider(p); 7496 p.syncable = p.info.isSyncable; 7497 if (p.info.authority != null) { 7498 String names[] = p.info.authority.split(";"); 7499 p.info.authority = null; 7500 for (int j = 0; j < names.length; j++) { 7501 if (j == 1 && p.syncable) { 7502 // We only want the first authority for a provider to possibly be 7503 // syncable, so if we already added this provider using a different 7504 // authority clear the syncable flag. We copy the provider before 7505 // changing it because the mProviders object contains a reference 7506 // to a provider that we don't want to change. 7507 // Only do this for the second authority since the resulting provider 7508 // object can be the same for all future authorities for this provider. 7509 p = new PackageParser.Provider(p); 7510 p.syncable = false; 7511 } 7512 if (!mProvidersByAuthority.containsKey(names[j])) { 7513 mProvidersByAuthority.put(names[j], p); 7514 if (p.info.authority == null) { 7515 p.info.authority = names[j]; 7516 } else { 7517 p.info.authority = p.info.authority + ";" + names[j]; 7518 } 7519 if (DEBUG_PACKAGE_SCANNING) { 7520 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7521 Log.d(TAG, "Registered content provider: " + names[j] 7522 + ", className = " + p.info.name + ", isSyncable = " 7523 + p.info.isSyncable); 7524 } 7525 } else { 7526 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7527 Slog.w(TAG, "Skipping provider name " + names[j] + 7528 " (in package " + pkg.applicationInfo.packageName + 7529 "): name already used by " 7530 + ((other != null && other.getComponentName() != null) 7531 ? other.getComponentName().getPackageName() : "?")); 7532 } 7533 } 7534 } 7535 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7536 if (r == null) { 7537 r = new StringBuilder(256); 7538 } else { 7539 r.append(' '); 7540 } 7541 r.append(p.info.name); 7542 } 7543 } 7544 if (r != null) { 7545 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7546 } 7547 7548 N = pkg.services.size(); 7549 r = null; 7550 for (i=0; i<N; i++) { 7551 PackageParser.Service s = pkg.services.get(i); 7552 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 7553 s.info.processName, pkg.applicationInfo.uid); 7554 mServices.addService(s); 7555 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7556 if (r == null) { 7557 r = new StringBuilder(256); 7558 } else { 7559 r.append(' '); 7560 } 7561 r.append(s.info.name); 7562 } 7563 } 7564 if (r != null) { 7565 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 7566 } 7567 7568 N = pkg.receivers.size(); 7569 r = null; 7570 for (i=0; i<N; i++) { 7571 PackageParser.Activity a = pkg.receivers.get(i); 7572 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7573 a.info.processName, pkg.applicationInfo.uid); 7574 mReceivers.addActivity(a, "receiver"); 7575 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7576 if (r == null) { 7577 r = new StringBuilder(256); 7578 } else { 7579 r.append(' '); 7580 } 7581 r.append(a.info.name); 7582 } 7583 } 7584 if (r != null) { 7585 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 7586 } 7587 7588 N = pkg.activities.size(); 7589 r = null; 7590 for (i=0; i<N; i++) { 7591 PackageParser.Activity a = pkg.activities.get(i); 7592 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7593 a.info.processName, pkg.applicationInfo.uid); 7594 mActivities.addActivity(a, "activity"); 7595 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7596 if (r == null) { 7597 r = new StringBuilder(256); 7598 } else { 7599 r.append(' '); 7600 } 7601 r.append(a.info.name); 7602 } 7603 } 7604 if (r != null) { 7605 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 7606 } 7607 7608 N = pkg.permissionGroups.size(); 7609 r = null; 7610 for (i=0; i<N; i++) { 7611 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 7612 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 7613 if (cur == null) { 7614 mPermissionGroups.put(pg.info.name, pg); 7615 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7616 if (r == null) { 7617 r = new StringBuilder(256); 7618 } else { 7619 r.append(' '); 7620 } 7621 r.append(pg.info.name); 7622 } 7623 } else { 7624 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 7625 + pg.info.packageName + " ignored: original from " 7626 + cur.info.packageName); 7627 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7628 if (r == null) { 7629 r = new StringBuilder(256); 7630 } else { 7631 r.append(' '); 7632 } 7633 r.append("DUP:"); 7634 r.append(pg.info.name); 7635 } 7636 } 7637 } 7638 if (r != null) { 7639 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 7640 } 7641 7642 N = pkg.permissions.size(); 7643 r = null; 7644 for (i=0; i<N; i++) { 7645 PackageParser.Permission p = pkg.permissions.get(i); 7646 7647 // Assume by default that we did not install this permission into the system. 7648 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 7649 7650 // Now that permission groups have a special meaning, we ignore permission 7651 // groups for legacy apps to prevent unexpected behavior. In particular, 7652 // permissions for one app being granted to someone just becuase they happen 7653 // to be in a group defined by another app (before this had no implications). 7654 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 7655 p.group = mPermissionGroups.get(p.info.group); 7656 // Warn for a permission in an unknown group. 7657 if (p.info.group != null && p.group == null) { 7658 Slog.w(TAG, "Permission " + p.info.name + " from package " 7659 + p.info.packageName + " in an unknown group " + p.info.group); 7660 } 7661 } 7662 7663 ArrayMap<String, BasePermission> permissionMap = 7664 p.tree ? mSettings.mPermissionTrees 7665 : mSettings.mPermissions; 7666 BasePermission bp = permissionMap.get(p.info.name); 7667 7668 // Allow system apps to redefine non-system permissions 7669 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 7670 final boolean currentOwnerIsSystem = (bp.perm != null 7671 && isSystemApp(bp.perm.owner)); 7672 if (isSystemApp(p.owner)) { 7673 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 7674 // It's a built-in permission and no owner, take ownership now 7675 bp.packageSetting = pkgSetting; 7676 bp.perm = p; 7677 bp.uid = pkg.applicationInfo.uid; 7678 bp.sourcePackage = p.info.packageName; 7679 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7680 } else if (!currentOwnerIsSystem) { 7681 String msg = "New decl " + p.owner + " of permission " 7682 + p.info.name + " is system; overriding " + bp.sourcePackage; 7683 reportSettingsProblem(Log.WARN, msg); 7684 bp = null; 7685 } 7686 } 7687 } 7688 7689 if (bp == null) { 7690 bp = new BasePermission(p.info.name, p.info.packageName, 7691 BasePermission.TYPE_NORMAL); 7692 permissionMap.put(p.info.name, bp); 7693 } 7694 7695 if (bp.perm == null) { 7696 if (bp.sourcePackage == null 7697 || bp.sourcePackage.equals(p.info.packageName)) { 7698 BasePermission tree = findPermissionTreeLP(p.info.name); 7699 if (tree == null 7700 || tree.sourcePackage.equals(p.info.packageName)) { 7701 bp.packageSetting = pkgSetting; 7702 bp.perm = p; 7703 bp.uid = pkg.applicationInfo.uid; 7704 bp.sourcePackage = p.info.packageName; 7705 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7706 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7707 if (r == null) { 7708 r = new StringBuilder(256); 7709 } else { 7710 r.append(' '); 7711 } 7712 r.append(p.info.name); 7713 } 7714 } else { 7715 Slog.w(TAG, "Permission " + p.info.name + " from package " 7716 + p.info.packageName + " ignored: base tree " 7717 + tree.name + " is from package " 7718 + tree.sourcePackage); 7719 } 7720 } else { 7721 Slog.w(TAG, "Permission " + p.info.name + " from package " 7722 + p.info.packageName + " ignored: original from " 7723 + bp.sourcePackage); 7724 } 7725 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7726 if (r == null) { 7727 r = new StringBuilder(256); 7728 } else { 7729 r.append(' '); 7730 } 7731 r.append("DUP:"); 7732 r.append(p.info.name); 7733 } 7734 if (bp.perm == p) { 7735 bp.protectionLevel = p.info.protectionLevel; 7736 } 7737 } 7738 7739 if (r != null) { 7740 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 7741 } 7742 7743 N = pkg.instrumentation.size(); 7744 r = null; 7745 for (i=0; i<N; i++) { 7746 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7747 a.info.packageName = pkg.applicationInfo.packageName; 7748 a.info.sourceDir = pkg.applicationInfo.sourceDir; 7749 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 7750 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 7751 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 7752 a.info.dataDir = pkg.applicationInfo.dataDir; 7753 a.info.deviceEncryptedDataDir = pkg.applicationInfo.deviceEncryptedDataDir; 7754 a.info.credentialEncryptedDataDir = pkg.applicationInfo.credentialEncryptedDataDir; 7755 7756 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 7757 // need other information about the application, like the ABI and what not ? 7758 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 7759 mInstrumentation.put(a.getComponentName(), a); 7760 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7761 if (r == null) { 7762 r = new StringBuilder(256); 7763 } else { 7764 r.append(' '); 7765 } 7766 r.append(a.info.name); 7767 } 7768 } 7769 if (r != null) { 7770 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 7771 } 7772 7773 if (pkg.protectedBroadcasts != null) { 7774 N = pkg.protectedBroadcasts.size(); 7775 for (i=0; i<N; i++) { 7776 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 7777 } 7778 } 7779 7780 pkgSetting.setTimeStamp(scanFileTime); 7781 7782 // Create idmap files for pairs of (packages, overlay packages). 7783 // Note: "android", ie framework-res.apk, is handled by native layers. 7784 if (pkg.mOverlayTarget != null) { 7785 // This is an overlay package. 7786 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 7787 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 7788 mOverlays.put(pkg.mOverlayTarget, 7789 new ArrayMap<String, PackageParser.Package>()); 7790 } 7791 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 7792 map.put(pkg.packageName, pkg); 7793 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 7794 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 7795 createIdmapFailed = true; 7796 } 7797 } 7798 } else if (mOverlays.containsKey(pkg.packageName) && 7799 !pkg.packageName.equals("android")) { 7800 // This is a regular package, with one or more known overlay packages. 7801 createIdmapsForPackageLI(pkg); 7802 } 7803 } 7804 7805 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7806 7807 if (createIdmapFailed) { 7808 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7809 "scanPackageLI failed to createIdmap"); 7810 } 7811 return pkg; 7812 } 7813 7814 /** 7815 * Derive the ABI of a non-system package located at {@code scanFile}. This information 7816 * is derived purely on the basis of the contents of {@code scanFile} and 7817 * {@code cpuAbiOverride}. 7818 * 7819 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 7820 */ 7821 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 7822 String cpuAbiOverride, boolean extractLibs) 7823 throws PackageManagerException { 7824 // TODO: We can probably be smarter about this stuff. For installed apps, 7825 // we can calculate this information at install time once and for all. For 7826 // system apps, we can probably assume that this information doesn't change 7827 // after the first boot scan. As things stand, we do lots of unnecessary work. 7828 7829 // Give ourselves some initial paths; we'll come back for another 7830 // pass once we've determined ABI below. 7831 setNativeLibraryPaths(pkg); 7832 7833 // We would never need to extract libs for forward-locked and external packages, 7834 // since the container service will do it for us. We shouldn't attempt to 7835 // extract libs from system app when it was not updated. 7836 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 7837 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 7838 extractLibs = false; 7839 } 7840 7841 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7842 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7843 7844 NativeLibraryHelper.Handle handle = null; 7845 try { 7846 handle = NativeLibraryHelper.Handle.create(pkg); 7847 // TODO(multiArch): This can be null for apps that didn't go through the 7848 // usual installation process. We can calculate it again, like we 7849 // do during install time. 7850 // 7851 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7852 // unnecessary. 7853 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7854 7855 // Null out the abis so that they can be recalculated. 7856 pkg.applicationInfo.primaryCpuAbi = null; 7857 pkg.applicationInfo.secondaryCpuAbi = null; 7858 if (isMultiArch(pkg.applicationInfo)) { 7859 // Warn if we've set an abiOverride for multi-lib packages.. 7860 // By definition, we need to copy both 32 and 64 bit libraries for 7861 // such packages. 7862 if (pkg.cpuAbiOverride != null 7863 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7864 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7865 } 7866 7867 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7868 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7869 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7870 if (extractLibs) { 7871 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7872 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7873 useIsaSpecificSubdirs); 7874 } else { 7875 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7876 } 7877 } 7878 7879 maybeThrowExceptionForMultiArchCopy( 7880 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7881 7882 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7883 if (extractLibs) { 7884 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7885 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7886 useIsaSpecificSubdirs); 7887 } else { 7888 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7889 } 7890 } 7891 7892 maybeThrowExceptionForMultiArchCopy( 7893 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7894 7895 if (abi64 >= 0) { 7896 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7897 } 7898 7899 if (abi32 >= 0) { 7900 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7901 if (abi64 >= 0) { 7902 pkg.applicationInfo.secondaryCpuAbi = abi; 7903 } else { 7904 pkg.applicationInfo.primaryCpuAbi = abi; 7905 } 7906 } 7907 } else { 7908 String[] abiList = (cpuAbiOverride != null) ? 7909 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7910 7911 // Enable gross and lame hacks for apps that are built with old 7912 // SDK tools. We must scan their APKs for renderscript bitcode and 7913 // not launch them if it's present. Don't bother checking on devices 7914 // that don't have 64 bit support. 7915 boolean needsRenderScriptOverride = false; 7916 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7917 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7918 abiList = Build.SUPPORTED_32_BIT_ABIS; 7919 needsRenderScriptOverride = true; 7920 } 7921 7922 final int copyRet; 7923 if (extractLibs) { 7924 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7925 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7926 } else { 7927 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7928 } 7929 7930 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7931 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7932 "Error unpackaging native libs for app, errorCode=" + copyRet); 7933 } 7934 7935 if (copyRet >= 0) { 7936 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7937 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7938 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7939 } else if (needsRenderScriptOverride) { 7940 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7941 } 7942 } 7943 } catch (IOException ioe) { 7944 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7945 } finally { 7946 IoUtils.closeQuietly(handle); 7947 } 7948 7949 // Now that we've calculated the ABIs and determined if it's an internal app, 7950 // we will go ahead and populate the nativeLibraryPath. 7951 setNativeLibraryPaths(pkg); 7952 } 7953 7954 /** 7955 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7956 * i.e, so that all packages can be run inside a single process if required. 7957 * 7958 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7959 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7960 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7961 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7962 * updating a package that belongs to a shared user. 7963 * 7964 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7965 * adds unnecessary complexity. 7966 */ 7967 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7968 PackageParser.Package scannedPackage, boolean bootComplete) { 7969 String requiredInstructionSet = null; 7970 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7971 requiredInstructionSet = VMRuntime.getInstructionSet( 7972 scannedPackage.applicationInfo.primaryCpuAbi); 7973 } 7974 7975 PackageSetting requirer = null; 7976 for (PackageSetting ps : packagesForUser) { 7977 // If packagesForUser contains scannedPackage, we skip it. This will happen 7978 // when scannedPackage is an update of an existing package. Without this check, 7979 // we will never be able to change the ABI of any package belonging to a shared 7980 // user, even if it's compatible with other packages. 7981 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7982 if (ps.primaryCpuAbiString == null) { 7983 continue; 7984 } 7985 7986 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7987 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7988 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7989 // this but there's not much we can do. 7990 String errorMessage = "Instruction set mismatch, " 7991 + ((requirer == null) ? "[caller]" : requirer) 7992 + " requires " + requiredInstructionSet + " whereas " + ps 7993 + " requires " + instructionSet; 7994 Slog.w(TAG, errorMessage); 7995 } 7996 7997 if (requiredInstructionSet == null) { 7998 requiredInstructionSet = instructionSet; 7999 requirer = ps; 8000 } 8001 } 8002 } 8003 8004 if (requiredInstructionSet != null) { 8005 String adjustedAbi; 8006 if (requirer != null) { 8007 // requirer != null implies that either scannedPackage was null or that scannedPackage 8008 // did not require an ABI, in which case we have to adjust scannedPackage to match 8009 // the ABI of the set (which is the same as requirer's ABI) 8010 adjustedAbi = requirer.primaryCpuAbiString; 8011 if (scannedPackage != null) { 8012 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 8013 } 8014 } else { 8015 // requirer == null implies that we're updating all ABIs in the set to 8016 // match scannedPackage. 8017 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 8018 } 8019 8020 for (PackageSetting ps : packagesForUser) { 8021 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8022 if (ps.primaryCpuAbiString != null) { 8023 continue; 8024 } 8025 8026 ps.primaryCpuAbiString = adjustedAbi; 8027 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 8028 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 8029 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 8030 mInstaller.rmdex(ps.codePathString, 8031 getDexCodeInstructionSet(getPreferredInstructionSet())); 8032 } 8033 } 8034 } 8035 } 8036 } 8037 8038 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 8039 synchronized (mPackages) { 8040 mResolverReplaced = true; 8041 // Set up information for custom user intent resolution activity. 8042 mResolveActivity.applicationInfo = pkg.applicationInfo; 8043 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 8044 mResolveActivity.packageName = pkg.applicationInfo.packageName; 8045 mResolveActivity.processName = pkg.applicationInfo.packageName; 8046 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8047 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8048 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8049 mResolveActivity.theme = 0; 8050 mResolveActivity.exported = true; 8051 mResolveActivity.enabled = true; 8052 mResolveInfo.activityInfo = mResolveActivity; 8053 mResolveInfo.priority = 0; 8054 mResolveInfo.preferredOrder = 0; 8055 mResolveInfo.match = 0; 8056 mResolveComponentName = mCustomResolverComponentName; 8057 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 8058 mResolveComponentName); 8059 } 8060 } 8061 8062 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 8063 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 8064 8065 // Set up information for ephemeral installer activity 8066 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 8067 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 8068 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 8069 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 8070 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8071 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8072 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8073 mEphemeralInstallerActivity.theme = 0; 8074 mEphemeralInstallerActivity.exported = true; 8075 mEphemeralInstallerActivity.enabled = true; 8076 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 8077 mEphemeralInstallerInfo.priority = 0; 8078 mEphemeralInstallerInfo.preferredOrder = 0; 8079 mEphemeralInstallerInfo.match = 0; 8080 8081 if (DEBUG_EPHEMERAL) { 8082 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 8083 } 8084 } 8085 8086 private static String calculateBundledApkRoot(final String codePathString) { 8087 final File codePath = new File(codePathString); 8088 final File codeRoot; 8089 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 8090 codeRoot = Environment.getRootDirectory(); 8091 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 8092 codeRoot = Environment.getOemDirectory(); 8093 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 8094 codeRoot = Environment.getVendorDirectory(); 8095 } else { 8096 // Unrecognized code path; take its top real segment as the apk root: 8097 // e.g. /something/app/blah.apk => /something 8098 try { 8099 File f = codePath.getCanonicalFile(); 8100 File parent = f.getParentFile(); // non-null because codePath is a file 8101 File tmp; 8102 while ((tmp = parent.getParentFile()) != null) { 8103 f = parent; 8104 parent = tmp; 8105 } 8106 codeRoot = f; 8107 Slog.w(TAG, "Unrecognized code path " 8108 + codePath + " - using " + codeRoot); 8109 } catch (IOException e) { 8110 // Can't canonicalize the code path -- shenanigans? 8111 Slog.w(TAG, "Can't canonicalize code path " + codePath); 8112 return Environment.getRootDirectory().getPath(); 8113 } 8114 } 8115 return codeRoot.getPath(); 8116 } 8117 8118 /** 8119 * Derive and set the location of native libraries for the given package, 8120 * which varies depending on where and how the package was installed. 8121 */ 8122 private void setNativeLibraryPaths(PackageParser.Package pkg) { 8123 final ApplicationInfo info = pkg.applicationInfo; 8124 final String codePath = pkg.codePath; 8125 final File codeFile = new File(codePath); 8126 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 8127 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 8128 8129 info.nativeLibraryRootDir = null; 8130 info.nativeLibraryRootRequiresIsa = false; 8131 info.nativeLibraryDir = null; 8132 info.secondaryNativeLibraryDir = null; 8133 8134 if (isApkFile(codeFile)) { 8135 // Monolithic install 8136 if (bundledApp) { 8137 // If "/system/lib64/apkname" exists, assume that is the per-package 8138 // native library directory to use; otherwise use "/system/lib/apkname". 8139 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 8140 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 8141 getPrimaryInstructionSet(info)); 8142 8143 // This is a bundled system app so choose the path based on the ABI. 8144 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 8145 // is just the default path. 8146 final String apkName = deriveCodePathName(codePath); 8147 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 8148 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 8149 apkName).getAbsolutePath(); 8150 8151 if (info.secondaryCpuAbi != null) { 8152 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 8153 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 8154 secondaryLibDir, apkName).getAbsolutePath(); 8155 } 8156 } else if (asecApp) { 8157 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 8158 .getAbsolutePath(); 8159 } else { 8160 final String apkName = deriveCodePathName(codePath); 8161 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 8162 .getAbsolutePath(); 8163 } 8164 8165 info.nativeLibraryRootRequiresIsa = false; 8166 info.nativeLibraryDir = info.nativeLibraryRootDir; 8167 } else { 8168 // Cluster install 8169 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 8170 info.nativeLibraryRootRequiresIsa = true; 8171 8172 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 8173 getPrimaryInstructionSet(info)).getAbsolutePath(); 8174 8175 if (info.secondaryCpuAbi != null) { 8176 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 8177 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 8178 } 8179 } 8180 } 8181 8182 /** 8183 * Calculate the abis and roots for a bundled app. These can uniquely 8184 * be determined from the contents of the system partition, i.e whether 8185 * it contains 64 or 32 bit shared libraries etc. We do not validate any 8186 * of this information, and instead assume that the system was built 8187 * sensibly. 8188 */ 8189 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 8190 PackageSetting pkgSetting) { 8191 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 8192 8193 // If "/system/lib64/apkname" exists, assume that is the per-package 8194 // native library directory to use; otherwise use "/system/lib/apkname". 8195 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 8196 setBundledAppAbi(pkg, apkRoot, apkName); 8197 // pkgSetting might be null during rescan following uninstall of updates 8198 // to a bundled app, so accommodate that possibility. The settings in 8199 // that case will be established later from the parsed package. 8200 // 8201 // If the settings aren't null, sync them up with what we've just derived. 8202 // note that apkRoot isn't stored in the package settings. 8203 if (pkgSetting != null) { 8204 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8205 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8206 } 8207 } 8208 8209 /** 8210 * Deduces the ABI of a bundled app and sets the relevant fields on the 8211 * parsed pkg object. 8212 * 8213 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 8214 * under which system libraries are installed. 8215 * @param apkName the name of the installed package. 8216 */ 8217 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 8218 final File codeFile = new File(pkg.codePath); 8219 8220 final boolean has64BitLibs; 8221 final boolean has32BitLibs; 8222 if (isApkFile(codeFile)) { 8223 // Monolithic install 8224 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 8225 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 8226 } else { 8227 // Cluster install 8228 final File rootDir = new File(codeFile, LIB_DIR_NAME); 8229 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 8230 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 8231 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 8232 has64BitLibs = (new File(rootDir, isa)).exists(); 8233 } else { 8234 has64BitLibs = false; 8235 } 8236 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 8237 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 8238 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 8239 has32BitLibs = (new File(rootDir, isa)).exists(); 8240 } else { 8241 has32BitLibs = false; 8242 } 8243 } 8244 8245 if (has64BitLibs && !has32BitLibs) { 8246 // The package has 64 bit libs, but not 32 bit libs. Its primary 8247 // ABI should be 64 bit. We can safely assume here that the bundled 8248 // native libraries correspond to the most preferred ABI in the list. 8249 8250 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8251 pkg.applicationInfo.secondaryCpuAbi = null; 8252 } else if (has32BitLibs && !has64BitLibs) { 8253 // The package has 32 bit libs but not 64 bit libs. Its primary 8254 // ABI should be 32 bit. 8255 8256 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8257 pkg.applicationInfo.secondaryCpuAbi = null; 8258 } else if (has32BitLibs && has64BitLibs) { 8259 // The application has both 64 and 32 bit bundled libraries. We check 8260 // here that the app declares multiArch support, and warn if it doesn't. 8261 // 8262 // We will be lenient here and record both ABIs. The primary will be the 8263 // ABI that's higher on the list, i.e, a device that's configured to prefer 8264 // 64 bit apps will see a 64 bit primary ABI, 8265 8266 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 8267 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 8268 } 8269 8270 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 8271 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8272 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8273 } else { 8274 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8275 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8276 } 8277 } else { 8278 pkg.applicationInfo.primaryCpuAbi = null; 8279 pkg.applicationInfo.secondaryCpuAbi = null; 8280 } 8281 } 8282 8283 private void killApplication(String pkgName, int appId, String reason) { 8284 // Request the ActivityManager to kill the process(only for existing packages) 8285 // so that we do not end up in a confused state while the user is still using the older 8286 // version of the application while the new one gets installed. 8287 IActivityManager am = ActivityManagerNative.getDefault(); 8288 if (am != null) { 8289 try { 8290 am.killApplicationWithAppId(pkgName, appId, reason); 8291 } catch (RemoteException e) { 8292 } 8293 } 8294 } 8295 8296 void removePackageLI(PackageSetting ps, boolean chatty) { 8297 if (DEBUG_INSTALL) { 8298 if (chatty) 8299 Log.d(TAG, "Removing package " + ps.name); 8300 } 8301 8302 // writer 8303 synchronized (mPackages) { 8304 mPackages.remove(ps.name); 8305 final PackageParser.Package pkg = ps.pkg; 8306 if (pkg != null) { 8307 cleanPackageDataStructuresLILPw(pkg, chatty); 8308 } 8309 } 8310 } 8311 8312 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 8313 if (DEBUG_INSTALL) { 8314 if (chatty) 8315 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 8316 } 8317 8318 // writer 8319 synchronized (mPackages) { 8320 mPackages.remove(pkg.applicationInfo.packageName); 8321 cleanPackageDataStructuresLILPw(pkg, chatty); 8322 } 8323 } 8324 8325 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 8326 int N = pkg.providers.size(); 8327 StringBuilder r = null; 8328 int i; 8329 for (i=0; i<N; i++) { 8330 PackageParser.Provider p = pkg.providers.get(i); 8331 mProviders.removeProvider(p); 8332 if (p.info.authority == null) { 8333 8334 /* There was another ContentProvider with this authority when 8335 * this app was installed so this authority is null, 8336 * Ignore it as we don't have to unregister the provider. 8337 */ 8338 continue; 8339 } 8340 String names[] = p.info.authority.split(";"); 8341 for (int j = 0; j < names.length; j++) { 8342 if (mProvidersByAuthority.get(names[j]) == p) { 8343 mProvidersByAuthority.remove(names[j]); 8344 if (DEBUG_REMOVE) { 8345 if (chatty) 8346 Log.d(TAG, "Unregistered content provider: " + names[j] 8347 + ", className = " + p.info.name + ", isSyncable = " 8348 + p.info.isSyncable); 8349 } 8350 } 8351 } 8352 if (DEBUG_REMOVE && chatty) { 8353 if (r == null) { 8354 r = new StringBuilder(256); 8355 } else { 8356 r.append(' '); 8357 } 8358 r.append(p.info.name); 8359 } 8360 } 8361 if (r != null) { 8362 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 8363 } 8364 8365 N = pkg.services.size(); 8366 r = null; 8367 for (i=0; i<N; i++) { 8368 PackageParser.Service s = pkg.services.get(i); 8369 mServices.removeService(s); 8370 if (chatty) { 8371 if (r == null) { 8372 r = new StringBuilder(256); 8373 } else { 8374 r.append(' '); 8375 } 8376 r.append(s.info.name); 8377 } 8378 } 8379 if (r != null) { 8380 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 8381 } 8382 8383 N = pkg.receivers.size(); 8384 r = null; 8385 for (i=0; i<N; i++) { 8386 PackageParser.Activity a = pkg.receivers.get(i); 8387 mReceivers.removeActivity(a, "receiver"); 8388 if (DEBUG_REMOVE && chatty) { 8389 if (r == null) { 8390 r = new StringBuilder(256); 8391 } else { 8392 r.append(' '); 8393 } 8394 r.append(a.info.name); 8395 } 8396 } 8397 if (r != null) { 8398 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 8399 } 8400 8401 N = pkg.activities.size(); 8402 r = null; 8403 for (i=0; i<N; i++) { 8404 PackageParser.Activity a = pkg.activities.get(i); 8405 mActivities.removeActivity(a, "activity"); 8406 if (DEBUG_REMOVE && chatty) { 8407 if (r == null) { 8408 r = new StringBuilder(256); 8409 } else { 8410 r.append(' '); 8411 } 8412 r.append(a.info.name); 8413 } 8414 } 8415 if (r != null) { 8416 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 8417 } 8418 8419 N = pkg.permissions.size(); 8420 r = null; 8421 for (i=0; i<N; i++) { 8422 PackageParser.Permission p = pkg.permissions.get(i); 8423 BasePermission bp = mSettings.mPermissions.get(p.info.name); 8424 if (bp == null) { 8425 bp = mSettings.mPermissionTrees.get(p.info.name); 8426 } 8427 if (bp != null && bp.perm == p) { 8428 bp.perm = null; 8429 if (DEBUG_REMOVE && chatty) { 8430 if (r == null) { 8431 r = new StringBuilder(256); 8432 } else { 8433 r.append(' '); 8434 } 8435 r.append(p.info.name); 8436 } 8437 } 8438 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8439 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 8440 if (appOpPkgs != null) { 8441 appOpPkgs.remove(pkg.packageName); 8442 } 8443 } 8444 } 8445 if (r != null) { 8446 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8447 } 8448 8449 N = pkg.requestedPermissions.size(); 8450 r = null; 8451 for (i=0; i<N; i++) { 8452 String perm = pkg.requestedPermissions.get(i); 8453 BasePermission bp = mSettings.mPermissions.get(perm); 8454 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8455 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 8456 if (appOpPkgs != null) { 8457 appOpPkgs.remove(pkg.packageName); 8458 if (appOpPkgs.isEmpty()) { 8459 mAppOpPermissionPackages.remove(perm); 8460 } 8461 } 8462 } 8463 } 8464 if (r != null) { 8465 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8466 } 8467 8468 N = pkg.instrumentation.size(); 8469 r = null; 8470 for (i=0; i<N; i++) { 8471 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8472 mInstrumentation.remove(a.getComponentName()); 8473 if (DEBUG_REMOVE && chatty) { 8474 if (r == null) { 8475 r = new StringBuilder(256); 8476 } else { 8477 r.append(' '); 8478 } 8479 r.append(a.info.name); 8480 } 8481 } 8482 if (r != null) { 8483 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 8484 } 8485 8486 r = null; 8487 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8488 // Only system apps can hold shared libraries. 8489 if (pkg.libraryNames != null) { 8490 for (i=0; i<pkg.libraryNames.size(); i++) { 8491 String name = pkg.libraryNames.get(i); 8492 SharedLibraryEntry cur = mSharedLibraries.get(name); 8493 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 8494 mSharedLibraries.remove(name); 8495 if (DEBUG_REMOVE && chatty) { 8496 if (r == null) { 8497 r = new StringBuilder(256); 8498 } else { 8499 r.append(' '); 8500 } 8501 r.append(name); 8502 } 8503 } 8504 } 8505 } 8506 } 8507 if (r != null) { 8508 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 8509 } 8510 } 8511 8512 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 8513 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 8514 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 8515 return true; 8516 } 8517 } 8518 return false; 8519 } 8520 8521 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 8522 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 8523 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 8524 8525 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 8526 int flags) { 8527 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 8528 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 8529 } 8530 8531 private void updatePermissionsLPw(String changingPkg, 8532 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 8533 // Make sure there are no dangling permission trees. 8534 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 8535 while (it.hasNext()) { 8536 final BasePermission bp = it.next(); 8537 if (bp.packageSetting == null) { 8538 // We may not yet have parsed the package, so just see if 8539 // we still know about its settings. 8540 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8541 } 8542 if (bp.packageSetting == null) { 8543 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 8544 + " from package " + bp.sourcePackage); 8545 it.remove(); 8546 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8547 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8548 Slog.i(TAG, "Removing old permission tree: " + bp.name 8549 + " from package " + bp.sourcePackage); 8550 flags |= UPDATE_PERMISSIONS_ALL; 8551 it.remove(); 8552 } 8553 } 8554 } 8555 8556 // Make sure all dynamic permissions have been assigned to a package, 8557 // and make sure there are no dangling permissions. 8558 it = mSettings.mPermissions.values().iterator(); 8559 while (it.hasNext()) { 8560 final BasePermission bp = it.next(); 8561 if (bp.type == BasePermission.TYPE_DYNAMIC) { 8562 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 8563 + bp.name + " pkg=" + bp.sourcePackage 8564 + " info=" + bp.pendingInfo); 8565 if (bp.packageSetting == null && bp.pendingInfo != null) { 8566 final BasePermission tree = findPermissionTreeLP(bp.name); 8567 if (tree != null && tree.perm != null) { 8568 bp.packageSetting = tree.packageSetting; 8569 bp.perm = new PackageParser.Permission(tree.perm.owner, 8570 new PermissionInfo(bp.pendingInfo)); 8571 bp.perm.info.packageName = tree.perm.info.packageName; 8572 bp.perm.info.name = bp.name; 8573 bp.uid = tree.uid; 8574 } 8575 } 8576 } 8577 if (bp.packageSetting == null) { 8578 // We may not yet have parsed the package, so just see if 8579 // we still know about its settings. 8580 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8581 } 8582 if (bp.packageSetting == null) { 8583 Slog.w(TAG, "Removing dangling permission: " + bp.name 8584 + " from package " + bp.sourcePackage); 8585 it.remove(); 8586 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8587 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8588 Slog.i(TAG, "Removing old permission: " + bp.name 8589 + " from package " + bp.sourcePackage); 8590 flags |= UPDATE_PERMISSIONS_ALL; 8591 it.remove(); 8592 } 8593 } 8594 } 8595 8596 // Now update the permissions for all packages, in particular 8597 // replace the granted permissions of the system packages. 8598 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 8599 for (PackageParser.Package pkg : mPackages.values()) { 8600 if (pkg != pkgInfo) { 8601 // Only replace for packages on requested volume 8602 final String volumeUuid = getVolumeUuidForPackage(pkg); 8603 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 8604 && Objects.equals(replaceVolumeUuid, volumeUuid); 8605 grantPermissionsLPw(pkg, replace, changingPkg); 8606 } 8607 } 8608 } 8609 8610 if (pkgInfo != null) { 8611 // Only replace for packages on requested volume 8612 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 8613 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 8614 && Objects.equals(replaceVolumeUuid, volumeUuid); 8615 grantPermissionsLPw(pkgInfo, replace, changingPkg); 8616 } 8617 } 8618 8619 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 8620 String packageOfInterest) { 8621 // IMPORTANT: There are two types of permissions: install and runtime. 8622 // Install time permissions are granted when the app is installed to 8623 // all device users and users added in the future. Runtime permissions 8624 // are granted at runtime explicitly to specific users. Normal and signature 8625 // protected permissions are install time permissions. Dangerous permissions 8626 // are install permissions if the app's target SDK is Lollipop MR1 or older, 8627 // otherwise they are runtime permissions. This function does not manage 8628 // runtime permissions except for the case an app targeting Lollipop MR1 8629 // being upgraded to target a newer SDK, in which case dangerous permissions 8630 // are transformed from install time to runtime ones. 8631 8632 final PackageSetting ps = (PackageSetting) pkg.mExtras; 8633 if (ps == null) { 8634 return; 8635 } 8636 8637 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 8638 8639 PermissionsState permissionsState = ps.getPermissionsState(); 8640 PermissionsState origPermissions = permissionsState; 8641 8642 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 8643 8644 boolean runtimePermissionsRevoked = false; 8645 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 8646 8647 boolean changedInstallPermission = false; 8648 8649 if (replace) { 8650 ps.installPermissionsFixed = false; 8651 if (!ps.isSharedUser()) { 8652 origPermissions = new PermissionsState(permissionsState); 8653 permissionsState.reset(); 8654 } else { 8655 // We need to know only about runtime permission changes since the 8656 // calling code always writes the install permissions state but 8657 // the runtime ones are written only if changed. The only cases of 8658 // changed runtime permissions here are promotion of an install to 8659 // runtime and revocation of a runtime from a shared user. 8660 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 8661 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 8662 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 8663 runtimePermissionsRevoked = true; 8664 } 8665 } 8666 } 8667 8668 permissionsState.setGlobalGids(mGlobalGids); 8669 8670 final int N = pkg.requestedPermissions.size(); 8671 for (int i=0; i<N; i++) { 8672 final String name = pkg.requestedPermissions.get(i); 8673 final BasePermission bp = mSettings.mPermissions.get(name); 8674 8675 if (DEBUG_INSTALL) { 8676 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 8677 } 8678 8679 if (bp == null || bp.packageSetting == null) { 8680 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8681 Slog.w(TAG, "Unknown permission " + name 8682 + " in package " + pkg.packageName); 8683 } 8684 continue; 8685 } 8686 8687 final String perm = bp.name; 8688 boolean allowedSig = false; 8689 int grant = GRANT_DENIED; 8690 8691 // Keep track of app op permissions. 8692 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8693 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 8694 if (pkgs == null) { 8695 pkgs = new ArraySet<>(); 8696 mAppOpPermissionPackages.put(bp.name, pkgs); 8697 } 8698 pkgs.add(pkg.packageName); 8699 } 8700 8701 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 8702 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 8703 >= Build.VERSION_CODES.M; 8704 switch (level) { 8705 case PermissionInfo.PROTECTION_NORMAL: { 8706 // For all apps normal permissions are install time ones. 8707 grant = GRANT_INSTALL; 8708 } break; 8709 8710 case PermissionInfo.PROTECTION_DANGEROUS: { 8711 // If a permission review is required for legacy apps we represent 8712 // their permissions as always granted runtime ones since we need 8713 // to keep the review required permission flag per user while an 8714 // install permission's state is shared across all users. 8715 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 8716 // For legacy apps dangerous permissions are install time ones. 8717 grant = GRANT_INSTALL; 8718 } else if (origPermissions.hasInstallPermission(bp.name)) { 8719 // For legacy apps that became modern, install becomes runtime. 8720 grant = GRANT_UPGRADE; 8721 } else if (mPromoteSystemApps 8722 && isSystemApp(ps) 8723 && mExistingSystemPackages.contains(ps.name)) { 8724 // For legacy system apps, install becomes runtime. 8725 // We cannot check hasInstallPermission() for system apps since those 8726 // permissions were granted implicitly and not persisted pre-M. 8727 grant = GRANT_UPGRADE; 8728 } else { 8729 // For modern apps keep runtime permissions unchanged. 8730 grant = GRANT_RUNTIME; 8731 } 8732 } break; 8733 8734 case PermissionInfo.PROTECTION_SIGNATURE: { 8735 // For all apps signature permissions are install time ones. 8736 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 8737 if (allowedSig) { 8738 grant = GRANT_INSTALL; 8739 } 8740 } break; 8741 } 8742 8743 if (DEBUG_INSTALL) { 8744 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 8745 } 8746 8747 if (grant != GRANT_DENIED) { 8748 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 8749 // If this is an existing, non-system package, then 8750 // we can't add any new permissions to it. 8751 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 8752 // Except... if this is a permission that was added 8753 // to the platform (note: need to only do this when 8754 // updating the platform). 8755 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 8756 grant = GRANT_DENIED; 8757 } 8758 } 8759 } 8760 8761 switch (grant) { 8762 case GRANT_INSTALL: { 8763 // Revoke this as runtime permission to handle the case of 8764 // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps 8765 for (int userId : UserManagerService.getInstance().getUserIds()) { 8766 if (origPermissions.getRuntimePermissionState( 8767 bp.name, userId) != null) { 8768 // Revoke the runtime permission and clear the flags. 8769 origPermissions.revokeRuntimePermission(bp, userId); 8770 origPermissions.updatePermissionFlags(bp, userId, 8771 PackageManager.MASK_PERMISSION_FLAGS, 0); 8772 // If we revoked a permission permission, we have to write. 8773 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8774 changedRuntimePermissionUserIds, userId); 8775 } 8776 } 8777 // Grant an install permission. 8778 if (permissionsState.grantInstallPermission(bp) != 8779 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8780 changedInstallPermission = true; 8781 } 8782 } break; 8783 8784 case GRANT_RUNTIME: { 8785 // Grant previously granted runtime permissions. 8786 for (int userId : UserManagerService.getInstance().getUserIds()) { 8787 PermissionState permissionState = origPermissions 8788 .getRuntimePermissionState(bp.name, userId); 8789 int flags = permissionState != null 8790 ? permissionState.getFlags() : 0; 8791 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8792 if (permissionsState.grantRuntimePermission(bp, userId) == 8793 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8794 // If we cannot put the permission as it was, we have to write. 8795 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8796 changedRuntimePermissionUserIds, userId); 8797 } 8798 // If the app supports runtime permissions no need for a review. 8799 if (Build.PERMISSIONS_REVIEW_REQUIRED 8800 && appSupportsRuntimePermissions 8801 && (flags & PackageManager 8802 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 8803 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 8804 // Since we changed the flags, we have to write. 8805 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8806 changedRuntimePermissionUserIds, userId); 8807 } 8808 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 8809 && !appSupportsRuntimePermissions) { 8810 // For legacy apps that need a permission review, every new 8811 // runtime permission is granted but it is pending a review. 8812 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 8813 permissionsState.grantRuntimePermission(bp, userId); 8814 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 8815 // We changed the permission and flags, hence have to write. 8816 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8817 changedRuntimePermissionUserIds, userId); 8818 } 8819 } 8820 // Propagate the permission flags. 8821 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 8822 } 8823 } break; 8824 8825 case GRANT_UPGRADE: { 8826 // Grant runtime permissions for a previously held install permission. 8827 PermissionState permissionState = origPermissions 8828 .getInstallPermissionState(bp.name); 8829 final int flags = permissionState != null ? permissionState.getFlags() : 0; 8830 8831 if (origPermissions.revokeInstallPermission(bp) 8832 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 8833 // We will be transferring the permission flags, so clear them. 8834 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 8835 PackageManager.MASK_PERMISSION_FLAGS, 0); 8836 changedInstallPermission = true; 8837 } 8838 8839 // If the permission is not to be promoted to runtime we ignore it and 8840 // also its other flags as they are not applicable to install permissions. 8841 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 8842 for (int userId : currentUserIds) { 8843 if (permissionsState.grantRuntimePermission(bp, userId) != 8844 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8845 // Transfer the permission flags. 8846 permissionsState.updatePermissionFlags(bp, userId, 8847 flags, flags); 8848 // If we granted the permission, we have to write. 8849 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8850 changedRuntimePermissionUserIds, userId); 8851 } 8852 } 8853 } 8854 } break; 8855 8856 default: { 8857 if (packageOfInterest == null 8858 || packageOfInterest.equals(pkg.packageName)) { 8859 Slog.w(TAG, "Not granting permission " + perm 8860 + " to package " + pkg.packageName 8861 + " because it was previously installed without"); 8862 } 8863 } break; 8864 } 8865 } else { 8866 if (permissionsState.revokeInstallPermission(bp) != 8867 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8868 // Also drop the permission flags. 8869 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 8870 PackageManager.MASK_PERMISSION_FLAGS, 0); 8871 changedInstallPermission = true; 8872 Slog.i(TAG, "Un-granting permission " + perm 8873 + " from package " + pkg.packageName 8874 + " (protectionLevel=" + bp.protectionLevel 8875 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8876 + ")"); 8877 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 8878 // Don't print warning for app op permissions, since it is fine for them 8879 // not to be granted, there is a UI for the user to decide. 8880 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8881 Slog.w(TAG, "Not granting permission " + perm 8882 + " to package " + pkg.packageName 8883 + " (protectionLevel=" + bp.protectionLevel 8884 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8885 + ")"); 8886 } 8887 } 8888 } 8889 } 8890 8891 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 8892 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 8893 // This is the first that we have heard about this package, so the 8894 // permissions we have now selected are fixed until explicitly 8895 // changed. 8896 ps.installPermissionsFixed = true; 8897 } 8898 8899 // Persist the runtime permissions state for users with changes. If permissions 8900 // were revoked because no app in the shared user declares them we have to 8901 // write synchronously to avoid losing runtime permissions state. 8902 for (int userId : changedRuntimePermissionUserIds) { 8903 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 8904 } 8905 8906 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8907 } 8908 8909 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8910 boolean allowed = false; 8911 final int NP = PackageParser.NEW_PERMISSIONS.length; 8912 for (int ip=0; ip<NP; ip++) { 8913 final PackageParser.NewPermissionInfo npi 8914 = PackageParser.NEW_PERMISSIONS[ip]; 8915 if (npi.name.equals(perm) 8916 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8917 allowed = true; 8918 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8919 + pkg.packageName); 8920 break; 8921 } 8922 } 8923 return allowed; 8924 } 8925 8926 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 8927 BasePermission bp, PermissionsState origPermissions) { 8928 boolean allowed; 8929 allowed = (compareSignatures( 8930 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 8931 == PackageManager.SIGNATURE_MATCH) 8932 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 8933 == PackageManager.SIGNATURE_MATCH); 8934 if (!allowed && (bp.protectionLevel 8935 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 8936 if (isSystemApp(pkg)) { 8937 // For updated system applications, a system permission 8938 // is granted only if it had been defined by the original application. 8939 if (pkg.isUpdatedSystemApp()) { 8940 final PackageSetting sysPs = mSettings 8941 .getDisabledSystemPkgLPr(pkg.packageName); 8942 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 8943 // If the original was granted this permission, we take 8944 // that grant decision as read and propagate it to the 8945 // update. 8946 if (sysPs.isPrivileged()) { 8947 allowed = true; 8948 } 8949 } else { 8950 // The system apk may have been updated with an older 8951 // version of the one on the data partition, but which 8952 // granted a new system permission that it didn't have 8953 // before. In this case we do want to allow the app to 8954 // now get the new permission if the ancestral apk is 8955 // privileged to get it. 8956 if (sysPs.pkg != null && sysPs.isPrivileged()) { 8957 for (int j=0; 8958 j<sysPs.pkg.requestedPermissions.size(); j++) { 8959 if (perm.equals( 8960 sysPs.pkg.requestedPermissions.get(j))) { 8961 allowed = true; 8962 break; 8963 } 8964 } 8965 } 8966 } 8967 } else { 8968 allowed = isPrivilegedApp(pkg); 8969 } 8970 } 8971 } 8972 if (!allowed) { 8973 if (!allowed && (bp.protectionLevel 8974 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 8975 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 8976 // If this was a previously normal/dangerous permission that got moved 8977 // to a system permission as part of the runtime permission redesign, then 8978 // we still want to blindly grant it to old apps. 8979 allowed = true; 8980 } 8981 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 8982 && pkg.packageName.equals(mRequiredInstallerPackage)) { 8983 // If this permission is to be granted to the system installer and 8984 // this app is an installer, then it gets the permission. 8985 allowed = true; 8986 } 8987 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 8988 && pkg.packageName.equals(mRequiredVerifierPackage)) { 8989 // If this permission is to be granted to the system verifier and 8990 // this app is a verifier, then it gets the permission. 8991 allowed = true; 8992 } 8993 if (!allowed && (bp.protectionLevel 8994 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 8995 && isSystemApp(pkg)) { 8996 // Any pre-installed system app is allowed to get this permission. 8997 allowed = true; 8998 } 8999 if (!allowed && (bp.protectionLevel 9000 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 9001 // For development permissions, a development permission 9002 // is granted only if it was already granted. 9003 allowed = origPermissions.hasInstallPermission(perm); 9004 } 9005 } 9006 return allowed; 9007 } 9008 9009 final class ActivityIntentResolver 9010 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 9011 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9012 boolean defaultOnly, int userId) { 9013 if (!sUserManager.exists(userId)) return null; 9014 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9015 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9016 } 9017 9018 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9019 int userId) { 9020 if (!sUserManager.exists(userId)) return null; 9021 mFlags = flags; 9022 return super.queryIntent(intent, resolvedType, 9023 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9024 } 9025 9026 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9027 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 9028 if (!sUserManager.exists(userId)) return null; 9029 if (packageActivities == null) { 9030 return null; 9031 } 9032 mFlags = flags; 9033 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9034 final int N = packageActivities.size(); 9035 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 9036 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 9037 9038 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 9039 for (int i = 0; i < N; ++i) { 9040 intentFilters = packageActivities.get(i).intents; 9041 if (intentFilters != null && intentFilters.size() > 0) { 9042 PackageParser.ActivityIntentInfo[] array = 9043 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 9044 intentFilters.toArray(array); 9045 listCut.add(array); 9046 } 9047 } 9048 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9049 } 9050 9051 public final void addActivity(PackageParser.Activity a, String type) { 9052 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 9053 mActivities.put(a.getComponentName(), a); 9054 if (DEBUG_SHOW_INFO) 9055 Log.v( 9056 TAG, " " + type + " " + 9057 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 9058 if (DEBUG_SHOW_INFO) 9059 Log.v(TAG, " Class=" + a.info.name); 9060 final int NI = a.intents.size(); 9061 for (int j=0; j<NI; j++) { 9062 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 9063 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 9064 intent.setPriority(0); 9065 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 9066 + a.className + " with priority > 0, forcing to 0"); 9067 } 9068 if (DEBUG_SHOW_INFO) { 9069 Log.v(TAG, " IntentFilter:"); 9070 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9071 } 9072 if (!intent.debugCheck()) { 9073 Log.w(TAG, "==> For Activity " + a.info.name); 9074 } 9075 addFilter(intent); 9076 } 9077 } 9078 9079 public final void removeActivity(PackageParser.Activity a, String type) { 9080 mActivities.remove(a.getComponentName()); 9081 if (DEBUG_SHOW_INFO) { 9082 Log.v(TAG, " " + type + " " 9083 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 9084 : a.info.name) + ":"); 9085 Log.v(TAG, " Class=" + a.info.name); 9086 } 9087 final int NI = a.intents.size(); 9088 for (int j=0; j<NI; j++) { 9089 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 9090 if (DEBUG_SHOW_INFO) { 9091 Log.v(TAG, " IntentFilter:"); 9092 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9093 } 9094 removeFilter(intent); 9095 } 9096 } 9097 9098 @Override 9099 protected boolean allowFilterResult( 9100 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 9101 ActivityInfo filterAi = filter.activity.info; 9102 for (int i=dest.size()-1; i>=0; i--) { 9103 ActivityInfo destAi = dest.get(i).activityInfo; 9104 if (destAi.name == filterAi.name 9105 && destAi.packageName == filterAi.packageName) { 9106 return false; 9107 } 9108 } 9109 return true; 9110 } 9111 9112 @Override 9113 protected ActivityIntentInfo[] newArray(int size) { 9114 return new ActivityIntentInfo[size]; 9115 } 9116 9117 @Override 9118 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 9119 if (!sUserManager.exists(userId)) return true; 9120 PackageParser.Package p = filter.activity.owner; 9121 if (p != null) { 9122 PackageSetting ps = (PackageSetting)p.mExtras; 9123 if (ps != null) { 9124 // System apps are never considered stopped for purposes of 9125 // filtering, because there may be no way for the user to 9126 // actually re-launch them. 9127 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 9128 && ps.getStopped(userId); 9129 } 9130 } 9131 return false; 9132 } 9133 9134 @Override 9135 protected boolean isPackageForFilter(String packageName, 9136 PackageParser.ActivityIntentInfo info) { 9137 return packageName.equals(info.activity.owner.packageName); 9138 } 9139 9140 @Override 9141 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 9142 int match, int userId) { 9143 if (!sUserManager.exists(userId)) return null; 9144 if (!mSettings.isEnabledAndVisibleLPr(info.activity.info, mFlags, userId)) { 9145 return null; 9146 } 9147 final PackageParser.Activity activity = info.activity; 9148 if (mSafeMode && (activity.info.applicationInfo.flags 9149 &ApplicationInfo.FLAG_SYSTEM) == 0) { 9150 return null; 9151 } 9152 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 9153 if (ps == null) { 9154 return null; 9155 } 9156 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 9157 ps.readUserState(userId), userId); 9158 if (ai == null) { 9159 return null; 9160 } 9161 final ResolveInfo res = new ResolveInfo(); 9162 res.activityInfo = ai; 9163 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9164 res.filter = info; 9165 } 9166 if (info != null) { 9167 res.handleAllWebDataURI = info.handleAllWebDataURI(); 9168 } 9169 res.priority = info.getPriority(); 9170 res.preferredOrder = activity.owner.mPreferredOrder; 9171 //System.out.println("Result: " + res.activityInfo.className + 9172 // " = " + res.priority); 9173 res.match = match; 9174 res.isDefault = info.hasDefault; 9175 res.labelRes = info.labelRes; 9176 res.nonLocalizedLabel = info.nonLocalizedLabel; 9177 if (userNeedsBadging(userId)) { 9178 res.noResourceId = true; 9179 } else { 9180 res.icon = info.icon; 9181 } 9182 res.iconResourceId = info.icon; 9183 res.system = res.activityInfo.applicationInfo.isSystemApp(); 9184 return res; 9185 } 9186 9187 @Override 9188 protected void sortResults(List<ResolveInfo> results) { 9189 Collections.sort(results, mResolvePrioritySorter); 9190 } 9191 9192 @Override 9193 protected void dumpFilter(PrintWriter out, String prefix, 9194 PackageParser.ActivityIntentInfo filter) { 9195 out.print(prefix); out.print( 9196 Integer.toHexString(System.identityHashCode(filter.activity))); 9197 out.print(' '); 9198 filter.activity.printComponentShortName(out); 9199 out.print(" filter "); 9200 out.println(Integer.toHexString(System.identityHashCode(filter))); 9201 } 9202 9203 @Override 9204 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 9205 return filter.activity; 9206 } 9207 9208 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9209 PackageParser.Activity activity = (PackageParser.Activity)label; 9210 out.print(prefix); out.print( 9211 Integer.toHexString(System.identityHashCode(activity))); 9212 out.print(' '); 9213 activity.printComponentShortName(out); 9214 if (count > 1) { 9215 out.print(" ("); out.print(count); out.print(" filters)"); 9216 } 9217 out.println(); 9218 } 9219 9220// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9221// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9222// final List<ResolveInfo> retList = Lists.newArrayList(); 9223// while (i.hasNext()) { 9224// final ResolveInfo resolveInfo = i.next(); 9225// if (isEnabledLP(resolveInfo.activityInfo)) { 9226// retList.add(resolveInfo); 9227// } 9228// } 9229// return retList; 9230// } 9231 9232 // Keys are String (activity class name), values are Activity. 9233 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 9234 = new ArrayMap<ComponentName, PackageParser.Activity>(); 9235 private int mFlags; 9236 } 9237 9238 private final class ServiceIntentResolver 9239 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 9240 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9241 boolean defaultOnly, int userId) { 9242 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9243 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9244 } 9245 9246 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9247 int userId) { 9248 if (!sUserManager.exists(userId)) return null; 9249 mFlags = flags; 9250 return super.queryIntent(intent, resolvedType, 9251 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9252 } 9253 9254 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9255 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 9256 if (!sUserManager.exists(userId)) return null; 9257 if (packageServices == null) { 9258 return null; 9259 } 9260 mFlags = flags; 9261 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9262 final int N = packageServices.size(); 9263 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 9264 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 9265 9266 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 9267 for (int i = 0; i < N; ++i) { 9268 intentFilters = packageServices.get(i).intents; 9269 if (intentFilters != null && intentFilters.size() > 0) { 9270 PackageParser.ServiceIntentInfo[] array = 9271 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 9272 intentFilters.toArray(array); 9273 listCut.add(array); 9274 } 9275 } 9276 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9277 } 9278 9279 public final void addService(PackageParser.Service s) { 9280 mServices.put(s.getComponentName(), s); 9281 if (DEBUG_SHOW_INFO) { 9282 Log.v(TAG, " " 9283 + (s.info.nonLocalizedLabel != null 9284 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9285 Log.v(TAG, " Class=" + s.info.name); 9286 } 9287 final int NI = s.intents.size(); 9288 int j; 9289 for (j=0; j<NI; j++) { 9290 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9291 if (DEBUG_SHOW_INFO) { 9292 Log.v(TAG, " IntentFilter:"); 9293 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9294 } 9295 if (!intent.debugCheck()) { 9296 Log.w(TAG, "==> For Service " + s.info.name); 9297 } 9298 addFilter(intent); 9299 } 9300 } 9301 9302 public final void removeService(PackageParser.Service s) { 9303 mServices.remove(s.getComponentName()); 9304 if (DEBUG_SHOW_INFO) { 9305 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 9306 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9307 Log.v(TAG, " Class=" + s.info.name); 9308 } 9309 final int NI = s.intents.size(); 9310 int j; 9311 for (j=0; j<NI; j++) { 9312 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9313 if (DEBUG_SHOW_INFO) { 9314 Log.v(TAG, " IntentFilter:"); 9315 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9316 } 9317 removeFilter(intent); 9318 } 9319 } 9320 9321 @Override 9322 protected boolean allowFilterResult( 9323 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 9324 ServiceInfo filterSi = filter.service.info; 9325 for (int i=dest.size()-1; i>=0; i--) { 9326 ServiceInfo destAi = dest.get(i).serviceInfo; 9327 if (destAi.name == filterSi.name 9328 && destAi.packageName == filterSi.packageName) { 9329 return false; 9330 } 9331 } 9332 return true; 9333 } 9334 9335 @Override 9336 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 9337 return new PackageParser.ServiceIntentInfo[size]; 9338 } 9339 9340 @Override 9341 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 9342 if (!sUserManager.exists(userId)) return true; 9343 PackageParser.Package p = filter.service.owner; 9344 if (p != null) { 9345 PackageSetting ps = (PackageSetting)p.mExtras; 9346 if (ps != null) { 9347 // System apps are never considered stopped for purposes of 9348 // filtering, because there may be no way for the user to 9349 // actually re-launch them. 9350 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9351 && ps.getStopped(userId); 9352 } 9353 } 9354 return false; 9355 } 9356 9357 @Override 9358 protected boolean isPackageForFilter(String packageName, 9359 PackageParser.ServiceIntentInfo info) { 9360 return packageName.equals(info.service.owner.packageName); 9361 } 9362 9363 @Override 9364 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 9365 int match, int userId) { 9366 if (!sUserManager.exists(userId)) return null; 9367 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 9368 if (!mSettings.isEnabledAndVisibleLPr(info.service.info, mFlags, userId)) { 9369 return null; 9370 } 9371 final PackageParser.Service service = info.service; 9372 if (mSafeMode && (service.info.applicationInfo.flags 9373 &ApplicationInfo.FLAG_SYSTEM) == 0) { 9374 return null; 9375 } 9376 PackageSetting ps = (PackageSetting) service.owner.mExtras; 9377 if (ps == null) { 9378 return null; 9379 } 9380 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 9381 ps.readUserState(userId), userId); 9382 if (si == null) { 9383 return null; 9384 } 9385 final ResolveInfo res = new ResolveInfo(); 9386 res.serviceInfo = si; 9387 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9388 res.filter = filter; 9389 } 9390 res.priority = info.getPriority(); 9391 res.preferredOrder = service.owner.mPreferredOrder; 9392 res.match = match; 9393 res.isDefault = info.hasDefault; 9394 res.labelRes = info.labelRes; 9395 res.nonLocalizedLabel = info.nonLocalizedLabel; 9396 res.icon = info.icon; 9397 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 9398 return res; 9399 } 9400 9401 @Override 9402 protected void sortResults(List<ResolveInfo> results) { 9403 Collections.sort(results, mResolvePrioritySorter); 9404 } 9405 9406 @Override 9407 protected void dumpFilter(PrintWriter out, String prefix, 9408 PackageParser.ServiceIntentInfo filter) { 9409 out.print(prefix); out.print( 9410 Integer.toHexString(System.identityHashCode(filter.service))); 9411 out.print(' '); 9412 filter.service.printComponentShortName(out); 9413 out.print(" filter "); 9414 out.println(Integer.toHexString(System.identityHashCode(filter))); 9415 } 9416 9417 @Override 9418 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 9419 return filter.service; 9420 } 9421 9422 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9423 PackageParser.Service service = (PackageParser.Service)label; 9424 out.print(prefix); out.print( 9425 Integer.toHexString(System.identityHashCode(service))); 9426 out.print(' '); 9427 service.printComponentShortName(out); 9428 if (count > 1) { 9429 out.print(" ("); out.print(count); out.print(" filters)"); 9430 } 9431 out.println(); 9432 } 9433 9434// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9435// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9436// final List<ResolveInfo> retList = Lists.newArrayList(); 9437// while (i.hasNext()) { 9438// final ResolveInfo resolveInfo = (ResolveInfo) i; 9439// if (isEnabledLP(resolveInfo.serviceInfo)) { 9440// retList.add(resolveInfo); 9441// } 9442// } 9443// return retList; 9444// } 9445 9446 // Keys are String (activity class name), values are Activity. 9447 private final ArrayMap<ComponentName, PackageParser.Service> mServices 9448 = new ArrayMap<ComponentName, PackageParser.Service>(); 9449 private int mFlags; 9450 }; 9451 9452 private final class ProviderIntentResolver 9453 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 9454 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9455 boolean defaultOnly, int userId) { 9456 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9457 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9458 } 9459 9460 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9461 int userId) { 9462 if (!sUserManager.exists(userId)) 9463 return null; 9464 mFlags = flags; 9465 return super.queryIntent(intent, resolvedType, 9466 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9467 } 9468 9469 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9470 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 9471 if (!sUserManager.exists(userId)) 9472 return null; 9473 if (packageProviders == null) { 9474 return null; 9475 } 9476 mFlags = flags; 9477 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 9478 final int N = packageProviders.size(); 9479 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 9480 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 9481 9482 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 9483 for (int i = 0; i < N; ++i) { 9484 intentFilters = packageProviders.get(i).intents; 9485 if (intentFilters != null && intentFilters.size() > 0) { 9486 PackageParser.ProviderIntentInfo[] array = 9487 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 9488 intentFilters.toArray(array); 9489 listCut.add(array); 9490 } 9491 } 9492 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9493 } 9494 9495 public final void addProvider(PackageParser.Provider p) { 9496 if (mProviders.containsKey(p.getComponentName())) { 9497 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 9498 return; 9499 } 9500 9501 mProviders.put(p.getComponentName(), p); 9502 if (DEBUG_SHOW_INFO) { 9503 Log.v(TAG, " " 9504 + (p.info.nonLocalizedLabel != null 9505 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9506 Log.v(TAG, " Class=" + p.info.name); 9507 } 9508 final int NI = p.intents.size(); 9509 int j; 9510 for (j = 0; j < NI; j++) { 9511 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9512 if (DEBUG_SHOW_INFO) { 9513 Log.v(TAG, " IntentFilter:"); 9514 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9515 } 9516 if (!intent.debugCheck()) { 9517 Log.w(TAG, "==> For Provider " + p.info.name); 9518 } 9519 addFilter(intent); 9520 } 9521 } 9522 9523 public final void removeProvider(PackageParser.Provider p) { 9524 mProviders.remove(p.getComponentName()); 9525 if (DEBUG_SHOW_INFO) { 9526 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 9527 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9528 Log.v(TAG, " Class=" + p.info.name); 9529 } 9530 final int NI = p.intents.size(); 9531 int j; 9532 for (j = 0; j < NI; j++) { 9533 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9534 if (DEBUG_SHOW_INFO) { 9535 Log.v(TAG, " IntentFilter:"); 9536 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9537 } 9538 removeFilter(intent); 9539 } 9540 } 9541 9542 @Override 9543 protected boolean allowFilterResult( 9544 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 9545 ProviderInfo filterPi = filter.provider.info; 9546 for (int i = dest.size() - 1; i >= 0; i--) { 9547 ProviderInfo destPi = dest.get(i).providerInfo; 9548 if (destPi.name == filterPi.name 9549 && destPi.packageName == filterPi.packageName) { 9550 return false; 9551 } 9552 } 9553 return true; 9554 } 9555 9556 @Override 9557 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 9558 return new PackageParser.ProviderIntentInfo[size]; 9559 } 9560 9561 @Override 9562 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 9563 if (!sUserManager.exists(userId)) 9564 return true; 9565 PackageParser.Package p = filter.provider.owner; 9566 if (p != null) { 9567 PackageSetting ps = (PackageSetting) p.mExtras; 9568 if (ps != null) { 9569 // System apps are never considered stopped for purposes of 9570 // filtering, because there may be no way for the user to 9571 // actually re-launch them. 9572 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9573 && ps.getStopped(userId); 9574 } 9575 } 9576 return false; 9577 } 9578 9579 @Override 9580 protected boolean isPackageForFilter(String packageName, 9581 PackageParser.ProviderIntentInfo info) { 9582 return packageName.equals(info.provider.owner.packageName); 9583 } 9584 9585 @Override 9586 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 9587 int match, int userId) { 9588 if (!sUserManager.exists(userId)) 9589 return null; 9590 final PackageParser.ProviderIntentInfo info = filter; 9591 if (!mSettings.isEnabledAndVisibleLPr(info.provider.info, mFlags, userId)) { 9592 return null; 9593 } 9594 final PackageParser.Provider provider = info.provider; 9595 if (mSafeMode && (provider.info.applicationInfo.flags 9596 & ApplicationInfo.FLAG_SYSTEM) == 0) { 9597 return null; 9598 } 9599 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 9600 if (ps == null) { 9601 return null; 9602 } 9603 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 9604 ps.readUserState(userId), userId); 9605 if (pi == null) { 9606 return null; 9607 } 9608 final ResolveInfo res = new ResolveInfo(); 9609 res.providerInfo = pi; 9610 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 9611 res.filter = filter; 9612 } 9613 res.priority = info.getPriority(); 9614 res.preferredOrder = provider.owner.mPreferredOrder; 9615 res.match = match; 9616 res.isDefault = info.hasDefault; 9617 res.labelRes = info.labelRes; 9618 res.nonLocalizedLabel = info.nonLocalizedLabel; 9619 res.icon = info.icon; 9620 res.system = res.providerInfo.applicationInfo.isSystemApp(); 9621 return res; 9622 } 9623 9624 @Override 9625 protected void sortResults(List<ResolveInfo> results) { 9626 Collections.sort(results, mResolvePrioritySorter); 9627 } 9628 9629 @Override 9630 protected void dumpFilter(PrintWriter out, String prefix, 9631 PackageParser.ProviderIntentInfo filter) { 9632 out.print(prefix); 9633 out.print( 9634 Integer.toHexString(System.identityHashCode(filter.provider))); 9635 out.print(' '); 9636 filter.provider.printComponentShortName(out); 9637 out.print(" filter "); 9638 out.println(Integer.toHexString(System.identityHashCode(filter))); 9639 } 9640 9641 @Override 9642 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 9643 return filter.provider; 9644 } 9645 9646 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9647 PackageParser.Provider provider = (PackageParser.Provider)label; 9648 out.print(prefix); out.print( 9649 Integer.toHexString(System.identityHashCode(provider))); 9650 out.print(' '); 9651 provider.printComponentShortName(out); 9652 if (count > 1) { 9653 out.print(" ("); out.print(count); out.print(" filters)"); 9654 } 9655 out.println(); 9656 } 9657 9658 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 9659 = new ArrayMap<ComponentName, PackageParser.Provider>(); 9660 private int mFlags; 9661 } 9662 9663 private static final class EphemeralIntentResolver 9664 extends IntentResolver<IntentFilter, ResolveInfo> { 9665 @Override 9666 protected IntentFilter[] newArray(int size) { 9667 return new IntentFilter[size]; 9668 } 9669 9670 @Override 9671 protected boolean isPackageForFilter(String packageName, IntentFilter info) { 9672 return true; 9673 } 9674 9675 @Override 9676 protected ResolveInfo newResult(IntentFilter info, int match, int userId) { 9677 if (!sUserManager.exists(userId)) return null; 9678 final ResolveInfo res = new ResolveInfo(); 9679 res.filter = info; 9680 return res; 9681 } 9682 } 9683 9684 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 9685 new Comparator<ResolveInfo>() { 9686 public int compare(ResolveInfo r1, ResolveInfo r2) { 9687 int v1 = r1.priority; 9688 int v2 = r2.priority; 9689 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 9690 if (v1 != v2) { 9691 return (v1 > v2) ? -1 : 1; 9692 } 9693 v1 = r1.preferredOrder; 9694 v2 = r2.preferredOrder; 9695 if (v1 != v2) { 9696 return (v1 > v2) ? -1 : 1; 9697 } 9698 if (r1.isDefault != r2.isDefault) { 9699 return r1.isDefault ? -1 : 1; 9700 } 9701 v1 = r1.match; 9702 v2 = r2.match; 9703 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 9704 if (v1 != v2) { 9705 return (v1 > v2) ? -1 : 1; 9706 } 9707 if (r1.system != r2.system) { 9708 return r1.system ? -1 : 1; 9709 } 9710 return 0; 9711 } 9712 }; 9713 9714 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 9715 new Comparator<ProviderInfo>() { 9716 public int compare(ProviderInfo p1, ProviderInfo p2) { 9717 final int v1 = p1.initOrder; 9718 final int v2 = p2.initOrder; 9719 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 9720 } 9721 }; 9722 9723 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 9724 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 9725 final int[] userIds) { 9726 mHandler.post(new Runnable() { 9727 @Override 9728 public void run() { 9729 try { 9730 final IActivityManager am = ActivityManagerNative.getDefault(); 9731 if (am == null) return; 9732 final int[] resolvedUserIds; 9733 if (userIds == null) { 9734 resolvedUserIds = am.getRunningUserIds(); 9735 } else { 9736 resolvedUserIds = userIds; 9737 } 9738 for (int id : resolvedUserIds) { 9739 final Intent intent = new Intent(action, 9740 pkg != null ? Uri.fromParts("package", pkg, null) : null); 9741 if (extras != null) { 9742 intent.putExtras(extras); 9743 } 9744 if (targetPkg != null) { 9745 intent.setPackage(targetPkg); 9746 } 9747 // Modify the UID when posting to other users 9748 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 9749 if (uid > 0 && UserHandle.getUserId(uid) != id) { 9750 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 9751 intent.putExtra(Intent.EXTRA_UID, uid); 9752 } 9753 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 9754 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 9755 if (DEBUG_BROADCASTS) { 9756 RuntimeException here = new RuntimeException("here"); 9757 here.fillInStackTrace(); 9758 Slog.d(TAG, "Sending to user " + id + ": " 9759 + intent.toShortString(false, true, false, false) 9760 + " " + intent.getExtras(), here); 9761 } 9762 am.broadcastIntent(null, intent, null, finishedReceiver, 9763 0, null, null, null, android.app.AppOpsManager.OP_NONE, 9764 null, finishedReceiver != null, false, id); 9765 } 9766 } catch (RemoteException ex) { 9767 } 9768 } 9769 }); 9770 } 9771 9772 /** 9773 * Check if the external storage media is available. This is true if there 9774 * is a mounted external storage medium or if the external storage is 9775 * emulated. 9776 */ 9777 private boolean isExternalMediaAvailable() { 9778 return mMediaMounted || Environment.isExternalStorageEmulated(); 9779 } 9780 9781 @Override 9782 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 9783 // writer 9784 synchronized (mPackages) { 9785 if (!isExternalMediaAvailable()) { 9786 // If the external storage is no longer mounted at this point, 9787 // the caller may not have been able to delete all of this 9788 // packages files and can not delete any more. Bail. 9789 return null; 9790 } 9791 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 9792 if (lastPackage != null) { 9793 pkgs.remove(lastPackage); 9794 } 9795 if (pkgs.size() > 0) { 9796 return pkgs.get(0); 9797 } 9798 } 9799 return null; 9800 } 9801 9802 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 9803 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 9804 userId, andCode ? 1 : 0, packageName); 9805 if (mSystemReady) { 9806 msg.sendToTarget(); 9807 } else { 9808 if (mPostSystemReadyMessages == null) { 9809 mPostSystemReadyMessages = new ArrayList<>(); 9810 } 9811 mPostSystemReadyMessages.add(msg); 9812 } 9813 } 9814 9815 void startCleaningPackages() { 9816 // reader 9817 synchronized (mPackages) { 9818 if (!isExternalMediaAvailable()) { 9819 return; 9820 } 9821 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 9822 return; 9823 } 9824 } 9825 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 9826 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 9827 IActivityManager am = ActivityManagerNative.getDefault(); 9828 if (am != null) { 9829 try { 9830 am.startService(null, intent, null, mContext.getOpPackageName(), 9831 UserHandle.USER_SYSTEM); 9832 } catch (RemoteException e) { 9833 } 9834 } 9835 } 9836 9837 @Override 9838 public void installPackage(String originPath, IPackageInstallObserver2 observer, 9839 int installFlags, String installerPackageName, VerificationParams verificationParams, 9840 String packageAbiOverride) { 9841 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 9842 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 9843 } 9844 9845 @Override 9846 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 9847 int installFlags, String installerPackageName, VerificationParams verificationParams, 9848 String packageAbiOverride, int userId) { 9849 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 9850 9851 final int callingUid = Binder.getCallingUid(); 9852 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 9853 9854 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9855 try { 9856 if (observer != null) { 9857 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 9858 } 9859 } catch (RemoteException re) { 9860 } 9861 return; 9862 } 9863 9864 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 9865 installFlags |= PackageManager.INSTALL_FROM_ADB; 9866 9867 } else { 9868 // Caller holds INSTALL_PACKAGES permission, so we're less strict 9869 // about installerPackageName. 9870 9871 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 9872 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 9873 } 9874 9875 UserHandle user; 9876 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 9877 user = UserHandle.ALL; 9878 } else { 9879 user = new UserHandle(userId); 9880 } 9881 9882 // Only system components can circumvent runtime permissions when installing. 9883 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 9884 && mContext.checkCallingOrSelfPermission(Manifest.permission 9885 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 9886 throw new SecurityException("You need the " 9887 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 9888 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 9889 } 9890 9891 verificationParams.setInstallerUid(callingUid); 9892 9893 final File originFile = new File(originPath); 9894 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 9895 9896 final Message msg = mHandler.obtainMessage(INIT_COPY); 9897 final InstallParams params = new InstallParams(origin, null, observer, installFlags, 9898 installerPackageName, null, verificationParams, user, packageAbiOverride, null); 9899 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 9900 msg.obj = params; 9901 9902 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 9903 System.identityHashCode(msg.obj)); 9904 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 9905 System.identityHashCode(msg.obj)); 9906 9907 mHandler.sendMessage(msg); 9908 } 9909 9910 void installStage(String packageName, File stagedDir, String stagedCid, 9911 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 9912 String installerPackageName, int installerUid, UserHandle user) { 9913 if (DEBUG_EPHEMERAL) { 9914 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 9915 Slog.d(TAG, "Ephemeral install of " + packageName); 9916 } 9917 } 9918 final VerificationParams verifParams = new VerificationParams( 9919 null, sessionParams.originatingUri, sessionParams.referrerUri, 9920 sessionParams.originatingUid, null); 9921 verifParams.setInstallerUid(installerUid); 9922 9923 final OriginInfo origin; 9924 if (stagedDir != null) { 9925 origin = OriginInfo.fromStagedFile(stagedDir); 9926 } else { 9927 origin = OriginInfo.fromStagedContainer(stagedCid); 9928 } 9929 9930 final Message msg = mHandler.obtainMessage(INIT_COPY); 9931 final InstallParams params = new InstallParams(origin, null, observer, 9932 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 9933 verifParams, user, sessionParams.abiOverride, 9934 sessionParams.grantedRuntimePermissions); 9935 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 9936 msg.obj = params; 9937 9938 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 9939 System.identityHashCode(msg.obj)); 9940 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 9941 System.identityHashCode(msg.obj)); 9942 9943 mHandler.sendMessage(msg); 9944 } 9945 9946 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 9947 Bundle extras = new Bundle(1); 9948 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 9949 9950 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 9951 packageName, extras, 0, null, null, new int[] {userId}); 9952 try { 9953 IActivityManager am = ActivityManagerNative.getDefault(); 9954 final boolean isSystem = 9955 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 9956 if (isSystem && am.isUserRunning(userId, 0)) { 9957 // The just-installed/enabled app is bundled on the system, so presumed 9958 // to be able to run automatically without needing an explicit launch. 9959 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 9960 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 9961 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 9962 .setPackage(packageName); 9963 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 9964 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 9965 } 9966 } catch (RemoteException e) { 9967 // shouldn't happen 9968 Slog.w(TAG, "Unable to bootstrap installed package", e); 9969 } 9970 } 9971 9972 @Override 9973 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 9974 int userId) { 9975 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9976 PackageSetting pkgSetting; 9977 final int uid = Binder.getCallingUid(); 9978 enforceCrossUserPermission(uid, userId, true, true, 9979 "setApplicationHiddenSetting for user " + userId); 9980 9981 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 9982 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 9983 return false; 9984 } 9985 9986 long callingId = Binder.clearCallingIdentity(); 9987 try { 9988 boolean sendAdded = false; 9989 boolean sendRemoved = false; 9990 // writer 9991 synchronized (mPackages) { 9992 pkgSetting = mSettings.mPackages.get(packageName); 9993 if (pkgSetting == null) { 9994 return false; 9995 } 9996 if (pkgSetting.getHidden(userId) != hidden) { 9997 pkgSetting.setHidden(hidden, userId); 9998 mSettings.writePackageRestrictionsLPr(userId); 9999 if (hidden) { 10000 sendRemoved = true; 10001 } else { 10002 sendAdded = true; 10003 } 10004 } 10005 } 10006 if (sendAdded) { 10007 sendPackageAddedForUser(packageName, pkgSetting, userId); 10008 return true; 10009 } 10010 if (sendRemoved) { 10011 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 10012 "hiding pkg"); 10013 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 10014 return true; 10015 } 10016 } finally { 10017 Binder.restoreCallingIdentity(callingId); 10018 } 10019 return false; 10020 } 10021 10022 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 10023 int userId) { 10024 final PackageRemovedInfo info = new PackageRemovedInfo(); 10025 info.removedPackage = packageName; 10026 info.removedUsers = new int[] {userId}; 10027 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 10028 info.sendBroadcast(false, false, false); 10029 } 10030 10031 /** 10032 * Returns true if application is not found or there was an error. Otherwise it returns 10033 * the hidden state of the package for the given user. 10034 */ 10035 @Override 10036 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 10037 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10038 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 10039 false, "getApplicationHidden for user " + userId); 10040 PackageSetting pkgSetting; 10041 long callingId = Binder.clearCallingIdentity(); 10042 try { 10043 // writer 10044 synchronized (mPackages) { 10045 pkgSetting = mSettings.mPackages.get(packageName); 10046 if (pkgSetting == null) { 10047 return true; 10048 } 10049 return pkgSetting.getHidden(userId); 10050 } 10051 } finally { 10052 Binder.restoreCallingIdentity(callingId); 10053 } 10054 } 10055 10056 /** 10057 * @hide 10058 */ 10059 @Override 10060 public int installExistingPackageAsUser(String packageName, int userId) { 10061 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 10062 null); 10063 PackageSetting pkgSetting; 10064 final int uid = Binder.getCallingUid(); 10065 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 10066 + userId); 10067 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 10068 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 10069 } 10070 10071 long callingId = Binder.clearCallingIdentity(); 10072 try { 10073 boolean sendAdded = false; 10074 10075 // writer 10076 synchronized (mPackages) { 10077 pkgSetting = mSettings.mPackages.get(packageName); 10078 if (pkgSetting == null) { 10079 return PackageManager.INSTALL_FAILED_INVALID_URI; 10080 } 10081 if (!pkgSetting.getInstalled(userId)) { 10082 pkgSetting.setInstalled(true, userId); 10083 pkgSetting.setHidden(false, userId); 10084 mSettings.writePackageRestrictionsLPr(userId); 10085 sendAdded = true; 10086 } 10087 } 10088 10089 if (sendAdded) { 10090 sendPackageAddedForUser(packageName, pkgSetting, userId); 10091 } 10092 } finally { 10093 Binder.restoreCallingIdentity(callingId); 10094 } 10095 10096 return PackageManager.INSTALL_SUCCEEDED; 10097 } 10098 10099 boolean isUserRestricted(int userId, String restrictionKey) { 10100 Bundle restrictions = sUserManager.getUserRestrictions(userId); 10101 if (restrictions.getBoolean(restrictionKey, false)) { 10102 Log.w(TAG, "User is restricted: " + restrictionKey); 10103 return true; 10104 } 10105 return false; 10106 } 10107 10108 @Override 10109 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 10110 mContext.enforceCallingOrSelfPermission( 10111 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10112 "Only package verification agents can verify applications"); 10113 10114 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 10115 final PackageVerificationResponse response = new PackageVerificationResponse( 10116 verificationCode, Binder.getCallingUid()); 10117 msg.arg1 = id; 10118 msg.obj = response; 10119 mHandler.sendMessage(msg); 10120 } 10121 10122 @Override 10123 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 10124 long millisecondsToDelay) { 10125 mContext.enforceCallingOrSelfPermission( 10126 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10127 "Only package verification agents can extend verification timeouts"); 10128 10129 final PackageVerificationState state = mPendingVerification.get(id); 10130 final PackageVerificationResponse response = new PackageVerificationResponse( 10131 verificationCodeAtTimeout, Binder.getCallingUid()); 10132 10133 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 10134 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 10135 } 10136 if (millisecondsToDelay < 0) { 10137 millisecondsToDelay = 0; 10138 } 10139 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 10140 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 10141 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 10142 } 10143 10144 if ((state != null) && !state.timeoutExtended()) { 10145 state.extendTimeout(); 10146 10147 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 10148 msg.arg1 = id; 10149 msg.obj = response; 10150 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 10151 } 10152 } 10153 10154 private void broadcastPackageVerified(int verificationId, Uri packageUri, 10155 int verificationCode, UserHandle user) { 10156 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 10157 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 10158 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10159 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10160 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 10161 10162 mContext.sendBroadcastAsUser(intent, user, 10163 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 10164 } 10165 10166 private ComponentName matchComponentForVerifier(String packageName, 10167 List<ResolveInfo> receivers) { 10168 ActivityInfo targetReceiver = null; 10169 10170 final int NR = receivers.size(); 10171 for (int i = 0; i < NR; i++) { 10172 final ResolveInfo info = receivers.get(i); 10173 if (info.activityInfo == null) { 10174 continue; 10175 } 10176 10177 if (packageName.equals(info.activityInfo.packageName)) { 10178 targetReceiver = info.activityInfo; 10179 break; 10180 } 10181 } 10182 10183 if (targetReceiver == null) { 10184 return null; 10185 } 10186 10187 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 10188 } 10189 10190 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 10191 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 10192 if (pkgInfo.verifiers.length == 0) { 10193 return null; 10194 } 10195 10196 final int N = pkgInfo.verifiers.length; 10197 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 10198 for (int i = 0; i < N; i++) { 10199 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 10200 10201 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 10202 receivers); 10203 if (comp == null) { 10204 continue; 10205 } 10206 10207 final int verifierUid = getUidForVerifier(verifierInfo); 10208 if (verifierUid == -1) { 10209 continue; 10210 } 10211 10212 if (DEBUG_VERIFY) { 10213 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 10214 + " with the correct signature"); 10215 } 10216 sufficientVerifiers.add(comp); 10217 verificationState.addSufficientVerifier(verifierUid); 10218 } 10219 10220 return sufficientVerifiers; 10221 } 10222 10223 private int getUidForVerifier(VerifierInfo verifierInfo) { 10224 synchronized (mPackages) { 10225 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 10226 if (pkg == null) { 10227 return -1; 10228 } else if (pkg.mSignatures.length != 1) { 10229 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10230 + " has more than one signature; ignoring"); 10231 return -1; 10232 } 10233 10234 /* 10235 * If the public key of the package's signature does not match 10236 * our expected public key, then this is a different package and 10237 * we should skip. 10238 */ 10239 10240 final byte[] expectedPublicKey; 10241 try { 10242 final Signature verifierSig = pkg.mSignatures[0]; 10243 final PublicKey publicKey = verifierSig.getPublicKey(); 10244 expectedPublicKey = publicKey.getEncoded(); 10245 } catch (CertificateException e) { 10246 return -1; 10247 } 10248 10249 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 10250 10251 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 10252 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10253 + " does not have the expected public key; ignoring"); 10254 return -1; 10255 } 10256 10257 return pkg.applicationInfo.uid; 10258 } 10259 } 10260 10261 @Override 10262 public void finishPackageInstall(int token) { 10263 enforceSystemOrRoot("Only the system is allowed to finish installs"); 10264 10265 if (DEBUG_INSTALL) { 10266 Slog.v(TAG, "BM finishing package install for " + token); 10267 } 10268 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10269 10270 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10271 mHandler.sendMessage(msg); 10272 } 10273 10274 /** 10275 * Get the verification agent timeout. 10276 * 10277 * @return verification timeout in milliseconds 10278 */ 10279 private long getVerificationTimeout() { 10280 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 10281 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 10282 DEFAULT_VERIFICATION_TIMEOUT); 10283 } 10284 10285 /** 10286 * Get the default verification agent response code. 10287 * 10288 * @return default verification response code 10289 */ 10290 private int getDefaultVerificationResponse() { 10291 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10292 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 10293 DEFAULT_VERIFICATION_RESPONSE); 10294 } 10295 10296 /** 10297 * Check whether or not package verification has been enabled. 10298 * 10299 * @return true if verification should be performed 10300 */ 10301 private boolean isVerificationEnabled(int userId, int installFlags) { 10302 if (!DEFAULT_VERIFY_ENABLE) { 10303 return false; 10304 } 10305 // TODO: fix b/25118622; don't bypass verification 10306 if (Build.IS_DEBUGGABLE && (installFlags & PackageManager.INSTALL_QUICK) != 0) { 10307 return false; 10308 } 10309 // Ephemeral apps don't get the full verification treatment 10310 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 10311 if (DEBUG_EPHEMERAL) { 10312 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 10313 } 10314 return false; 10315 } 10316 10317 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 10318 10319 // Check if installing from ADB 10320 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 10321 // Do not run verification in a test harness environment 10322 if (ActivityManager.isRunningInTestHarness()) { 10323 return false; 10324 } 10325 if (ensureVerifyAppsEnabled) { 10326 return true; 10327 } 10328 // Check if the developer does not want package verification for ADB installs 10329 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10330 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 10331 return false; 10332 } 10333 } 10334 10335 if (ensureVerifyAppsEnabled) { 10336 return true; 10337 } 10338 10339 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10340 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 10341 } 10342 10343 @Override 10344 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 10345 throws RemoteException { 10346 mContext.enforceCallingOrSelfPermission( 10347 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 10348 "Only intentfilter verification agents can verify applications"); 10349 10350 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 10351 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 10352 Binder.getCallingUid(), verificationCode, failedDomains); 10353 msg.arg1 = id; 10354 msg.obj = response; 10355 mHandler.sendMessage(msg); 10356 } 10357 10358 @Override 10359 public int getIntentVerificationStatus(String packageName, int userId) { 10360 synchronized (mPackages) { 10361 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 10362 } 10363 } 10364 10365 @Override 10366 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 10367 mContext.enforceCallingOrSelfPermission( 10368 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10369 10370 boolean result = false; 10371 synchronized (mPackages) { 10372 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 10373 } 10374 if (result) { 10375 scheduleWritePackageRestrictionsLocked(userId); 10376 } 10377 return result; 10378 } 10379 10380 @Override 10381 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 10382 synchronized (mPackages) { 10383 return mSettings.getIntentFilterVerificationsLPr(packageName); 10384 } 10385 } 10386 10387 @Override 10388 public List<IntentFilter> getAllIntentFilters(String packageName) { 10389 if (TextUtils.isEmpty(packageName)) { 10390 return Collections.<IntentFilter>emptyList(); 10391 } 10392 synchronized (mPackages) { 10393 PackageParser.Package pkg = mPackages.get(packageName); 10394 if (pkg == null || pkg.activities == null) { 10395 return Collections.<IntentFilter>emptyList(); 10396 } 10397 final int count = pkg.activities.size(); 10398 ArrayList<IntentFilter> result = new ArrayList<>(); 10399 for (int n=0; n<count; n++) { 10400 PackageParser.Activity activity = pkg.activities.get(n); 10401 if (activity.intents != null || activity.intents.size() > 0) { 10402 result.addAll(activity.intents); 10403 } 10404 } 10405 return result; 10406 } 10407 } 10408 10409 @Override 10410 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 10411 mContext.enforceCallingOrSelfPermission( 10412 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10413 10414 synchronized (mPackages) { 10415 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 10416 if (packageName != null) { 10417 result |= updateIntentVerificationStatus(packageName, 10418 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 10419 userId); 10420 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 10421 packageName, userId); 10422 } 10423 return result; 10424 } 10425 } 10426 10427 @Override 10428 public String getDefaultBrowserPackageName(int userId) { 10429 synchronized (mPackages) { 10430 return mSettings.getDefaultBrowserPackageNameLPw(userId); 10431 } 10432 } 10433 10434 /** 10435 * Get the "allow unknown sources" setting. 10436 * 10437 * @return the current "allow unknown sources" setting 10438 */ 10439 private int getUnknownSourcesSettings() { 10440 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10441 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 10442 -1); 10443 } 10444 10445 @Override 10446 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 10447 final int uid = Binder.getCallingUid(); 10448 // writer 10449 synchronized (mPackages) { 10450 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 10451 if (targetPackageSetting == null) { 10452 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 10453 } 10454 10455 PackageSetting installerPackageSetting; 10456 if (installerPackageName != null) { 10457 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 10458 if (installerPackageSetting == null) { 10459 throw new IllegalArgumentException("Unknown installer package: " 10460 + installerPackageName); 10461 } 10462 } else { 10463 installerPackageSetting = null; 10464 } 10465 10466 Signature[] callerSignature; 10467 Object obj = mSettings.getUserIdLPr(uid); 10468 if (obj != null) { 10469 if (obj instanceof SharedUserSetting) { 10470 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 10471 } else if (obj instanceof PackageSetting) { 10472 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 10473 } else { 10474 throw new SecurityException("Bad object " + obj + " for uid " + uid); 10475 } 10476 } else { 10477 throw new SecurityException("Unknown calling uid " + uid); 10478 } 10479 10480 // Verify: can't set installerPackageName to a package that is 10481 // not signed with the same cert as the caller. 10482 if (installerPackageSetting != null) { 10483 if (compareSignatures(callerSignature, 10484 installerPackageSetting.signatures.mSignatures) 10485 != PackageManager.SIGNATURE_MATCH) { 10486 throw new SecurityException( 10487 "Caller does not have same cert as new installer package " 10488 + installerPackageName); 10489 } 10490 } 10491 10492 // Verify: if target already has an installer package, it must 10493 // be signed with the same cert as the caller. 10494 if (targetPackageSetting.installerPackageName != null) { 10495 PackageSetting setting = mSettings.mPackages.get( 10496 targetPackageSetting.installerPackageName); 10497 // If the currently set package isn't valid, then it's always 10498 // okay to change it. 10499 if (setting != null) { 10500 if (compareSignatures(callerSignature, 10501 setting.signatures.mSignatures) 10502 != PackageManager.SIGNATURE_MATCH) { 10503 throw new SecurityException( 10504 "Caller does not have same cert as old installer package " 10505 + targetPackageSetting.installerPackageName); 10506 } 10507 } 10508 } 10509 10510 // Okay! 10511 targetPackageSetting.installerPackageName = installerPackageName; 10512 scheduleWriteSettingsLocked(); 10513 } 10514 } 10515 10516 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 10517 // Queue up an async operation since the package installation may take a little while. 10518 mHandler.post(new Runnable() { 10519 public void run() { 10520 mHandler.removeCallbacks(this); 10521 // Result object to be returned 10522 PackageInstalledInfo res = new PackageInstalledInfo(); 10523 res.returnCode = currentStatus; 10524 res.uid = -1; 10525 res.pkg = null; 10526 res.removedInfo = new PackageRemovedInfo(); 10527 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10528 args.doPreInstall(res.returnCode); 10529 synchronized (mInstallLock) { 10530 installPackageTracedLI(args, res); 10531 } 10532 args.doPostInstall(res.returnCode, res.uid); 10533 } 10534 10535 // A restore should be performed at this point if (a) the install 10536 // succeeded, (b) the operation is not an update, and (c) the new 10537 // package has not opted out of backup participation. 10538 final boolean update = res.removedInfo.removedPackage != null; 10539 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 10540 boolean doRestore = !update 10541 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 10542 10543 // Set up the post-install work request bookkeeping. This will be used 10544 // and cleaned up by the post-install event handling regardless of whether 10545 // there's a restore pass performed. Token values are >= 1. 10546 int token; 10547 if (mNextInstallToken < 0) mNextInstallToken = 1; 10548 token = mNextInstallToken++; 10549 10550 PostInstallData data = new PostInstallData(args, res); 10551 mRunningInstalls.put(token, data); 10552 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 10553 10554 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 10555 // Pass responsibility to the Backup Manager. It will perform a 10556 // restore if appropriate, then pass responsibility back to the 10557 // Package Manager to run the post-install observer callbacks 10558 // and broadcasts. 10559 IBackupManager bm = IBackupManager.Stub.asInterface( 10560 ServiceManager.getService(Context.BACKUP_SERVICE)); 10561 if (bm != null) { 10562 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 10563 + " to BM for possible restore"); 10564 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10565 try { 10566 // TODO: http://b/22388012 10567 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 10568 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 10569 } else { 10570 doRestore = false; 10571 } 10572 } catch (RemoteException e) { 10573 // can't happen; the backup manager is local 10574 } catch (Exception e) { 10575 Slog.e(TAG, "Exception trying to enqueue restore", e); 10576 doRestore = false; 10577 } 10578 } else { 10579 Slog.e(TAG, "Backup Manager not found!"); 10580 doRestore = false; 10581 } 10582 } 10583 10584 if (!doRestore) { 10585 // No restore possible, or the Backup Manager was mysteriously not 10586 // available -- just fire the post-install work request directly. 10587 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 10588 10589 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 10590 10591 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10592 mHandler.sendMessage(msg); 10593 } 10594 } 10595 }); 10596 } 10597 10598 private abstract class HandlerParams { 10599 private static final int MAX_RETRIES = 4; 10600 10601 /** 10602 * Number of times startCopy() has been attempted and had a non-fatal 10603 * error. 10604 */ 10605 private int mRetries = 0; 10606 10607 /** User handle for the user requesting the information or installation. */ 10608 private final UserHandle mUser; 10609 String traceMethod; 10610 int traceCookie; 10611 10612 HandlerParams(UserHandle user) { 10613 mUser = user; 10614 } 10615 10616 UserHandle getUser() { 10617 return mUser; 10618 } 10619 10620 HandlerParams setTraceMethod(String traceMethod) { 10621 this.traceMethod = traceMethod; 10622 return this; 10623 } 10624 10625 HandlerParams setTraceCookie(int traceCookie) { 10626 this.traceCookie = traceCookie; 10627 return this; 10628 } 10629 10630 final boolean startCopy() { 10631 boolean res; 10632 try { 10633 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 10634 10635 if (++mRetries > MAX_RETRIES) { 10636 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 10637 mHandler.sendEmptyMessage(MCS_GIVE_UP); 10638 handleServiceError(); 10639 return false; 10640 } else { 10641 handleStartCopy(); 10642 res = true; 10643 } 10644 } catch (RemoteException e) { 10645 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 10646 mHandler.sendEmptyMessage(MCS_RECONNECT); 10647 res = false; 10648 } 10649 handleReturnCode(); 10650 return res; 10651 } 10652 10653 final void serviceError() { 10654 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 10655 handleServiceError(); 10656 handleReturnCode(); 10657 } 10658 10659 abstract void handleStartCopy() throws RemoteException; 10660 abstract void handleServiceError(); 10661 abstract void handleReturnCode(); 10662 } 10663 10664 class MeasureParams extends HandlerParams { 10665 private final PackageStats mStats; 10666 private boolean mSuccess; 10667 10668 private final IPackageStatsObserver mObserver; 10669 10670 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 10671 super(new UserHandle(stats.userHandle)); 10672 mObserver = observer; 10673 mStats = stats; 10674 } 10675 10676 @Override 10677 public String toString() { 10678 return "MeasureParams{" 10679 + Integer.toHexString(System.identityHashCode(this)) 10680 + " " + mStats.packageName + "}"; 10681 } 10682 10683 @Override 10684 void handleStartCopy() throws RemoteException { 10685 synchronized (mInstallLock) { 10686 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 10687 } 10688 10689 if (mSuccess) { 10690 final boolean mounted; 10691 if (Environment.isExternalStorageEmulated()) { 10692 mounted = true; 10693 } else { 10694 final String status = Environment.getExternalStorageState(); 10695 mounted = (Environment.MEDIA_MOUNTED.equals(status) 10696 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 10697 } 10698 10699 if (mounted) { 10700 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 10701 10702 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 10703 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 10704 10705 mStats.externalDataSize = calculateDirectorySize(mContainerService, 10706 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 10707 10708 // Always subtract cache size, since it's a subdirectory 10709 mStats.externalDataSize -= mStats.externalCacheSize; 10710 10711 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 10712 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 10713 10714 mStats.externalObbSize = calculateDirectorySize(mContainerService, 10715 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 10716 } 10717 } 10718 } 10719 10720 @Override 10721 void handleReturnCode() { 10722 if (mObserver != null) { 10723 try { 10724 mObserver.onGetStatsCompleted(mStats, mSuccess); 10725 } catch (RemoteException e) { 10726 Slog.i(TAG, "Observer no longer exists."); 10727 } 10728 } 10729 } 10730 10731 @Override 10732 void handleServiceError() { 10733 Slog.e(TAG, "Could not measure application " + mStats.packageName 10734 + " external storage"); 10735 } 10736 } 10737 10738 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 10739 throws RemoteException { 10740 long result = 0; 10741 for (File path : paths) { 10742 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 10743 } 10744 return result; 10745 } 10746 10747 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 10748 for (File path : paths) { 10749 try { 10750 mcs.clearDirectory(path.getAbsolutePath()); 10751 } catch (RemoteException e) { 10752 } 10753 } 10754 } 10755 10756 static class OriginInfo { 10757 /** 10758 * Location where install is coming from, before it has been 10759 * copied/renamed into place. This could be a single monolithic APK 10760 * file, or a cluster directory. This location may be untrusted. 10761 */ 10762 final File file; 10763 final String cid; 10764 10765 /** 10766 * Flag indicating that {@link #file} or {@link #cid} has already been 10767 * staged, meaning downstream users don't need to defensively copy the 10768 * contents. 10769 */ 10770 final boolean staged; 10771 10772 /** 10773 * Flag indicating that {@link #file} or {@link #cid} is an already 10774 * installed app that is being moved. 10775 */ 10776 final boolean existing; 10777 10778 final String resolvedPath; 10779 final File resolvedFile; 10780 10781 static OriginInfo fromNothing() { 10782 return new OriginInfo(null, null, false, false); 10783 } 10784 10785 static OriginInfo fromUntrustedFile(File file) { 10786 return new OriginInfo(file, null, false, false); 10787 } 10788 10789 static OriginInfo fromExistingFile(File file) { 10790 return new OriginInfo(file, null, false, true); 10791 } 10792 10793 static OriginInfo fromStagedFile(File file) { 10794 return new OriginInfo(file, null, true, false); 10795 } 10796 10797 static OriginInfo fromStagedContainer(String cid) { 10798 return new OriginInfo(null, cid, true, false); 10799 } 10800 10801 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 10802 this.file = file; 10803 this.cid = cid; 10804 this.staged = staged; 10805 this.existing = existing; 10806 10807 if (cid != null) { 10808 resolvedPath = PackageHelper.getSdDir(cid); 10809 resolvedFile = new File(resolvedPath); 10810 } else if (file != null) { 10811 resolvedPath = file.getAbsolutePath(); 10812 resolvedFile = file; 10813 } else { 10814 resolvedPath = null; 10815 resolvedFile = null; 10816 } 10817 } 10818 } 10819 10820 class MoveInfo { 10821 final int moveId; 10822 final String fromUuid; 10823 final String toUuid; 10824 final String packageName; 10825 final String dataAppName; 10826 final int appId; 10827 final String seinfo; 10828 10829 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 10830 String dataAppName, int appId, String seinfo) { 10831 this.moveId = moveId; 10832 this.fromUuid = fromUuid; 10833 this.toUuid = toUuid; 10834 this.packageName = packageName; 10835 this.dataAppName = dataAppName; 10836 this.appId = appId; 10837 this.seinfo = seinfo; 10838 } 10839 } 10840 10841 class InstallParams extends HandlerParams { 10842 final OriginInfo origin; 10843 final MoveInfo move; 10844 final IPackageInstallObserver2 observer; 10845 int installFlags; 10846 final String installerPackageName; 10847 final String volumeUuid; 10848 final VerificationParams verificationParams; 10849 private InstallArgs mArgs; 10850 private int mRet; 10851 final String packageAbiOverride; 10852 final String[] grantedRuntimePermissions; 10853 10854 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10855 int installFlags, String installerPackageName, String volumeUuid, 10856 VerificationParams verificationParams, UserHandle user, String packageAbiOverride, 10857 String[] grantedPermissions) { 10858 super(user); 10859 this.origin = origin; 10860 this.move = move; 10861 this.observer = observer; 10862 this.installFlags = installFlags; 10863 this.installerPackageName = installerPackageName; 10864 this.volumeUuid = volumeUuid; 10865 this.verificationParams = verificationParams; 10866 this.packageAbiOverride = packageAbiOverride; 10867 this.grantedRuntimePermissions = grantedPermissions; 10868 } 10869 10870 @Override 10871 public String toString() { 10872 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 10873 + " file=" + origin.file + " cid=" + origin.cid + "}"; 10874 } 10875 10876 public ManifestDigest getManifestDigest() { 10877 if (verificationParams == null) { 10878 return null; 10879 } 10880 return verificationParams.getManifestDigest(); 10881 } 10882 10883 private int installLocationPolicy(PackageInfoLite pkgLite) { 10884 String packageName = pkgLite.packageName; 10885 int installLocation = pkgLite.installLocation; 10886 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10887 // reader 10888 synchronized (mPackages) { 10889 PackageParser.Package pkg = mPackages.get(packageName); 10890 if (pkg != null) { 10891 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10892 // Check for downgrading. 10893 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 10894 try { 10895 checkDowngrade(pkg, pkgLite); 10896 } catch (PackageManagerException e) { 10897 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 10898 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 10899 } 10900 } 10901 // Check for updated system application. 10902 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10903 if (onSd) { 10904 Slog.w(TAG, "Cannot install update to system app on sdcard"); 10905 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 10906 } 10907 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10908 } else { 10909 if (onSd) { 10910 // Install flag overrides everything. 10911 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10912 } 10913 // If current upgrade specifies particular preference 10914 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 10915 // Application explicitly specified internal. 10916 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10917 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 10918 // App explictly prefers external. Let policy decide 10919 } else { 10920 // Prefer previous location 10921 if (isExternal(pkg)) { 10922 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10923 } 10924 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10925 } 10926 } 10927 } else { 10928 // Invalid install. Return error code 10929 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 10930 } 10931 } 10932 } 10933 // All the special cases have been taken care of. 10934 // Return result based on recommended install location. 10935 if (onSd) { 10936 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10937 } 10938 return pkgLite.recommendedInstallLocation; 10939 } 10940 10941 /* 10942 * Invoke remote method to get package information and install 10943 * location values. Override install location based on default 10944 * policy if needed and then create install arguments based 10945 * on the install location. 10946 */ 10947 public void handleStartCopy() throws RemoteException { 10948 int ret = PackageManager.INSTALL_SUCCEEDED; 10949 10950 // If we're already staged, we've firmly committed to an install location 10951 if (origin.staged) { 10952 if (origin.file != null) { 10953 installFlags |= PackageManager.INSTALL_INTERNAL; 10954 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10955 } else if (origin.cid != null) { 10956 installFlags |= PackageManager.INSTALL_EXTERNAL; 10957 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10958 } else { 10959 throw new IllegalStateException("Invalid stage location"); 10960 } 10961 } 10962 10963 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10964 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 10965 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 10966 PackageInfoLite pkgLite = null; 10967 10968 if (onInt && onSd) { 10969 // Check if both bits are set. 10970 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 10971 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10972 } else if (onSd && ephemeral) { 10973 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 10974 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10975 } else { 10976 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 10977 packageAbiOverride); 10978 10979 if (DEBUG_EPHEMERAL && ephemeral) { 10980 Slog.v(TAG, "pkgLite for install: " + pkgLite); 10981 } 10982 10983 /* 10984 * If we have too little free space, try to free cache 10985 * before giving up. 10986 */ 10987 if (!origin.staged && pkgLite.recommendedInstallLocation 10988 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10989 // TODO: focus freeing disk space on the target device 10990 final StorageManager storage = StorageManager.from(mContext); 10991 final long lowThreshold = storage.getStorageLowBytes( 10992 Environment.getDataDirectory()); 10993 10994 final long sizeBytes = mContainerService.calculateInstalledSize( 10995 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 10996 10997 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 10998 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 10999 installFlags, packageAbiOverride); 11000 } 11001 11002 /* 11003 * The cache free must have deleted the file we 11004 * downloaded to install. 11005 * 11006 * TODO: fix the "freeCache" call to not delete 11007 * the file we care about. 11008 */ 11009 if (pkgLite.recommendedInstallLocation 11010 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 11011 pkgLite.recommendedInstallLocation 11012 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 11013 } 11014 } 11015 } 11016 11017 if (ret == PackageManager.INSTALL_SUCCEEDED) { 11018 int loc = pkgLite.recommendedInstallLocation; 11019 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 11020 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11021 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 11022 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 11023 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 11024 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11025 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 11026 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 11027 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 11028 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 11029 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 11030 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 11031 } else { 11032 // Override with defaults if needed. 11033 loc = installLocationPolicy(pkgLite); 11034 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 11035 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 11036 } else if (!onSd && !onInt) { 11037 // Override install location with flags 11038 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 11039 // Set the flag to install on external media. 11040 installFlags |= PackageManager.INSTALL_EXTERNAL; 11041 installFlags &= ~PackageManager.INSTALL_INTERNAL; 11042 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 11043 if (DEBUG_EPHEMERAL) { 11044 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 11045 } 11046 installFlags |= PackageManager.INSTALL_EPHEMERAL; 11047 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 11048 |PackageManager.INSTALL_INTERNAL); 11049 } else { 11050 // Make sure the flag for installing on external 11051 // media is unset 11052 installFlags |= PackageManager.INSTALL_INTERNAL; 11053 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 11054 } 11055 } 11056 } 11057 } 11058 11059 final InstallArgs args = createInstallArgs(this); 11060 mArgs = args; 11061 11062 if (ret == PackageManager.INSTALL_SUCCEEDED) { 11063 // TODO: http://b/22976637 11064 // Apps installed for "all" users use the device owner to verify the app 11065 UserHandle verifierUser = getUser(); 11066 if (verifierUser == UserHandle.ALL) { 11067 verifierUser = UserHandle.SYSTEM; 11068 } 11069 11070 /* 11071 * Determine if we have any installed package verifiers. If we 11072 * do, then we'll defer to them to verify the packages. 11073 */ 11074 final int requiredUid = mRequiredVerifierPackage == null ? -1 11075 : getPackageUid(mRequiredVerifierPackage, verifierUser.getIdentifier()); 11076 if (!origin.existing && requiredUid != -1 11077 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 11078 final Intent verification = new Intent( 11079 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 11080 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 11081 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 11082 PACKAGE_MIME_TYPE); 11083 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11084 11085 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 11086 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 11087 verifierUser.getIdentifier()); 11088 11089 if (DEBUG_VERIFY) { 11090 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 11091 + verification.toString() + " with " + pkgLite.verifiers.length 11092 + " optional verifiers"); 11093 } 11094 11095 final int verificationId = mPendingVerificationToken++; 11096 11097 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11098 11099 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 11100 installerPackageName); 11101 11102 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 11103 installFlags); 11104 11105 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 11106 pkgLite.packageName); 11107 11108 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 11109 pkgLite.versionCode); 11110 11111 if (verificationParams != null) { 11112 if (verificationParams.getVerificationURI() != null) { 11113 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 11114 verificationParams.getVerificationURI()); 11115 } 11116 if (verificationParams.getOriginatingURI() != null) { 11117 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 11118 verificationParams.getOriginatingURI()); 11119 } 11120 if (verificationParams.getReferrer() != null) { 11121 verification.putExtra(Intent.EXTRA_REFERRER, 11122 verificationParams.getReferrer()); 11123 } 11124 if (verificationParams.getOriginatingUid() >= 0) { 11125 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 11126 verificationParams.getOriginatingUid()); 11127 } 11128 if (verificationParams.getInstallerUid() >= 0) { 11129 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 11130 verificationParams.getInstallerUid()); 11131 } 11132 } 11133 11134 final PackageVerificationState verificationState = new PackageVerificationState( 11135 requiredUid, args); 11136 11137 mPendingVerification.append(verificationId, verificationState); 11138 11139 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 11140 receivers, verificationState); 11141 11142 /* 11143 * If any sufficient verifiers were listed in the package 11144 * manifest, attempt to ask them. 11145 */ 11146 if (sufficientVerifiers != null) { 11147 final int N = sufficientVerifiers.size(); 11148 if (N == 0) { 11149 Slog.i(TAG, "Additional verifiers required, but none installed."); 11150 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 11151 } else { 11152 for (int i = 0; i < N; i++) { 11153 final ComponentName verifierComponent = sufficientVerifiers.get(i); 11154 11155 final Intent sufficientIntent = new Intent(verification); 11156 sufficientIntent.setComponent(verifierComponent); 11157 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 11158 } 11159 } 11160 } 11161 11162 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 11163 mRequiredVerifierPackage, receivers); 11164 if (ret == PackageManager.INSTALL_SUCCEEDED 11165 && mRequiredVerifierPackage != null) { 11166 Trace.asyncTraceBegin( 11167 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 11168 /* 11169 * Send the intent to the required verification agent, 11170 * but only start the verification timeout after the 11171 * target BroadcastReceivers have run. 11172 */ 11173 verification.setComponent(requiredVerifierComponent); 11174 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 11175 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11176 new BroadcastReceiver() { 11177 @Override 11178 public void onReceive(Context context, Intent intent) { 11179 final Message msg = mHandler 11180 .obtainMessage(CHECK_PENDING_VERIFICATION); 11181 msg.arg1 = verificationId; 11182 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 11183 } 11184 }, null, 0, null, null); 11185 11186 /* 11187 * We don't want the copy to proceed until verification 11188 * succeeds, so null out this field. 11189 */ 11190 mArgs = null; 11191 } 11192 } else { 11193 /* 11194 * No package verification is enabled, so immediately start 11195 * the remote call to initiate copy using temporary file. 11196 */ 11197 ret = args.copyApk(mContainerService, true); 11198 } 11199 } 11200 11201 mRet = ret; 11202 } 11203 11204 @Override 11205 void handleReturnCode() { 11206 // If mArgs is null, then MCS couldn't be reached. When it 11207 // reconnects, it will try again to install. At that point, this 11208 // will succeed. 11209 if (mArgs != null) { 11210 processPendingInstall(mArgs, mRet); 11211 } 11212 } 11213 11214 @Override 11215 void handleServiceError() { 11216 mArgs = createInstallArgs(this); 11217 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11218 } 11219 11220 public boolean isForwardLocked() { 11221 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11222 } 11223 } 11224 11225 /** 11226 * Used during creation of InstallArgs 11227 * 11228 * @param installFlags package installation flags 11229 * @return true if should be installed on external storage 11230 */ 11231 private static boolean installOnExternalAsec(int installFlags) { 11232 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 11233 return false; 11234 } 11235 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 11236 return true; 11237 } 11238 return false; 11239 } 11240 11241 /** 11242 * Used during creation of InstallArgs 11243 * 11244 * @param installFlags package installation flags 11245 * @return true if should be installed as forward locked 11246 */ 11247 private static boolean installForwardLocked(int installFlags) { 11248 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11249 } 11250 11251 private InstallArgs createInstallArgs(InstallParams params) { 11252 if (params.move != null) { 11253 return new MoveInstallArgs(params); 11254 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 11255 return new AsecInstallArgs(params); 11256 } else { 11257 return new FileInstallArgs(params); 11258 } 11259 } 11260 11261 /** 11262 * Create args that describe an existing installed package. Typically used 11263 * when cleaning up old installs, or used as a move source. 11264 */ 11265 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 11266 String resourcePath, String[] instructionSets) { 11267 final boolean isInAsec; 11268 if (installOnExternalAsec(installFlags)) { 11269 /* Apps on SD card are always in ASEC containers. */ 11270 isInAsec = true; 11271 } else if (installForwardLocked(installFlags) 11272 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 11273 /* 11274 * Forward-locked apps are only in ASEC containers if they're the 11275 * new style 11276 */ 11277 isInAsec = true; 11278 } else { 11279 isInAsec = false; 11280 } 11281 11282 if (isInAsec) { 11283 return new AsecInstallArgs(codePath, instructionSets, 11284 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 11285 } else { 11286 return new FileInstallArgs(codePath, resourcePath, instructionSets); 11287 } 11288 } 11289 11290 static abstract class InstallArgs { 11291 /** @see InstallParams#origin */ 11292 final OriginInfo origin; 11293 /** @see InstallParams#move */ 11294 final MoveInfo move; 11295 11296 final IPackageInstallObserver2 observer; 11297 // Always refers to PackageManager flags only 11298 final int installFlags; 11299 final String installerPackageName; 11300 final String volumeUuid; 11301 final ManifestDigest manifestDigest; 11302 final UserHandle user; 11303 final String abiOverride; 11304 final String[] installGrantPermissions; 11305 /** If non-null, drop an async trace when the install completes */ 11306 final String traceMethod; 11307 final int traceCookie; 11308 11309 // The list of instruction sets supported by this app. This is currently 11310 // only used during the rmdex() phase to clean up resources. We can get rid of this 11311 // if we move dex files under the common app path. 11312 /* nullable */ String[] instructionSets; 11313 11314 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 11315 int installFlags, String installerPackageName, String volumeUuid, 11316 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 11317 String abiOverride, String[] installGrantPermissions, 11318 String traceMethod, int traceCookie) { 11319 this.origin = origin; 11320 this.move = move; 11321 this.installFlags = installFlags; 11322 this.observer = observer; 11323 this.installerPackageName = installerPackageName; 11324 this.volumeUuid = volumeUuid; 11325 this.manifestDigest = manifestDigest; 11326 this.user = user; 11327 this.instructionSets = instructionSets; 11328 this.abiOverride = abiOverride; 11329 this.installGrantPermissions = installGrantPermissions; 11330 this.traceMethod = traceMethod; 11331 this.traceCookie = traceCookie; 11332 } 11333 11334 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 11335 abstract int doPreInstall(int status); 11336 11337 /** 11338 * Rename package into final resting place. All paths on the given 11339 * scanned package should be updated to reflect the rename. 11340 */ 11341 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 11342 abstract int doPostInstall(int status, int uid); 11343 11344 /** @see PackageSettingBase#codePathString */ 11345 abstract String getCodePath(); 11346 /** @see PackageSettingBase#resourcePathString */ 11347 abstract String getResourcePath(); 11348 11349 // Need installer lock especially for dex file removal. 11350 abstract void cleanUpResourcesLI(); 11351 abstract boolean doPostDeleteLI(boolean delete); 11352 11353 /** 11354 * Called before the source arguments are copied. This is used mostly 11355 * for MoveParams when it needs to read the source file to put it in the 11356 * destination. 11357 */ 11358 int doPreCopy() { 11359 return PackageManager.INSTALL_SUCCEEDED; 11360 } 11361 11362 /** 11363 * Called after the source arguments are copied. This is used mostly for 11364 * MoveParams when it needs to read the source file to put it in the 11365 * destination. 11366 * 11367 * @return 11368 */ 11369 int doPostCopy(int uid) { 11370 return PackageManager.INSTALL_SUCCEEDED; 11371 } 11372 11373 protected boolean isFwdLocked() { 11374 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11375 } 11376 11377 protected boolean isExternalAsec() { 11378 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11379 } 11380 11381 protected boolean isEphemeral() { 11382 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 11383 } 11384 11385 UserHandle getUser() { 11386 return user; 11387 } 11388 } 11389 11390 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 11391 if (!allCodePaths.isEmpty()) { 11392 if (instructionSets == null) { 11393 throw new IllegalStateException("instructionSet == null"); 11394 } 11395 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 11396 for (String codePath : allCodePaths) { 11397 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 11398 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 11399 if (retCode < 0) { 11400 Slog.w(TAG, "Couldn't remove dex file for package: " 11401 + " at location " + codePath + ", retcode=" + retCode); 11402 // we don't consider this to be a failure of the core package deletion 11403 } 11404 } 11405 } 11406 } 11407 } 11408 11409 /** 11410 * Logic to handle installation of non-ASEC applications, including copying 11411 * and renaming logic. 11412 */ 11413 class FileInstallArgs extends InstallArgs { 11414 private File codeFile; 11415 private File resourceFile; 11416 11417 // Example topology: 11418 // /data/app/com.example/base.apk 11419 // /data/app/com.example/split_foo.apk 11420 // /data/app/com.example/lib/arm/libfoo.so 11421 // /data/app/com.example/lib/arm64/libfoo.so 11422 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 11423 11424 /** New install */ 11425 FileInstallArgs(InstallParams params) { 11426 super(params.origin, params.move, params.observer, params.installFlags, 11427 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11428 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11429 params.grantedRuntimePermissions, 11430 params.traceMethod, params.traceCookie); 11431 if (isFwdLocked()) { 11432 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 11433 } 11434 } 11435 11436 /** Existing install */ 11437 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 11438 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 11439 null, null, null, 0); 11440 this.codeFile = (codePath != null) ? new File(codePath) : null; 11441 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 11442 } 11443 11444 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11445 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 11446 try { 11447 return doCopyApk(imcs, temp); 11448 } finally { 11449 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11450 } 11451 } 11452 11453 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11454 if (origin.staged) { 11455 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 11456 codeFile = origin.file; 11457 resourceFile = origin.file; 11458 return PackageManager.INSTALL_SUCCEEDED; 11459 } 11460 11461 try { 11462 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 11463 final File tempDir = 11464 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 11465 codeFile = tempDir; 11466 resourceFile = tempDir; 11467 } catch (IOException e) { 11468 Slog.w(TAG, "Failed to create copy file: " + e); 11469 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11470 } 11471 11472 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 11473 @Override 11474 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 11475 if (!FileUtils.isValidExtFilename(name)) { 11476 throw new IllegalArgumentException("Invalid filename: " + name); 11477 } 11478 try { 11479 final File file = new File(codeFile, name); 11480 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 11481 O_RDWR | O_CREAT, 0644); 11482 Os.chmod(file.getAbsolutePath(), 0644); 11483 return new ParcelFileDescriptor(fd); 11484 } catch (ErrnoException e) { 11485 throw new RemoteException("Failed to open: " + e.getMessage()); 11486 } 11487 } 11488 }; 11489 11490 int ret = PackageManager.INSTALL_SUCCEEDED; 11491 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 11492 if (ret != PackageManager.INSTALL_SUCCEEDED) { 11493 Slog.e(TAG, "Failed to copy package"); 11494 return ret; 11495 } 11496 11497 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 11498 NativeLibraryHelper.Handle handle = null; 11499 try { 11500 handle = NativeLibraryHelper.Handle.create(codeFile); 11501 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 11502 abiOverride); 11503 } catch (IOException e) { 11504 Slog.e(TAG, "Copying native libraries failed", e); 11505 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11506 } finally { 11507 IoUtils.closeQuietly(handle); 11508 } 11509 11510 return ret; 11511 } 11512 11513 int doPreInstall(int status) { 11514 if (status != PackageManager.INSTALL_SUCCEEDED) { 11515 cleanUp(); 11516 } 11517 return status; 11518 } 11519 11520 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11521 if (status != PackageManager.INSTALL_SUCCEEDED) { 11522 cleanUp(); 11523 return false; 11524 } 11525 11526 final File targetDir = codeFile.getParentFile(); 11527 final File beforeCodeFile = codeFile; 11528 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 11529 11530 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 11531 try { 11532 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 11533 } catch (ErrnoException e) { 11534 Slog.w(TAG, "Failed to rename", e); 11535 return false; 11536 } 11537 11538 if (!SELinux.restoreconRecursive(afterCodeFile)) { 11539 Slog.w(TAG, "Failed to restorecon"); 11540 return false; 11541 } 11542 11543 // Reflect the rename internally 11544 codeFile = afterCodeFile; 11545 resourceFile = afterCodeFile; 11546 11547 // Reflect the rename in scanned details 11548 pkg.codePath = afterCodeFile.getAbsolutePath(); 11549 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11550 pkg.baseCodePath); 11551 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11552 pkg.splitCodePaths); 11553 11554 // Reflect the rename in app info 11555 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11556 pkg.applicationInfo.setCodePath(pkg.codePath); 11557 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11558 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11559 pkg.applicationInfo.setResourcePath(pkg.codePath); 11560 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11561 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11562 11563 return true; 11564 } 11565 11566 int doPostInstall(int status, int uid) { 11567 if (status != PackageManager.INSTALL_SUCCEEDED) { 11568 cleanUp(); 11569 } 11570 return status; 11571 } 11572 11573 @Override 11574 String getCodePath() { 11575 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11576 } 11577 11578 @Override 11579 String getResourcePath() { 11580 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11581 } 11582 11583 private boolean cleanUp() { 11584 if (codeFile == null || !codeFile.exists()) { 11585 return false; 11586 } 11587 11588 if (codeFile.isDirectory()) { 11589 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11590 } else { 11591 codeFile.delete(); 11592 } 11593 11594 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 11595 resourceFile.delete(); 11596 } 11597 11598 return true; 11599 } 11600 11601 void cleanUpResourcesLI() { 11602 // Try enumerating all code paths before deleting 11603 List<String> allCodePaths = Collections.EMPTY_LIST; 11604 if (codeFile != null && codeFile.exists()) { 11605 try { 11606 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11607 allCodePaths = pkg.getAllCodePaths(); 11608 } catch (PackageParserException e) { 11609 // Ignored; we tried our best 11610 } 11611 } 11612 11613 cleanUp(); 11614 removeDexFiles(allCodePaths, instructionSets); 11615 } 11616 11617 boolean doPostDeleteLI(boolean delete) { 11618 // XXX err, shouldn't we respect the delete flag? 11619 cleanUpResourcesLI(); 11620 return true; 11621 } 11622 } 11623 11624 private boolean isAsecExternal(String cid) { 11625 final String asecPath = PackageHelper.getSdFilesystem(cid); 11626 return !asecPath.startsWith(mAsecInternalPath); 11627 } 11628 11629 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 11630 PackageManagerException { 11631 if (copyRet < 0) { 11632 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 11633 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 11634 throw new PackageManagerException(copyRet, message); 11635 } 11636 } 11637 } 11638 11639 /** 11640 * Extract the MountService "container ID" from the full code path of an 11641 * .apk. 11642 */ 11643 static String cidFromCodePath(String fullCodePath) { 11644 int eidx = fullCodePath.lastIndexOf("/"); 11645 String subStr1 = fullCodePath.substring(0, eidx); 11646 int sidx = subStr1.lastIndexOf("/"); 11647 return subStr1.substring(sidx+1, eidx); 11648 } 11649 11650 /** 11651 * Logic to handle installation of ASEC applications, including copying and 11652 * renaming logic. 11653 */ 11654 class AsecInstallArgs extends InstallArgs { 11655 static final String RES_FILE_NAME = "pkg.apk"; 11656 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 11657 11658 String cid; 11659 String packagePath; 11660 String resourcePath; 11661 11662 /** New install */ 11663 AsecInstallArgs(InstallParams params) { 11664 super(params.origin, params.move, params.observer, params.installFlags, 11665 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11666 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11667 params.grantedRuntimePermissions, 11668 params.traceMethod, params.traceCookie); 11669 } 11670 11671 /** Existing install */ 11672 AsecInstallArgs(String fullCodePath, String[] instructionSets, 11673 boolean isExternal, boolean isForwardLocked) { 11674 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 11675 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11676 instructionSets, null, null, null, 0); 11677 // Hackily pretend we're still looking at a full code path 11678 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 11679 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 11680 } 11681 11682 // Extract cid from fullCodePath 11683 int eidx = fullCodePath.lastIndexOf("/"); 11684 String subStr1 = fullCodePath.substring(0, eidx); 11685 int sidx = subStr1.lastIndexOf("/"); 11686 cid = subStr1.substring(sidx+1, eidx); 11687 setMountPath(subStr1); 11688 } 11689 11690 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 11691 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 11692 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11693 instructionSets, null, null, null, 0); 11694 this.cid = cid; 11695 setMountPath(PackageHelper.getSdDir(cid)); 11696 } 11697 11698 void createCopyFile() { 11699 cid = mInstallerService.allocateExternalStageCidLegacy(); 11700 } 11701 11702 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11703 if (origin.staged && origin.cid != null) { 11704 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 11705 cid = origin.cid; 11706 setMountPath(PackageHelper.getSdDir(cid)); 11707 return PackageManager.INSTALL_SUCCEEDED; 11708 } 11709 11710 if (temp) { 11711 createCopyFile(); 11712 } else { 11713 /* 11714 * Pre-emptively destroy the container since it's destroyed if 11715 * copying fails due to it existing anyway. 11716 */ 11717 PackageHelper.destroySdDir(cid); 11718 } 11719 11720 final String newMountPath = imcs.copyPackageToContainer( 11721 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 11722 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 11723 11724 if (newMountPath != null) { 11725 setMountPath(newMountPath); 11726 return PackageManager.INSTALL_SUCCEEDED; 11727 } else { 11728 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11729 } 11730 } 11731 11732 @Override 11733 String getCodePath() { 11734 return packagePath; 11735 } 11736 11737 @Override 11738 String getResourcePath() { 11739 return resourcePath; 11740 } 11741 11742 int doPreInstall(int status) { 11743 if (status != PackageManager.INSTALL_SUCCEEDED) { 11744 // Destroy container 11745 PackageHelper.destroySdDir(cid); 11746 } else { 11747 boolean mounted = PackageHelper.isContainerMounted(cid); 11748 if (!mounted) { 11749 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 11750 Process.SYSTEM_UID); 11751 if (newMountPath != null) { 11752 setMountPath(newMountPath); 11753 } else { 11754 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11755 } 11756 } 11757 } 11758 return status; 11759 } 11760 11761 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11762 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 11763 String newMountPath = null; 11764 if (PackageHelper.isContainerMounted(cid)) { 11765 // Unmount the container 11766 if (!PackageHelper.unMountSdDir(cid)) { 11767 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 11768 return false; 11769 } 11770 } 11771 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11772 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 11773 " which might be stale. Will try to clean up."); 11774 // Clean up the stale container and proceed to recreate. 11775 if (!PackageHelper.destroySdDir(newCacheId)) { 11776 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 11777 return false; 11778 } 11779 // Successfully cleaned up stale container. Try to rename again. 11780 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11781 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 11782 + " inspite of cleaning it up."); 11783 return false; 11784 } 11785 } 11786 if (!PackageHelper.isContainerMounted(newCacheId)) { 11787 Slog.w(TAG, "Mounting container " + newCacheId); 11788 newMountPath = PackageHelper.mountSdDir(newCacheId, 11789 getEncryptKey(), Process.SYSTEM_UID); 11790 } else { 11791 newMountPath = PackageHelper.getSdDir(newCacheId); 11792 } 11793 if (newMountPath == null) { 11794 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 11795 return false; 11796 } 11797 Log.i(TAG, "Succesfully renamed " + cid + 11798 " to " + newCacheId + 11799 " at new path: " + newMountPath); 11800 cid = newCacheId; 11801 11802 final File beforeCodeFile = new File(packagePath); 11803 setMountPath(newMountPath); 11804 final File afterCodeFile = new File(packagePath); 11805 11806 // Reflect the rename in scanned details 11807 pkg.codePath = afterCodeFile.getAbsolutePath(); 11808 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11809 pkg.baseCodePath); 11810 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11811 pkg.splitCodePaths); 11812 11813 // Reflect the rename in app info 11814 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11815 pkg.applicationInfo.setCodePath(pkg.codePath); 11816 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11817 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11818 pkg.applicationInfo.setResourcePath(pkg.codePath); 11819 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11820 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11821 11822 return true; 11823 } 11824 11825 private void setMountPath(String mountPath) { 11826 final File mountFile = new File(mountPath); 11827 11828 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 11829 if (monolithicFile.exists()) { 11830 packagePath = monolithicFile.getAbsolutePath(); 11831 if (isFwdLocked()) { 11832 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 11833 } else { 11834 resourcePath = packagePath; 11835 } 11836 } else { 11837 packagePath = mountFile.getAbsolutePath(); 11838 resourcePath = packagePath; 11839 } 11840 } 11841 11842 int doPostInstall(int status, int uid) { 11843 if (status != PackageManager.INSTALL_SUCCEEDED) { 11844 cleanUp(); 11845 } else { 11846 final int groupOwner; 11847 final String protectedFile; 11848 if (isFwdLocked()) { 11849 groupOwner = UserHandle.getSharedAppGid(uid); 11850 protectedFile = RES_FILE_NAME; 11851 } else { 11852 groupOwner = -1; 11853 protectedFile = null; 11854 } 11855 11856 if (uid < Process.FIRST_APPLICATION_UID 11857 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 11858 Slog.e(TAG, "Failed to finalize " + cid); 11859 PackageHelper.destroySdDir(cid); 11860 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11861 } 11862 11863 boolean mounted = PackageHelper.isContainerMounted(cid); 11864 if (!mounted) { 11865 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 11866 } 11867 } 11868 return status; 11869 } 11870 11871 private void cleanUp() { 11872 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 11873 11874 // Destroy secure container 11875 PackageHelper.destroySdDir(cid); 11876 } 11877 11878 private List<String> getAllCodePaths() { 11879 final File codeFile = new File(getCodePath()); 11880 if (codeFile != null && codeFile.exists()) { 11881 try { 11882 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11883 return pkg.getAllCodePaths(); 11884 } catch (PackageParserException e) { 11885 // Ignored; we tried our best 11886 } 11887 } 11888 return Collections.EMPTY_LIST; 11889 } 11890 11891 void cleanUpResourcesLI() { 11892 // Enumerate all code paths before deleting 11893 cleanUpResourcesLI(getAllCodePaths()); 11894 } 11895 11896 private void cleanUpResourcesLI(List<String> allCodePaths) { 11897 cleanUp(); 11898 removeDexFiles(allCodePaths, instructionSets); 11899 } 11900 11901 String getPackageName() { 11902 return getAsecPackageName(cid); 11903 } 11904 11905 boolean doPostDeleteLI(boolean delete) { 11906 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 11907 final List<String> allCodePaths = getAllCodePaths(); 11908 boolean mounted = PackageHelper.isContainerMounted(cid); 11909 if (mounted) { 11910 // Unmount first 11911 if (PackageHelper.unMountSdDir(cid)) { 11912 mounted = false; 11913 } 11914 } 11915 if (!mounted && delete) { 11916 cleanUpResourcesLI(allCodePaths); 11917 } 11918 return !mounted; 11919 } 11920 11921 @Override 11922 int doPreCopy() { 11923 if (isFwdLocked()) { 11924 if (!PackageHelper.fixSdPermissions(cid, 11925 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 11926 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11927 } 11928 } 11929 11930 return PackageManager.INSTALL_SUCCEEDED; 11931 } 11932 11933 @Override 11934 int doPostCopy(int uid) { 11935 if (isFwdLocked()) { 11936 if (uid < Process.FIRST_APPLICATION_UID 11937 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 11938 RES_FILE_NAME)) { 11939 Slog.e(TAG, "Failed to finalize " + cid); 11940 PackageHelper.destroySdDir(cid); 11941 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11942 } 11943 } 11944 11945 return PackageManager.INSTALL_SUCCEEDED; 11946 } 11947 } 11948 11949 /** 11950 * Logic to handle movement of existing installed applications. 11951 */ 11952 class MoveInstallArgs extends InstallArgs { 11953 private File codeFile; 11954 private File resourceFile; 11955 11956 /** New install */ 11957 MoveInstallArgs(InstallParams params) { 11958 super(params.origin, params.move, params.observer, params.installFlags, 11959 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11960 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11961 params.grantedRuntimePermissions, 11962 params.traceMethod, params.traceCookie); 11963 } 11964 11965 int copyApk(IMediaContainerService imcs, boolean temp) { 11966 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 11967 + move.fromUuid + " to " + move.toUuid); 11968 synchronized (mInstaller) { 11969 if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName, 11970 move.dataAppName, move.appId, move.seinfo) != 0) { 11971 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11972 } 11973 } 11974 11975 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 11976 resourceFile = codeFile; 11977 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 11978 11979 return PackageManager.INSTALL_SUCCEEDED; 11980 } 11981 11982 int doPreInstall(int status) { 11983 if (status != PackageManager.INSTALL_SUCCEEDED) { 11984 cleanUp(move.toUuid); 11985 } 11986 return status; 11987 } 11988 11989 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11990 if (status != PackageManager.INSTALL_SUCCEEDED) { 11991 cleanUp(move.toUuid); 11992 return false; 11993 } 11994 11995 // Reflect the move in app info 11996 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11997 pkg.applicationInfo.setCodePath(pkg.codePath); 11998 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11999 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 12000 pkg.applicationInfo.setResourcePath(pkg.codePath); 12001 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 12002 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 12003 12004 return true; 12005 } 12006 12007 int doPostInstall(int status, int uid) { 12008 if (status == PackageManager.INSTALL_SUCCEEDED) { 12009 cleanUp(move.fromUuid); 12010 } else { 12011 cleanUp(move.toUuid); 12012 } 12013 return status; 12014 } 12015 12016 @Override 12017 String getCodePath() { 12018 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 12019 } 12020 12021 @Override 12022 String getResourcePath() { 12023 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 12024 } 12025 12026 private boolean cleanUp(String volumeUuid) { 12027 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 12028 move.dataAppName); 12029 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 12030 synchronized (mInstallLock) { 12031 // Clean up both app data and code 12032 removeDataDirsLI(volumeUuid, move.packageName); 12033 if (codeFile.isDirectory()) { 12034 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 12035 } else { 12036 codeFile.delete(); 12037 } 12038 } 12039 return true; 12040 } 12041 12042 void cleanUpResourcesLI() { 12043 throw new UnsupportedOperationException(); 12044 } 12045 12046 boolean doPostDeleteLI(boolean delete) { 12047 throw new UnsupportedOperationException(); 12048 } 12049 } 12050 12051 static String getAsecPackageName(String packageCid) { 12052 int idx = packageCid.lastIndexOf("-"); 12053 if (idx == -1) { 12054 return packageCid; 12055 } 12056 return packageCid.substring(0, idx); 12057 } 12058 12059 // Utility method used to create code paths based on package name and available index. 12060 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 12061 String idxStr = ""; 12062 int idx = 1; 12063 // Fall back to default value of idx=1 if prefix is not 12064 // part of oldCodePath 12065 if (oldCodePath != null) { 12066 String subStr = oldCodePath; 12067 // Drop the suffix right away 12068 if (suffix != null && subStr.endsWith(suffix)) { 12069 subStr = subStr.substring(0, subStr.length() - suffix.length()); 12070 } 12071 // If oldCodePath already contains prefix find out the 12072 // ending index to either increment or decrement. 12073 int sidx = subStr.lastIndexOf(prefix); 12074 if (sidx != -1) { 12075 subStr = subStr.substring(sidx + prefix.length()); 12076 if (subStr != null) { 12077 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 12078 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 12079 } 12080 try { 12081 idx = Integer.parseInt(subStr); 12082 if (idx <= 1) { 12083 idx++; 12084 } else { 12085 idx--; 12086 } 12087 } catch(NumberFormatException e) { 12088 } 12089 } 12090 } 12091 } 12092 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 12093 return prefix + idxStr; 12094 } 12095 12096 private File getNextCodePath(File targetDir, String packageName) { 12097 int suffix = 1; 12098 File result; 12099 do { 12100 result = new File(targetDir, packageName + "-" + suffix); 12101 suffix++; 12102 } while (result.exists()); 12103 return result; 12104 } 12105 12106 // Utility method that returns the relative package path with respect 12107 // to the installation directory. Like say for /data/data/com.test-1.apk 12108 // string com.test-1 is returned. 12109 static String deriveCodePathName(String codePath) { 12110 if (codePath == null) { 12111 return null; 12112 } 12113 final File codeFile = new File(codePath); 12114 final String name = codeFile.getName(); 12115 if (codeFile.isDirectory()) { 12116 return name; 12117 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 12118 final int lastDot = name.lastIndexOf('.'); 12119 return name.substring(0, lastDot); 12120 } else { 12121 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 12122 return null; 12123 } 12124 } 12125 12126 class PackageInstalledInfo { 12127 String name; 12128 int uid; 12129 // The set of users that originally had this package installed. 12130 int[] origUsers; 12131 // The set of users that now have this package installed. 12132 int[] newUsers; 12133 PackageParser.Package pkg; 12134 int returnCode; 12135 String returnMsg; 12136 PackageRemovedInfo removedInfo; 12137 12138 public void setError(int code, String msg) { 12139 returnCode = code; 12140 returnMsg = msg; 12141 Slog.w(TAG, msg); 12142 } 12143 12144 public void setError(String msg, PackageParserException e) { 12145 returnCode = e.error; 12146 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 12147 Slog.w(TAG, msg, e); 12148 } 12149 12150 public void setError(String msg, PackageManagerException e) { 12151 returnCode = e.error; 12152 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 12153 Slog.w(TAG, msg, e); 12154 } 12155 12156 // In some error cases we want to convey more info back to the observer 12157 String origPackage; 12158 String origPermission; 12159 } 12160 12161 /* 12162 * Install a non-existing package. 12163 */ 12164 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 12165 UserHandle user, String installerPackageName, String volumeUuid, 12166 PackageInstalledInfo res) { 12167 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 12168 12169 // Remember this for later, in case we need to rollback this install 12170 String pkgName = pkg.packageName; 12171 12172 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 12173 // TODO: b/23350563 12174 final boolean dataDirExists = Environment 12175 .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists(); 12176 12177 synchronized(mPackages) { 12178 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 12179 // A package with the same name is already installed, though 12180 // it has been renamed to an older name. The package we 12181 // are trying to install should be installed as an update to 12182 // the existing one, but that has not been requested, so bail. 12183 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 12184 + " without first uninstalling package running as " 12185 + mSettings.mRenamedPackages.get(pkgName)); 12186 return; 12187 } 12188 if (mPackages.containsKey(pkgName)) { 12189 // Don't allow installation over an existing package with the same name. 12190 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 12191 + " without first uninstalling."); 12192 return; 12193 } 12194 } 12195 12196 try { 12197 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 12198 System.currentTimeMillis(), user); 12199 12200 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 12201 // delete the partially installed application. the data directory will have to be 12202 // restored if it was already existing 12203 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12204 // remove package from internal structures. Note that we want deletePackageX to 12205 // delete the package data and cache directories that it created in 12206 // scanPackageLocked, unless those directories existed before we even tried to 12207 // install. 12208 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 12209 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 12210 res.removedInfo, true); 12211 } 12212 12213 } catch (PackageManagerException e) { 12214 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12215 } 12216 12217 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12218 } 12219 12220 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 12221 // Can't rotate keys during boot or if sharedUser. 12222 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 12223 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 12224 return false; 12225 } 12226 // app is using upgradeKeySets; make sure all are valid 12227 KeySetManagerService ksms = mSettings.mKeySetManagerService; 12228 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 12229 for (int i = 0; i < upgradeKeySets.length; i++) { 12230 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 12231 Slog.wtf(TAG, "Package " 12232 + (oldPs.name != null ? oldPs.name : "<null>") 12233 + " contains upgrade-key-set reference to unknown key-set: " 12234 + upgradeKeySets[i] 12235 + " reverting to signatures check."); 12236 return false; 12237 } 12238 } 12239 return true; 12240 } 12241 12242 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 12243 // Upgrade keysets are being used. Determine if new package has a superset of the 12244 // required keys. 12245 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 12246 KeySetManagerService ksms = mSettings.mKeySetManagerService; 12247 for (int i = 0; i < upgradeKeySets.length; i++) { 12248 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 12249 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 12250 return true; 12251 } 12252 } 12253 return false; 12254 } 12255 12256 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 12257 UserHandle user, String installerPackageName, String volumeUuid, 12258 PackageInstalledInfo res) { 12259 final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 12260 12261 final PackageParser.Package oldPackage; 12262 final String pkgName = pkg.packageName; 12263 final int[] allUsers; 12264 final boolean[] perUserInstalled; 12265 12266 // First find the old package info and check signatures 12267 synchronized(mPackages) { 12268 oldPackage = mPackages.get(pkgName); 12269 final boolean oldIsEphemeral 12270 = ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_EPHEMERAL) != 0); 12271 if (isEphemeral && !oldIsEphemeral) { 12272 // can't downgrade from full to ephemeral 12273 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 12274 res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 12275 return; 12276 } 12277 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 12278 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12279 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12280 if(!checkUpgradeKeySetLP(ps, pkg)) { 12281 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 12282 "New package not signed by keys specified by upgrade-keysets: " 12283 + pkgName); 12284 return; 12285 } 12286 } else { 12287 // default to original signature matching 12288 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 12289 != PackageManager.SIGNATURE_MATCH) { 12290 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 12291 "New package has a different signature: " + pkgName); 12292 return; 12293 } 12294 } 12295 12296 // In case of rollback, remember per-user/profile install state 12297 allUsers = sUserManager.getUserIds(); 12298 perUserInstalled = new boolean[allUsers.length]; 12299 for (int i = 0; i < allUsers.length; i++) { 12300 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12301 } 12302 } 12303 12304 boolean sysPkg = (isSystemApp(oldPackage)); 12305 if (sysPkg) { 12306 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 12307 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 12308 } else { 12309 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 12310 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 12311 } 12312 } 12313 12314 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 12315 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 12316 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 12317 String volumeUuid, PackageInstalledInfo res) { 12318 String pkgName = deletedPackage.packageName; 12319 boolean deletedPkg = true; 12320 boolean updatedSettings = false; 12321 12322 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 12323 + deletedPackage); 12324 long origUpdateTime; 12325 if (pkg.mExtras != null) { 12326 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 12327 } else { 12328 origUpdateTime = 0; 12329 } 12330 12331 // First delete the existing package while retaining the data directory 12332 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 12333 res.removedInfo, true)) { 12334 // If the existing package wasn't successfully deleted 12335 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 12336 deletedPkg = false; 12337 } else { 12338 // Successfully deleted the old package; proceed with replace. 12339 12340 // If deleted package lived in a container, give users a chance to 12341 // relinquish resources before killing. 12342 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 12343 if (DEBUG_INSTALL) { 12344 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 12345 } 12346 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 12347 final ArrayList<String> pkgList = new ArrayList<String>(1); 12348 pkgList.add(deletedPackage.applicationInfo.packageName); 12349 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 12350 } 12351 12352 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 12353 try { 12354 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 12355 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 12356 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12357 perUserInstalled, res, user); 12358 updatedSettings = true; 12359 } catch (PackageManagerException e) { 12360 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12361 } 12362 } 12363 12364 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12365 // remove package from internal structures. Note that we want deletePackageX to 12366 // delete the package data and cache directories that it created in 12367 // scanPackageLocked, unless those directories existed before we even tried to 12368 // install. 12369 if(updatedSettings) { 12370 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 12371 deletePackageLI( 12372 pkgName, null, true, allUsers, perUserInstalled, 12373 PackageManager.DELETE_KEEP_DATA, 12374 res.removedInfo, true); 12375 } 12376 // Since we failed to install the new package we need to restore the old 12377 // package that we deleted. 12378 if (deletedPkg) { 12379 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 12380 File restoreFile = new File(deletedPackage.codePath); 12381 // Parse old package 12382 boolean oldExternal = isExternal(deletedPackage); 12383 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 12384 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 12385 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 12386 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 12387 try { 12388 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 12389 null); 12390 } catch (PackageManagerException e) { 12391 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 12392 + e.getMessage()); 12393 return; 12394 } 12395 // Restore of old package succeeded. Update permissions. 12396 // writer 12397 synchronized (mPackages) { 12398 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 12399 UPDATE_PERMISSIONS_ALL); 12400 // can downgrade to reader 12401 mSettings.writeLPr(); 12402 } 12403 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 12404 } 12405 } 12406 } 12407 12408 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 12409 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 12410 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 12411 String volumeUuid, PackageInstalledInfo res) { 12412 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 12413 + ", old=" + deletedPackage); 12414 boolean disabledSystem = false; 12415 boolean updatedSettings = false; 12416 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 12417 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 12418 != 0) { 12419 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12420 } 12421 String packageName = deletedPackage.packageName; 12422 if (packageName == null) { 12423 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12424 "Attempt to delete null packageName."); 12425 return; 12426 } 12427 PackageParser.Package oldPkg; 12428 PackageSetting oldPkgSetting; 12429 // reader 12430 synchronized (mPackages) { 12431 oldPkg = mPackages.get(packageName); 12432 oldPkgSetting = mSettings.mPackages.get(packageName); 12433 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 12434 (oldPkgSetting == null)) { 12435 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12436 "Couldn't find package:" + packageName + " information"); 12437 return; 12438 } 12439 } 12440 12441 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 12442 12443 res.removedInfo.uid = oldPkg.applicationInfo.uid; 12444 res.removedInfo.removedPackage = packageName; 12445 // Remove existing system package 12446 removePackageLI(oldPkgSetting, true); 12447 // writer 12448 synchronized (mPackages) { 12449 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 12450 if (!disabledSystem && deletedPackage != null) { 12451 // We didn't need to disable the .apk as a current system package, 12452 // which means we are replacing another update that is already 12453 // installed. We need to make sure to delete the older one's .apk. 12454 res.removedInfo.args = createInstallArgsForExisting(0, 12455 deletedPackage.applicationInfo.getCodePath(), 12456 deletedPackage.applicationInfo.getResourcePath(), 12457 getAppDexInstructionSets(deletedPackage.applicationInfo)); 12458 } else { 12459 res.removedInfo.args = null; 12460 } 12461 } 12462 12463 // Successfully disabled the old package. Now proceed with re-installation 12464 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 12465 12466 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12467 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 12468 12469 PackageParser.Package newPackage = null; 12470 try { 12471 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 12472 if (newPackage.mExtras != null) { 12473 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 12474 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 12475 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 12476 12477 // is the update attempting to change shared user? that isn't going to work... 12478 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 12479 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 12480 "Forbidding shared user change from " + oldPkgSetting.sharedUser 12481 + " to " + newPkgSetting.sharedUser); 12482 updatedSettings = true; 12483 } 12484 } 12485 12486 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12487 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12488 perUserInstalled, res, user); 12489 updatedSettings = true; 12490 } 12491 12492 } catch (PackageManagerException e) { 12493 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12494 } 12495 12496 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12497 // Re installation failed. Restore old information 12498 // Remove new pkg information 12499 if (newPackage != null) { 12500 removeInstalledPackageLI(newPackage, true); 12501 } 12502 // Add back the old system package 12503 try { 12504 scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 12505 } catch (PackageManagerException e) { 12506 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 12507 } 12508 // Restore the old system information in Settings 12509 synchronized (mPackages) { 12510 if (disabledSystem) { 12511 mSettings.enableSystemPackageLPw(packageName); 12512 } 12513 if (updatedSettings) { 12514 mSettings.setInstallerPackageName(packageName, 12515 oldPkgSetting.installerPackageName); 12516 } 12517 mSettings.writeLPr(); 12518 } 12519 } 12520 } 12521 12522 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 12523 // Collect all used permissions in the UID 12524 ArraySet<String> usedPermissions = new ArraySet<>(); 12525 final int packageCount = su.packages.size(); 12526 for (int i = 0; i < packageCount; i++) { 12527 PackageSetting ps = su.packages.valueAt(i); 12528 if (ps.pkg == null) { 12529 continue; 12530 } 12531 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 12532 for (int j = 0; j < requestedPermCount; j++) { 12533 String permission = ps.pkg.requestedPermissions.get(j); 12534 BasePermission bp = mSettings.mPermissions.get(permission); 12535 if (bp != null) { 12536 usedPermissions.add(permission); 12537 } 12538 } 12539 } 12540 12541 PermissionsState permissionsState = su.getPermissionsState(); 12542 // Prune install permissions 12543 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 12544 final int installPermCount = installPermStates.size(); 12545 for (int i = installPermCount - 1; i >= 0; i--) { 12546 PermissionState permissionState = installPermStates.get(i); 12547 if (!usedPermissions.contains(permissionState.getName())) { 12548 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 12549 if (bp != null) { 12550 permissionsState.revokeInstallPermission(bp); 12551 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 12552 PackageManager.MASK_PERMISSION_FLAGS, 0); 12553 } 12554 } 12555 } 12556 12557 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 12558 12559 // Prune runtime permissions 12560 for (int userId : allUserIds) { 12561 List<PermissionState> runtimePermStates = permissionsState 12562 .getRuntimePermissionStates(userId); 12563 final int runtimePermCount = runtimePermStates.size(); 12564 for (int i = runtimePermCount - 1; i >= 0; i--) { 12565 PermissionState permissionState = runtimePermStates.get(i); 12566 if (!usedPermissions.contains(permissionState.getName())) { 12567 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 12568 if (bp != null) { 12569 permissionsState.revokeRuntimePermission(bp, userId); 12570 permissionsState.updatePermissionFlags(bp, userId, 12571 PackageManager.MASK_PERMISSION_FLAGS, 0); 12572 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 12573 runtimePermissionChangedUserIds, userId); 12574 } 12575 } 12576 } 12577 } 12578 12579 return runtimePermissionChangedUserIds; 12580 } 12581 12582 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 12583 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 12584 UserHandle user) { 12585 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 12586 12587 String pkgName = newPackage.packageName; 12588 synchronized (mPackages) { 12589 //write settings. the installStatus will be incomplete at this stage. 12590 //note that the new package setting would have already been 12591 //added to mPackages. It hasn't been persisted yet. 12592 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 12593 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 12594 mSettings.writeLPr(); 12595 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12596 } 12597 12598 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 12599 synchronized (mPackages) { 12600 updatePermissionsLPw(newPackage.packageName, newPackage, 12601 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 12602 ? UPDATE_PERMISSIONS_ALL : 0)); 12603 // For system-bundled packages, we assume that installing an upgraded version 12604 // of the package implies that the user actually wants to run that new code, 12605 // so we enable the package. 12606 PackageSetting ps = mSettings.mPackages.get(pkgName); 12607 if (ps != null) { 12608 if (isSystemApp(newPackage)) { 12609 // NB: implicit assumption that system package upgrades apply to all users 12610 if (DEBUG_INSTALL) { 12611 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 12612 } 12613 if (res.origUsers != null) { 12614 for (int userHandle : res.origUsers) { 12615 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 12616 userHandle, installerPackageName); 12617 } 12618 } 12619 // Also convey the prior install/uninstall state 12620 if (allUsers != null && perUserInstalled != null) { 12621 for (int i = 0; i < allUsers.length; i++) { 12622 if (DEBUG_INSTALL) { 12623 Slog.d(TAG, " user " + allUsers[i] 12624 + " => " + perUserInstalled[i]); 12625 } 12626 ps.setInstalled(perUserInstalled[i], allUsers[i]); 12627 } 12628 // these install state changes will be persisted in the 12629 // upcoming call to mSettings.writeLPr(). 12630 } 12631 } 12632 // It's implied that when a user requests installation, they want the app to be 12633 // installed and enabled. 12634 int userId = user.getIdentifier(); 12635 if (userId != UserHandle.USER_ALL) { 12636 ps.setInstalled(true, userId); 12637 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 12638 } 12639 } 12640 res.name = pkgName; 12641 res.uid = newPackage.applicationInfo.uid; 12642 res.pkg = newPackage; 12643 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 12644 mSettings.setInstallerPackageName(pkgName, installerPackageName); 12645 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12646 //to update install status 12647 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 12648 mSettings.writeLPr(); 12649 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12650 } 12651 12652 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12653 } 12654 12655 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 12656 try { 12657 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 12658 installPackageLI(args, res); 12659 } finally { 12660 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12661 } 12662 } 12663 12664 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 12665 final int installFlags = args.installFlags; 12666 final String installerPackageName = args.installerPackageName; 12667 final String volumeUuid = args.volumeUuid; 12668 final File tmpPackageFile = new File(args.getCodePath()); 12669 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 12670 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 12671 || (args.volumeUuid != null)); 12672 final boolean quickInstall = ((installFlags & PackageManager.INSTALL_QUICK) != 0); 12673 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 12674 boolean replace = false; 12675 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 12676 if (args.move != null) { 12677 // moving a complete application; perfom an initial scan on the new install location 12678 scanFlags |= SCAN_INITIAL; 12679 } 12680 // Result object to be returned 12681 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12682 12683 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 12684 12685 // Sanity check 12686 if (ephemeral && (forwardLocked || onExternal)) { 12687 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 12688 + " external=" + onExternal); 12689 res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 12690 return; 12691 } 12692 12693 // Retrieve PackageSettings and parse package 12694 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 12695 | PackageParser.PARSE_ENFORCE_CODE 12696 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 12697 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 12698 | (quickInstall ? PackageParser.PARSE_SKIP_VERIFICATION : 0) 12699 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0); 12700 PackageParser pp = new PackageParser(); 12701 pp.setSeparateProcesses(mSeparateProcesses); 12702 pp.setDisplayMetrics(mMetrics); 12703 12704 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 12705 final PackageParser.Package pkg; 12706 try { 12707 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 12708 } catch (PackageParserException e) { 12709 res.setError("Failed parse during installPackageLI", e); 12710 return; 12711 } finally { 12712 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12713 } 12714 12715 // Mark that we have an install time CPU ABI override. 12716 pkg.cpuAbiOverride = args.abiOverride; 12717 12718 String pkgName = res.name = pkg.packageName; 12719 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 12720 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 12721 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 12722 return; 12723 } 12724 } 12725 12726 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 12727 try { 12728 pp.collectCertificates(pkg, parseFlags); 12729 } catch (PackageParserException e) { 12730 res.setError("Failed collect during installPackageLI", e); 12731 return; 12732 } finally { 12733 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12734 } 12735 12736 /* If the installer passed in a manifest digest, compare it now. */ 12737 if (args.manifestDigest != null) { 12738 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectManifestDigest"); 12739 try { 12740 pp.collectManifestDigest(pkg); 12741 } catch (PackageParserException e) { 12742 res.setError("Failed collect during installPackageLI", e); 12743 return; 12744 } finally { 12745 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12746 } 12747 12748 if (DEBUG_INSTALL) { 12749 final String parsedManifest = pkg.manifestDigest == null ? "null" 12750 : pkg.manifestDigest.toString(); 12751 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 12752 + parsedManifest); 12753 } 12754 12755 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 12756 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 12757 return; 12758 } 12759 } else if (DEBUG_INSTALL) { 12760 final String parsedManifest = pkg.manifestDigest == null 12761 ? "null" : pkg.manifestDigest.toString(); 12762 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 12763 } 12764 12765 // Get rid of all references to package scan path via parser. 12766 pp = null; 12767 String oldCodePath = null; 12768 boolean systemApp = false; 12769 synchronized (mPackages) { 12770 // Check if installing already existing package 12771 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12772 String oldName = mSettings.mRenamedPackages.get(pkgName); 12773 if (pkg.mOriginalPackages != null 12774 && pkg.mOriginalPackages.contains(oldName) 12775 && mPackages.containsKey(oldName)) { 12776 // This package is derived from an original package, 12777 // and this device has been updating from that original 12778 // name. We must continue using the original name, so 12779 // rename the new package here. 12780 pkg.setPackageName(oldName); 12781 pkgName = pkg.packageName; 12782 replace = true; 12783 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 12784 + oldName + " pkgName=" + pkgName); 12785 } else if (mPackages.containsKey(pkgName)) { 12786 // This package, under its official name, already exists 12787 // on the device; we should replace it. 12788 replace = true; 12789 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 12790 } 12791 12792 // Prevent apps opting out from runtime permissions 12793 if (replace) { 12794 PackageParser.Package oldPackage = mPackages.get(pkgName); 12795 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 12796 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 12797 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 12798 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 12799 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 12800 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 12801 + " doesn't support runtime permissions but the old" 12802 + " target SDK " + oldTargetSdk + " does."); 12803 return; 12804 } 12805 } 12806 } 12807 12808 PackageSetting ps = mSettings.mPackages.get(pkgName); 12809 if (ps != null) { 12810 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 12811 12812 // Quick sanity check that we're signed correctly if updating; 12813 // we'll check this again later when scanning, but we want to 12814 // bail early here before tripping over redefined permissions. 12815 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12816 if (!checkUpgradeKeySetLP(ps, pkg)) { 12817 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 12818 + pkg.packageName + " upgrade keys do not match the " 12819 + "previously installed version"); 12820 return; 12821 } 12822 } else { 12823 try { 12824 verifySignaturesLP(ps, pkg); 12825 } catch (PackageManagerException e) { 12826 res.setError(e.error, e.getMessage()); 12827 return; 12828 } 12829 } 12830 12831 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 12832 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 12833 systemApp = (ps.pkg.applicationInfo.flags & 12834 ApplicationInfo.FLAG_SYSTEM) != 0; 12835 } 12836 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12837 } 12838 12839 // Check whether the newly-scanned package wants to define an already-defined perm 12840 int N = pkg.permissions.size(); 12841 for (int i = N-1; i >= 0; i--) { 12842 PackageParser.Permission perm = pkg.permissions.get(i); 12843 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 12844 if (bp != null) { 12845 // If the defining package is signed with our cert, it's okay. This 12846 // also includes the "updating the same package" case, of course. 12847 // "updating same package" could also involve key-rotation. 12848 final boolean sigsOk; 12849 if (bp.sourcePackage.equals(pkg.packageName) 12850 && (bp.packageSetting instanceof PackageSetting) 12851 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 12852 scanFlags))) { 12853 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 12854 } else { 12855 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 12856 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 12857 } 12858 if (!sigsOk) { 12859 // If the owning package is the system itself, we log but allow 12860 // install to proceed; we fail the install on all other permission 12861 // redefinitions. 12862 if (!bp.sourcePackage.equals("android")) { 12863 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 12864 + pkg.packageName + " attempting to redeclare permission " 12865 + perm.info.name + " already owned by " + bp.sourcePackage); 12866 res.origPermission = perm.info.name; 12867 res.origPackage = bp.sourcePackage; 12868 return; 12869 } else { 12870 Slog.w(TAG, "Package " + pkg.packageName 12871 + " attempting to redeclare system permission " 12872 + perm.info.name + "; ignoring new declaration"); 12873 pkg.permissions.remove(i); 12874 } 12875 } 12876 } 12877 } 12878 12879 } 12880 12881 if (systemApp) { 12882 if (onExternal) { 12883 // Abort update; system app can't be replaced with app on sdcard 12884 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 12885 "Cannot install updates to system apps on sdcard"); 12886 return; 12887 } else if (ephemeral) { 12888 // Abort update; system app can't be replaced with an ephemeral app 12889 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 12890 "Cannot update a system app with an ephemeral app"); 12891 return; 12892 } 12893 } 12894 12895 if (args.move != null) { 12896 // We did an in-place move, so dex is ready to roll 12897 scanFlags |= SCAN_NO_DEX; 12898 scanFlags |= SCAN_MOVE; 12899 12900 synchronized (mPackages) { 12901 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12902 if (ps == null) { 12903 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 12904 "Missing settings for moved package " + pkgName); 12905 } 12906 12907 // We moved the entire application as-is, so bring over the 12908 // previously derived ABI information. 12909 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 12910 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 12911 } 12912 12913 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 12914 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 12915 scanFlags |= SCAN_NO_DEX; 12916 12917 try { 12918 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 12919 true /* extract libs */); 12920 } catch (PackageManagerException pme) { 12921 Slog.e(TAG, "Error deriving application ABI", pme); 12922 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 12923 return; 12924 } 12925 } 12926 12927 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 12928 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 12929 return; 12930 } 12931 12932 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 12933 12934 if (replace) { 12935 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 12936 installerPackageName, volumeUuid, res); 12937 } else { 12938 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 12939 args.user, installerPackageName, volumeUuid, res); 12940 } 12941 synchronized (mPackages) { 12942 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12943 if (ps != null) { 12944 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12945 } 12946 } 12947 } 12948 12949 private void startIntentFilterVerifications(int userId, boolean replacing, 12950 PackageParser.Package pkg) { 12951 if (mIntentFilterVerifierComponent == null) { 12952 Slog.w(TAG, "No IntentFilter verification will not be done as " 12953 + "there is no IntentFilterVerifier available!"); 12954 return; 12955 } 12956 12957 final int verifierUid = getPackageUid( 12958 mIntentFilterVerifierComponent.getPackageName(), 12959 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 12960 12961 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 12962 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 12963 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 12964 mHandler.sendMessage(msg); 12965 } 12966 12967 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 12968 PackageParser.Package pkg) { 12969 int size = pkg.activities.size(); 12970 if (size == 0) { 12971 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12972 "No activity, so no need to verify any IntentFilter!"); 12973 return; 12974 } 12975 12976 final boolean hasDomainURLs = hasDomainURLs(pkg); 12977 if (!hasDomainURLs) { 12978 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12979 "No domain URLs, so no need to verify any IntentFilter!"); 12980 return; 12981 } 12982 12983 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 12984 + " if any IntentFilter from the " + size 12985 + " Activities needs verification ..."); 12986 12987 int count = 0; 12988 final String packageName = pkg.packageName; 12989 12990 synchronized (mPackages) { 12991 // If this is a new install and we see that we've already run verification for this 12992 // package, we have nothing to do: it means the state was restored from backup. 12993 if (!replacing) { 12994 IntentFilterVerificationInfo ivi = 12995 mSettings.getIntentFilterVerificationLPr(packageName); 12996 if (ivi != null) { 12997 if (DEBUG_DOMAIN_VERIFICATION) { 12998 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 12999 + ivi.getStatusString()); 13000 } 13001 return; 13002 } 13003 } 13004 13005 // If any filters need to be verified, then all need to be. 13006 boolean needToVerify = false; 13007 for (PackageParser.Activity a : pkg.activities) { 13008 for (ActivityIntentInfo filter : a.intents) { 13009 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 13010 if (DEBUG_DOMAIN_VERIFICATION) { 13011 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 13012 } 13013 needToVerify = true; 13014 break; 13015 } 13016 } 13017 } 13018 13019 if (needToVerify) { 13020 final int verificationId = mIntentFilterVerificationToken++; 13021 for (PackageParser.Activity a : pkg.activities) { 13022 for (ActivityIntentInfo filter : a.intents) { 13023 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 13024 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 13025 "Verification needed for IntentFilter:" + filter.toString()); 13026 mIntentFilterVerifier.addOneIntentFilterVerification( 13027 verifierUid, userId, verificationId, filter, packageName); 13028 count++; 13029 } 13030 } 13031 } 13032 } 13033 } 13034 13035 if (count > 0) { 13036 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 13037 + " IntentFilter verification" + (count > 1 ? "s" : "") 13038 + " for userId:" + userId); 13039 mIntentFilterVerifier.startVerifications(userId); 13040 } else { 13041 if (DEBUG_DOMAIN_VERIFICATION) { 13042 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 13043 } 13044 } 13045 } 13046 13047 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 13048 final ComponentName cn = filter.activity.getComponentName(); 13049 final String packageName = cn.getPackageName(); 13050 13051 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 13052 packageName); 13053 if (ivi == null) { 13054 return true; 13055 } 13056 int status = ivi.getStatus(); 13057 switch (status) { 13058 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 13059 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 13060 return true; 13061 13062 default: 13063 // Nothing to do 13064 return false; 13065 } 13066 } 13067 13068 private static boolean isMultiArch(PackageSetting ps) { 13069 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 13070 } 13071 13072 private static boolean isMultiArch(ApplicationInfo info) { 13073 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 13074 } 13075 13076 private static boolean isExternal(PackageParser.Package pkg) { 13077 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 13078 } 13079 13080 private static boolean isExternal(PackageSetting ps) { 13081 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 13082 } 13083 13084 private static boolean isExternal(ApplicationInfo info) { 13085 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 13086 } 13087 13088 private static boolean isEphemeral(PackageParser.Package pkg) { 13089 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EPHEMERAL) != 0; 13090 } 13091 13092 private static boolean isEphemeral(PackageSetting ps) { 13093 return (ps.pkgFlags & ApplicationInfo.FLAG_EPHEMERAL) != 0; 13094 } 13095 13096 private static boolean isSystemApp(PackageParser.Package pkg) { 13097 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 13098 } 13099 13100 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 13101 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 13102 } 13103 13104 private static boolean hasDomainURLs(PackageParser.Package pkg) { 13105 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 13106 } 13107 13108 private static boolean isSystemApp(PackageSetting ps) { 13109 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 13110 } 13111 13112 private static boolean isUpdatedSystemApp(PackageSetting ps) { 13113 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 13114 } 13115 13116 private int packageFlagsToInstallFlags(PackageSetting ps) { 13117 int installFlags = 0; 13118 if (isEphemeral(ps)) { 13119 installFlags |= PackageManager.INSTALL_EPHEMERAL; 13120 } 13121 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 13122 // This existing package was an external ASEC install when we have 13123 // the external flag without a UUID 13124 installFlags |= PackageManager.INSTALL_EXTERNAL; 13125 } 13126 if (ps.isForwardLocked()) { 13127 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 13128 } 13129 return installFlags; 13130 } 13131 13132 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 13133 if (isExternal(pkg)) { 13134 if (TextUtils.isEmpty(pkg.volumeUuid)) { 13135 return StorageManager.UUID_PRIMARY_PHYSICAL; 13136 } else { 13137 return pkg.volumeUuid; 13138 } 13139 } else { 13140 return StorageManager.UUID_PRIVATE_INTERNAL; 13141 } 13142 } 13143 13144 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 13145 if (isExternal(pkg)) { 13146 if (TextUtils.isEmpty(pkg.volumeUuid)) { 13147 return mSettings.getExternalVersion(); 13148 } else { 13149 return mSettings.findOrCreateVersion(pkg.volumeUuid); 13150 } 13151 } else { 13152 return mSettings.getInternalVersion(); 13153 } 13154 } 13155 13156 private void deleteTempPackageFiles() { 13157 final FilenameFilter filter = new FilenameFilter() { 13158 public boolean accept(File dir, String name) { 13159 return name.startsWith("vmdl") && name.endsWith(".tmp"); 13160 } 13161 }; 13162 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 13163 file.delete(); 13164 } 13165 } 13166 13167 @Override 13168 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 13169 int flags) { 13170 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 13171 flags); 13172 } 13173 13174 @Override 13175 public void deletePackage(final String packageName, 13176 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 13177 mContext.enforceCallingOrSelfPermission( 13178 android.Manifest.permission.DELETE_PACKAGES, null); 13179 Preconditions.checkNotNull(packageName); 13180 Preconditions.checkNotNull(observer); 13181 final int uid = Binder.getCallingUid(); 13182 final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0; 13183 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 13184 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 13185 mContext.enforceCallingOrSelfPermission( 13186 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 13187 "deletePackage for user " + userId); 13188 } 13189 13190 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 13191 try { 13192 observer.onPackageDeleted(packageName, 13193 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 13194 } catch (RemoteException re) { 13195 } 13196 return; 13197 } 13198 13199 for (int currentUserId : users) { 13200 if (getBlockUninstallForUser(packageName, currentUserId)) { 13201 try { 13202 observer.onPackageDeleted(packageName, 13203 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 13204 } catch (RemoteException re) { 13205 } 13206 return; 13207 } 13208 } 13209 13210 if (DEBUG_REMOVE) { 13211 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 13212 } 13213 // Queue up an async operation since the package deletion may take a little while. 13214 mHandler.post(new Runnable() { 13215 public void run() { 13216 mHandler.removeCallbacks(this); 13217 final int returnCode = deletePackageX(packageName, userId, flags); 13218 try { 13219 observer.onPackageDeleted(packageName, returnCode, null); 13220 } catch (RemoteException e) { 13221 Log.i(TAG, "Observer no longer exists."); 13222 } //end catch 13223 } //end run 13224 }); 13225 } 13226 13227 private boolean isPackageDeviceAdmin(String packageName, int userId) { 13228 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 13229 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 13230 try { 13231 if (dpm != null) { 13232 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 13233 /* callingUserOnly =*/ false); 13234 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 13235 : deviceOwnerComponentName.getPackageName(); 13236 // Does the package contains the device owner? 13237 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 13238 // this check is probably not needed, since DO should be registered as a device 13239 // admin on some user too. (Original bug for this: b/17657954) 13240 if (packageName.equals(deviceOwnerPackageName)) { 13241 return true; 13242 } 13243 // Does it contain a device admin for any user? 13244 int[] users; 13245 if (userId == UserHandle.USER_ALL) { 13246 users = sUserManager.getUserIds(); 13247 } else { 13248 users = new int[]{userId}; 13249 } 13250 for (int i = 0; i < users.length; ++i) { 13251 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 13252 return true; 13253 } 13254 } 13255 } 13256 } catch (RemoteException e) { 13257 } 13258 return false; 13259 } 13260 13261 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 13262 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 13263 } 13264 13265 /** 13266 * This method is an internal method that could be get invoked either 13267 * to delete an installed package or to clean up a failed installation. 13268 * After deleting an installed package, a broadcast is sent to notify any 13269 * listeners that the package has been installed. For cleaning up a failed 13270 * installation, the broadcast is not necessary since the package's 13271 * installation wouldn't have sent the initial broadcast either 13272 * The key steps in deleting a package are 13273 * deleting the package information in internal structures like mPackages, 13274 * deleting the packages base directories through installd 13275 * updating mSettings to reflect current status 13276 * persisting settings for later use 13277 * sending a broadcast if necessary 13278 */ 13279 private int deletePackageX(String packageName, int userId, int flags) { 13280 final PackageRemovedInfo info = new PackageRemovedInfo(); 13281 final boolean res; 13282 13283 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 13284 ? UserHandle.ALL : new UserHandle(userId); 13285 13286 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 13287 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 13288 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 13289 } 13290 13291 boolean removedForAllUsers = false; 13292 boolean systemUpdate = false; 13293 13294 // for the uninstall-updates case and restricted profiles, remember the per- 13295 // userhandle installed state 13296 int[] allUsers; 13297 boolean[] perUserInstalled; 13298 synchronized (mPackages) { 13299 PackageSetting ps = mSettings.mPackages.get(packageName); 13300 allUsers = sUserManager.getUserIds(); 13301 perUserInstalled = new boolean[allUsers.length]; 13302 for (int i = 0; i < allUsers.length; i++) { 13303 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 13304 } 13305 } 13306 13307 synchronized (mInstallLock) { 13308 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 13309 res = deletePackageLI(packageName, removeForUser, 13310 true, allUsers, perUserInstalled, 13311 flags | REMOVE_CHATTY, info, true); 13312 systemUpdate = info.isRemovedPackageSystemUpdate; 13313 if (res && !systemUpdate && mPackages.get(packageName) == null) { 13314 removedForAllUsers = true; 13315 } 13316 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 13317 + " removedForAllUsers=" + removedForAllUsers); 13318 } 13319 13320 if (res) { 13321 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 13322 13323 // If the removed package was a system update, the old system package 13324 // was re-enabled; we need to broadcast this information 13325 if (systemUpdate) { 13326 Bundle extras = new Bundle(1); 13327 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 13328 ? info.removedAppId : info.uid); 13329 extras.putBoolean(Intent.EXTRA_REPLACING, true); 13330 13331 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 13332 extras, 0, null, null, null); 13333 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 13334 extras, 0, null, null, null); 13335 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 13336 null, 0, packageName, null, null); 13337 } 13338 } 13339 // Force a gc here. 13340 Runtime.getRuntime().gc(); 13341 // Delete the resources here after sending the broadcast to let 13342 // other processes clean up before deleting resources. 13343 if (info.args != null) { 13344 synchronized (mInstallLock) { 13345 info.args.doPostDeleteLI(true); 13346 } 13347 } 13348 13349 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 13350 } 13351 13352 class PackageRemovedInfo { 13353 String removedPackage; 13354 int uid = -1; 13355 int removedAppId = -1; 13356 int[] removedUsers = null; 13357 boolean isRemovedPackageSystemUpdate = false; 13358 // Clean up resources deleted packages. 13359 InstallArgs args = null; 13360 13361 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 13362 Bundle extras = new Bundle(1); 13363 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 13364 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 13365 if (replacing) { 13366 extras.putBoolean(Intent.EXTRA_REPLACING, true); 13367 } 13368 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 13369 if (removedPackage != null) { 13370 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 13371 extras, 0, null, null, removedUsers); 13372 if (fullRemove && !replacing) { 13373 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 13374 extras, 0, null, null, removedUsers); 13375 } 13376 } 13377 if (removedAppId >= 0) { 13378 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 13379 removedUsers); 13380 } 13381 } 13382 } 13383 13384 /* 13385 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 13386 * flag is not set, the data directory is removed as well. 13387 * make sure this flag is set for partially installed apps. If not its meaningless to 13388 * delete a partially installed application. 13389 */ 13390 private void removePackageDataLI(PackageSetting ps, 13391 int[] allUserHandles, boolean[] perUserInstalled, 13392 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 13393 String packageName = ps.name; 13394 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 13395 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 13396 // Retrieve object to delete permissions for shared user later on 13397 final PackageSetting deletedPs; 13398 // reader 13399 synchronized (mPackages) { 13400 deletedPs = mSettings.mPackages.get(packageName); 13401 if (outInfo != null) { 13402 outInfo.removedPackage = packageName; 13403 outInfo.removedUsers = deletedPs != null 13404 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 13405 : null; 13406 } 13407 } 13408 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 13409 removeDataDirsLI(ps.volumeUuid, packageName); 13410 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 13411 } 13412 // writer 13413 synchronized (mPackages) { 13414 if (deletedPs != null) { 13415 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 13416 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 13417 clearDefaultBrowserIfNeeded(packageName); 13418 if (outInfo != null) { 13419 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 13420 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 13421 } 13422 updatePermissionsLPw(deletedPs.name, null, 0); 13423 if (deletedPs.sharedUser != null) { 13424 // Remove permissions associated with package. Since runtime 13425 // permissions are per user we have to kill the removed package 13426 // or packages running under the shared user of the removed 13427 // package if revoking the permissions requested only by the removed 13428 // package is successful and this causes a change in gids. 13429 for (int userId : UserManagerService.getInstance().getUserIds()) { 13430 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 13431 userId); 13432 if (userIdToKill == UserHandle.USER_ALL 13433 || userIdToKill >= UserHandle.USER_SYSTEM) { 13434 // If gids changed for this user, kill all affected packages. 13435 mHandler.post(new Runnable() { 13436 @Override 13437 public void run() { 13438 // This has to happen with no lock held. 13439 killApplication(deletedPs.name, deletedPs.appId, 13440 KILL_APP_REASON_GIDS_CHANGED); 13441 } 13442 }); 13443 break; 13444 } 13445 } 13446 } 13447 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 13448 } 13449 // make sure to preserve per-user disabled state if this removal was just 13450 // a downgrade of a system app to the factory package 13451 if (allUserHandles != null && perUserInstalled != null) { 13452 if (DEBUG_REMOVE) { 13453 Slog.d(TAG, "Propagating install state across downgrade"); 13454 } 13455 for (int i = 0; i < allUserHandles.length; i++) { 13456 if (DEBUG_REMOVE) { 13457 Slog.d(TAG, " user " + allUserHandles[i] 13458 + " => " + perUserInstalled[i]); 13459 } 13460 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13461 } 13462 } 13463 } 13464 // can downgrade to reader 13465 if (writeSettings) { 13466 // Save settings now 13467 mSettings.writeLPr(); 13468 } 13469 } 13470 if (outInfo != null) { 13471 // A user ID was deleted here. Go through all users and remove it 13472 // from KeyStore. 13473 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 13474 } 13475 } 13476 13477 static boolean locationIsPrivileged(File path) { 13478 try { 13479 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 13480 .getCanonicalPath(); 13481 return path.getCanonicalPath().startsWith(privilegedAppDir); 13482 } catch (IOException e) { 13483 Slog.e(TAG, "Unable to access code path " + path); 13484 } 13485 return false; 13486 } 13487 13488 /* 13489 * Tries to delete system package. 13490 */ 13491 private boolean deleteSystemPackageLI(PackageSetting newPs, 13492 int[] allUserHandles, boolean[] perUserInstalled, 13493 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 13494 final boolean applyUserRestrictions 13495 = (allUserHandles != null) && (perUserInstalled != null); 13496 PackageSetting disabledPs = null; 13497 // Confirm if the system package has been updated 13498 // An updated system app can be deleted. This will also have to restore 13499 // the system pkg from system partition 13500 // reader 13501 synchronized (mPackages) { 13502 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 13503 } 13504 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 13505 + " disabledPs=" + disabledPs); 13506 if (disabledPs == null) { 13507 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 13508 return false; 13509 } else if (DEBUG_REMOVE) { 13510 Slog.d(TAG, "Deleting system pkg from data partition"); 13511 } 13512 if (DEBUG_REMOVE) { 13513 if (applyUserRestrictions) { 13514 Slog.d(TAG, "Remembering install states:"); 13515 for (int i = 0; i < allUserHandles.length; i++) { 13516 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 13517 } 13518 } 13519 } 13520 // Delete the updated package 13521 outInfo.isRemovedPackageSystemUpdate = true; 13522 if (disabledPs.versionCode < newPs.versionCode) { 13523 // Delete data for downgrades 13524 flags &= ~PackageManager.DELETE_KEEP_DATA; 13525 } else { 13526 // Preserve data by setting flag 13527 flags |= PackageManager.DELETE_KEEP_DATA; 13528 } 13529 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 13530 allUserHandles, perUserInstalled, outInfo, writeSettings); 13531 if (!ret) { 13532 return false; 13533 } 13534 // writer 13535 synchronized (mPackages) { 13536 // Reinstate the old system package 13537 mSettings.enableSystemPackageLPw(newPs.name); 13538 // Remove any native libraries from the upgraded package. 13539 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 13540 } 13541 // Install the system package 13542 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 13543 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 13544 if (locationIsPrivileged(disabledPs.codePath)) { 13545 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 13546 } 13547 13548 final PackageParser.Package newPkg; 13549 try { 13550 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 13551 } catch (PackageManagerException e) { 13552 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 13553 return false; 13554 } 13555 13556 // writer 13557 synchronized (mPackages) { 13558 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 13559 13560 // Propagate the permissions state as we do not want to drop on the floor 13561 // runtime permissions. The update permissions method below will take 13562 // care of removing obsolete permissions and grant install permissions. 13563 ps.getPermissionsState().copyFrom(newPs.getPermissionsState()); 13564 updatePermissionsLPw(newPkg.packageName, newPkg, 13565 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 13566 13567 if (applyUserRestrictions) { 13568 if (DEBUG_REMOVE) { 13569 Slog.d(TAG, "Propagating install state across reinstall"); 13570 } 13571 for (int i = 0; i < allUserHandles.length; i++) { 13572 if (DEBUG_REMOVE) { 13573 Slog.d(TAG, " user " + allUserHandles[i] 13574 + " => " + perUserInstalled[i]); 13575 } 13576 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13577 13578 mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false); 13579 } 13580 // Regardless of writeSettings we need to ensure that this restriction 13581 // state propagation is persisted 13582 mSettings.writeAllUsersPackageRestrictionsLPr(); 13583 } 13584 // can downgrade to reader here 13585 if (writeSettings) { 13586 mSettings.writeLPr(); 13587 } 13588 } 13589 return true; 13590 } 13591 13592 private boolean deleteInstalledPackageLI(PackageSetting ps, 13593 boolean deleteCodeAndResources, int flags, 13594 int[] allUserHandles, boolean[] perUserInstalled, 13595 PackageRemovedInfo outInfo, boolean writeSettings) { 13596 if (outInfo != null) { 13597 outInfo.uid = ps.appId; 13598 } 13599 13600 // Delete package data from internal structures and also remove data if flag is set 13601 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 13602 13603 // Delete application code and resources 13604 if (deleteCodeAndResources && (outInfo != null)) { 13605 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 13606 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 13607 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 13608 } 13609 return true; 13610 } 13611 13612 @Override 13613 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 13614 int userId) { 13615 mContext.enforceCallingOrSelfPermission( 13616 android.Manifest.permission.DELETE_PACKAGES, null); 13617 synchronized (mPackages) { 13618 PackageSetting ps = mSettings.mPackages.get(packageName); 13619 if (ps == null) { 13620 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 13621 return false; 13622 } 13623 if (!ps.getInstalled(userId)) { 13624 // Can't block uninstall for an app that is not installed or enabled. 13625 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 13626 return false; 13627 } 13628 ps.setBlockUninstall(blockUninstall, userId); 13629 mSettings.writePackageRestrictionsLPr(userId); 13630 } 13631 return true; 13632 } 13633 13634 @Override 13635 public boolean getBlockUninstallForUser(String packageName, int userId) { 13636 synchronized (mPackages) { 13637 PackageSetting ps = mSettings.mPackages.get(packageName); 13638 if (ps == null) { 13639 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 13640 return false; 13641 } 13642 return ps.getBlockUninstall(userId); 13643 } 13644 } 13645 13646 /* 13647 * This method handles package deletion in general 13648 */ 13649 private boolean deletePackageLI(String packageName, UserHandle user, 13650 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 13651 int flags, PackageRemovedInfo outInfo, 13652 boolean writeSettings) { 13653 if (packageName == null) { 13654 Slog.w(TAG, "Attempt to delete null packageName."); 13655 return false; 13656 } 13657 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 13658 PackageSetting ps; 13659 boolean dataOnly = false; 13660 int removeUser = -1; 13661 int appId = -1; 13662 synchronized (mPackages) { 13663 ps = mSettings.mPackages.get(packageName); 13664 if (ps == null) { 13665 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13666 return false; 13667 } 13668 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 13669 && user.getIdentifier() != UserHandle.USER_ALL) { 13670 // The caller is asking that the package only be deleted for a single 13671 // user. To do this, we just mark its uninstalled state and delete 13672 // its data. If this is a system app, we only allow this to happen if 13673 // they have set the special DELETE_SYSTEM_APP which requests different 13674 // semantics than normal for uninstalling system apps. 13675 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 13676 final int userId = user.getIdentifier(); 13677 ps.setUserState(userId, 13678 COMPONENT_ENABLED_STATE_DEFAULT, 13679 false, //installed 13680 true, //stopped 13681 true, //notLaunched 13682 false, //hidden 13683 null, null, null, 13684 false, // blockUninstall 13685 ps.readUserState(userId).domainVerificationStatus, 0); 13686 if (!isSystemApp(ps)) { 13687 // Do not uninstall the APK if an app should be cached 13688 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 13689 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 13690 // Other user still have this package installed, so all 13691 // we need to do is clear this user's data and save that 13692 // it is uninstalled. 13693 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 13694 removeUser = user.getIdentifier(); 13695 appId = ps.appId; 13696 scheduleWritePackageRestrictionsLocked(removeUser); 13697 } else { 13698 // We need to set it back to 'installed' so the uninstall 13699 // broadcasts will be sent correctly. 13700 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 13701 ps.setInstalled(true, user.getIdentifier()); 13702 } 13703 } else { 13704 // This is a system app, so we assume that the 13705 // other users still have this package installed, so all 13706 // we need to do is clear this user's data and save that 13707 // it is uninstalled. 13708 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 13709 removeUser = user.getIdentifier(); 13710 appId = ps.appId; 13711 scheduleWritePackageRestrictionsLocked(removeUser); 13712 } 13713 } 13714 } 13715 13716 if (removeUser >= 0) { 13717 // From above, we determined that we are deleting this only 13718 // for a single user. Continue the work here. 13719 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 13720 if (outInfo != null) { 13721 outInfo.removedPackage = packageName; 13722 outInfo.removedAppId = appId; 13723 outInfo.removedUsers = new int[] {removeUser}; 13724 } 13725 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 13726 removeKeystoreDataIfNeeded(removeUser, appId); 13727 schedulePackageCleaning(packageName, removeUser, false); 13728 synchronized (mPackages) { 13729 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 13730 scheduleWritePackageRestrictionsLocked(removeUser); 13731 } 13732 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser); 13733 } 13734 return true; 13735 } 13736 13737 if (dataOnly) { 13738 // Delete application data first 13739 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 13740 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 13741 return true; 13742 } 13743 13744 boolean ret = false; 13745 if (isSystemApp(ps)) { 13746 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 13747 // When an updated system application is deleted we delete the existing resources as well and 13748 // fall back to existing code in system partition 13749 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 13750 flags, outInfo, writeSettings); 13751 } else { 13752 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 13753 // Kill application pre-emptively especially for apps on sd. 13754 killApplication(packageName, ps.appId, "uninstall pkg"); 13755 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 13756 allUserHandles, perUserInstalled, 13757 outInfo, writeSettings); 13758 } 13759 13760 return ret; 13761 } 13762 13763 private final class ClearStorageConnection implements ServiceConnection { 13764 IMediaContainerService mContainerService; 13765 13766 @Override 13767 public void onServiceConnected(ComponentName name, IBinder service) { 13768 synchronized (this) { 13769 mContainerService = IMediaContainerService.Stub.asInterface(service); 13770 notifyAll(); 13771 } 13772 } 13773 13774 @Override 13775 public void onServiceDisconnected(ComponentName name) { 13776 } 13777 } 13778 13779 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 13780 final boolean mounted; 13781 if (Environment.isExternalStorageEmulated()) { 13782 mounted = true; 13783 } else { 13784 final String status = Environment.getExternalStorageState(); 13785 13786 mounted = status.equals(Environment.MEDIA_MOUNTED) 13787 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 13788 } 13789 13790 if (!mounted) { 13791 return; 13792 } 13793 13794 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 13795 int[] users; 13796 if (userId == UserHandle.USER_ALL) { 13797 users = sUserManager.getUserIds(); 13798 } else { 13799 users = new int[] { userId }; 13800 } 13801 final ClearStorageConnection conn = new ClearStorageConnection(); 13802 if (mContext.bindServiceAsUser( 13803 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 13804 try { 13805 for (int curUser : users) { 13806 long timeout = SystemClock.uptimeMillis() + 5000; 13807 synchronized (conn) { 13808 long now = SystemClock.uptimeMillis(); 13809 while (conn.mContainerService == null && now < timeout) { 13810 try { 13811 conn.wait(timeout - now); 13812 } catch (InterruptedException e) { 13813 } 13814 } 13815 } 13816 if (conn.mContainerService == null) { 13817 return; 13818 } 13819 13820 final UserEnvironment userEnv = new UserEnvironment(curUser); 13821 clearDirectory(conn.mContainerService, 13822 userEnv.buildExternalStorageAppCacheDirs(packageName)); 13823 if (allData) { 13824 clearDirectory(conn.mContainerService, 13825 userEnv.buildExternalStorageAppDataDirs(packageName)); 13826 clearDirectory(conn.mContainerService, 13827 userEnv.buildExternalStorageAppMediaDirs(packageName)); 13828 } 13829 } 13830 } finally { 13831 mContext.unbindService(conn); 13832 } 13833 } 13834 } 13835 13836 @Override 13837 public void clearApplicationUserData(final String packageName, 13838 final IPackageDataObserver observer, final int userId) { 13839 mContext.enforceCallingOrSelfPermission( 13840 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 13841 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 13842 // Queue up an async operation since the package deletion may take a little while. 13843 mHandler.post(new Runnable() { 13844 public void run() { 13845 mHandler.removeCallbacks(this); 13846 final boolean succeeded; 13847 synchronized (mInstallLock) { 13848 succeeded = clearApplicationUserDataLI(packageName, userId); 13849 } 13850 clearExternalStorageDataSync(packageName, userId, true); 13851 if (succeeded) { 13852 // invoke DeviceStorageMonitor's update method to clear any notifications 13853 DeviceStorageMonitorInternal 13854 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13855 if (dsm != null) { 13856 dsm.checkMemory(); 13857 } 13858 } 13859 if(observer != null) { 13860 try { 13861 observer.onRemoveCompleted(packageName, succeeded); 13862 } catch (RemoteException e) { 13863 Log.i(TAG, "Observer no longer exists."); 13864 } 13865 } //end if observer 13866 } //end run 13867 }); 13868 } 13869 13870 private boolean clearApplicationUserDataLI(String packageName, int userId) { 13871 if (packageName == null) { 13872 Slog.w(TAG, "Attempt to delete null packageName."); 13873 return false; 13874 } 13875 13876 // Try finding details about the requested package 13877 PackageParser.Package pkg; 13878 synchronized (mPackages) { 13879 pkg = mPackages.get(packageName); 13880 if (pkg == null) { 13881 final PackageSetting ps = mSettings.mPackages.get(packageName); 13882 if (ps != null) { 13883 pkg = ps.pkg; 13884 } 13885 } 13886 13887 if (pkg == null) { 13888 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13889 return false; 13890 } 13891 13892 PackageSetting ps = (PackageSetting) pkg.mExtras; 13893 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 13894 } 13895 13896 // Always delete data directories for package, even if we found no other 13897 // record of app. This helps users recover from UID mismatches without 13898 // resorting to a full data wipe. 13899 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 13900 if (retCode < 0) { 13901 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 13902 return false; 13903 } 13904 13905 final int appId = pkg.applicationInfo.uid; 13906 removeKeystoreDataIfNeeded(userId, appId); 13907 13908 // Create a native library symlink only if we have native libraries 13909 // and if the native libraries are 32 bit libraries. We do not provide 13910 // this symlink for 64 bit libraries. 13911 if (pkg.applicationInfo.primaryCpuAbi != null && 13912 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 13913 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 13914 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 13915 nativeLibPath, userId) < 0) { 13916 Slog.w(TAG, "Failed linking native library dir"); 13917 return false; 13918 } 13919 } 13920 13921 return true; 13922 } 13923 13924 /** 13925 * Reverts user permission state changes (permissions and flags) in 13926 * all packages for a given user. 13927 * 13928 * @param userId The device user for which to do a reset. 13929 */ 13930 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 13931 final int packageCount = mPackages.size(); 13932 for (int i = 0; i < packageCount; i++) { 13933 PackageParser.Package pkg = mPackages.valueAt(i); 13934 PackageSetting ps = (PackageSetting) pkg.mExtras; 13935 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 13936 } 13937 } 13938 13939 /** 13940 * Reverts user permission state changes (permissions and flags). 13941 * 13942 * @param ps The package for which to reset. 13943 * @param userId The device user for which to do a reset. 13944 */ 13945 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 13946 final PackageSetting ps, final int userId) { 13947 if (ps.pkg == null) { 13948 return; 13949 } 13950 13951 // These are flags that can change base on user actions. 13952 final int userSettableMask = FLAG_PERMISSION_USER_SET 13953 | FLAG_PERMISSION_USER_FIXED 13954 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 13955 | FLAG_PERMISSION_REVIEW_REQUIRED; 13956 13957 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 13958 | FLAG_PERMISSION_POLICY_FIXED; 13959 13960 boolean writeInstallPermissions = false; 13961 boolean writeRuntimePermissions = false; 13962 13963 final int permissionCount = ps.pkg.requestedPermissions.size(); 13964 for (int i = 0; i < permissionCount; i++) { 13965 String permission = ps.pkg.requestedPermissions.get(i); 13966 13967 BasePermission bp = mSettings.mPermissions.get(permission); 13968 if (bp == null) { 13969 continue; 13970 } 13971 13972 // If shared user we just reset the state to which only this app contributed. 13973 if (ps.sharedUser != null) { 13974 boolean used = false; 13975 final int packageCount = ps.sharedUser.packages.size(); 13976 for (int j = 0; j < packageCount; j++) { 13977 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 13978 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 13979 && pkg.pkg.requestedPermissions.contains(permission)) { 13980 used = true; 13981 break; 13982 } 13983 } 13984 if (used) { 13985 continue; 13986 } 13987 } 13988 13989 PermissionsState permissionsState = ps.getPermissionsState(); 13990 13991 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 13992 13993 // Always clear the user settable flags. 13994 final boolean hasInstallState = permissionsState.getInstallPermissionState( 13995 bp.name) != null; 13996 // If permission review is enabled and this is a legacy app, mark the 13997 // permission as requiring a review as this is the initial state. 13998 int flags = 0; 13999 if (Build.PERMISSIONS_REVIEW_REQUIRED 14000 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 14001 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 14002 } 14003 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 14004 if (hasInstallState) { 14005 writeInstallPermissions = true; 14006 } else { 14007 writeRuntimePermissions = true; 14008 } 14009 } 14010 14011 // Below is only runtime permission handling. 14012 if (!bp.isRuntime()) { 14013 continue; 14014 } 14015 14016 // Never clobber system or policy. 14017 if ((oldFlags & policyOrSystemFlags) != 0) { 14018 continue; 14019 } 14020 14021 // If this permission was granted by default, make sure it is. 14022 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 14023 if (permissionsState.grantRuntimePermission(bp, userId) 14024 != PERMISSION_OPERATION_FAILURE) { 14025 writeRuntimePermissions = true; 14026 } 14027 // If permission review is enabled the permissions for a legacy apps 14028 // are represented as constantly granted runtime ones, so don't revoke. 14029 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 14030 // Otherwise, reset the permission. 14031 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 14032 switch (revokeResult) { 14033 case PERMISSION_OPERATION_SUCCESS: { 14034 writeRuntimePermissions = true; 14035 } break; 14036 14037 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 14038 writeRuntimePermissions = true; 14039 final int appId = ps.appId; 14040 mHandler.post(new Runnable() { 14041 @Override 14042 public void run() { 14043 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 14044 } 14045 }); 14046 } break; 14047 } 14048 } 14049 } 14050 14051 // Synchronously write as we are taking permissions away. 14052 if (writeRuntimePermissions) { 14053 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 14054 } 14055 14056 // Synchronously write as we are taking permissions away. 14057 if (writeInstallPermissions) { 14058 mSettings.writeLPr(); 14059 } 14060 } 14061 14062 /** 14063 * Remove entries from the keystore daemon. Will only remove it if the 14064 * {@code appId} is valid. 14065 */ 14066 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 14067 if (appId < 0) { 14068 return; 14069 } 14070 14071 final KeyStore keyStore = KeyStore.getInstance(); 14072 if (keyStore != null) { 14073 if (userId == UserHandle.USER_ALL) { 14074 for (final int individual : sUserManager.getUserIds()) { 14075 keyStore.clearUid(UserHandle.getUid(individual, appId)); 14076 } 14077 } else { 14078 keyStore.clearUid(UserHandle.getUid(userId, appId)); 14079 } 14080 } else { 14081 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 14082 } 14083 } 14084 14085 @Override 14086 public void deleteApplicationCacheFiles(final String packageName, 14087 final IPackageDataObserver observer) { 14088 mContext.enforceCallingOrSelfPermission( 14089 android.Manifest.permission.DELETE_CACHE_FILES, null); 14090 // Queue up an async operation since the package deletion may take a little while. 14091 final int userId = UserHandle.getCallingUserId(); 14092 mHandler.post(new Runnable() { 14093 public void run() { 14094 mHandler.removeCallbacks(this); 14095 final boolean succeded; 14096 synchronized (mInstallLock) { 14097 succeded = deleteApplicationCacheFilesLI(packageName, userId); 14098 } 14099 clearExternalStorageDataSync(packageName, userId, false); 14100 if (observer != null) { 14101 try { 14102 observer.onRemoveCompleted(packageName, succeded); 14103 } catch (RemoteException e) { 14104 Log.i(TAG, "Observer no longer exists."); 14105 } 14106 } //end if observer 14107 } //end run 14108 }); 14109 } 14110 14111 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 14112 if (packageName == null) { 14113 Slog.w(TAG, "Attempt to delete null packageName."); 14114 return false; 14115 } 14116 PackageParser.Package p; 14117 synchronized (mPackages) { 14118 p = mPackages.get(packageName); 14119 } 14120 if (p == null) { 14121 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 14122 return false; 14123 } 14124 final ApplicationInfo applicationInfo = p.applicationInfo; 14125 if (applicationInfo == null) { 14126 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 14127 return false; 14128 } 14129 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 14130 if (retCode < 0) { 14131 Slog.w(TAG, "Couldn't remove cache files for package: " 14132 + packageName + " u" + userId); 14133 return false; 14134 } 14135 return true; 14136 } 14137 14138 @Override 14139 public void getPackageSizeInfo(final String packageName, int userHandle, 14140 final IPackageStatsObserver observer) { 14141 mContext.enforceCallingOrSelfPermission( 14142 android.Manifest.permission.GET_PACKAGE_SIZE, null); 14143 if (packageName == null) { 14144 throw new IllegalArgumentException("Attempt to get size of null packageName"); 14145 } 14146 14147 PackageStats stats = new PackageStats(packageName, userHandle); 14148 14149 /* 14150 * Queue up an async operation since the package measurement may take a 14151 * little while. 14152 */ 14153 Message msg = mHandler.obtainMessage(INIT_COPY); 14154 msg.obj = new MeasureParams(stats, observer); 14155 mHandler.sendMessage(msg); 14156 } 14157 14158 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 14159 PackageStats pStats) { 14160 if (packageName == null) { 14161 Slog.w(TAG, "Attempt to get size of null packageName."); 14162 return false; 14163 } 14164 PackageParser.Package p; 14165 boolean dataOnly = false; 14166 String libDirRoot = null; 14167 String asecPath = null; 14168 PackageSetting ps = null; 14169 synchronized (mPackages) { 14170 p = mPackages.get(packageName); 14171 ps = mSettings.mPackages.get(packageName); 14172 if(p == null) { 14173 dataOnly = true; 14174 if((ps == null) || (ps.pkg == null)) { 14175 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 14176 return false; 14177 } 14178 p = ps.pkg; 14179 } 14180 if (ps != null) { 14181 libDirRoot = ps.legacyNativeLibraryPathString; 14182 } 14183 if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) { 14184 final long token = Binder.clearCallingIdentity(); 14185 try { 14186 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 14187 if (secureContainerId != null) { 14188 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 14189 } 14190 } finally { 14191 Binder.restoreCallingIdentity(token); 14192 } 14193 } 14194 } 14195 String publicSrcDir = null; 14196 if(!dataOnly) { 14197 final ApplicationInfo applicationInfo = p.applicationInfo; 14198 if (applicationInfo == null) { 14199 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 14200 return false; 14201 } 14202 if (p.isForwardLocked()) { 14203 publicSrcDir = applicationInfo.getBaseResourcePath(); 14204 } 14205 } 14206 // TODO: extend to measure size of split APKs 14207 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 14208 // not just the first level. 14209 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 14210 // just the primary. 14211 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 14212 14213 String apkPath; 14214 File packageDir = new File(p.codePath); 14215 14216 if (packageDir.isDirectory() && p.canHaveOatDir()) { 14217 apkPath = packageDir.getAbsolutePath(); 14218 // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice 14219 if (libDirRoot != null && libDirRoot.startsWith(apkPath)) { 14220 libDirRoot = null; 14221 } 14222 } else { 14223 apkPath = p.baseCodePath; 14224 } 14225 14226 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, apkPath, 14227 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 14228 if (res < 0) { 14229 return false; 14230 } 14231 14232 // Fix-up for forward-locked applications in ASEC containers. 14233 if (!isExternal(p)) { 14234 pStats.codeSize += pStats.externalCodeSize; 14235 pStats.externalCodeSize = 0L; 14236 } 14237 14238 return true; 14239 } 14240 14241 14242 @Override 14243 public void addPackageToPreferred(String packageName) { 14244 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 14245 } 14246 14247 @Override 14248 public void removePackageFromPreferred(String packageName) { 14249 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 14250 } 14251 14252 @Override 14253 public List<PackageInfo> getPreferredPackages(int flags) { 14254 return new ArrayList<PackageInfo>(); 14255 } 14256 14257 private int getUidTargetSdkVersionLockedLPr(int uid) { 14258 Object obj = mSettings.getUserIdLPr(uid); 14259 if (obj instanceof SharedUserSetting) { 14260 final SharedUserSetting sus = (SharedUserSetting) obj; 14261 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 14262 final Iterator<PackageSetting> it = sus.packages.iterator(); 14263 while (it.hasNext()) { 14264 final PackageSetting ps = it.next(); 14265 if (ps.pkg != null) { 14266 int v = ps.pkg.applicationInfo.targetSdkVersion; 14267 if (v < vers) vers = v; 14268 } 14269 } 14270 return vers; 14271 } else if (obj instanceof PackageSetting) { 14272 final PackageSetting ps = (PackageSetting) obj; 14273 if (ps.pkg != null) { 14274 return ps.pkg.applicationInfo.targetSdkVersion; 14275 } 14276 } 14277 return Build.VERSION_CODES.CUR_DEVELOPMENT; 14278 } 14279 14280 @Override 14281 public void addPreferredActivity(IntentFilter filter, int match, 14282 ComponentName[] set, ComponentName activity, int userId) { 14283 addPreferredActivityInternal(filter, match, set, activity, true, userId, 14284 "Adding preferred"); 14285 } 14286 14287 private void addPreferredActivityInternal(IntentFilter filter, int match, 14288 ComponentName[] set, ComponentName activity, boolean always, int userId, 14289 String opname) { 14290 // writer 14291 int callingUid = Binder.getCallingUid(); 14292 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 14293 if (filter.countActions() == 0) { 14294 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 14295 return; 14296 } 14297 synchronized (mPackages) { 14298 if (mContext.checkCallingOrSelfPermission( 14299 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14300 != PackageManager.PERMISSION_GRANTED) { 14301 if (getUidTargetSdkVersionLockedLPr(callingUid) 14302 < Build.VERSION_CODES.FROYO) { 14303 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 14304 + callingUid); 14305 return; 14306 } 14307 mContext.enforceCallingOrSelfPermission( 14308 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14309 } 14310 14311 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 14312 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 14313 + userId + ":"); 14314 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14315 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 14316 scheduleWritePackageRestrictionsLocked(userId); 14317 } 14318 } 14319 14320 @Override 14321 public void replacePreferredActivity(IntentFilter filter, int match, 14322 ComponentName[] set, ComponentName activity, int userId) { 14323 if (filter.countActions() != 1) { 14324 throw new IllegalArgumentException( 14325 "replacePreferredActivity expects filter to have only 1 action."); 14326 } 14327 if (filter.countDataAuthorities() != 0 14328 || filter.countDataPaths() != 0 14329 || filter.countDataSchemes() > 1 14330 || filter.countDataTypes() != 0) { 14331 throw new IllegalArgumentException( 14332 "replacePreferredActivity expects filter to have no data authorities, " + 14333 "paths, or types; and at most one scheme."); 14334 } 14335 14336 final int callingUid = Binder.getCallingUid(); 14337 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 14338 synchronized (mPackages) { 14339 if (mContext.checkCallingOrSelfPermission( 14340 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14341 != PackageManager.PERMISSION_GRANTED) { 14342 if (getUidTargetSdkVersionLockedLPr(callingUid) 14343 < Build.VERSION_CODES.FROYO) { 14344 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 14345 + Binder.getCallingUid()); 14346 return; 14347 } 14348 mContext.enforceCallingOrSelfPermission( 14349 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14350 } 14351 14352 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 14353 if (pir != null) { 14354 // Get all of the existing entries that exactly match this filter. 14355 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 14356 if (existing != null && existing.size() == 1) { 14357 PreferredActivity cur = existing.get(0); 14358 if (DEBUG_PREFERRED) { 14359 Slog.i(TAG, "Checking replace of preferred:"); 14360 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14361 if (!cur.mPref.mAlways) { 14362 Slog.i(TAG, " -- CUR; not mAlways!"); 14363 } else { 14364 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 14365 Slog.i(TAG, " -- CUR: mSet=" 14366 + Arrays.toString(cur.mPref.mSetComponents)); 14367 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 14368 Slog.i(TAG, " -- NEW: mMatch=" 14369 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 14370 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 14371 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 14372 } 14373 } 14374 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 14375 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 14376 && cur.mPref.sameSet(set)) { 14377 // Setting the preferred activity to what it happens to be already 14378 if (DEBUG_PREFERRED) { 14379 Slog.i(TAG, "Replacing with same preferred activity " 14380 + cur.mPref.mShortComponent + " for user " 14381 + userId + ":"); 14382 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14383 } 14384 return; 14385 } 14386 } 14387 14388 if (existing != null) { 14389 if (DEBUG_PREFERRED) { 14390 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 14391 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14392 } 14393 for (int i = 0; i < existing.size(); i++) { 14394 PreferredActivity pa = existing.get(i); 14395 if (DEBUG_PREFERRED) { 14396 Slog.i(TAG, "Removing existing preferred activity " 14397 + pa.mPref.mComponent + ":"); 14398 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 14399 } 14400 pir.removeFilter(pa); 14401 } 14402 } 14403 } 14404 addPreferredActivityInternal(filter, match, set, activity, true, userId, 14405 "Replacing preferred"); 14406 } 14407 } 14408 14409 @Override 14410 public void clearPackagePreferredActivities(String packageName) { 14411 final int uid = Binder.getCallingUid(); 14412 // writer 14413 synchronized (mPackages) { 14414 PackageParser.Package pkg = mPackages.get(packageName); 14415 if (pkg == null || pkg.applicationInfo.uid != uid) { 14416 if (mContext.checkCallingOrSelfPermission( 14417 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14418 != PackageManager.PERMISSION_GRANTED) { 14419 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 14420 < Build.VERSION_CODES.FROYO) { 14421 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 14422 + Binder.getCallingUid()); 14423 return; 14424 } 14425 mContext.enforceCallingOrSelfPermission( 14426 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14427 } 14428 } 14429 14430 int user = UserHandle.getCallingUserId(); 14431 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 14432 scheduleWritePackageRestrictionsLocked(user); 14433 } 14434 } 14435 } 14436 14437 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14438 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 14439 ArrayList<PreferredActivity> removed = null; 14440 boolean changed = false; 14441 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14442 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 14443 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14444 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 14445 continue; 14446 } 14447 Iterator<PreferredActivity> it = pir.filterIterator(); 14448 while (it.hasNext()) { 14449 PreferredActivity pa = it.next(); 14450 // Mark entry for removal only if it matches the package name 14451 // and the entry is of type "always". 14452 if (packageName == null || 14453 (pa.mPref.mComponent.getPackageName().equals(packageName) 14454 && pa.mPref.mAlways)) { 14455 if (removed == null) { 14456 removed = new ArrayList<PreferredActivity>(); 14457 } 14458 removed.add(pa); 14459 } 14460 } 14461 if (removed != null) { 14462 for (int j=0; j<removed.size(); j++) { 14463 PreferredActivity pa = removed.get(j); 14464 pir.removeFilter(pa); 14465 } 14466 changed = true; 14467 } 14468 } 14469 return changed; 14470 } 14471 14472 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14473 private void clearIntentFilterVerificationsLPw(int userId) { 14474 final int packageCount = mPackages.size(); 14475 for (int i = 0; i < packageCount; i++) { 14476 PackageParser.Package pkg = mPackages.valueAt(i); 14477 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 14478 } 14479 } 14480 14481 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14482 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 14483 if (userId == UserHandle.USER_ALL) { 14484 if (mSettings.removeIntentFilterVerificationLPw(packageName, 14485 sUserManager.getUserIds())) { 14486 for (int oneUserId : sUserManager.getUserIds()) { 14487 scheduleWritePackageRestrictionsLocked(oneUserId); 14488 } 14489 } 14490 } else { 14491 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 14492 scheduleWritePackageRestrictionsLocked(userId); 14493 } 14494 } 14495 } 14496 14497 void clearDefaultBrowserIfNeeded(String packageName) { 14498 for (int oneUserId : sUserManager.getUserIds()) { 14499 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 14500 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 14501 if (packageName.equals(defaultBrowserPackageName)) { 14502 setDefaultBrowserPackageName(null, oneUserId); 14503 } 14504 } 14505 } 14506 14507 @Override 14508 public void resetApplicationPreferences(int userId) { 14509 mContext.enforceCallingOrSelfPermission( 14510 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14511 // writer 14512 synchronized (mPackages) { 14513 final long identity = Binder.clearCallingIdentity(); 14514 try { 14515 clearPackagePreferredActivitiesLPw(null, userId); 14516 mSettings.applyDefaultPreferredAppsLPw(this, userId); 14517 // TODO: We have to reset the default SMS and Phone. This requires 14518 // significant refactoring to keep all default apps in the package 14519 // manager (cleaner but more work) or have the services provide 14520 // callbacks to the package manager to request a default app reset. 14521 applyFactoryDefaultBrowserLPw(userId); 14522 clearIntentFilterVerificationsLPw(userId); 14523 primeDomainVerificationsLPw(userId); 14524 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 14525 scheduleWritePackageRestrictionsLocked(userId); 14526 } finally { 14527 Binder.restoreCallingIdentity(identity); 14528 } 14529 } 14530 } 14531 14532 @Override 14533 public int getPreferredActivities(List<IntentFilter> outFilters, 14534 List<ComponentName> outActivities, String packageName) { 14535 14536 int num = 0; 14537 final int userId = UserHandle.getCallingUserId(); 14538 // reader 14539 synchronized (mPackages) { 14540 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 14541 if (pir != null) { 14542 final Iterator<PreferredActivity> it = pir.filterIterator(); 14543 while (it.hasNext()) { 14544 final PreferredActivity pa = it.next(); 14545 if (packageName == null 14546 || (pa.mPref.mComponent.getPackageName().equals(packageName) 14547 && pa.mPref.mAlways)) { 14548 if (outFilters != null) { 14549 outFilters.add(new IntentFilter(pa)); 14550 } 14551 if (outActivities != null) { 14552 outActivities.add(pa.mPref.mComponent); 14553 } 14554 } 14555 } 14556 } 14557 } 14558 14559 return num; 14560 } 14561 14562 @Override 14563 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 14564 int userId) { 14565 int callingUid = Binder.getCallingUid(); 14566 if (callingUid != Process.SYSTEM_UID) { 14567 throw new SecurityException( 14568 "addPersistentPreferredActivity can only be run by the system"); 14569 } 14570 if (filter.countActions() == 0) { 14571 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 14572 return; 14573 } 14574 synchronized (mPackages) { 14575 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 14576 " :"); 14577 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14578 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 14579 new PersistentPreferredActivity(filter, activity)); 14580 scheduleWritePackageRestrictionsLocked(userId); 14581 } 14582 } 14583 14584 @Override 14585 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 14586 int callingUid = Binder.getCallingUid(); 14587 if (callingUid != Process.SYSTEM_UID) { 14588 throw new SecurityException( 14589 "clearPackagePersistentPreferredActivities can only be run by the system"); 14590 } 14591 ArrayList<PersistentPreferredActivity> removed = null; 14592 boolean changed = false; 14593 synchronized (mPackages) { 14594 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 14595 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 14596 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 14597 .valueAt(i); 14598 if (userId != thisUserId) { 14599 continue; 14600 } 14601 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 14602 while (it.hasNext()) { 14603 PersistentPreferredActivity ppa = it.next(); 14604 // Mark entry for removal only if it matches the package name. 14605 if (ppa.mComponent.getPackageName().equals(packageName)) { 14606 if (removed == null) { 14607 removed = new ArrayList<PersistentPreferredActivity>(); 14608 } 14609 removed.add(ppa); 14610 } 14611 } 14612 if (removed != null) { 14613 for (int j=0; j<removed.size(); j++) { 14614 PersistentPreferredActivity ppa = removed.get(j); 14615 ppir.removeFilter(ppa); 14616 } 14617 changed = true; 14618 } 14619 } 14620 14621 if (changed) { 14622 scheduleWritePackageRestrictionsLocked(userId); 14623 } 14624 } 14625 } 14626 14627 /** 14628 * Common machinery for picking apart a restored XML blob and passing 14629 * it to a caller-supplied functor to be applied to the running system. 14630 */ 14631 private void restoreFromXml(XmlPullParser parser, int userId, 14632 String expectedStartTag, BlobXmlRestorer functor) 14633 throws IOException, XmlPullParserException { 14634 int type; 14635 while ((type = parser.next()) != XmlPullParser.START_TAG 14636 && type != XmlPullParser.END_DOCUMENT) { 14637 } 14638 if (type != XmlPullParser.START_TAG) { 14639 // oops didn't find a start tag?! 14640 if (DEBUG_BACKUP) { 14641 Slog.e(TAG, "Didn't find start tag during restore"); 14642 } 14643 return; 14644 } 14645 14646 // this is supposed to be TAG_PREFERRED_BACKUP 14647 if (!expectedStartTag.equals(parser.getName())) { 14648 if (DEBUG_BACKUP) { 14649 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 14650 } 14651 return; 14652 } 14653 14654 // skip interfering stuff, then we're aligned with the backing implementation 14655 while ((type = parser.next()) == XmlPullParser.TEXT) { } 14656 functor.apply(parser, userId); 14657 } 14658 14659 private interface BlobXmlRestorer { 14660 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 14661 } 14662 14663 /** 14664 * Non-Binder method, support for the backup/restore mechanism: write the 14665 * full set of preferred activities in its canonical XML format. Returns the 14666 * XML output as a byte array, or null if there is none. 14667 */ 14668 @Override 14669 public byte[] getPreferredActivityBackup(int userId) { 14670 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14671 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 14672 } 14673 14674 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14675 try { 14676 final XmlSerializer serializer = new FastXmlSerializer(); 14677 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14678 serializer.startDocument(null, true); 14679 serializer.startTag(null, TAG_PREFERRED_BACKUP); 14680 14681 synchronized (mPackages) { 14682 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 14683 } 14684 14685 serializer.endTag(null, TAG_PREFERRED_BACKUP); 14686 serializer.endDocument(); 14687 serializer.flush(); 14688 } catch (Exception e) { 14689 if (DEBUG_BACKUP) { 14690 Slog.e(TAG, "Unable to write preferred activities for backup", e); 14691 } 14692 return null; 14693 } 14694 14695 return dataStream.toByteArray(); 14696 } 14697 14698 @Override 14699 public void restorePreferredActivities(byte[] backup, int userId) { 14700 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14701 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14702 } 14703 14704 try { 14705 final XmlPullParser parser = Xml.newPullParser(); 14706 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14707 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 14708 new BlobXmlRestorer() { 14709 @Override 14710 public void apply(XmlPullParser parser, int userId) 14711 throws XmlPullParserException, IOException { 14712 synchronized (mPackages) { 14713 mSettings.readPreferredActivitiesLPw(parser, userId); 14714 } 14715 } 14716 } ); 14717 } catch (Exception e) { 14718 if (DEBUG_BACKUP) { 14719 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14720 } 14721 } 14722 } 14723 14724 /** 14725 * Non-Binder method, support for the backup/restore mechanism: write the 14726 * default browser (etc) settings in its canonical XML format. Returns the default 14727 * browser XML representation as a byte array, or null if there is none. 14728 */ 14729 @Override 14730 public byte[] getDefaultAppsBackup(int userId) { 14731 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14732 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 14733 } 14734 14735 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14736 try { 14737 final XmlSerializer serializer = new FastXmlSerializer(); 14738 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14739 serializer.startDocument(null, true); 14740 serializer.startTag(null, TAG_DEFAULT_APPS); 14741 14742 synchronized (mPackages) { 14743 mSettings.writeDefaultAppsLPr(serializer, userId); 14744 } 14745 14746 serializer.endTag(null, TAG_DEFAULT_APPS); 14747 serializer.endDocument(); 14748 serializer.flush(); 14749 } catch (Exception e) { 14750 if (DEBUG_BACKUP) { 14751 Slog.e(TAG, "Unable to write default apps for backup", e); 14752 } 14753 return null; 14754 } 14755 14756 return dataStream.toByteArray(); 14757 } 14758 14759 @Override 14760 public void restoreDefaultApps(byte[] backup, int userId) { 14761 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14762 throw new SecurityException("Only the system may call restoreDefaultApps()"); 14763 } 14764 14765 try { 14766 final XmlPullParser parser = Xml.newPullParser(); 14767 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14768 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 14769 new BlobXmlRestorer() { 14770 @Override 14771 public void apply(XmlPullParser parser, int userId) 14772 throws XmlPullParserException, IOException { 14773 synchronized (mPackages) { 14774 mSettings.readDefaultAppsLPw(parser, userId); 14775 } 14776 } 14777 } ); 14778 } catch (Exception e) { 14779 if (DEBUG_BACKUP) { 14780 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 14781 } 14782 } 14783 } 14784 14785 @Override 14786 public byte[] getIntentFilterVerificationBackup(int userId) { 14787 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14788 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 14789 } 14790 14791 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14792 try { 14793 final XmlSerializer serializer = new FastXmlSerializer(); 14794 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14795 serializer.startDocument(null, true); 14796 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 14797 14798 synchronized (mPackages) { 14799 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 14800 } 14801 14802 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 14803 serializer.endDocument(); 14804 serializer.flush(); 14805 } catch (Exception e) { 14806 if (DEBUG_BACKUP) { 14807 Slog.e(TAG, "Unable to write default apps for backup", e); 14808 } 14809 return null; 14810 } 14811 14812 return dataStream.toByteArray(); 14813 } 14814 14815 @Override 14816 public void restoreIntentFilterVerification(byte[] backup, int userId) { 14817 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14818 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14819 } 14820 14821 try { 14822 final XmlPullParser parser = Xml.newPullParser(); 14823 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14824 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 14825 new BlobXmlRestorer() { 14826 @Override 14827 public void apply(XmlPullParser parser, int userId) 14828 throws XmlPullParserException, IOException { 14829 synchronized (mPackages) { 14830 mSettings.readAllDomainVerificationsLPr(parser, userId); 14831 mSettings.writeLPr(); 14832 } 14833 } 14834 } ); 14835 } catch (Exception e) { 14836 if (DEBUG_BACKUP) { 14837 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14838 } 14839 } 14840 } 14841 14842 @Override 14843 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 14844 int sourceUserId, int targetUserId, int flags) { 14845 mContext.enforceCallingOrSelfPermission( 14846 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14847 int callingUid = Binder.getCallingUid(); 14848 enforceOwnerRights(ownerPackage, callingUid); 14849 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14850 if (intentFilter.countActions() == 0) { 14851 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 14852 return; 14853 } 14854 synchronized (mPackages) { 14855 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 14856 ownerPackage, targetUserId, flags); 14857 CrossProfileIntentResolver resolver = 14858 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14859 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 14860 // We have all those whose filter is equal. Now checking if the rest is equal as well. 14861 if (existing != null) { 14862 int size = existing.size(); 14863 for (int i = 0; i < size; i++) { 14864 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 14865 return; 14866 } 14867 } 14868 } 14869 resolver.addFilter(newFilter); 14870 scheduleWritePackageRestrictionsLocked(sourceUserId); 14871 } 14872 } 14873 14874 @Override 14875 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 14876 mContext.enforceCallingOrSelfPermission( 14877 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14878 int callingUid = Binder.getCallingUid(); 14879 enforceOwnerRights(ownerPackage, callingUid); 14880 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14881 synchronized (mPackages) { 14882 CrossProfileIntentResolver resolver = 14883 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14884 ArraySet<CrossProfileIntentFilter> set = 14885 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 14886 for (CrossProfileIntentFilter filter : set) { 14887 if (filter.getOwnerPackage().equals(ownerPackage)) { 14888 resolver.removeFilter(filter); 14889 } 14890 } 14891 scheduleWritePackageRestrictionsLocked(sourceUserId); 14892 } 14893 } 14894 14895 // Enforcing that callingUid is owning pkg on userId 14896 private void enforceOwnerRights(String pkg, int callingUid) { 14897 // The system owns everything. 14898 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 14899 return; 14900 } 14901 int callingUserId = UserHandle.getUserId(callingUid); 14902 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 14903 if (pi == null) { 14904 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 14905 + callingUserId); 14906 } 14907 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 14908 throw new SecurityException("Calling uid " + callingUid 14909 + " does not own package " + pkg); 14910 } 14911 } 14912 14913 @Override 14914 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 14915 Intent intent = new Intent(Intent.ACTION_MAIN); 14916 intent.addCategory(Intent.CATEGORY_HOME); 14917 14918 final int callingUserId = UserHandle.getCallingUserId(); 14919 List<ResolveInfo> list = queryIntentActivities(intent, null, 14920 PackageManager.GET_META_DATA, callingUserId); 14921 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 14922 true, false, false, callingUserId); 14923 14924 allHomeCandidates.clear(); 14925 if (list != null) { 14926 for (ResolveInfo ri : list) { 14927 allHomeCandidates.add(ri); 14928 } 14929 } 14930 return (preferred == null || preferred.activityInfo == null) 14931 ? null 14932 : new ComponentName(preferred.activityInfo.packageName, 14933 preferred.activityInfo.name); 14934 } 14935 14936 @Override 14937 public void setApplicationEnabledSetting(String appPackageName, 14938 int newState, int flags, int userId, String callingPackage) { 14939 if (!sUserManager.exists(userId)) return; 14940 if (callingPackage == null) { 14941 callingPackage = Integer.toString(Binder.getCallingUid()); 14942 } 14943 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 14944 } 14945 14946 @Override 14947 public void setComponentEnabledSetting(ComponentName componentName, 14948 int newState, int flags, int userId) { 14949 if (!sUserManager.exists(userId)) return; 14950 setEnabledSetting(componentName.getPackageName(), 14951 componentName.getClassName(), newState, flags, userId, null); 14952 } 14953 14954 private void setEnabledSetting(final String packageName, String className, int newState, 14955 final int flags, int userId, String callingPackage) { 14956 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 14957 || newState == COMPONENT_ENABLED_STATE_ENABLED 14958 || newState == COMPONENT_ENABLED_STATE_DISABLED 14959 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 14960 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 14961 throw new IllegalArgumentException("Invalid new component state: " 14962 + newState); 14963 } 14964 PackageSetting pkgSetting; 14965 final int uid = Binder.getCallingUid(); 14966 final int permission = mContext.checkCallingOrSelfPermission( 14967 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14968 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 14969 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14970 boolean sendNow = false; 14971 boolean isApp = (className == null); 14972 String componentName = isApp ? packageName : className; 14973 int packageUid = -1; 14974 ArrayList<String> components; 14975 14976 // writer 14977 synchronized (mPackages) { 14978 pkgSetting = mSettings.mPackages.get(packageName); 14979 if (pkgSetting == null) { 14980 if (className == null) { 14981 throw new IllegalArgumentException( 14982 "Unknown package: " + packageName); 14983 } 14984 throw new IllegalArgumentException( 14985 "Unknown component: " + packageName 14986 + "/" + className); 14987 } 14988 // Allow root and verify that userId is not being specified by a different user 14989 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 14990 throw new SecurityException( 14991 "Permission Denial: attempt to change component state from pid=" 14992 + Binder.getCallingPid() 14993 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 14994 } 14995 if (className == null) { 14996 // We're dealing with an application/package level state change 14997 if (pkgSetting.getEnabled(userId) == newState) { 14998 // Nothing to do 14999 return; 15000 } 15001 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 15002 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 15003 // Don't care about who enables an app. 15004 callingPackage = null; 15005 } 15006 pkgSetting.setEnabled(newState, userId, callingPackage); 15007 // pkgSetting.pkg.mSetEnabled = newState; 15008 } else { 15009 // We're dealing with a component level state change 15010 // First, verify that this is a valid class name. 15011 PackageParser.Package pkg = pkgSetting.pkg; 15012 if (pkg == null || !pkg.hasComponentClassName(className)) { 15013 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 15014 throw new IllegalArgumentException("Component class " + className 15015 + " does not exist in " + packageName); 15016 } else { 15017 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 15018 + className + " does not exist in " + packageName); 15019 } 15020 } 15021 switch (newState) { 15022 case COMPONENT_ENABLED_STATE_ENABLED: 15023 if (!pkgSetting.enableComponentLPw(className, userId)) { 15024 return; 15025 } 15026 break; 15027 case COMPONENT_ENABLED_STATE_DISABLED: 15028 if (!pkgSetting.disableComponentLPw(className, userId)) { 15029 return; 15030 } 15031 break; 15032 case COMPONENT_ENABLED_STATE_DEFAULT: 15033 if (!pkgSetting.restoreComponentLPw(className, userId)) { 15034 return; 15035 } 15036 break; 15037 default: 15038 Slog.e(TAG, "Invalid new component state: " + newState); 15039 return; 15040 } 15041 } 15042 scheduleWritePackageRestrictionsLocked(userId); 15043 components = mPendingBroadcasts.get(userId, packageName); 15044 final boolean newPackage = components == null; 15045 if (newPackage) { 15046 components = new ArrayList<String>(); 15047 } 15048 if (!components.contains(componentName)) { 15049 components.add(componentName); 15050 } 15051 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 15052 sendNow = true; 15053 // Purge entry from pending broadcast list if another one exists already 15054 // since we are sending one right away. 15055 mPendingBroadcasts.remove(userId, packageName); 15056 } else { 15057 if (newPackage) { 15058 mPendingBroadcasts.put(userId, packageName, components); 15059 } 15060 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 15061 // Schedule a message 15062 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 15063 } 15064 } 15065 } 15066 15067 long callingId = Binder.clearCallingIdentity(); 15068 try { 15069 if (sendNow) { 15070 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 15071 sendPackageChangedBroadcast(packageName, 15072 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 15073 } 15074 } finally { 15075 Binder.restoreCallingIdentity(callingId); 15076 } 15077 } 15078 15079 private void sendPackageChangedBroadcast(String packageName, 15080 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 15081 if (DEBUG_INSTALL) 15082 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 15083 + componentNames); 15084 Bundle extras = new Bundle(4); 15085 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 15086 String nameList[] = new String[componentNames.size()]; 15087 componentNames.toArray(nameList); 15088 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 15089 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 15090 extras.putInt(Intent.EXTRA_UID, packageUid); 15091 // If this is not reporting a change of the overall package, then only send it 15092 // to registered receivers. We don't want to launch a swath of apps for every 15093 // little component state change. 15094 final int flags = !componentNames.contains(packageName) 15095 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 15096 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 15097 new int[] {UserHandle.getUserId(packageUid)}); 15098 } 15099 15100 @Override 15101 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 15102 if (!sUserManager.exists(userId)) return; 15103 final int uid = Binder.getCallingUid(); 15104 final int permission = mContext.checkCallingOrSelfPermission( 15105 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 15106 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 15107 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 15108 // writer 15109 synchronized (mPackages) { 15110 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 15111 allowedByPermission, uid, userId)) { 15112 scheduleWritePackageRestrictionsLocked(userId); 15113 } 15114 } 15115 } 15116 15117 @Override 15118 public String getInstallerPackageName(String packageName) { 15119 // reader 15120 synchronized (mPackages) { 15121 return mSettings.getInstallerPackageNameLPr(packageName); 15122 } 15123 } 15124 15125 @Override 15126 public int getApplicationEnabledSetting(String packageName, int userId) { 15127 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 15128 int uid = Binder.getCallingUid(); 15129 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 15130 // reader 15131 synchronized (mPackages) { 15132 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 15133 } 15134 } 15135 15136 @Override 15137 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 15138 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 15139 int uid = Binder.getCallingUid(); 15140 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 15141 // reader 15142 synchronized (mPackages) { 15143 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 15144 } 15145 } 15146 15147 @Override 15148 public void enterSafeMode() { 15149 enforceSystemOrRoot("Only the system can request entering safe mode"); 15150 15151 if (!mSystemReady) { 15152 mSafeMode = true; 15153 } 15154 } 15155 15156 @Override 15157 public void systemReady() { 15158 mSystemReady = true; 15159 15160 // Read the compatibilty setting when the system is ready. 15161 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 15162 mContext.getContentResolver(), 15163 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 15164 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 15165 if (DEBUG_SETTINGS) { 15166 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 15167 } 15168 15169 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 15170 15171 synchronized (mPackages) { 15172 // Verify that all of the preferred activity components actually 15173 // exist. It is possible for applications to be updated and at 15174 // that point remove a previously declared activity component that 15175 // had been set as a preferred activity. We try to clean this up 15176 // the next time we encounter that preferred activity, but it is 15177 // possible for the user flow to never be able to return to that 15178 // situation so here we do a sanity check to make sure we haven't 15179 // left any junk around. 15180 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 15181 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 15182 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 15183 removed.clear(); 15184 for (PreferredActivity pa : pir.filterSet()) { 15185 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 15186 removed.add(pa); 15187 } 15188 } 15189 if (removed.size() > 0) { 15190 for (int r=0; r<removed.size(); r++) { 15191 PreferredActivity pa = removed.get(r); 15192 Slog.w(TAG, "Removing dangling preferred activity: " 15193 + pa.mPref.mComponent); 15194 pir.removeFilter(pa); 15195 } 15196 mSettings.writePackageRestrictionsLPr( 15197 mSettings.mPreferredActivities.keyAt(i)); 15198 } 15199 } 15200 15201 for (int userId : UserManagerService.getInstance().getUserIds()) { 15202 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 15203 grantPermissionsUserIds = ArrayUtils.appendInt( 15204 grantPermissionsUserIds, userId); 15205 } 15206 } 15207 } 15208 sUserManager.systemReady(); 15209 15210 // If we upgraded grant all default permissions before kicking off. 15211 for (int userId : grantPermissionsUserIds) { 15212 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 15213 } 15214 15215 // Kick off any messages waiting for system ready 15216 if (mPostSystemReadyMessages != null) { 15217 for (Message msg : mPostSystemReadyMessages) { 15218 msg.sendToTarget(); 15219 } 15220 mPostSystemReadyMessages = null; 15221 } 15222 15223 // Watch for external volumes that come and go over time 15224 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15225 storage.registerListener(mStorageListener); 15226 15227 mInstallerService.systemReady(); 15228 mPackageDexOptimizer.systemReady(); 15229 15230 MountServiceInternal mountServiceInternal = LocalServices.getService( 15231 MountServiceInternal.class); 15232 mountServiceInternal.addExternalStoragePolicy( 15233 new MountServiceInternal.ExternalStorageMountPolicy() { 15234 @Override 15235 public int getMountMode(int uid, String packageName) { 15236 if (Process.isIsolated(uid)) { 15237 return Zygote.MOUNT_EXTERNAL_NONE; 15238 } 15239 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 15240 return Zygote.MOUNT_EXTERNAL_DEFAULT; 15241 } 15242 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 15243 return Zygote.MOUNT_EXTERNAL_DEFAULT; 15244 } 15245 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 15246 return Zygote.MOUNT_EXTERNAL_READ; 15247 } 15248 return Zygote.MOUNT_EXTERNAL_WRITE; 15249 } 15250 15251 @Override 15252 public boolean hasExternalStorage(int uid, String packageName) { 15253 return true; 15254 } 15255 }); 15256 } 15257 15258 @Override 15259 public boolean isSafeMode() { 15260 return mSafeMode; 15261 } 15262 15263 @Override 15264 public boolean hasSystemUidErrors() { 15265 return mHasSystemUidErrors; 15266 } 15267 15268 static String arrayToString(int[] array) { 15269 StringBuffer buf = new StringBuffer(128); 15270 buf.append('['); 15271 if (array != null) { 15272 for (int i=0; i<array.length; i++) { 15273 if (i > 0) buf.append(", "); 15274 buf.append(array[i]); 15275 } 15276 } 15277 buf.append(']'); 15278 return buf.toString(); 15279 } 15280 15281 static class DumpState { 15282 public static final int DUMP_LIBS = 1 << 0; 15283 public static final int DUMP_FEATURES = 1 << 1; 15284 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 15285 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 15286 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 15287 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 15288 public static final int DUMP_PERMISSIONS = 1 << 6; 15289 public static final int DUMP_PACKAGES = 1 << 7; 15290 public static final int DUMP_SHARED_USERS = 1 << 8; 15291 public static final int DUMP_MESSAGES = 1 << 9; 15292 public static final int DUMP_PROVIDERS = 1 << 10; 15293 public static final int DUMP_VERIFIERS = 1 << 11; 15294 public static final int DUMP_PREFERRED = 1 << 12; 15295 public static final int DUMP_PREFERRED_XML = 1 << 13; 15296 public static final int DUMP_KEYSETS = 1 << 14; 15297 public static final int DUMP_VERSION = 1 << 15; 15298 public static final int DUMP_INSTALLS = 1 << 16; 15299 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 15300 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 15301 15302 public static final int OPTION_SHOW_FILTERS = 1 << 0; 15303 15304 private int mTypes; 15305 15306 private int mOptions; 15307 15308 private boolean mTitlePrinted; 15309 15310 private SharedUserSetting mSharedUser; 15311 15312 public boolean isDumping(int type) { 15313 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 15314 return true; 15315 } 15316 15317 return (mTypes & type) != 0; 15318 } 15319 15320 public void setDump(int type) { 15321 mTypes |= type; 15322 } 15323 15324 public boolean isOptionEnabled(int option) { 15325 return (mOptions & option) != 0; 15326 } 15327 15328 public void setOptionEnabled(int option) { 15329 mOptions |= option; 15330 } 15331 15332 public boolean onTitlePrinted() { 15333 final boolean printed = mTitlePrinted; 15334 mTitlePrinted = true; 15335 return printed; 15336 } 15337 15338 public boolean getTitlePrinted() { 15339 return mTitlePrinted; 15340 } 15341 15342 public void setTitlePrinted(boolean enabled) { 15343 mTitlePrinted = enabled; 15344 } 15345 15346 public SharedUserSetting getSharedUser() { 15347 return mSharedUser; 15348 } 15349 15350 public void setSharedUser(SharedUserSetting user) { 15351 mSharedUser = user; 15352 } 15353 } 15354 15355 @Override 15356 public void onShellCommand(FileDescriptor in, FileDescriptor out, 15357 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 15358 (new PackageManagerShellCommand(this)).exec( 15359 this, in, out, err, args, resultReceiver); 15360 } 15361 15362 @Override 15363 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 15364 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 15365 != PackageManager.PERMISSION_GRANTED) { 15366 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 15367 + Binder.getCallingPid() 15368 + ", uid=" + Binder.getCallingUid() 15369 + " without permission " 15370 + android.Manifest.permission.DUMP); 15371 return; 15372 } 15373 15374 DumpState dumpState = new DumpState(); 15375 boolean fullPreferred = false; 15376 boolean checkin = false; 15377 15378 String packageName = null; 15379 ArraySet<String> permissionNames = null; 15380 15381 int opti = 0; 15382 while (opti < args.length) { 15383 String opt = args[opti]; 15384 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 15385 break; 15386 } 15387 opti++; 15388 15389 if ("-a".equals(opt)) { 15390 // Right now we only know how to print all. 15391 } else if ("-h".equals(opt)) { 15392 pw.println("Package manager dump options:"); 15393 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 15394 pw.println(" --checkin: dump for a checkin"); 15395 pw.println(" -f: print details of intent filters"); 15396 pw.println(" -h: print this help"); 15397 pw.println(" cmd may be one of:"); 15398 pw.println(" l[ibraries]: list known shared libraries"); 15399 pw.println(" f[eatures]: list device features"); 15400 pw.println(" k[eysets]: print known keysets"); 15401 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 15402 pw.println(" perm[issions]: dump permissions"); 15403 pw.println(" permission [name ...]: dump declaration and use of given permission"); 15404 pw.println(" pref[erred]: print preferred package settings"); 15405 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 15406 pw.println(" prov[iders]: dump content providers"); 15407 pw.println(" p[ackages]: dump installed packages"); 15408 pw.println(" s[hared-users]: dump shared user IDs"); 15409 pw.println(" m[essages]: print collected runtime messages"); 15410 pw.println(" v[erifiers]: print package verifier info"); 15411 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 15412 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 15413 pw.println(" version: print database version info"); 15414 pw.println(" write: write current settings now"); 15415 pw.println(" installs: details about install sessions"); 15416 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 15417 pw.println(" <package.name>: info about given package"); 15418 return; 15419 } else if ("--checkin".equals(opt)) { 15420 checkin = true; 15421 } else if ("-f".equals(opt)) { 15422 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 15423 } else { 15424 pw.println("Unknown argument: " + opt + "; use -h for help"); 15425 } 15426 } 15427 15428 // Is the caller requesting to dump a particular piece of data? 15429 if (opti < args.length) { 15430 String cmd = args[opti]; 15431 opti++; 15432 // Is this a package name? 15433 if ("android".equals(cmd) || cmd.contains(".")) { 15434 packageName = cmd; 15435 // When dumping a single package, we always dump all of its 15436 // filter information since the amount of data will be reasonable. 15437 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 15438 } else if ("check-permission".equals(cmd)) { 15439 if (opti >= args.length) { 15440 pw.println("Error: check-permission missing permission argument"); 15441 return; 15442 } 15443 String perm = args[opti]; 15444 opti++; 15445 if (opti >= args.length) { 15446 pw.println("Error: check-permission missing package argument"); 15447 return; 15448 } 15449 String pkg = args[opti]; 15450 opti++; 15451 int user = UserHandle.getUserId(Binder.getCallingUid()); 15452 if (opti < args.length) { 15453 try { 15454 user = Integer.parseInt(args[opti]); 15455 } catch (NumberFormatException e) { 15456 pw.println("Error: check-permission user argument is not a number: " 15457 + args[opti]); 15458 return; 15459 } 15460 } 15461 pw.println(checkPermission(perm, pkg, user)); 15462 return; 15463 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 15464 dumpState.setDump(DumpState.DUMP_LIBS); 15465 } else if ("f".equals(cmd) || "features".equals(cmd)) { 15466 dumpState.setDump(DumpState.DUMP_FEATURES); 15467 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 15468 if (opti >= args.length) { 15469 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 15470 | DumpState.DUMP_SERVICE_RESOLVERS 15471 | DumpState.DUMP_RECEIVER_RESOLVERS 15472 | DumpState.DUMP_CONTENT_RESOLVERS); 15473 } else { 15474 while (opti < args.length) { 15475 String name = args[opti]; 15476 if ("a".equals(name) || "activity".equals(name)) { 15477 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 15478 } else if ("s".equals(name) || "service".equals(name)) { 15479 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 15480 } else if ("r".equals(name) || "receiver".equals(name)) { 15481 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 15482 } else if ("c".equals(name) || "content".equals(name)) { 15483 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 15484 } else { 15485 pw.println("Error: unknown resolver table type: " + name); 15486 return; 15487 } 15488 opti++; 15489 } 15490 } 15491 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 15492 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 15493 } else if ("permission".equals(cmd)) { 15494 if (opti >= args.length) { 15495 pw.println("Error: permission requires permission name"); 15496 return; 15497 } 15498 permissionNames = new ArraySet<>(); 15499 while (opti < args.length) { 15500 permissionNames.add(args[opti]); 15501 opti++; 15502 } 15503 dumpState.setDump(DumpState.DUMP_PERMISSIONS 15504 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 15505 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 15506 dumpState.setDump(DumpState.DUMP_PREFERRED); 15507 } else if ("preferred-xml".equals(cmd)) { 15508 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 15509 if (opti < args.length && "--full".equals(args[opti])) { 15510 fullPreferred = true; 15511 opti++; 15512 } 15513 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 15514 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 15515 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 15516 dumpState.setDump(DumpState.DUMP_PACKAGES); 15517 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 15518 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 15519 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 15520 dumpState.setDump(DumpState.DUMP_PROVIDERS); 15521 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 15522 dumpState.setDump(DumpState.DUMP_MESSAGES); 15523 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 15524 dumpState.setDump(DumpState.DUMP_VERIFIERS); 15525 } else if ("i".equals(cmd) || "ifv".equals(cmd) 15526 || "intent-filter-verifiers".equals(cmd)) { 15527 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 15528 } else if ("version".equals(cmd)) { 15529 dumpState.setDump(DumpState.DUMP_VERSION); 15530 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 15531 dumpState.setDump(DumpState.DUMP_KEYSETS); 15532 } else if ("installs".equals(cmd)) { 15533 dumpState.setDump(DumpState.DUMP_INSTALLS); 15534 } else if ("write".equals(cmd)) { 15535 synchronized (mPackages) { 15536 mSettings.writeLPr(); 15537 pw.println("Settings written."); 15538 return; 15539 } 15540 } 15541 } 15542 15543 if (checkin) { 15544 pw.println("vers,1"); 15545 } 15546 15547 // reader 15548 synchronized (mPackages) { 15549 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 15550 if (!checkin) { 15551 if (dumpState.onTitlePrinted()) 15552 pw.println(); 15553 pw.println("Database versions:"); 15554 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 15555 } 15556 } 15557 15558 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 15559 if (!checkin) { 15560 if (dumpState.onTitlePrinted()) 15561 pw.println(); 15562 pw.println("Verifiers:"); 15563 pw.print(" Required: "); 15564 pw.print(mRequiredVerifierPackage); 15565 pw.print(" (uid="); 15566 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 15567 pw.println(")"); 15568 } else if (mRequiredVerifierPackage != null) { 15569 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 15570 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 15571 } 15572 } 15573 15574 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 15575 packageName == null) { 15576 if (mIntentFilterVerifierComponent != null) { 15577 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 15578 if (!checkin) { 15579 if (dumpState.onTitlePrinted()) 15580 pw.println(); 15581 pw.println("Intent Filter Verifier:"); 15582 pw.print(" Using: "); 15583 pw.print(verifierPackageName); 15584 pw.print(" (uid="); 15585 pw.print(getPackageUid(verifierPackageName, 0)); 15586 pw.println(")"); 15587 } else if (verifierPackageName != null) { 15588 pw.print("ifv,"); pw.print(verifierPackageName); 15589 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 15590 } 15591 } else { 15592 pw.println(); 15593 pw.println("No Intent Filter Verifier available!"); 15594 } 15595 } 15596 15597 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 15598 boolean printedHeader = false; 15599 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 15600 while (it.hasNext()) { 15601 String name = it.next(); 15602 SharedLibraryEntry ent = mSharedLibraries.get(name); 15603 if (!checkin) { 15604 if (!printedHeader) { 15605 if (dumpState.onTitlePrinted()) 15606 pw.println(); 15607 pw.println("Libraries:"); 15608 printedHeader = true; 15609 } 15610 pw.print(" "); 15611 } else { 15612 pw.print("lib,"); 15613 } 15614 pw.print(name); 15615 if (!checkin) { 15616 pw.print(" -> "); 15617 } 15618 if (ent.path != null) { 15619 if (!checkin) { 15620 pw.print("(jar) "); 15621 pw.print(ent.path); 15622 } else { 15623 pw.print(",jar,"); 15624 pw.print(ent.path); 15625 } 15626 } else { 15627 if (!checkin) { 15628 pw.print("(apk) "); 15629 pw.print(ent.apk); 15630 } else { 15631 pw.print(",apk,"); 15632 pw.print(ent.apk); 15633 } 15634 } 15635 pw.println(); 15636 } 15637 } 15638 15639 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 15640 if (dumpState.onTitlePrinted()) 15641 pw.println(); 15642 if (!checkin) { 15643 pw.println("Features:"); 15644 } 15645 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 15646 while (it.hasNext()) { 15647 String name = it.next(); 15648 if (!checkin) { 15649 pw.print(" "); 15650 } else { 15651 pw.print("feat,"); 15652 } 15653 pw.println(name); 15654 } 15655 } 15656 15657 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 15658 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 15659 : "Activity Resolver Table:", " ", packageName, 15660 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15661 dumpState.setTitlePrinted(true); 15662 } 15663 } 15664 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 15665 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 15666 : "Receiver Resolver Table:", " ", packageName, 15667 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15668 dumpState.setTitlePrinted(true); 15669 } 15670 } 15671 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 15672 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 15673 : "Service Resolver Table:", " ", packageName, 15674 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15675 dumpState.setTitlePrinted(true); 15676 } 15677 } 15678 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 15679 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 15680 : "Provider Resolver Table:", " ", packageName, 15681 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15682 dumpState.setTitlePrinted(true); 15683 } 15684 } 15685 15686 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 15687 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 15688 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 15689 int user = mSettings.mPreferredActivities.keyAt(i); 15690 if (pir.dump(pw, 15691 dumpState.getTitlePrinted() 15692 ? "\nPreferred Activities User " + user + ":" 15693 : "Preferred Activities User " + user + ":", " ", 15694 packageName, true, false)) { 15695 dumpState.setTitlePrinted(true); 15696 } 15697 } 15698 } 15699 15700 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 15701 pw.flush(); 15702 FileOutputStream fout = new FileOutputStream(fd); 15703 BufferedOutputStream str = new BufferedOutputStream(fout); 15704 XmlSerializer serializer = new FastXmlSerializer(); 15705 try { 15706 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 15707 serializer.startDocument(null, true); 15708 serializer.setFeature( 15709 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 15710 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 15711 serializer.endDocument(); 15712 serializer.flush(); 15713 } catch (IllegalArgumentException e) { 15714 pw.println("Failed writing: " + e); 15715 } catch (IllegalStateException e) { 15716 pw.println("Failed writing: " + e); 15717 } catch (IOException e) { 15718 pw.println("Failed writing: " + e); 15719 } 15720 } 15721 15722 if (!checkin 15723 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 15724 && packageName == null) { 15725 pw.println(); 15726 int count = mSettings.mPackages.size(); 15727 if (count == 0) { 15728 pw.println("No applications!"); 15729 pw.println(); 15730 } else { 15731 final String prefix = " "; 15732 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 15733 if (allPackageSettings.size() == 0) { 15734 pw.println("No domain preferred apps!"); 15735 pw.println(); 15736 } else { 15737 pw.println("App verification status:"); 15738 pw.println(); 15739 count = 0; 15740 for (PackageSetting ps : allPackageSettings) { 15741 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 15742 if (ivi == null || ivi.getPackageName() == null) continue; 15743 pw.println(prefix + "Package: " + ivi.getPackageName()); 15744 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 15745 pw.println(prefix + "Status: " + ivi.getStatusString()); 15746 pw.println(); 15747 count++; 15748 } 15749 if (count == 0) { 15750 pw.println(prefix + "No app verification established."); 15751 pw.println(); 15752 } 15753 for (int userId : sUserManager.getUserIds()) { 15754 pw.println("App linkages for user " + userId + ":"); 15755 pw.println(); 15756 count = 0; 15757 for (PackageSetting ps : allPackageSettings) { 15758 final long status = ps.getDomainVerificationStatusForUser(userId); 15759 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 15760 continue; 15761 } 15762 pw.println(prefix + "Package: " + ps.name); 15763 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 15764 String statusStr = IntentFilterVerificationInfo. 15765 getStatusStringFromValue(status); 15766 pw.println(prefix + "Status: " + statusStr); 15767 pw.println(); 15768 count++; 15769 } 15770 if (count == 0) { 15771 pw.println(prefix + "No configured app linkages."); 15772 pw.println(); 15773 } 15774 } 15775 } 15776 } 15777 } 15778 15779 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 15780 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 15781 if (packageName == null && permissionNames == null) { 15782 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 15783 if (iperm == 0) { 15784 if (dumpState.onTitlePrinted()) 15785 pw.println(); 15786 pw.println("AppOp Permissions:"); 15787 } 15788 pw.print(" AppOp Permission "); 15789 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 15790 pw.println(":"); 15791 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 15792 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 15793 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 15794 } 15795 } 15796 } 15797 } 15798 15799 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 15800 boolean printedSomething = false; 15801 for (PackageParser.Provider p : mProviders.mProviders.values()) { 15802 if (packageName != null && !packageName.equals(p.info.packageName)) { 15803 continue; 15804 } 15805 if (!printedSomething) { 15806 if (dumpState.onTitlePrinted()) 15807 pw.println(); 15808 pw.println("Registered ContentProviders:"); 15809 printedSomething = true; 15810 } 15811 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 15812 pw.print(" "); pw.println(p.toString()); 15813 } 15814 printedSomething = false; 15815 for (Map.Entry<String, PackageParser.Provider> entry : 15816 mProvidersByAuthority.entrySet()) { 15817 PackageParser.Provider p = entry.getValue(); 15818 if (packageName != null && !packageName.equals(p.info.packageName)) { 15819 continue; 15820 } 15821 if (!printedSomething) { 15822 if (dumpState.onTitlePrinted()) 15823 pw.println(); 15824 pw.println("ContentProvider Authorities:"); 15825 printedSomething = true; 15826 } 15827 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 15828 pw.print(" "); pw.println(p.toString()); 15829 if (p.info != null && p.info.applicationInfo != null) { 15830 final String appInfo = p.info.applicationInfo.toString(); 15831 pw.print(" applicationInfo="); pw.println(appInfo); 15832 } 15833 } 15834 } 15835 15836 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 15837 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 15838 } 15839 15840 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 15841 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 15842 } 15843 15844 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 15845 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 15846 } 15847 15848 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 15849 // XXX should handle packageName != null by dumping only install data that 15850 // the given package is involved with. 15851 if (dumpState.onTitlePrinted()) pw.println(); 15852 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 15853 } 15854 15855 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 15856 if (dumpState.onTitlePrinted()) pw.println(); 15857 mSettings.dumpReadMessagesLPr(pw, dumpState); 15858 15859 pw.println(); 15860 pw.println("Package warning messages:"); 15861 BufferedReader in = null; 15862 String line = null; 15863 try { 15864 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15865 while ((line = in.readLine()) != null) { 15866 if (line.contains("ignored: updated version")) continue; 15867 pw.println(line); 15868 } 15869 } catch (IOException ignored) { 15870 } finally { 15871 IoUtils.closeQuietly(in); 15872 } 15873 } 15874 15875 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 15876 BufferedReader in = null; 15877 String line = null; 15878 try { 15879 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15880 while ((line = in.readLine()) != null) { 15881 if (line.contains("ignored: updated version")) continue; 15882 pw.print("msg,"); 15883 pw.println(line); 15884 } 15885 } catch (IOException ignored) { 15886 } finally { 15887 IoUtils.closeQuietly(in); 15888 } 15889 } 15890 } 15891 } 15892 15893 private String dumpDomainString(String packageName) { 15894 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName); 15895 List<IntentFilter> filters = getAllIntentFilters(packageName); 15896 15897 ArraySet<String> result = new ArraySet<>(); 15898 if (iviList.size() > 0) { 15899 for (IntentFilterVerificationInfo ivi : iviList) { 15900 for (String host : ivi.getDomains()) { 15901 result.add(host); 15902 } 15903 } 15904 } 15905 if (filters != null && filters.size() > 0) { 15906 for (IntentFilter filter : filters) { 15907 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 15908 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 15909 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 15910 result.addAll(filter.getHostsList()); 15911 } 15912 } 15913 } 15914 15915 StringBuilder sb = new StringBuilder(result.size() * 16); 15916 for (String domain : result) { 15917 if (sb.length() > 0) sb.append(" "); 15918 sb.append(domain); 15919 } 15920 return sb.toString(); 15921 } 15922 15923 // ------- apps on sdcard specific code ------- 15924 static final boolean DEBUG_SD_INSTALL = false; 15925 15926 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 15927 15928 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 15929 15930 private boolean mMediaMounted = false; 15931 15932 static String getEncryptKey() { 15933 try { 15934 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 15935 SD_ENCRYPTION_KEYSTORE_NAME); 15936 if (sdEncKey == null) { 15937 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 15938 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 15939 if (sdEncKey == null) { 15940 Slog.e(TAG, "Failed to create encryption keys"); 15941 return null; 15942 } 15943 } 15944 return sdEncKey; 15945 } catch (NoSuchAlgorithmException nsae) { 15946 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 15947 return null; 15948 } catch (IOException ioe) { 15949 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 15950 return null; 15951 } 15952 } 15953 15954 /* 15955 * Update media status on PackageManager. 15956 */ 15957 @Override 15958 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 15959 int callingUid = Binder.getCallingUid(); 15960 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 15961 throw new SecurityException("Media status can only be updated by the system"); 15962 } 15963 // reader; this apparently protects mMediaMounted, but should probably 15964 // be a different lock in that case. 15965 synchronized (mPackages) { 15966 Log.i(TAG, "Updating external media status from " 15967 + (mMediaMounted ? "mounted" : "unmounted") + " to " 15968 + (mediaStatus ? "mounted" : "unmounted")); 15969 if (DEBUG_SD_INSTALL) 15970 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 15971 + ", mMediaMounted=" + mMediaMounted); 15972 if (mediaStatus == mMediaMounted) { 15973 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 15974 : 0, -1); 15975 mHandler.sendMessage(msg); 15976 return; 15977 } 15978 mMediaMounted = mediaStatus; 15979 } 15980 // Queue up an async operation since the package installation may take a 15981 // little while. 15982 mHandler.post(new Runnable() { 15983 public void run() { 15984 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 15985 } 15986 }); 15987 } 15988 15989 /** 15990 * Called by MountService when the initial ASECs to scan are available. 15991 * Should block until all the ASEC containers are finished being scanned. 15992 */ 15993 public void scanAvailableAsecs() { 15994 updateExternalMediaStatusInner(true, false, false); 15995 if (mShouldRestoreconData) { 15996 SELinuxMMAC.setRestoreconDone(); 15997 mShouldRestoreconData = false; 15998 } 15999 } 16000 16001 /* 16002 * Collect information of applications on external media, map them against 16003 * existing containers and update information based on current mount status. 16004 * Please note that we always have to report status if reportStatus has been 16005 * set to true especially when unloading packages. 16006 */ 16007 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 16008 boolean externalStorage) { 16009 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 16010 int[] uidArr = EmptyArray.INT; 16011 16012 final String[] list = PackageHelper.getSecureContainerList(); 16013 if (ArrayUtils.isEmpty(list)) { 16014 Log.i(TAG, "No secure containers found"); 16015 } else { 16016 // Process list of secure containers and categorize them 16017 // as active or stale based on their package internal state. 16018 16019 // reader 16020 synchronized (mPackages) { 16021 for (String cid : list) { 16022 // Leave stages untouched for now; installer service owns them 16023 if (PackageInstallerService.isStageName(cid)) continue; 16024 16025 if (DEBUG_SD_INSTALL) 16026 Log.i(TAG, "Processing container " + cid); 16027 String pkgName = getAsecPackageName(cid); 16028 if (pkgName == null) { 16029 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 16030 continue; 16031 } 16032 if (DEBUG_SD_INSTALL) 16033 Log.i(TAG, "Looking for pkg : " + pkgName); 16034 16035 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16036 if (ps == null) { 16037 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 16038 continue; 16039 } 16040 16041 /* 16042 * Skip packages that are not external if we're unmounting 16043 * external storage. 16044 */ 16045 if (externalStorage && !isMounted && !isExternal(ps)) { 16046 continue; 16047 } 16048 16049 final AsecInstallArgs args = new AsecInstallArgs(cid, 16050 getAppDexInstructionSets(ps), ps.isForwardLocked()); 16051 // The package status is changed only if the code path 16052 // matches between settings and the container id. 16053 if (ps.codePathString != null 16054 && ps.codePathString.startsWith(args.getCodePath())) { 16055 if (DEBUG_SD_INSTALL) { 16056 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 16057 + " at code path: " + ps.codePathString); 16058 } 16059 16060 // We do have a valid package installed on sdcard 16061 processCids.put(args, ps.codePathString); 16062 final int uid = ps.appId; 16063 if (uid != -1) { 16064 uidArr = ArrayUtils.appendInt(uidArr, uid); 16065 } 16066 } else { 16067 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 16068 + ps.codePathString); 16069 } 16070 } 16071 } 16072 16073 Arrays.sort(uidArr); 16074 } 16075 16076 // Process packages with valid entries. 16077 if (isMounted) { 16078 if (DEBUG_SD_INSTALL) 16079 Log.i(TAG, "Loading packages"); 16080 loadMediaPackages(processCids, uidArr, externalStorage); 16081 startCleaningPackages(); 16082 mInstallerService.onSecureContainersAvailable(); 16083 } else { 16084 if (DEBUG_SD_INSTALL) 16085 Log.i(TAG, "Unloading packages"); 16086 unloadMediaPackages(processCids, uidArr, reportStatus); 16087 } 16088 } 16089 16090 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 16091 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 16092 final int size = infos.size(); 16093 final String[] packageNames = new String[size]; 16094 final int[] packageUids = new int[size]; 16095 for (int i = 0; i < size; i++) { 16096 final ApplicationInfo info = infos.get(i); 16097 packageNames[i] = info.packageName; 16098 packageUids[i] = info.uid; 16099 } 16100 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 16101 finishedReceiver); 16102 } 16103 16104 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 16105 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 16106 sendResourcesChangedBroadcast(mediaStatus, replacing, 16107 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 16108 } 16109 16110 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 16111 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 16112 int size = pkgList.length; 16113 if (size > 0) { 16114 // Send broadcasts here 16115 Bundle extras = new Bundle(); 16116 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 16117 if (uidArr != null) { 16118 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 16119 } 16120 if (replacing) { 16121 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 16122 } 16123 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 16124 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 16125 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 16126 } 16127 } 16128 16129 /* 16130 * Look at potentially valid container ids from processCids If package 16131 * information doesn't match the one on record or package scanning fails, 16132 * the cid is added to list of removeCids. We currently don't delete stale 16133 * containers. 16134 */ 16135 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 16136 boolean externalStorage) { 16137 ArrayList<String> pkgList = new ArrayList<String>(); 16138 Set<AsecInstallArgs> keys = processCids.keySet(); 16139 16140 for (AsecInstallArgs args : keys) { 16141 String codePath = processCids.get(args); 16142 if (DEBUG_SD_INSTALL) 16143 Log.i(TAG, "Loading container : " + args.cid); 16144 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 16145 try { 16146 // Make sure there are no container errors first. 16147 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 16148 Slog.e(TAG, "Failed to mount cid : " + args.cid 16149 + " when installing from sdcard"); 16150 continue; 16151 } 16152 // Check code path here. 16153 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 16154 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 16155 + " does not match one in settings " + codePath); 16156 continue; 16157 } 16158 // Parse package 16159 int parseFlags = mDefParseFlags; 16160 if (args.isExternalAsec()) { 16161 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 16162 } 16163 if (args.isFwdLocked()) { 16164 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 16165 } 16166 16167 synchronized (mInstallLock) { 16168 PackageParser.Package pkg = null; 16169 try { 16170 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null); 16171 } catch (PackageManagerException e) { 16172 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 16173 } 16174 // Scan the package 16175 if (pkg != null) { 16176 /* 16177 * TODO why is the lock being held? doPostInstall is 16178 * called in other places without the lock. This needs 16179 * to be straightened out. 16180 */ 16181 // writer 16182 synchronized (mPackages) { 16183 retCode = PackageManager.INSTALL_SUCCEEDED; 16184 pkgList.add(pkg.packageName); 16185 // Post process args 16186 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 16187 pkg.applicationInfo.uid); 16188 } 16189 } else { 16190 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 16191 } 16192 } 16193 16194 } finally { 16195 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 16196 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 16197 } 16198 } 16199 } 16200 // writer 16201 synchronized (mPackages) { 16202 // If the platform SDK has changed since the last time we booted, 16203 // we need to re-grant app permission to catch any new ones that 16204 // appear. This is really a hack, and means that apps can in some 16205 // cases get permissions that the user didn't initially explicitly 16206 // allow... it would be nice to have some better way to handle 16207 // this situation. 16208 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 16209 : mSettings.getInternalVersion(); 16210 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 16211 : StorageManager.UUID_PRIVATE_INTERNAL; 16212 16213 int updateFlags = UPDATE_PERMISSIONS_ALL; 16214 if (ver.sdkVersion != mSdkVersion) { 16215 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 16216 + mSdkVersion + "; regranting permissions for external"); 16217 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 16218 } 16219 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 16220 16221 // Yay, everything is now upgraded 16222 ver.forceCurrent(); 16223 16224 // can downgrade to reader 16225 // Persist settings 16226 mSettings.writeLPr(); 16227 } 16228 // Send a broadcast to let everyone know we are done processing 16229 if (pkgList.size() > 0) { 16230 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 16231 } 16232 } 16233 16234 /* 16235 * Utility method to unload a list of specified containers 16236 */ 16237 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 16238 // Just unmount all valid containers. 16239 for (AsecInstallArgs arg : cidArgs) { 16240 synchronized (mInstallLock) { 16241 arg.doPostDeleteLI(false); 16242 } 16243 } 16244 } 16245 16246 /* 16247 * Unload packages mounted on external media. This involves deleting package 16248 * data from internal structures, sending broadcasts about diabled packages, 16249 * gc'ing to free up references, unmounting all secure containers 16250 * corresponding to packages on external media, and posting a 16251 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 16252 * that we always have to post this message if status has been requested no 16253 * matter what. 16254 */ 16255 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 16256 final boolean reportStatus) { 16257 if (DEBUG_SD_INSTALL) 16258 Log.i(TAG, "unloading media packages"); 16259 ArrayList<String> pkgList = new ArrayList<String>(); 16260 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 16261 final Set<AsecInstallArgs> keys = processCids.keySet(); 16262 for (AsecInstallArgs args : keys) { 16263 String pkgName = args.getPackageName(); 16264 if (DEBUG_SD_INSTALL) 16265 Log.i(TAG, "Trying to unload pkg : " + pkgName); 16266 // Delete package internally 16267 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 16268 synchronized (mInstallLock) { 16269 boolean res = deletePackageLI(pkgName, null, false, null, null, 16270 PackageManager.DELETE_KEEP_DATA, outInfo, false); 16271 if (res) { 16272 pkgList.add(pkgName); 16273 } else { 16274 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 16275 failedList.add(args); 16276 } 16277 } 16278 } 16279 16280 // reader 16281 synchronized (mPackages) { 16282 // We didn't update the settings after removing each package; 16283 // write them now for all packages. 16284 mSettings.writeLPr(); 16285 } 16286 16287 // We have to absolutely send UPDATED_MEDIA_STATUS only 16288 // after confirming that all the receivers processed the ordered 16289 // broadcast when packages get disabled, force a gc to clean things up. 16290 // and unload all the containers. 16291 if (pkgList.size() > 0) { 16292 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 16293 new IIntentReceiver.Stub() { 16294 public void performReceive(Intent intent, int resultCode, String data, 16295 Bundle extras, boolean ordered, boolean sticky, 16296 int sendingUser) throws RemoteException { 16297 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 16298 reportStatus ? 1 : 0, 1, keys); 16299 mHandler.sendMessage(msg); 16300 } 16301 }); 16302 } else { 16303 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 16304 keys); 16305 mHandler.sendMessage(msg); 16306 } 16307 } 16308 16309 private void loadPrivatePackages(final VolumeInfo vol) { 16310 mHandler.post(new Runnable() { 16311 @Override 16312 public void run() { 16313 loadPrivatePackagesInner(vol); 16314 } 16315 }); 16316 } 16317 16318 private void loadPrivatePackagesInner(VolumeInfo vol) { 16319 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 16320 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 16321 16322 final VersionInfo ver; 16323 final List<PackageSetting> packages; 16324 synchronized (mPackages) { 16325 ver = mSettings.findOrCreateVersion(vol.fsUuid); 16326 packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 16327 } 16328 16329 for (PackageSetting ps : packages) { 16330 synchronized (mInstallLock) { 16331 final PackageParser.Package pkg; 16332 try { 16333 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 16334 loaded.add(pkg.applicationInfo); 16335 } catch (PackageManagerException e) { 16336 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 16337 } 16338 16339 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 16340 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 16341 } 16342 } 16343 } 16344 16345 synchronized (mPackages) { 16346 int updateFlags = UPDATE_PERMISSIONS_ALL; 16347 if (ver.sdkVersion != mSdkVersion) { 16348 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 16349 + mSdkVersion + "; regranting permissions for " + vol.fsUuid); 16350 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 16351 } 16352 updatePermissionsLPw(null, null, vol.fsUuid, updateFlags); 16353 16354 // Yay, everything is now upgraded 16355 ver.forceCurrent(); 16356 16357 mSettings.writeLPr(); 16358 } 16359 16360 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 16361 sendResourcesChangedBroadcast(true, false, loaded, null); 16362 } 16363 16364 private void unloadPrivatePackages(final VolumeInfo vol) { 16365 mHandler.post(new Runnable() { 16366 @Override 16367 public void run() { 16368 unloadPrivatePackagesInner(vol); 16369 } 16370 }); 16371 } 16372 16373 private void unloadPrivatePackagesInner(VolumeInfo vol) { 16374 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 16375 synchronized (mInstallLock) { 16376 synchronized (mPackages) { 16377 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 16378 for (PackageSetting ps : packages) { 16379 if (ps.pkg == null) continue; 16380 16381 final ApplicationInfo info = ps.pkg.applicationInfo; 16382 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 16383 if (deletePackageLI(ps.name, null, false, null, null, 16384 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 16385 unloaded.add(info); 16386 } else { 16387 Slog.w(TAG, "Failed to unload " + ps.codePath); 16388 } 16389 } 16390 16391 mSettings.writeLPr(); 16392 } 16393 } 16394 16395 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 16396 sendResourcesChangedBroadcast(false, false, unloaded, null); 16397 } 16398 16399 /** 16400 * Examine all users present on given mounted volume, and destroy data 16401 * belonging to users that are no longer valid, or whose user ID has been 16402 * recycled. 16403 */ 16404 private void reconcileUsers(String volumeUuid) { 16405 final File[] files = FileUtils 16406 .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid)); 16407 for (File file : files) { 16408 if (!file.isDirectory()) continue; 16409 16410 final int userId; 16411 final UserInfo info; 16412 try { 16413 userId = Integer.parseInt(file.getName()); 16414 info = sUserManager.getUserInfo(userId); 16415 } catch (NumberFormatException e) { 16416 Slog.w(TAG, "Invalid user directory " + file); 16417 continue; 16418 } 16419 16420 boolean destroyUser = false; 16421 if (info == null) { 16422 logCriticalInfo(Log.WARN, "Destroying user directory " + file 16423 + " because no matching user was found"); 16424 destroyUser = true; 16425 } else { 16426 try { 16427 UserManagerService.enforceSerialNumber(file, info.serialNumber); 16428 } catch (IOException e) { 16429 logCriticalInfo(Log.WARN, "Destroying user directory " + file 16430 + " because we failed to enforce serial number: " + e); 16431 destroyUser = true; 16432 } 16433 } 16434 16435 if (destroyUser) { 16436 synchronized (mInstallLock) { 16437 mInstaller.removeUserDataDirs(volumeUuid, userId); 16438 } 16439 } 16440 } 16441 16442 final StorageManager sm = mContext.getSystemService(StorageManager.class); 16443 final UserManager um = mContext.getSystemService(UserManager.class); 16444 for (UserInfo user : um.getUsers()) { 16445 final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id); 16446 if (userDir.exists()) continue; 16447 16448 try { 16449 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber); 16450 UserManagerService.enforceSerialNumber(userDir, user.serialNumber); 16451 } catch (IOException e) { 16452 Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e); 16453 } 16454 } 16455 } 16456 16457 /** 16458 * Examine all apps present on given mounted volume, and destroy apps that 16459 * aren't expected, either due to uninstallation or reinstallation on 16460 * another volume. 16461 */ 16462 private void reconcileApps(String volumeUuid) { 16463 final File[] files = FileUtils 16464 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 16465 for (File file : files) { 16466 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 16467 && !PackageInstallerService.isStageName(file.getName()); 16468 if (!isPackage) { 16469 // Ignore entries which are not packages 16470 continue; 16471 } 16472 16473 boolean destroyApp = false; 16474 String packageName = null; 16475 try { 16476 final PackageLite pkg = PackageParser.parsePackageLite(file, 16477 PackageParser.PARSE_MUST_BE_APK); 16478 packageName = pkg.packageName; 16479 16480 synchronized (mPackages) { 16481 final PackageSetting ps = mSettings.mPackages.get(packageName); 16482 if (ps == null) { 16483 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + " 16484 + volumeUuid + " because we found no install record"); 16485 destroyApp = true; 16486 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 16487 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on " 16488 + volumeUuid + " because we expected it on " + ps.volumeUuid); 16489 destroyApp = true; 16490 } 16491 } 16492 16493 } catch (PackageParserException e) { 16494 logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e); 16495 destroyApp = true; 16496 } 16497 16498 if (destroyApp) { 16499 synchronized (mInstallLock) { 16500 if (packageName != null) { 16501 removeDataDirsLI(volumeUuid, packageName); 16502 } 16503 if (file.isDirectory()) { 16504 mInstaller.rmPackageDir(file.getAbsolutePath()); 16505 } else { 16506 file.delete(); 16507 } 16508 } 16509 } 16510 } 16511 } 16512 16513 private void unfreezePackage(String packageName) { 16514 synchronized (mPackages) { 16515 final PackageSetting ps = mSettings.mPackages.get(packageName); 16516 if (ps != null) { 16517 ps.frozen = false; 16518 } 16519 } 16520 } 16521 16522 @Override 16523 public int movePackage(final String packageName, final String volumeUuid) { 16524 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 16525 16526 final int moveId = mNextMoveId.getAndIncrement(); 16527 mHandler.post(new Runnable() { 16528 @Override 16529 public void run() { 16530 try { 16531 movePackageInternal(packageName, volumeUuid, moveId); 16532 } catch (PackageManagerException e) { 16533 Slog.w(TAG, "Failed to move " + packageName, e); 16534 mMoveCallbacks.notifyStatusChanged(moveId, 16535 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 16536 } 16537 } 16538 }); 16539 return moveId; 16540 } 16541 16542 private void movePackageInternal(final String packageName, final String volumeUuid, 16543 final int moveId) throws PackageManagerException { 16544 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 16545 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16546 final PackageManager pm = mContext.getPackageManager(); 16547 16548 final boolean currentAsec; 16549 final String currentVolumeUuid; 16550 final File codeFile; 16551 final String installerPackageName; 16552 final String packageAbiOverride; 16553 final int appId; 16554 final String seinfo; 16555 final String label; 16556 16557 // reader 16558 synchronized (mPackages) { 16559 final PackageParser.Package pkg = mPackages.get(packageName); 16560 final PackageSetting ps = mSettings.mPackages.get(packageName); 16561 if (pkg == null || ps == null) { 16562 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 16563 } 16564 16565 if (pkg.applicationInfo.isSystemApp()) { 16566 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 16567 "Cannot move system application"); 16568 } 16569 16570 if (pkg.applicationInfo.isExternalAsec()) { 16571 currentAsec = true; 16572 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 16573 } else if (pkg.applicationInfo.isForwardLocked()) { 16574 currentAsec = true; 16575 currentVolumeUuid = "forward_locked"; 16576 } else { 16577 currentAsec = false; 16578 currentVolumeUuid = ps.volumeUuid; 16579 16580 final File probe = new File(pkg.codePath); 16581 final File probeOat = new File(probe, "oat"); 16582 if (!probe.isDirectory() || !probeOat.isDirectory()) { 16583 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16584 "Move only supported for modern cluster style installs"); 16585 } 16586 } 16587 16588 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 16589 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16590 "Package already moved to " + volumeUuid); 16591 } 16592 16593 if (ps.frozen) { 16594 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 16595 "Failed to move already frozen package"); 16596 } 16597 ps.frozen = true; 16598 16599 codeFile = new File(pkg.codePath); 16600 installerPackageName = ps.installerPackageName; 16601 packageAbiOverride = ps.cpuAbiOverrideString; 16602 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16603 seinfo = pkg.applicationInfo.seinfo; 16604 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 16605 } 16606 16607 // Now that we're guarded by frozen state, kill app during move 16608 final long token = Binder.clearCallingIdentity(); 16609 try { 16610 killApplication(packageName, appId, "move pkg"); 16611 } finally { 16612 Binder.restoreCallingIdentity(token); 16613 } 16614 16615 final Bundle extras = new Bundle(); 16616 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 16617 extras.putString(Intent.EXTRA_TITLE, label); 16618 mMoveCallbacks.notifyCreated(moveId, extras); 16619 16620 int installFlags; 16621 final boolean moveCompleteApp; 16622 final File measurePath; 16623 16624 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 16625 installFlags = INSTALL_INTERNAL; 16626 moveCompleteApp = !currentAsec; 16627 measurePath = Environment.getDataAppDirectory(volumeUuid); 16628 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 16629 installFlags = INSTALL_EXTERNAL; 16630 moveCompleteApp = false; 16631 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 16632 } else { 16633 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 16634 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 16635 || !volume.isMountedWritable()) { 16636 unfreezePackage(packageName); 16637 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16638 "Move location not mounted private volume"); 16639 } 16640 16641 Preconditions.checkState(!currentAsec); 16642 16643 installFlags = INSTALL_INTERNAL; 16644 moveCompleteApp = true; 16645 measurePath = Environment.getDataAppDirectory(volumeUuid); 16646 } 16647 16648 final PackageStats stats = new PackageStats(null, -1); 16649 synchronized (mInstaller) { 16650 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 16651 unfreezePackage(packageName); 16652 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16653 "Failed to measure package size"); 16654 } 16655 } 16656 16657 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 16658 + stats.dataSize); 16659 16660 final long startFreeBytes = measurePath.getFreeSpace(); 16661 final long sizeBytes; 16662 if (moveCompleteApp) { 16663 sizeBytes = stats.codeSize + stats.dataSize; 16664 } else { 16665 sizeBytes = stats.codeSize; 16666 } 16667 16668 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 16669 unfreezePackage(packageName); 16670 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16671 "Not enough free space to move"); 16672 } 16673 16674 mMoveCallbacks.notifyStatusChanged(moveId, 10); 16675 16676 final CountDownLatch installedLatch = new CountDownLatch(1); 16677 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 16678 @Override 16679 public void onUserActionRequired(Intent intent) throws RemoteException { 16680 throw new IllegalStateException(); 16681 } 16682 16683 @Override 16684 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 16685 Bundle extras) throws RemoteException { 16686 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 16687 + PackageManager.installStatusToString(returnCode, msg)); 16688 16689 installedLatch.countDown(); 16690 16691 // Regardless of success or failure of the move operation, 16692 // always unfreeze the package 16693 unfreezePackage(packageName); 16694 16695 final int status = PackageManager.installStatusToPublicStatus(returnCode); 16696 switch (status) { 16697 case PackageInstaller.STATUS_SUCCESS: 16698 mMoveCallbacks.notifyStatusChanged(moveId, 16699 PackageManager.MOVE_SUCCEEDED); 16700 break; 16701 case PackageInstaller.STATUS_FAILURE_STORAGE: 16702 mMoveCallbacks.notifyStatusChanged(moveId, 16703 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 16704 break; 16705 default: 16706 mMoveCallbacks.notifyStatusChanged(moveId, 16707 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 16708 break; 16709 } 16710 } 16711 }; 16712 16713 final MoveInfo move; 16714 if (moveCompleteApp) { 16715 // Kick off a thread to report progress estimates 16716 new Thread() { 16717 @Override 16718 public void run() { 16719 while (true) { 16720 try { 16721 if (installedLatch.await(1, TimeUnit.SECONDS)) { 16722 break; 16723 } 16724 } catch (InterruptedException ignored) { 16725 } 16726 16727 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 16728 final int progress = 10 + (int) MathUtils.constrain( 16729 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 16730 mMoveCallbacks.notifyStatusChanged(moveId, progress); 16731 } 16732 } 16733 }.start(); 16734 16735 final String dataAppName = codeFile.getName(); 16736 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 16737 dataAppName, appId, seinfo); 16738 } else { 16739 move = null; 16740 } 16741 16742 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 16743 16744 final Message msg = mHandler.obtainMessage(INIT_COPY); 16745 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 16746 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 16747 installerPackageName, volumeUuid, null, user, packageAbiOverride, null); 16748 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 16749 msg.obj = params; 16750 16751 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 16752 System.identityHashCode(msg.obj)); 16753 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 16754 System.identityHashCode(msg.obj)); 16755 16756 mHandler.sendMessage(msg); 16757 } 16758 16759 @Override 16760 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 16761 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 16762 16763 final int realMoveId = mNextMoveId.getAndIncrement(); 16764 final Bundle extras = new Bundle(); 16765 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 16766 mMoveCallbacks.notifyCreated(realMoveId, extras); 16767 16768 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 16769 @Override 16770 public void onCreated(int moveId, Bundle extras) { 16771 // Ignored 16772 } 16773 16774 @Override 16775 public void onStatusChanged(int moveId, int status, long estMillis) { 16776 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 16777 } 16778 }; 16779 16780 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16781 storage.setPrimaryStorageUuid(volumeUuid, callback); 16782 return realMoveId; 16783 } 16784 16785 @Override 16786 public int getMoveStatus(int moveId) { 16787 mContext.enforceCallingOrSelfPermission( 16788 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16789 return mMoveCallbacks.mLastStatus.get(moveId); 16790 } 16791 16792 @Override 16793 public void registerMoveCallback(IPackageMoveObserver callback) { 16794 mContext.enforceCallingOrSelfPermission( 16795 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16796 mMoveCallbacks.register(callback); 16797 } 16798 16799 @Override 16800 public void unregisterMoveCallback(IPackageMoveObserver callback) { 16801 mContext.enforceCallingOrSelfPermission( 16802 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16803 mMoveCallbacks.unregister(callback); 16804 } 16805 16806 @Override 16807 public boolean setInstallLocation(int loc) { 16808 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 16809 null); 16810 if (getInstallLocation() == loc) { 16811 return true; 16812 } 16813 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 16814 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 16815 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 16816 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 16817 return true; 16818 } 16819 return false; 16820 } 16821 16822 @Override 16823 public int getInstallLocation() { 16824 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 16825 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 16826 PackageHelper.APP_INSTALL_AUTO); 16827 } 16828 16829 /** Called by UserManagerService */ 16830 void cleanUpUser(UserManagerService userManager, int userHandle) { 16831 synchronized (mPackages) { 16832 mDirtyUsers.remove(userHandle); 16833 mUserNeedsBadging.delete(userHandle); 16834 mSettings.removeUserLPw(userHandle); 16835 mPendingBroadcasts.remove(userHandle); 16836 } 16837 synchronized (mInstallLock) { 16838 if (mInstaller != null) { 16839 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16840 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 16841 final String volumeUuid = vol.getFsUuid(); 16842 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 16843 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 16844 } 16845 } 16846 synchronized (mPackages) { 16847 removeUnusedPackagesLILPw(userManager, userHandle); 16848 } 16849 } 16850 } 16851 16852 /** 16853 * We're removing userHandle and would like to remove any downloaded packages 16854 * that are no longer in use by any other user. 16855 * @param userHandle the user being removed 16856 */ 16857 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 16858 final boolean DEBUG_CLEAN_APKS = false; 16859 int [] users = userManager.getUserIds(); 16860 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 16861 while (psit.hasNext()) { 16862 PackageSetting ps = psit.next(); 16863 if (ps.pkg == null) { 16864 continue; 16865 } 16866 final String packageName = ps.pkg.packageName; 16867 // Skip over if system app 16868 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 16869 continue; 16870 } 16871 if (DEBUG_CLEAN_APKS) { 16872 Slog.i(TAG, "Checking package " + packageName); 16873 } 16874 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 16875 if (keep) { 16876 if (DEBUG_CLEAN_APKS) { 16877 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 16878 } 16879 } else { 16880 for (int i = 0; i < users.length; i++) { 16881 if (users[i] != userHandle && ps.getInstalled(users[i])) { 16882 keep = true; 16883 if (DEBUG_CLEAN_APKS) { 16884 Slog.i(TAG, " Keeping package " + packageName + " for user " 16885 + users[i]); 16886 } 16887 break; 16888 } 16889 } 16890 } 16891 if (!keep) { 16892 if (DEBUG_CLEAN_APKS) { 16893 Slog.i(TAG, " Removing package " + packageName); 16894 } 16895 mHandler.post(new Runnable() { 16896 public void run() { 16897 deletePackageX(packageName, userHandle, 0); 16898 } //end run 16899 }); 16900 } 16901 } 16902 } 16903 16904 /** Called by UserManagerService */ 16905 void createNewUser(int userHandle) { 16906 if (mInstaller != null) { 16907 synchronized (mInstallLock) { 16908 synchronized (mPackages) { 16909 mInstaller.createUserConfig(userHandle); 16910 mSettings.createNewUserLILPw(this, mInstaller, userHandle); 16911 } 16912 } 16913 synchronized (mPackages) { 16914 applyFactoryDefaultBrowserLPw(userHandle); 16915 primeDomainVerificationsLPw(userHandle); 16916 } 16917 } 16918 } 16919 16920 void newUserCreated(final int userHandle) { 16921 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 16922 // If permission review for legacy apps is required, we represent 16923 // dagerous permissions for such apps as always granted runtime 16924 // permissions to keep per user flag state whether review is needed. 16925 // Hence, if a new user is added we have to propagate dangerous 16926 // permission grants for these legacy apps. 16927 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 16928 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 16929 | UPDATE_PERMISSIONS_REPLACE_ALL); 16930 } 16931 } 16932 16933 @Override 16934 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 16935 mContext.enforceCallingOrSelfPermission( 16936 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 16937 "Only package verification agents can read the verifier device identity"); 16938 16939 synchronized (mPackages) { 16940 return mSettings.getVerifierDeviceIdentityLPw(); 16941 } 16942 } 16943 16944 @Override 16945 public void setPermissionEnforced(String permission, boolean enforced) { 16946 // TODO: Now that we no longer change GID for storage, this should to away. 16947 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 16948 "setPermissionEnforced"); 16949 if (READ_EXTERNAL_STORAGE.equals(permission)) { 16950 synchronized (mPackages) { 16951 if (mSettings.mReadExternalStorageEnforced == null 16952 || mSettings.mReadExternalStorageEnforced != enforced) { 16953 mSettings.mReadExternalStorageEnforced = enforced; 16954 mSettings.writeLPr(); 16955 } 16956 } 16957 // kill any non-foreground processes so we restart them and 16958 // grant/revoke the GID. 16959 final IActivityManager am = ActivityManagerNative.getDefault(); 16960 if (am != null) { 16961 final long token = Binder.clearCallingIdentity(); 16962 try { 16963 am.killProcessesBelowForeground("setPermissionEnforcement"); 16964 } catch (RemoteException e) { 16965 } finally { 16966 Binder.restoreCallingIdentity(token); 16967 } 16968 } 16969 } else { 16970 throw new IllegalArgumentException("No selective enforcement for " + permission); 16971 } 16972 } 16973 16974 @Override 16975 @Deprecated 16976 public boolean isPermissionEnforced(String permission) { 16977 return true; 16978 } 16979 16980 @Override 16981 public boolean isStorageLow() { 16982 final long token = Binder.clearCallingIdentity(); 16983 try { 16984 final DeviceStorageMonitorInternal 16985 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 16986 if (dsm != null) { 16987 return dsm.isMemoryLow(); 16988 } else { 16989 return false; 16990 } 16991 } finally { 16992 Binder.restoreCallingIdentity(token); 16993 } 16994 } 16995 16996 @Override 16997 public IPackageInstaller getPackageInstaller() { 16998 return mInstallerService; 16999 } 17000 17001 private boolean userNeedsBadging(int userId) { 17002 int index = mUserNeedsBadging.indexOfKey(userId); 17003 if (index < 0) { 17004 final UserInfo userInfo; 17005 final long token = Binder.clearCallingIdentity(); 17006 try { 17007 userInfo = sUserManager.getUserInfo(userId); 17008 } finally { 17009 Binder.restoreCallingIdentity(token); 17010 } 17011 final boolean b; 17012 if (userInfo != null && userInfo.isManagedProfile()) { 17013 b = true; 17014 } else { 17015 b = false; 17016 } 17017 mUserNeedsBadging.put(userId, b); 17018 return b; 17019 } 17020 return mUserNeedsBadging.valueAt(index); 17021 } 17022 17023 @Override 17024 public KeySet getKeySetByAlias(String packageName, String alias) { 17025 if (packageName == null || alias == null) { 17026 return null; 17027 } 17028 synchronized(mPackages) { 17029 final PackageParser.Package pkg = mPackages.get(packageName); 17030 if (pkg == null) { 17031 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 17032 throw new IllegalArgumentException("Unknown package: " + packageName); 17033 } 17034 KeySetManagerService ksms = mSettings.mKeySetManagerService; 17035 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 17036 } 17037 } 17038 17039 @Override 17040 public KeySet getSigningKeySet(String packageName) { 17041 if (packageName == null) { 17042 return null; 17043 } 17044 synchronized(mPackages) { 17045 final PackageParser.Package pkg = mPackages.get(packageName); 17046 if (pkg == null) { 17047 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 17048 throw new IllegalArgumentException("Unknown package: " + packageName); 17049 } 17050 if (pkg.applicationInfo.uid != Binder.getCallingUid() 17051 && Process.SYSTEM_UID != Binder.getCallingUid()) { 17052 throw new SecurityException("May not access signing KeySet of other apps."); 17053 } 17054 KeySetManagerService ksms = mSettings.mKeySetManagerService; 17055 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 17056 } 17057 } 17058 17059 @Override 17060 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 17061 if (packageName == null || ks == null) { 17062 return false; 17063 } 17064 synchronized(mPackages) { 17065 final PackageParser.Package pkg = mPackages.get(packageName); 17066 if (pkg == null) { 17067 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 17068 throw new IllegalArgumentException("Unknown package: " + packageName); 17069 } 17070 IBinder ksh = ks.getToken(); 17071 if (ksh instanceof KeySetHandle) { 17072 KeySetManagerService ksms = mSettings.mKeySetManagerService; 17073 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 17074 } 17075 return false; 17076 } 17077 } 17078 17079 @Override 17080 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 17081 if (packageName == null || ks == null) { 17082 return false; 17083 } 17084 synchronized(mPackages) { 17085 final PackageParser.Package pkg = mPackages.get(packageName); 17086 if (pkg == null) { 17087 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 17088 throw new IllegalArgumentException("Unknown package: " + packageName); 17089 } 17090 IBinder ksh = ks.getToken(); 17091 if (ksh instanceof KeySetHandle) { 17092 KeySetManagerService ksms = mSettings.mKeySetManagerService; 17093 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 17094 } 17095 return false; 17096 } 17097 } 17098 17099 private void deletePackageIfUnusedLPr(final String packageName) { 17100 PackageSetting ps = mSettings.mPackages.get(packageName); 17101 if (ps == null) { 17102 return; 17103 } 17104 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 17105 // TODO Implement atomic delete if package is unused 17106 // It is currently possible that the package will be deleted even if it is installed 17107 // after this method returns. 17108 mHandler.post(new Runnable() { 17109 public void run() { 17110 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 17111 } 17112 }); 17113 } 17114 } 17115 17116 /** 17117 * Check and throw if the given before/after packages would be considered a 17118 * downgrade. 17119 */ 17120 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 17121 throws PackageManagerException { 17122 if (after.versionCode < before.mVersionCode) { 17123 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 17124 "Update version code " + after.versionCode + " is older than current " 17125 + before.mVersionCode); 17126 } else if (after.versionCode == before.mVersionCode) { 17127 if (after.baseRevisionCode < before.baseRevisionCode) { 17128 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 17129 "Update base revision code " + after.baseRevisionCode 17130 + " is older than current " + before.baseRevisionCode); 17131 } 17132 17133 if (!ArrayUtils.isEmpty(after.splitNames)) { 17134 for (int i = 0; i < after.splitNames.length; i++) { 17135 final String splitName = after.splitNames[i]; 17136 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 17137 if (j != -1) { 17138 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 17139 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 17140 "Update split " + splitName + " revision code " 17141 + after.splitRevisionCodes[i] + " is older than current " 17142 + before.splitRevisionCodes[j]); 17143 } 17144 } 17145 } 17146 } 17147 } 17148 } 17149 17150 private static class MoveCallbacks extends Handler { 17151 private static final int MSG_CREATED = 1; 17152 private static final int MSG_STATUS_CHANGED = 2; 17153 17154 private final RemoteCallbackList<IPackageMoveObserver> 17155 mCallbacks = new RemoteCallbackList<>(); 17156 17157 private final SparseIntArray mLastStatus = new SparseIntArray(); 17158 17159 public MoveCallbacks(Looper looper) { 17160 super(looper); 17161 } 17162 17163 public void register(IPackageMoveObserver callback) { 17164 mCallbacks.register(callback); 17165 } 17166 17167 public void unregister(IPackageMoveObserver callback) { 17168 mCallbacks.unregister(callback); 17169 } 17170 17171 @Override 17172 public void handleMessage(Message msg) { 17173 final SomeArgs args = (SomeArgs) msg.obj; 17174 final int n = mCallbacks.beginBroadcast(); 17175 for (int i = 0; i < n; i++) { 17176 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 17177 try { 17178 invokeCallback(callback, msg.what, args); 17179 } catch (RemoteException ignored) { 17180 } 17181 } 17182 mCallbacks.finishBroadcast(); 17183 args.recycle(); 17184 } 17185 17186 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 17187 throws RemoteException { 17188 switch (what) { 17189 case MSG_CREATED: { 17190 callback.onCreated(args.argi1, (Bundle) args.arg2); 17191 break; 17192 } 17193 case MSG_STATUS_CHANGED: { 17194 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 17195 break; 17196 } 17197 } 17198 } 17199 17200 private void notifyCreated(int moveId, Bundle extras) { 17201 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 17202 17203 final SomeArgs args = SomeArgs.obtain(); 17204 args.argi1 = moveId; 17205 args.arg2 = extras; 17206 obtainMessage(MSG_CREATED, args).sendToTarget(); 17207 } 17208 17209 private void notifyStatusChanged(int moveId, int status) { 17210 notifyStatusChanged(moveId, status, -1); 17211 } 17212 17213 private void notifyStatusChanged(int moveId, int status, long estMillis) { 17214 Slog.v(TAG, "Move " + moveId + " status " + status); 17215 17216 final SomeArgs args = SomeArgs.obtain(); 17217 args.argi1 = moveId; 17218 args.argi2 = status; 17219 args.arg3 = estMillis; 17220 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 17221 17222 synchronized (mLastStatus) { 17223 mLastStatus.put(moveId, status); 17224 } 17225 } 17226 } 17227 17228 private final class OnPermissionChangeListeners extends Handler { 17229 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 17230 17231 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 17232 new RemoteCallbackList<>(); 17233 17234 public OnPermissionChangeListeners(Looper looper) { 17235 super(looper); 17236 } 17237 17238 @Override 17239 public void handleMessage(Message msg) { 17240 switch (msg.what) { 17241 case MSG_ON_PERMISSIONS_CHANGED: { 17242 final int uid = msg.arg1; 17243 handleOnPermissionsChanged(uid); 17244 } break; 17245 } 17246 } 17247 17248 public void addListenerLocked(IOnPermissionsChangeListener listener) { 17249 mPermissionListeners.register(listener); 17250 17251 } 17252 17253 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 17254 mPermissionListeners.unregister(listener); 17255 } 17256 17257 public void onPermissionsChanged(int uid) { 17258 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 17259 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 17260 } 17261 } 17262 17263 private void handleOnPermissionsChanged(int uid) { 17264 final int count = mPermissionListeners.beginBroadcast(); 17265 try { 17266 for (int i = 0; i < count; i++) { 17267 IOnPermissionsChangeListener callback = mPermissionListeners 17268 .getBroadcastItem(i); 17269 try { 17270 callback.onPermissionsChanged(uid); 17271 } catch (RemoteException e) { 17272 Log.e(TAG, "Permission listener is dead", e); 17273 } 17274 } 17275 } finally { 17276 mPermissionListeners.finishBroadcast(); 17277 } 17278 } 17279 } 17280 17281 private class PackageManagerInternalImpl extends PackageManagerInternal { 17282 @Override 17283 public void setLocationPackagesProvider(PackagesProvider provider) { 17284 synchronized (mPackages) { 17285 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 17286 } 17287 } 17288 17289 @Override 17290 public void setImePackagesProvider(PackagesProvider provider) { 17291 synchronized (mPackages) { 17292 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 17293 } 17294 } 17295 17296 @Override 17297 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 17298 synchronized (mPackages) { 17299 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 17300 } 17301 } 17302 17303 @Override 17304 public void setSmsAppPackagesProvider(PackagesProvider provider) { 17305 synchronized (mPackages) { 17306 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 17307 } 17308 } 17309 17310 @Override 17311 public void setDialerAppPackagesProvider(PackagesProvider provider) { 17312 synchronized (mPackages) { 17313 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 17314 } 17315 } 17316 17317 @Override 17318 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 17319 synchronized (mPackages) { 17320 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 17321 } 17322 } 17323 17324 @Override 17325 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 17326 synchronized (mPackages) { 17327 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 17328 } 17329 } 17330 17331 @Override 17332 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 17333 synchronized (mPackages) { 17334 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 17335 packageName, userId); 17336 } 17337 } 17338 17339 @Override 17340 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 17341 synchronized (mPackages) { 17342 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 17343 packageName, userId); 17344 } 17345 } 17346 17347 @Override 17348 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 17349 synchronized (mPackages) { 17350 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 17351 packageName, userId); 17352 } 17353 } 17354 17355 @Override 17356 public void setKeepUninstalledPackages(final List<String> packageList) { 17357 Preconditions.checkNotNull(packageList); 17358 List<String> removedFromList = null; 17359 synchronized (mPackages) { 17360 if (mKeepUninstalledPackages != null) { 17361 final int packagesCount = mKeepUninstalledPackages.size(); 17362 for (int i = 0; i < packagesCount; i++) { 17363 String oldPackage = mKeepUninstalledPackages.get(i); 17364 if (packageList != null && packageList.contains(oldPackage)) { 17365 continue; 17366 } 17367 if (removedFromList == null) { 17368 removedFromList = new ArrayList<>(); 17369 } 17370 removedFromList.add(oldPackage); 17371 } 17372 } 17373 mKeepUninstalledPackages = new ArrayList<>(packageList); 17374 if (removedFromList != null) { 17375 final int removedCount = removedFromList.size(); 17376 for (int i = 0; i < removedCount; i++) { 17377 deletePackageIfUnusedLPr(removedFromList.get(i)); 17378 } 17379 } 17380 } 17381 } 17382 17383 @Override 17384 public boolean isPermissionsReviewRequired(String packageName, int userId) { 17385 synchronized (mPackages) { 17386 // If we do not support permission review, done. 17387 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 17388 return false; 17389 } 17390 17391 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 17392 if (packageSetting == null) { 17393 return false; 17394 } 17395 17396 // Permission review applies only to apps not supporting the new permission model. 17397 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 17398 return false; 17399 } 17400 17401 // Legacy apps have the permission and get user consent on launch. 17402 PermissionsState permissionsState = packageSetting.getPermissionsState(); 17403 return permissionsState.isPermissionReviewRequired(userId); 17404 } 17405 } 17406 } 17407 17408 @Override 17409 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 17410 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 17411 synchronized (mPackages) { 17412 final long identity = Binder.clearCallingIdentity(); 17413 try { 17414 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 17415 packageNames, userId); 17416 } finally { 17417 Binder.restoreCallingIdentity(identity); 17418 } 17419 } 17420 } 17421 17422 private static void enforceSystemOrPhoneCaller(String tag) { 17423 int callingUid = Binder.getCallingUid(); 17424 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 17425 throw new SecurityException( 17426 "Cannot call " + tag + " from UID " + callingUid); 17427 } 17428 } 17429} 17430