PackageManagerService.java revision 9352af2a9ef95e3f577a04474625249d3da62a04
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_REVOKE_ON_UPGRADE; 30import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 31import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 32import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 33import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 34import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 35import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 36import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 37import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 39import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 40import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 41import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 42import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 43import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 44import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 45import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 46import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 47import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 48import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED; 49import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 50import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 51import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 52import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 53import static android.content.pm.PackageManager.INSTALL_INTERNAL; 54import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 55import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 59import static android.content.pm.PackageManager.MATCH_ALL; 60import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 61import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 62import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 63import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 64import static android.content.pm.PackageManager.PERMISSION_DENIED; 65import static android.content.pm.PackageManager.PERMISSION_GRANTED; 66import static android.content.pm.PackageParser.isApkFile; 67import static android.os.Process.PACKAGE_INFO_GID; 68import static android.os.Process.SYSTEM_UID; 69import static android.system.OsConstants.O_CREAT; 70import static android.system.OsConstants.O_RDWR; 71import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 72import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER; 73import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 74import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 75import static com.android.internal.util.ArrayUtils.appendInt; 76import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 77import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 78import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 79import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 80import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 81import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 82import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 83import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 84 85import android.Manifest; 86import android.app.ActivityManager; 87import android.app.ActivityManagerNative; 88import android.app.AppGlobals; 89import android.app.IActivityManager; 90import android.app.admin.IDevicePolicyManager; 91import android.app.backup.IBackupManager; 92import android.app.usage.UsageStats; 93import android.app.usage.UsageStatsManager; 94import android.content.BroadcastReceiver; 95import android.content.ComponentName; 96import android.content.Context; 97import android.content.IIntentReceiver; 98import android.content.Intent; 99import android.content.IntentFilter; 100import android.content.IntentSender; 101import android.content.IntentSender.SendIntentException; 102import android.content.ServiceConnection; 103import android.content.pm.ActivityInfo; 104import android.content.pm.ApplicationInfo; 105import android.content.pm.FeatureInfo; 106import android.content.pm.IOnPermissionsChangeListener; 107import android.content.pm.IPackageDataObserver; 108import android.content.pm.IPackageDeleteObserver; 109import android.content.pm.IPackageDeleteObserver2; 110import android.content.pm.IPackageInstallObserver2; 111import android.content.pm.IPackageInstaller; 112import android.content.pm.IPackageManager; 113import android.content.pm.IPackageMoveObserver; 114import android.content.pm.IPackageStatsObserver; 115import android.content.pm.InstrumentationInfo; 116import android.content.pm.IntentFilterVerificationInfo; 117import android.content.pm.KeySet; 118import android.content.pm.ManifestDigest; 119import android.content.pm.PackageCleanItem; 120import android.content.pm.PackageInfo; 121import android.content.pm.PackageInfoLite; 122import android.content.pm.PackageInstaller; 123import android.content.pm.PackageManager; 124import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 125import android.content.pm.PackageManagerInternal; 126import android.content.pm.PackageParser; 127import android.content.pm.PackageParser.ActivityIntentInfo; 128import android.content.pm.PackageParser.PackageLite; 129import android.content.pm.PackageParser.PackageParserException; 130import android.content.pm.PackageStats; 131import android.content.pm.PackageUserState; 132import android.content.pm.ParceledListSlice; 133import android.content.pm.PermissionGroupInfo; 134import android.content.pm.PermissionInfo; 135import android.content.pm.ProviderInfo; 136import android.content.pm.ResolveInfo; 137import android.content.pm.ServiceInfo; 138import android.content.pm.Signature; 139import android.content.pm.UserInfo; 140import android.content.pm.VerificationParams; 141import android.content.pm.VerifierDeviceIdentity; 142import android.content.pm.VerifierInfo; 143import android.content.res.Resources; 144import android.hardware.display.DisplayManager; 145import android.net.Uri; 146import android.os.Debug; 147import android.os.Binder; 148import android.os.Build; 149import android.os.Bundle; 150import android.os.Environment; 151import android.os.Environment.UserEnvironment; 152import android.os.FileUtils; 153import android.os.Handler; 154import android.os.IBinder; 155import android.os.Looper; 156import android.os.Message; 157import android.os.Parcel; 158import android.os.ParcelFileDescriptor; 159import android.os.Process; 160import android.os.RemoteCallbackList; 161import android.os.RemoteException; 162import android.os.SELinux; 163import android.os.ServiceManager; 164import android.os.SystemClock; 165import android.os.SystemProperties; 166import android.os.UserHandle; 167import android.os.UserManager; 168import android.os.storage.IMountService; 169import android.os.storage.MountServiceInternal; 170import android.os.storage.StorageEventListener; 171import android.os.storage.StorageManager; 172import android.os.storage.VolumeInfo; 173import android.os.storage.VolumeRecord; 174import android.security.KeyStore; 175import android.security.SystemKeyStore; 176import android.system.ErrnoException; 177import android.system.Os; 178import android.system.StructStat; 179import android.text.TextUtils; 180import android.text.format.DateUtils; 181import android.util.ArrayMap; 182import android.util.ArraySet; 183import android.util.AtomicFile; 184import android.util.DisplayMetrics; 185import android.util.EventLog; 186import android.util.ExceptionUtils; 187import android.util.Log; 188import android.util.LogPrinter; 189import android.util.MathUtils; 190import android.util.PrintStreamPrinter; 191import android.util.Slog; 192import android.util.SparseArray; 193import android.util.SparseBooleanArray; 194import android.util.SparseIntArray; 195import android.util.Xml; 196import android.view.Display; 197 198import dalvik.system.DexFile; 199import dalvik.system.VMRuntime; 200 201import libcore.io.IoUtils; 202import libcore.util.EmptyArray; 203 204import com.android.internal.R; 205import com.android.internal.annotations.GuardedBy; 206import com.android.internal.app.IMediaContainerService; 207import com.android.internal.app.ResolverActivity; 208import com.android.internal.content.NativeLibraryHelper; 209import com.android.internal.content.PackageHelper; 210import com.android.internal.os.IParcelFileDescriptorFactory; 211import com.android.internal.os.SomeArgs; 212import com.android.internal.os.Zygote; 213import com.android.internal.util.ArrayUtils; 214import com.android.internal.util.FastPrintWriter; 215import com.android.internal.util.FastXmlSerializer; 216import com.android.internal.util.IndentingPrintWriter; 217import com.android.internal.util.Preconditions; 218import com.android.server.EventLogTags; 219import com.android.server.FgThread; 220import com.android.server.IntentResolver; 221import com.android.server.LocalServices; 222import com.android.server.ServiceThread; 223import com.android.server.SystemConfig; 224import com.android.server.Watchdog; 225import com.android.server.pm.PermissionsState.PermissionState; 226import com.android.server.pm.Settings.DatabaseVersion; 227import com.android.server.pm.Settings.VersionInfo; 228import com.android.server.storage.DeviceStorageMonitorInternal; 229 230import org.xmlpull.v1.XmlPullParser; 231import org.xmlpull.v1.XmlPullParserException; 232import org.xmlpull.v1.XmlSerializer; 233 234import java.io.BufferedInputStream; 235import java.io.BufferedOutputStream; 236import java.io.BufferedReader; 237import java.io.ByteArrayInputStream; 238import java.io.ByteArrayOutputStream; 239import java.io.File; 240import java.io.FileDescriptor; 241import java.io.FileNotFoundException; 242import java.io.FileOutputStream; 243import java.io.FileReader; 244import java.io.FilenameFilter; 245import java.io.IOException; 246import java.io.InputStream; 247import java.io.PrintWriter; 248import java.nio.charset.StandardCharsets; 249import java.security.NoSuchAlgorithmException; 250import java.security.PublicKey; 251import java.security.cert.CertificateEncodingException; 252import java.security.cert.CertificateException; 253import java.text.SimpleDateFormat; 254import java.util.ArrayList; 255import java.util.Arrays; 256import java.util.Collection; 257import java.util.Collections; 258import java.util.Comparator; 259import java.util.Date; 260import java.util.Iterator; 261import java.util.List; 262import java.util.Map; 263import java.util.Objects; 264import java.util.Set; 265import java.util.concurrent.CountDownLatch; 266import java.util.concurrent.TimeUnit; 267import java.util.concurrent.atomic.AtomicBoolean; 268import java.util.concurrent.atomic.AtomicInteger; 269import java.util.concurrent.atomic.AtomicLong; 270 271/** 272 * Keep track of all those .apks everywhere. 273 * 274 * This is very central to the platform's security; please run the unit 275 * tests whenever making modifications here: 276 * 277mmm frameworks/base/tests/AndroidTests 278adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 279adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 280 * 281 * {@hide} 282 */ 283public class PackageManagerService extends IPackageManager.Stub { 284 static final String TAG = "PackageManager"; 285 static final boolean DEBUG_SETTINGS = false; 286 static final boolean DEBUG_PREFERRED = false; 287 static final boolean DEBUG_UPGRADE = false; 288 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 289 private static final boolean DEBUG_BACKUP = false; 290 private static final boolean DEBUG_INSTALL = false; 291 private static final boolean DEBUG_REMOVE = false; 292 private static final boolean DEBUG_BROADCASTS = false; 293 private static final boolean DEBUG_SHOW_INFO = false; 294 private static final boolean DEBUG_PACKAGE_INFO = false; 295 private static final boolean DEBUG_INTENT_MATCHING = false; 296 private static final boolean DEBUG_PACKAGE_SCANNING = false; 297 private static final boolean DEBUG_VERIFY = false; 298 private static final boolean DEBUG_DEXOPT = false; 299 private static final boolean DEBUG_ABI_SELECTION = false; 300 301 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 302 303 private static final int RADIO_UID = Process.PHONE_UID; 304 private static final int LOG_UID = Process.LOG_UID; 305 private static final int NFC_UID = Process.NFC_UID; 306 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 307 private static final int SHELL_UID = Process.SHELL_UID; 308 309 // Cap the size of permission trees that 3rd party apps can define 310 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 311 312 // Suffix used during package installation when copying/moving 313 // package apks to install directory. 314 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 315 316 static final int SCAN_NO_DEX = 1<<1; 317 static final int SCAN_FORCE_DEX = 1<<2; 318 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 319 static final int SCAN_NEW_INSTALL = 1<<4; 320 static final int SCAN_NO_PATHS = 1<<5; 321 static final int SCAN_UPDATE_TIME = 1<<6; 322 static final int SCAN_DEFER_DEX = 1<<7; 323 static final int SCAN_BOOTING = 1<<8; 324 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 325 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 326 static final int SCAN_REPLACING = 1<<11; 327 static final int SCAN_REQUIRE_KNOWN = 1<<12; 328 static final int SCAN_MOVE = 1<<13; 329 static final int SCAN_INITIAL = 1<<14; 330 331 static final int REMOVE_CHATTY = 1<<16; 332 333 private static final int[] EMPTY_INT_ARRAY = new int[0]; 334 335 /** 336 * Timeout (in milliseconds) after which the watchdog should declare that 337 * our handler thread is wedged. The usual default for such things is one 338 * minute but we sometimes do very lengthy I/O operations on this thread, 339 * such as installing multi-gigabyte applications, so ours needs to be longer. 340 */ 341 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 342 343 /** 344 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 345 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 346 * settings entry if available, otherwise we use the hardcoded default. If it's been 347 * more than this long since the last fstrim, we force one during the boot sequence. 348 * 349 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 350 * one gets run at the next available charging+idle time. This final mandatory 351 * no-fstrim check kicks in only of the other scheduling criteria is never met. 352 */ 353 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 354 355 /** 356 * Whether verification is enabled by default. 357 */ 358 private static final boolean DEFAULT_VERIFY_ENABLE = true; 359 360 /** 361 * The default maximum time to wait for the verification agent to return in 362 * milliseconds. 363 */ 364 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 365 366 /** 367 * The default response for package verification timeout. 368 * 369 * This can be either PackageManager.VERIFICATION_ALLOW or 370 * PackageManager.VERIFICATION_REJECT. 371 */ 372 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 373 374 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 375 376 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 377 DEFAULT_CONTAINER_PACKAGE, 378 "com.android.defcontainer.DefaultContainerService"); 379 380 private static final String KILL_APP_REASON_GIDS_CHANGED = 381 "permission grant or revoke changed gids"; 382 383 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 384 "permissions revoked"; 385 386 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 387 388 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 389 390 /** Permission grant: not grant the permission. */ 391 private static final int GRANT_DENIED = 1; 392 393 /** Permission grant: grant the permission as an install permission. */ 394 private static final int GRANT_INSTALL = 2; 395 396 /** Permission grant: grant the permission as an install permission for a legacy app. */ 397 private static final int GRANT_INSTALL_LEGACY = 3; 398 399 /** Permission grant: grant the permission as a runtime one. */ 400 private static final int GRANT_RUNTIME = 4; 401 402 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 403 private static final int GRANT_UPGRADE = 5; 404 405 /** Canonical intent used to identify what counts as a "web browser" app */ 406 private static final Intent sBrowserIntent; 407 static { 408 sBrowserIntent = new Intent(); 409 sBrowserIntent.setAction(Intent.ACTION_VIEW); 410 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 411 sBrowserIntent.setData(Uri.parse("http:")); 412 } 413 414 final ServiceThread mHandlerThread; 415 416 final PackageHandler mHandler; 417 418 /** 419 * Messages for {@link #mHandler} that need to wait for system ready before 420 * being dispatched. 421 */ 422 private ArrayList<Message> mPostSystemReadyMessages; 423 424 final int mSdkVersion = Build.VERSION.SDK_INT; 425 426 final Context mContext; 427 final boolean mFactoryTest; 428 final boolean mOnlyCore; 429 final boolean mLazyDexOpt; 430 final long mDexOptLRUThresholdInMills; 431 final DisplayMetrics mMetrics; 432 final int mDefParseFlags; 433 final String[] mSeparateProcesses; 434 final boolean mIsUpgrade; 435 436 // This is where all application persistent data goes. 437 final File mAppDataDir; 438 439 // This is where all application persistent data goes for secondary users. 440 final File mUserAppDataDir; 441 442 /** The location for ASEC container files on internal storage. */ 443 final String mAsecInternalPath; 444 445 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 446 // LOCK HELD. Can be called with mInstallLock held. 447 @GuardedBy("mInstallLock") 448 final Installer mInstaller; 449 450 /** Directory where installed third-party apps stored */ 451 final File mAppInstallDir; 452 453 /** 454 * Directory to which applications installed internally have their 455 * 32 bit native libraries copied. 456 */ 457 private File mAppLib32InstallDir; 458 459 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 460 // apps. 461 final File mDrmAppPrivateInstallDir; 462 463 // ---------------------------------------------------------------- 464 465 // Lock for state used when installing and doing other long running 466 // operations. Methods that must be called with this lock held have 467 // the suffix "LI". 468 final Object mInstallLock = new Object(); 469 470 // ---------------------------------------------------------------- 471 472 // Keys are String (package name), values are Package. This also serves 473 // as the lock for the global state. Methods that must be called with 474 // this lock held have the prefix "LP". 475 @GuardedBy("mPackages") 476 final ArrayMap<String, PackageParser.Package> mPackages = 477 new ArrayMap<String, PackageParser.Package>(); 478 479 // Tracks available target package names -> overlay package paths. 480 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 481 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 482 483 /** 484 * Tracks new system packages [receiving in an OTA] that we expect to 485 * find updated user-installed versions. Keys are package name, values 486 * are package location. 487 */ 488 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 489 490 final Settings mSettings; 491 boolean mRestoredSettings; 492 493 // System configuration read by SystemConfig. 494 final int[] mGlobalGids; 495 final SparseArray<ArraySet<String>> mSystemPermissions; 496 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 497 498 // If mac_permissions.xml was found for seinfo labeling. 499 boolean mFoundPolicyFile; 500 501 // If a recursive restorecon of /data/data/<pkg> is needed. 502 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 503 504 public static final class SharedLibraryEntry { 505 public final String path; 506 public final String apk; 507 508 SharedLibraryEntry(String _path, String _apk) { 509 path = _path; 510 apk = _apk; 511 } 512 } 513 514 // Currently known shared libraries. 515 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 516 new ArrayMap<String, SharedLibraryEntry>(); 517 518 // All available activities, for your resolving pleasure. 519 final ActivityIntentResolver mActivities = 520 new ActivityIntentResolver(); 521 522 // All available receivers, for your resolving pleasure. 523 final ActivityIntentResolver mReceivers = 524 new ActivityIntentResolver(); 525 526 // All available services, for your resolving pleasure. 527 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 528 529 // All available providers, for your resolving pleasure. 530 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 531 532 // Mapping from provider base names (first directory in content URI codePath) 533 // to the provider information. 534 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 535 new ArrayMap<String, PackageParser.Provider>(); 536 537 // Mapping from instrumentation class names to info about them. 538 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 539 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 540 541 // Mapping from permission names to info about them. 542 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 543 new ArrayMap<String, PackageParser.PermissionGroup>(); 544 545 // Packages whose data we have transfered into another package, thus 546 // should no longer exist. 547 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 548 549 // Broadcast actions that are only available to the system. 550 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 551 552 /** List of packages waiting for verification. */ 553 final SparseArray<PackageVerificationState> mPendingVerification 554 = new SparseArray<PackageVerificationState>(); 555 556 /** Set of packages associated with each app op permission. */ 557 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 558 559 final PackageInstallerService mInstallerService; 560 561 private final PackageDexOptimizer mPackageDexOptimizer; 562 563 private AtomicInteger mNextMoveId = new AtomicInteger(); 564 private final MoveCallbacks mMoveCallbacks; 565 566 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 567 568 // Cache of users who need badging. 569 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 570 571 /** Token for keys in mPendingVerification. */ 572 private int mPendingVerificationToken = 0; 573 574 volatile boolean mSystemReady; 575 volatile boolean mSafeMode; 576 volatile boolean mHasSystemUidErrors; 577 578 ApplicationInfo mAndroidApplication; 579 final ActivityInfo mResolveActivity = new ActivityInfo(); 580 final ResolveInfo mResolveInfo = new ResolveInfo(); 581 ComponentName mResolveComponentName; 582 PackageParser.Package mPlatformPackage; 583 ComponentName mCustomResolverComponentName; 584 585 boolean mResolverReplaced = false; 586 587 private final ComponentName mIntentFilterVerifierComponent; 588 private int mIntentFilterVerificationToken = 0; 589 590 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 591 = new SparseArray<IntentFilterVerificationState>(); 592 593 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 594 new DefaultPermissionGrantPolicy(this); 595 596 private static class IFVerificationParams { 597 PackageParser.Package pkg; 598 boolean replacing; 599 int userId; 600 int verifierUid; 601 602 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 603 int _userId, int _verifierUid) { 604 pkg = _pkg; 605 replacing = _replacing; 606 userId = _userId; 607 replacing = _replacing; 608 verifierUid = _verifierUid; 609 } 610 } 611 612 private interface IntentFilterVerifier<T extends IntentFilter> { 613 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 614 T filter, String packageName); 615 void startVerifications(int userId); 616 void receiveVerificationResponse(int verificationId); 617 } 618 619 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 620 private Context mContext; 621 private ComponentName mIntentFilterVerifierComponent; 622 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 623 624 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 625 mContext = context; 626 mIntentFilterVerifierComponent = verifierComponent; 627 } 628 629 private String getDefaultScheme() { 630 return IntentFilter.SCHEME_HTTPS; 631 } 632 633 @Override 634 public void startVerifications(int userId) { 635 // Launch verifications requests 636 int count = mCurrentIntentFilterVerifications.size(); 637 for (int n=0; n<count; n++) { 638 int verificationId = mCurrentIntentFilterVerifications.get(n); 639 final IntentFilterVerificationState ivs = 640 mIntentFilterVerificationStates.get(verificationId); 641 642 String packageName = ivs.getPackageName(); 643 644 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 645 final int filterCount = filters.size(); 646 ArraySet<String> domainsSet = new ArraySet<>(); 647 for (int m=0; m<filterCount; m++) { 648 PackageParser.ActivityIntentInfo filter = filters.get(m); 649 domainsSet.addAll(filter.getHostsList()); 650 } 651 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 652 synchronized (mPackages) { 653 if (mSettings.createIntentFilterVerificationIfNeededLPw( 654 packageName, domainsList) != null) { 655 scheduleWriteSettingsLocked(); 656 } 657 } 658 sendVerificationRequest(userId, verificationId, ivs); 659 } 660 mCurrentIntentFilterVerifications.clear(); 661 } 662 663 private void sendVerificationRequest(int userId, int verificationId, 664 IntentFilterVerificationState ivs) { 665 666 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 667 verificationIntent.putExtra( 668 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 669 verificationId); 670 verificationIntent.putExtra( 671 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 672 getDefaultScheme()); 673 verificationIntent.putExtra( 674 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 675 ivs.getHostsString()); 676 verificationIntent.putExtra( 677 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 678 ivs.getPackageName()); 679 verificationIntent.setComponent(mIntentFilterVerifierComponent); 680 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 681 682 UserHandle user = new UserHandle(userId); 683 mContext.sendBroadcastAsUser(verificationIntent, user); 684 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 685 "Sending IntentFilter verification broadcast"); 686 } 687 688 public void receiveVerificationResponse(int verificationId) { 689 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 690 691 final boolean verified = ivs.isVerified(); 692 693 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 694 final int count = filters.size(); 695 if (DEBUG_DOMAIN_VERIFICATION) { 696 Slog.i(TAG, "Received verification response " + verificationId 697 + " for " + count + " filters, verified=" + verified); 698 } 699 for (int n=0; n<count; n++) { 700 PackageParser.ActivityIntentInfo filter = filters.get(n); 701 filter.setVerified(verified); 702 703 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 704 + " verified with result:" + verified + " and hosts:" 705 + ivs.getHostsString()); 706 } 707 708 mIntentFilterVerificationStates.remove(verificationId); 709 710 final String packageName = ivs.getPackageName(); 711 IntentFilterVerificationInfo ivi = null; 712 713 synchronized (mPackages) { 714 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 715 } 716 if (ivi == null) { 717 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 718 + verificationId + " packageName:" + packageName); 719 return; 720 } 721 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 722 "Updating IntentFilterVerificationInfo for package " + packageName 723 +" verificationId:" + verificationId); 724 725 synchronized (mPackages) { 726 if (verified) { 727 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 728 } else { 729 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 730 } 731 scheduleWriteSettingsLocked(); 732 733 final int userId = ivs.getUserId(); 734 if (userId != UserHandle.USER_ALL) { 735 final int userStatus = 736 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 737 738 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 739 boolean needUpdate = false; 740 741 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 742 // already been set by the User thru the Disambiguation dialog 743 switch (userStatus) { 744 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 745 if (verified) { 746 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 747 } else { 748 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 749 } 750 needUpdate = true; 751 break; 752 753 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 754 if (verified) { 755 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 756 needUpdate = true; 757 } 758 break; 759 760 default: 761 // Nothing to do 762 } 763 764 if (needUpdate) { 765 mSettings.updateIntentFilterVerificationStatusLPw( 766 packageName, updatedStatus, userId); 767 scheduleWritePackageRestrictionsLocked(userId); 768 } 769 } 770 } 771 } 772 773 @Override 774 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 775 ActivityIntentInfo filter, String packageName) { 776 if (!hasValidDomains(filter)) { 777 return false; 778 } 779 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 780 if (ivs == null) { 781 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 782 packageName); 783 } 784 if (DEBUG_DOMAIN_VERIFICATION) { 785 Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter); 786 } 787 ivs.addFilter(filter); 788 return true; 789 } 790 791 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 792 int userId, int verificationId, String packageName) { 793 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 794 verifierUid, userId, packageName); 795 ivs.setPendingState(); 796 synchronized (mPackages) { 797 mIntentFilterVerificationStates.append(verificationId, ivs); 798 mCurrentIntentFilterVerifications.add(verificationId); 799 } 800 return ivs; 801 } 802 } 803 804 private static boolean hasValidDomains(ActivityIntentInfo filter) { 805 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 806 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 807 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 808 } 809 810 private IntentFilterVerifier mIntentFilterVerifier; 811 812 // Set of pending broadcasts for aggregating enable/disable of components. 813 static class PendingPackageBroadcasts { 814 // for each user id, a map of <package name -> components within that package> 815 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 816 817 public PendingPackageBroadcasts() { 818 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 819 } 820 821 public ArrayList<String> get(int userId, String packageName) { 822 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 823 return packages.get(packageName); 824 } 825 826 public void put(int userId, String packageName, ArrayList<String> components) { 827 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 828 packages.put(packageName, components); 829 } 830 831 public void remove(int userId, String packageName) { 832 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 833 if (packages != null) { 834 packages.remove(packageName); 835 } 836 } 837 838 public void remove(int userId) { 839 mUidMap.remove(userId); 840 } 841 842 public int userIdCount() { 843 return mUidMap.size(); 844 } 845 846 public int userIdAt(int n) { 847 return mUidMap.keyAt(n); 848 } 849 850 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 851 return mUidMap.get(userId); 852 } 853 854 public int size() { 855 // total number of pending broadcast entries across all userIds 856 int num = 0; 857 for (int i = 0; i< mUidMap.size(); i++) { 858 num += mUidMap.valueAt(i).size(); 859 } 860 return num; 861 } 862 863 public void clear() { 864 mUidMap.clear(); 865 } 866 867 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 868 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 869 if (map == null) { 870 map = new ArrayMap<String, ArrayList<String>>(); 871 mUidMap.put(userId, map); 872 } 873 return map; 874 } 875 } 876 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 877 878 // Service Connection to remote media container service to copy 879 // package uri's from external media onto secure containers 880 // or internal storage. 881 private IMediaContainerService mContainerService = null; 882 883 static final int SEND_PENDING_BROADCAST = 1; 884 static final int MCS_BOUND = 3; 885 static final int END_COPY = 4; 886 static final int INIT_COPY = 5; 887 static final int MCS_UNBIND = 6; 888 static final int START_CLEANING_PACKAGE = 7; 889 static final int FIND_INSTALL_LOC = 8; 890 static final int POST_INSTALL = 9; 891 static final int MCS_RECONNECT = 10; 892 static final int MCS_GIVE_UP = 11; 893 static final int UPDATED_MEDIA_STATUS = 12; 894 static final int WRITE_SETTINGS = 13; 895 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 896 static final int PACKAGE_VERIFIED = 15; 897 static final int CHECK_PENDING_VERIFICATION = 16; 898 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 899 static final int INTENT_FILTER_VERIFIED = 18; 900 901 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 902 903 // Delay time in millisecs 904 static final int BROADCAST_DELAY = 10 * 1000; 905 906 static UserManagerService sUserManager; 907 908 // Stores a list of users whose package restrictions file needs to be updated 909 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 910 911 final private DefaultContainerConnection mDefContainerConn = 912 new DefaultContainerConnection(); 913 class DefaultContainerConnection implements ServiceConnection { 914 public void onServiceConnected(ComponentName name, IBinder service) { 915 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 916 IMediaContainerService imcs = 917 IMediaContainerService.Stub.asInterface(service); 918 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 919 } 920 921 public void onServiceDisconnected(ComponentName name) { 922 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 923 } 924 } 925 926 // Recordkeeping of restore-after-install operations that are currently in flight 927 // between the Package Manager and the Backup Manager 928 class PostInstallData { 929 public InstallArgs args; 930 public PackageInstalledInfo res; 931 932 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 933 args = _a; 934 res = _r; 935 } 936 } 937 938 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 939 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 940 941 // XML tags for backup/restore of various bits of state 942 private static final String TAG_PREFERRED_BACKUP = "pa"; 943 private static final String TAG_DEFAULT_APPS = "da"; 944 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 945 946 final String mRequiredVerifierPackage; 947 final String mRequiredInstallerPackage; 948 949 private final PackageUsage mPackageUsage = new PackageUsage(); 950 951 private class PackageUsage { 952 private static final int WRITE_INTERVAL 953 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 954 955 private final Object mFileLock = new Object(); 956 private final AtomicLong mLastWritten = new AtomicLong(0); 957 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 958 959 private boolean mIsHistoricalPackageUsageAvailable = true; 960 961 boolean isHistoricalPackageUsageAvailable() { 962 return mIsHistoricalPackageUsageAvailable; 963 } 964 965 void write(boolean force) { 966 if (force) { 967 writeInternal(); 968 return; 969 } 970 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 971 && !DEBUG_DEXOPT) { 972 return; 973 } 974 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 975 new Thread("PackageUsage_DiskWriter") { 976 @Override 977 public void run() { 978 try { 979 writeInternal(); 980 } finally { 981 mBackgroundWriteRunning.set(false); 982 } 983 } 984 }.start(); 985 } 986 } 987 988 private void writeInternal() { 989 synchronized (mPackages) { 990 synchronized (mFileLock) { 991 AtomicFile file = getFile(); 992 FileOutputStream f = null; 993 try { 994 f = file.startWrite(); 995 BufferedOutputStream out = new BufferedOutputStream(f); 996 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 997 StringBuilder sb = new StringBuilder(); 998 for (PackageParser.Package pkg : mPackages.values()) { 999 if (pkg.mLastPackageUsageTimeInMills == 0) { 1000 continue; 1001 } 1002 sb.setLength(0); 1003 sb.append(pkg.packageName); 1004 sb.append(' '); 1005 sb.append((long)pkg.mLastPackageUsageTimeInMills); 1006 sb.append('\n'); 1007 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1008 } 1009 out.flush(); 1010 file.finishWrite(f); 1011 } catch (IOException e) { 1012 if (f != null) { 1013 file.failWrite(f); 1014 } 1015 Log.e(TAG, "Failed to write package usage times", e); 1016 } 1017 } 1018 } 1019 mLastWritten.set(SystemClock.elapsedRealtime()); 1020 } 1021 1022 void readLP() { 1023 synchronized (mFileLock) { 1024 AtomicFile file = getFile(); 1025 BufferedInputStream in = null; 1026 try { 1027 in = new BufferedInputStream(file.openRead()); 1028 StringBuffer sb = new StringBuffer(); 1029 while (true) { 1030 String packageName = readToken(in, sb, ' '); 1031 if (packageName == null) { 1032 break; 1033 } 1034 String timeInMillisString = readToken(in, sb, '\n'); 1035 if (timeInMillisString == null) { 1036 throw new IOException("Failed to find last usage time for package " 1037 + packageName); 1038 } 1039 PackageParser.Package pkg = mPackages.get(packageName); 1040 if (pkg == null) { 1041 continue; 1042 } 1043 long timeInMillis; 1044 try { 1045 timeInMillis = Long.parseLong(timeInMillisString.toString()); 1046 } catch (NumberFormatException e) { 1047 throw new IOException("Failed to parse " + timeInMillisString 1048 + " as a long.", e); 1049 } 1050 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1051 } 1052 } catch (FileNotFoundException expected) { 1053 mIsHistoricalPackageUsageAvailable = false; 1054 } catch (IOException e) { 1055 Log.w(TAG, "Failed to read package usage times", e); 1056 } finally { 1057 IoUtils.closeQuietly(in); 1058 } 1059 } 1060 mLastWritten.set(SystemClock.elapsedRealtime()); 1061 } 1062 1063 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1064 throws IOException { 1065 sb.setLength(0); 1066 while (true) { 1067 int ch = in.read(); 1068 if (ch == -1) { 1069 if (sb.length() == 0) { 1070 return null; 1071 } 1072 throw new IOException("Unexpected EOF"); 1073 } 1074 if (ch == endOfToken) { 1075 return sb.toString(); 1076 } 1077 sb.append((char)ch); 1078 } 1079 } 1080 1081 private AtomicFile getFile() { 1082 File dataDir = Environment.getDataDirectory(); 1083 File systemDir = new File(dataDir, "system"); 1084 File fname = new File(systemDir, "package-usage.list"); 1085 return new AtomicFile(fname); 1086 } 1087 } 1088 1089 class PackageHandler extends Handler { 1090 private boolean mBound = false; 1091 final ArrayList<HandlerParams> mPendingInstalls = 1092 new ArrayList<HandlerParams>(); 1093 1094 private boolean connectToService() { 1095 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1096 " DefaultContainerService"); 1097 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1098 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1099 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1100 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 1101 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1102 mBound = true; 1103 return true; 1104 } 1105 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1106 return false; 1107 } 1108 1109 private void disconnectService() { 1110 mContainerService = null; 1111 mBound = false; 1112 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1113 mContext.unbindService(mDefContainerConn); 1114 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1115 } 1116 1117 PackageHandler(Looper looper) { 1118 super(looper); 1119 } 1120 1121 public void handleMessage(Message msg) { 1122 try { 1123 doHandleMessage(msg); 1124 } finally { 1125 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1126 } 1127 } 1128 1129 void doHandleMessage(Message msg) { 1130 switch (msg.what) { 1131 case INIT_COPY: { 1132 HandlerParams params = (HandlerParams) msg.obj; 1133 int idx = mPendingInstalls.size(); 1134 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1135 // If a bind was already initiated we dont really 1136 // need to do anything. The pending install 1137 // will be processed later on. 1138 if (!mBound) { 1139 // If this is the only one pending we might 1140 // have to bind to the service again. 1141 if (!connectToService()) { 1142 Slog.e(TAG, "Failed to bind to media container service"); 1143 params.serviceError(); 1144 return; 1145 } else { 1146 // Once we bind to the service, the first 1147 // pending request will be processed. 1148 mPendingInstalls.add(idx, params); 1149 } 1150 } else { 1151 mPendingInstalls.add(idx, params); 1152 // Already bound to the service. Just make 1153 // sure we trigger off processing the first request. 1154 if (idx == 0) { 1155 mHandler.sendEmptyMessage(MCS_BOUND); 1156 } 1157 } 1158 break; 1159 } 1160 case MCS_BOUND: { 1161 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1162 if (msg.obj != null) { 1163 mContainerService = (IMediaContainerService) msg.obj; 1164 } 1165 if (mContainerService == null) { 1166 if (!mBound) { 1167 // Something seriously wrong since we are not bound and we are not 1168 // waiting for connection. Bail out. 1169 Slog.e(TAG, "Cannot bind to media container service"); 1170 for (HandlerParams params : mPendingInstalls) { 1171 // Indicate service bind error 1172 params.serviceError(); 1173 } 1174 mPendingInstalls.clear(); 1175 } else { 1176 Slog.w(TAG, "Waiting to connect to media container service"); 1177 } 1178 } else if (mPendingInstalls.size() > 0) { 1179 HandlerParams params = mPendingInstalls.get(0); 1180 if (params != null) { 1181 if (params.startCopy()) { 1182 // We are done... look for more work or to 1183 // go idle. 1184 if (DEBUG_SD_INSTALL) Log.i(TAG, 1185 "Checking for more work or unbind..."); 1186 // Delete pending install 1187 if (mPendingInstalls.size() > 0) { 1188 mPendingInstalls.remove(0); 1189 } 1190 if (mPendingInstalls.size() == 0) { 1191 if (mBound) { 1192 if (DEBUG_SD_INSTALL) Log.i(TAG, 1193 "Posting delayed MCS_UNBIND"); 1194 removeMessages(MCS_UNBIND); 1195 Message ubmsg = obtainMessage(MCS_UNBIND); 1196 // Unbind after a little delay, to avoid 1197 // continual thrashing. 1198 sendMessageDelayed(ubmsg, 10000); 1199 } 1200 } else { 1201 // There are more pending requests in queue. 1202 // Just post MCS_BOUND message to trigger processing 1203 // of next pending install. 1204 if (DEBUG_SD_INSTALL) Log.i(TAG, 1205 "Posting MCS_BOUND for next work"); 1206 mHandler.sendEmptyMessage(MCS_BOUND); 1207 } 1208 } 1209 } 1210 } else { 1211 // Should never happen ideally. 1212 Slog.w(TAG, "Empty queue"); 1213 } 1214 break; 1215 } 1216 case MCS_RECONNECT: { 1217 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1218 if (mPendingInstalls.size() > 0) { 1219 if (mBound) { 1220 disconnectService(); 1221 } 1222 if (!connectToService()) { 1223 Slog.e(TAG, "Failed to bind to media container service"); 1224 for (HandlerParams params : mPendingInstalls) { 1225 // Indicate service bind error 1226 params.serviceError(); 1227 } 1228 mPendingInstalls.clear(); 1229 } 1230 } 1231 break; 1232 } 1233 case MCS_UNBIND: { 1234 // If there is no actual work left, then time to unbind. 1235 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1236 1237 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1238 if (mBound) { 1239 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1240 1241 disconnectService(); 1242 } 1243 } else if (mPendingInstalls.size() > 0) { 1244 // There are more pending requests in queue. 1245 // Just post MCS_BOUND message to trigger processing 1246 // of next pending install. 1247 mHandler.sendEmptyMessage(MCS_BOUND); 1248 } 1249 1250 break; 1251 } 1252 case MCS_GIVE_UP: { 1253 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1254 mPendingInstalls.remove(0); 1255 break; 1256 } 1257 case SEND_PENDING_BROADCAST: { 1258 String packages[]; 1259 ArrayList<String> components[]; 1260 int size = 0; 1261 int uids[]; 1262 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1263 synchronized (mPackages) { 1264 if (mPendingBroadcasts == null) { 1265 return; 1266 } 1267 size = mPendingBroadcasts.size(); 1268 if (size <= 0) { 1269 // Nothing to be done. Just return 1270 return; 1271 } 1272 packages = new String[size]; 1273 components = new ArrayList[size]; 1274 uids = new int[size]; 1275 int i = 0; // filling out the above arrays 1276 1277 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1278 int packageUserId = mPendingBroadcasts.userIdAt(n); 1279 Iterator<Map.Entry<String, ArrayList<String>>> it 1280 = mPendingBroadcasts.packagesForUserId(packageUserId) 1281 .entrySet().iterator(); 1282 while (it.hasNext() && i < size) { 1283 Map.Entry<String, ArrayList<String>> ent = it.next(); 1284 packages[i] = ent.getKey(); 1285 components[i] = ent.getValue(); 1286 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1287 uids[i] = (ps != null) 1288 ? UserHandle.getUid(packageUserId, ps.appId) 1289 : -1; 1290 i++; 1291 } 1292 } 1293 size = i; 1294 mPendingBroadcasts.clear(); 1295 } 1296 // Send broadcasts 1297 for (int i = 0; i < size; i++) { 1298 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1299 } 1300 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1301 break; 1302 } 1303 case START_CLEANING_PACKAGE: { 1304 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1305 final String packageName = (String)msg.obj; 1306 final int userId = msg.arg1; 1307 final boolean andCode = msg.arg2 != 0; 1308 synchronized (mPackages) { 1309 if (userId == UserHandle.USER_ALL) { 1310 int[] users = sUserManager.getUserIds(); 1311 for (int user : users) { 1312 mSettings.addPackageToCleanLPw( 1313 new PackageCleanItem(user, packageName, andCode)); 1314 } 1315 } else { 1316 mSettings.addPackageToCleanLPw( 1317 new PackageCleanItem(userId, packageName, andCode)); 1318 } 1319 } 1320 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1321 startCleaningPackages(); 1322 } break; 1323 case POST_INSTALL: { 1324 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1325 PostInstallData data = mRunningInstalls.get(msg.arg1); 1326 mRunningInstalls.delete(msg.arg1); 1327 boolean deleteOld = false; 1328 1329 if (data != null) { 1330 InstallArgs args = data.args; 1331 PackageInstalledInfo res = data.res; 1332 1333 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1334 final String packageName = res.pkg.applicationInfo.packageName; 1335 res.removedInfo.sendBroadcast(false, true, false); 1336 Bundle extras = new Bundle(1); 1337 extras.putInt(Intent.EXTRA_UID, res.uid); 1338 1339 // Now that we successfully installed the package, grant runtime 1340 // permissions if requested before broadcasting the install. 1341 if ((args.installFlags 1342 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1343 grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(), 1344 args.installGrantPermissions); 1345 } 1346 1347 // Determine the set of users who are adding this 1348 // package for the first time vs. those who are seeing 1349 // an update. 1350 int[] firstUsers; 1351 int[] updateUsers = new int[0]; 1352 if (res.origUsers == null || res.origUsers.length == 0) { 1353 firstUsers = res.newUsers; 1354 } else { 1355 firstUsers = new int[0]; 1356 for (int i=0; i<res.newUsers.length; i++) { 1357 int user = res.newUsers[i]; 1358 boolean isNew = true; 1359 for (int j=0; j<res.origUsers.length; j++) { 1360 if (res.origUsers[j] == user) { 1361 isNew = false; 1362 break; 1363 } 1364 } 1365 if (isNew) { 1366 int[] newFirst = new int[firstUsers.length+1]; 1367 System.arraycopy(firstUsers, 0, newFirst, 0, 1368 firstUsers.length); 1369 newFirst[firstUsers.length] = user; 1370 firstUsers = newFirst; 1371 } else { 1372 int[] newUpdate = new int[updateUsers.length+1]; 1373 System.arraycopy(updateUsers, 0, newUpdate, 0, 1374 updateUsers.length); 1375 newUpdate[updateUsers.length] = user; 1376 updateUsers = newUpdate; 1377 } 1378 } 1379 } 1380 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1381 packageName, extras, null, null, firstUsers); 1382 final boolean update = res.removedInfo.removedPackage != null; 1383 if (update) { 1384 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1385 } 1386 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1387 packageName, extras, null, null, updateUsers); 1388 if (update) { 1389 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1390 packageName, extras, null, null, updateUsers); 1391 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1392 null, null, packageName, null, updateUsers); 1393 1394 // treat asec-hosted packages like removable media on upgrade 1395 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1396 if (DEBUG_INSTALL) { 1397 Slog.i(TAG, "upgrading pkg " + res.pkg 1398 + " is ASEC-hosted -> AVAILABLE"); 1399 } 1400 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1401 ArrayList<String> pkgList = new ArrayList<String>(1); 1402 pkgList.add(packageName); 1403 sendResourcesChangedBroadcast(true, true, 1404 pkgList,uidArray, null); 1405 } 1406 } 1407 if (res.removedInfo.args != null) { 1408 // Remove the replaced package's older resources safely now 1409 deleteOld = true; 1410 } 1411 1412 // If this app is a browser and it's newly-installed for some 1413 // users, clear any default-browser state in those users 1414 if (firstUsers.length > 0) { 1415 // the app's nature doesn't depend on the user, so we can just 1416 // check its browser nature in any user and generalize. 1417 if (packageIsBrowser(packageName, firstUsers[0])) { 1418 synchronized (mPackages) { 1419 for (int userId : firstUsers) { 1420 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1421 } 1422 } 1423 } 1424 } 1425 // Log current value of "unknown sources" setting 1426 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1427 getUnknownSourcesSettings()); 1428 } 1429 // Force a gc to clear up things 1430 Runtime.getRuntime().gc(); 1431 // We delete after a gc for applications on sdcard. 1432 if (deleteOld) { 1433 synchronized (mInstallLock) { 1434 res.removedInfo.args.doPostDeleteLI(true); 1435 } 1436 } 1437 if (args.observer != null) { 1438 try { 1439 Bundle extras = extrasForInstallResult(res); 1440 args.observer.onPackageInstalled(res.name, res.returnCode, 1441 res.returnMsg, extras); 1442 } catch (RemoteException e) { 1443 Slog.i(TAG, "Observer no longer exists."); 1444 } 1445 } 1446 } else { 1447 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1448 } 1449 } break; 1450 case UPDATED_MEDIA_STATUS: { 1451 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1452 boolean reportStatus = msg.arg1 == 1; 1453 boolean doGc = msg.arg2 == 1; 1454 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1455 if (doGc) { 1456 // Force a gc to clear up stale containers. 1457 Runtime.getRuntime().gc(); 1458 } 1459 if (msg.obj != null) { 1460 @SuppressWarnings("unchecked") 1461 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1462 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1463 // Unload containers 1464 unloadAllContainers(args); 1465 } 1466 if (reportStatus) { 1467 try { 1468 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1469 PackageHelper.getMountService().finishMediaUpdate(); 1470 } catch (RemoteException e) { 1471 Log.e(TAG, "MountService not running?"); 1472 } 1473 } 1474 } break; 1475 case WRITE_SETTINGS: { 1476 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1477 synchronized (mPackages) { 1478 removeMessages(WRITE_SETTINGS); 1479 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1480 mSettings.writeLPr(); 1481 mDirtyUsers.clear(); 1482 } 1483 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1484 } break; 1485 case WRITE_PACKAGE_RESTRICTIONS: { 1486 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1487 synchronized (mPackages) { 1488 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1489 for (int userId : mDirtyUsers) { 1490 mSettings.writePackageRestrictionsLPr(userId); 1491 } 1492 mDirtyUsers.clear(); 1493 } 1494 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1495 } break; 1496 case CHECK_PENDING_VERIFICATION: { 1497 final int verificationId = msg.arg1; 1498 final PackageVerificationState state = mPendingVerification.get(verificationId); 1499 1500 if ((state != null) && !state.timeoutExtended()) { 1501 final InstallArgs args = state.getInstallArgs(); 1502 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1503 1504 Slog.i(TAG, "Verification timed out for " + originUri); 1505 mPendingVerification.remove(verificationId); 1506 1507 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1508 1509 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1510 Slog.i(TAG, "Continuing with installation of " + originUri); 1511 state.setVerifierResponse(Binder.getCallingUid(), 1512 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1513 broadcastPackageVerified(verificationId, originUri, 1514 PackageManager.VERIFICATION_ALLOW, 1515 state.getInstallArgs().getUser()); 1516 try { 1517 ret = args.copyApk(mContainerService, true); 1518 } catch (RemoteException e) { 1519 Slog.e(TAG, "Could not contact the ContainerService"); 1520 } 1521 } else { 1522 broadcastPackageVerified(verificationId, originUri, 1523 PackageManager.VERIFICATION_REJECT, 1524 state.getInstallArgs().getUser()); 1525 } 1526 1527 processPendingInstall(args, ret); 1528 mHandler.sendEmptyMessage(MCS_UNBIND); 1529 } 1530 break; 1531 } 1532 case PACKAGE_VERIFIED: { 1533 final int verificationId = msg.arg1; 1534 1535 final PackageVerificationState state = mPendingVerification.get(verificationId); 1536 if (state == null) { 1537 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1538 break; 1539 } 1540 1541 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1542 1543 state.setVerifierResponse(response.callerUid, response.code); 1544 1545 if (state.isVerificationComplete()) { 1546 mPendingVerification.remove(verificationId); 1547 1548 final InstallArgs args = state.getInstallArgs(); 1549 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1550 1551 int ret; 1552 if (state.isInstallAllowed()) { 1553 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1554 broadcastPackageVerified(verificationId, originUri, 1555 response.code, state.getInstallArgs().getUser()); 1556 try { 1557 ret = args.copyApk(mContainerService, true); 1558 } catch (RemoteException e) { 1559 Slog.e(TAG, "Could not contact the ContainerService"); 1560 } 1561 } else { 1562 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1563 } 1564 1565 processPendingInstall(args, ret); 1566 1567 mHandler.sendEmptyMessage(MCS_UNBIND); 1568 } 1569 1570 break; 1571 } 1572 case START_INTENT_FILTER_VERIFICATIONS: { 1573 IFVerificationParams params = (IFVerificationParams) msg.obj; 1574 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1575 params.replacing, params.pkg); 1576 break; 1577 } 1578 case INTENT_FILTER_VERIFIED: { 1579 final int verificationId = msg.arg1; 1580 1581 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1582 verificationId); 1583 if (state == null) { 1584 Slog.w(TAG, "Invalid IntentFilter verification token " 1585 + verificationId + " received"); 1586 break; 1587 } 1588 1589 final int userId = state.getUserId(); 1590 1591 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1592 "Processing IntentFilter verification with token:" 1593 + verificationId + " and userId:" + userId); 1594 1595 final IntentFilterVerificationResponse response = 1596 (IntentFilterVerificationResponse) msg.obj; 1597 1598 state.setVerifierResponse(response.callerUid, response.code); 1599 1600 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1601 "IntentFilter verification with token:" + verificationId 1602 + " and userId:" + userId 1603 + " is settings verifier response with response code:" 1604 + response.code); 1605 1606 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1607 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1608 + response.getFailedDomainsString()); 1609 } 1610 1611 if (state.isVerificationComplete()) { 1612 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1613 } else { 1614 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1615 "IntentFilter verification with token:" + verificationId 1616 + " was not said to be complete"); 1617 } 1618 1619 break; 1620 } 1621 } 1622 } 1623 } 1624 1625 private StorageEventListener mStorageListener = new StorageEventListener() { 1626 @Override 1627 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1628 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1629 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1630 final String volumeUuid = vol.getFsUuid(); 1631 1632 // Clean up any users or apps that were removed or recreated 1633 // while this volume was missing 1634 reconcileUsers(volumeUuid); 1635 reconcileApps(volumeUuid); 1636 1637 // Clean up any install sessions that expired or were 1638 // cancelled while this volume was missing 1639 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1640 1641 loadPrivatePackages(vol); 1642 1643 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1644 unloadPrivatePackages(vol); 1645 } 1646 } 1647 1648 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1649 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1650 updateExternalMediaStatus(true, false); 1651 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1652 updateExternalMediaStatus(false, false); 1653 } 1654 } 1655 } 1656 1657 @Override 1658 public void onVolumeForgotten(String fsUuid) { 1659 if (TextUtils.isEmpty(fsUuid)) { 1660 Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1661 return; 1662 } 1663 1664 // Remove any apps installed on the forgotten volume 1665 synchronized (mPackages) { 1666 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1667 for (PackageSetting ps : packages) { 1668 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1669 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1670 UserHandle.USER_OWNER, PackageManager.DELETE_ALL_USERS); 1671 } 1672 1673 mSettings.onVolumeForgotten(fsUuid); 1674 mSettings.writeLPr(); 1675 } 1676 } 1677 }; 1678 1679 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId, 1680 String[] grantedPermissions) { 1681 if (userId >= UserHandle.USER_OWNER) { 1682 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1683 } else if (userId == UserHandle.USER_ALL) { 1684 final int[] userIds; 1685 synchronized (mPackages) { 1686 userIds = UserManagerService.getInstance().getUserIds(); 1687 } 1688 for (int someUserId : userIds) { 1689 grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions); 1690 } 1691 } 1692 1693 // We could have touched GID membership, so flush out packages.list 1694 synchronized (mPackages) { 1695 mSettings.writePackageListLPr(); 1696 } 1697 } 1698 1699 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1700 String[] grantedPermissions) { 1701 SettingBase sb = (SettingBase) pkg.mExtras; 1702 if (sb == null) { 1703 return; 1704 } 1705 1706 PermissionsState permissionsState = sb.getPermissionsState(); 1707 1708 for (String permission : pkg.requestedPermissions) { 1709 BasePermission bp = mSettings.mPermissions.get(permission); 1710 if (bp != null && bp.isRuntime() && (grantedPermissions == null 1711 || ArrayUtils.contains(grantedPermissions, permission))) { 1712 permissionsState.grantRuntimePermission(bp, userId); 1713 } 1714 } 1715 } 1716 1717 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1718 Bundle extras = null; 1719 switch (res.returnCode) { 1720 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1721 extras = new Bundle(); 1722 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1723 res.origPermission); 1724 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1725 res.origPackage); 1726 break; 1727 } 1728 case PackageManager.INSTALL_SUCCEEDED: { 1729 extras = new Bundle(); 1730 extras.putBoolean(Intent.EXTRA_REPLACING, 1731 res.removedInfo != null && res.removedInfo.removedPackage != null); 1732 break; 1733 } 1734 } 1735 return extras; 1736 } 1737 1738 void scheduleWriteSettingsLocked() { 1739 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1740 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1741 } 1742 } 1743 1744 void scheduleWritePackageRestrictionsLocked(int userId) { 1745 if (!sUserManager.exists(userId)) return; 1746 mDirtyUsers.add(userId); 1747 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1748 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1749 } 1750 } 1751 1752 public static PackageManagerService main(Context context, Installer installer, 1753 boolean factoryTest, boolean onlyCore) { 1754 PackageManagerService m = new PackageManagerService(context, installer, 1755 factoryTest, onlyCore); 1756 ServiceManager.addService("package", m); 1757 return m; 1758 } 1759 1760 static String[] splitString(String str, char sep) { 1761 int count = 1; 1762 int i = 0; 1763 while ((i=str.indexOf(sep, i)) >= 0) { 1764 count++; 1765 i++; 1766 } 1767 1768 String[] res = new String[count]; 1769 i=0; 1770 count = 0; 1771 int lastI=0; 1772 while ((i=str.indexOf(sep, i)) >= 0) { 1773 res[count] = str.substring(lastI, i); 1774 count++; 1775 i++; 1776 lastI = i; 1777 } 1778 res[count] = str.substring(lastI, str.length()); 1779 return res; 1780 } 1781 1782 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1783 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1784 Context.DISPLAY_SERVICE); 1785 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1786 } 1787 1788 public PackageManagerService(Context context, Installer installer, 1789 boolean factoryTest, boolean onlyCore) { 1790 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1791 SystemClock.uptimeMillis()); 1792 1793 if (mSdkVersion <= 0) { 1794 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1795 } 1796 1797 mContext = context; 1798 mFactoryTest = factoryTest; 1799 mOnlyCore = onlyCore; 1800 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1801 mMetrics = new DisplayMetrics(); 1802 mSettings = new Settings(mPackages); 1803 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1804 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1805 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1806 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1807 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1808 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1809 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1810 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1811 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1812 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1813 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1814 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1815 1816 // TODO: add a property to control this? 1817 long dexOptLRUThresholdInMinutes; 1818 if (mLazyDexOpt) { 1819 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1820 } else { 1821 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1822 } 1823 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1824 1825 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1826 if (separateProcesses != null && separateProcesses.length() > 0) { 1827 if ("*".equals(separateProcesses)) { 1828 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1829 mSeparateProcesses = null; 1830 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1831 } else { 1832 mDefParseFlags = 0; 1833 mSeparateProcesses = separateProcesses.split(","); 1834 Slog.w(TAG, "Running with debug.separate_processes: " 1835 + separateProcesses); 1836 } 1837 } else { 1838 mDefParseFlags = 0; 1839 mSeparateProcesses = null; 1840 } 1841 1842 mInstaller = installer; 1843 mPackageDexOptimizer = new PackageDexOptimizer(this); 1844 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1845 1846 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 1847 FgThread.get().getLooper()); 1848 1849 getDefaultDisplayMetrics(context, mMetrics); 1850 1851 SystemConfig systemConfig = SystemConfig.getInstance(); 1852 mGlobalGids = systemConfig.getGlobalGids(); 1853 mSystemPermissions = systemConfig.getSystemPermissions(); 1854 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1855 1856 synchronized (mInstallLock) { 1857 // writer 1858 synchronized (mPackages) { 1859 mHandlerThread = new ServiceThread(TAG, 1860 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1861 mHandlerThread.start(); 1862 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1863 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1864 1865 File dataDir = Environment.getDataDirectory(); 1866 mAppDataDir = new File(dataDir, "data"); 1867 mAppInstallDir = new File(dataDir, "app"); 1868 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1869 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1870 mUserAppDataDir = new File(dataDir, "user"); 1871 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1872 1873 sUserManager = new UserManagerService(context, this, 1874 mInstallLock, mPackages); 1875 1876 // Propagate permission configuration in to package manager. 1877 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1878 = systemConfig.getPermissions(); 1879 for (int i=0; i<permConfig.size(); i++) { 1880 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1881 BasePermission bp = mSettings.mPermissions.get(perm.name); 1882 if (bp == null) { 1883 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1884 mSettings.mPermissions.put(perm.name, bp); 1885 } 1886 if (perm.gids != null) { 1887 bp.setGids(perm.gids, perm.perUser); 1888 } 1889 } 1890 1891 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1892 for (int i=0; i<libConfig.size(); i++) { 1893 mSharedLibraries.put(libConfig.keyAt(i), 1894 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1895 } 1896 1897 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1898 1899 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1900 mSdkVersion, mOnlyCore); 1901 1902 String customResolverActivity = Resources.getSystem().getString( 1903 R.string.config_customResolverActivity); 1904 if (TextUtils.isEmpty(customResolverActivity)) { 1905 customResolverActivity = null; 1906 } else { 1907 mCustomResolverComponentName = ComponentName.unflattenFromString( 1908 customResolverActivity); 1909 } 1910 1911 long startTime = SystemClock.uptimeMillis(); 1912 1913 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1914 startTime); 1915 1916 // Set flag to monitor and not change apk file paths when 1917 // scanning install directories. 1918 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 1919 1920 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1921 1922 /** 1923 * Add everything in the in the boot class path to the 1924 * list of process files because dexopt will have been run 1925 * if necessary during zygote startup. 1926 */ 1927 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1928 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1929 1930 if (bootClassPath != null) { 1931 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1932 for (String element : bootClassPathElements) { 1933 alreadyDexOpted.add(element); 1934 } 1935 } else { 1936 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1937 } 1938 1939 if (systemServerClassPath != null) { 1940 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1941 for (String element : systemServerClassPathElements) { 1942 alreadyDexOpted.add(element); 1943 } 1944 } else { 1945 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1946 } 1947 1948 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1949 final String[] dexCodeInstructionSets = 1950 getDexCodeInstructionSets( 1951 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1952 1953 /** 1954 * Ensure all external libraries have had dexopt run on them. 1955 */ 1956 if (mSharedLibraries.size() > 0) { 1957 // NOTE: For now, we're compiling these system "shared libraries" 1958 // (and framework jars) into all available architectures. It's possible 1959 // to compile them only when we come across an app that uses them (there's 1960 // already logic for that in scanPackageLI) but that adds some complexity. 1961 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1962 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1963 final String lib = libEntry.path; 1964 if (lib == null) { 1965 continue; 1966 } 1967 1968 try { 1969 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 1970 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1971 alreadyDexOpted.add(lib); 1972 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1973 } 1974 } catch (FileNotFoundException e) { 1975 Slog.w(TAG, "Library not found: " + lib); 1976 } catch (IOException e) { 1977 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1978 + e.getMessage()); 1979 } 1980 } 1981 } 1982 } 1983 1984 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1985 1986 // Gross hack for now: we know this file doesn't contain any 1987 // code, so don't dexopt it to avoid the resulting log spew. 1988 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1989 1990 // Gross hack for now: we know this file is only part of 1991 // the boot class path for art, so don't dexopt it to 1992 // avoid the resulting log spew. 1993 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1994 1995 /** 1996 * There are a number of commands implemented in Java, which 1997 * we currently need to do the dexopt on so that they can be 1998 * run from a non-root shell. 1999 */ 2000 String[] frameworkFiles = frameworkDir.list(); 2001 if (frameworkFiles != null) { 2002 // TODO: We could compile these only for the most preferred ABI. We should 2003 // first double check that the dex files for these commands are not referenced 2004 // by other system apps. 2005 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2006 for (int i=0; i<frameworkFiles.length; i++) { 2007 File libPath = new File(frameworkDir, frameworkFiles[i]); 2008 String path = libPath.getPath(); 2009 // Skip the file if we already did it. 2010 if (alreadyDexOpted.contains(path)) { 2011 continue; 2012 } 2013 // Skip the file if it is not a type we want to dexopt. 2014 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 2015 continue; 2016 } 2017 try { 2018 int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false); 2019 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2020 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 2021 } 2022 } catch (FileNotFoundException e) { 2023 Slog.w(TAG, "Jar not found: " + path); 2024 } catch (IOException e) { 2025 Slog.w(TAG, "Exception reading jar: " + path, e); 2026 } 2027 } 2028 } 2029 } 2030 2031 // Collect vendor overlay packages. 2032 // (Do this before scanning any apps.) 2033 // For security and version matching reason, only consider 2034 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2035 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2036 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2037 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2038 2039 // Find base frameworks (resource packages without code). 2040 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2041 | PackageParser.PARSE_IS_SYSTEM_DIR 2042 | PackageParser.PARSE_IS_PRIVILEGED, 2043 scanFlags | SCAN_NO_DEX, 0); 2044 2045 // Collected privileged system packages. 2046 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2047 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2048 | PackageParser.PARSE_IS_SYSTEM_DIR 2049 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2050 2051 // Collect ordinary system packages. 2052 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2053 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2054 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2055 2056 // Collect all vendor packages. 2057 File vendorAppDir = new File("/vendor/app"); 2058 try { 2059 vendorAppDir = vendorAppDir.getCanonicalFile(); 2060 } catch (IOException e) { 2061 // failed to look up canonical path, continue with original one 2062 } 2063 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2064 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2065 2066 // Collect all OEM packages. 2067 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2068 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2069 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2070 2071 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 2072 mInstaller.moveFiles(); 2073 2074 // Prune any system packages that no longer exist. 2075 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2076 if (!mOnlyCore) { 2077 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2078 while (psit.hasNext()) { 2079 PackageSetting ps = psit.next(); 2080 2081 /* 2082 * If this is not a system app, it can't be a 2083 * disable system app. 2084 */ 2085 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2086 continue; 2087 } 2088 2089 /* 2090 * If the package is scanned, it's not erased. 2091 */ 2092 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2093 if (scannedPkg != null) { 2094 /* 2095 * If the system app is both scanned and in the 2096 * disabled packages list, then it must have been 2097 * added via OTA. Remove it from the currently 2098 * scanned package so the previously user-installed 2099 * application can be scanned. 2100 */ 2101 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2102 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2103 + ps.name + "; removing system app. Last known codePath=" 2104 + ps.codePathString + ", installStatus=" + ps.installStatus 2105 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2106 + scannedPkg.mVersionCode); 2107 removePackageLI(ps, true); 2108 mExpectingBetter.put(ps.name, ps.codePath); 2109 } 2110 2111 continue; 2112 } 2113 2114 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2115 psit.remove(); 2116 logCriticalInfo(Log.WARN, "System package " + ps.name 2117 + " no longer exists; wiping its data"); 2118 removeDataDirsLI(null, ps.name); 2119 } else { 2120 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2121 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2122 possiblyDeletedUpdatedSystemApps.add(ps.name); 2123 } 2124 } 2125 } 2126 } 2127 2128 //look for any incomplete package installations 2129 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2130 //clean up list 2131 for(int i = 0; i < deletePkgsList.size(); i++) { 2132 //clean up here 2133 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2134 } 2135 //delete tmp files 2136 deleteTempPackageFiles(); 2137 2138 // Remove any shared userIDs that have no associated packages 2139 mSettings.pruneSharedUsersLPw(); 2140 2141 if (!mOnlyCore) { 2142 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2143 SystemClock.uptimeMillis()); 2144 scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2145 2146 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2147 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2148 2149 /** 2150 * Remove disable package settings for any updated system 2151 * apps that were removed via an OTA. If they're not a 2152 * previously-updated app, remove them completely. 2153 * Otherwise, just revoke their system-level permissions. 2154 */ 2155 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2156 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2157 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2158 2159 String msg; 2160 if (deletedPkg == null) { 2161 msg = "Updated system package " + deletedAppName 2162 + " no longer exists; wiping its data"; 2163 removeDataDirsLI(null, deletedAppName); 2164 } else { 2165 msg = "Updated system app + " + deletedAppName 2166 + " no longer present; removing system privileges for " 2167 + deletedAppName; 2168 2169 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2170 2171 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2172 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2173 } 2174 logCriticalInfo(Log.WARN, msg); 2175 } 2176 2177 /** 2178 * Make sure all system apps that we expected to appear on 2179 * the userdata partition actually showed up. If they never 2180 * appeared, crawl back and revive the system version. 2181 */ 2182 for (int i = 0; i < mExpectingBetter.size(); i++) { 2183 final String packageName = mExpectingBetter.keyAt(i); 2184 if (!mPackages.containsKey(packageName)) { 2185 final File scanFile = mExpectingBetter.valueAt(i); 2186 2187 logCriticalInfo(Log.WARN, "Expected better " + packageName 2188 + " but never showed up; reverting to system"); 2189 2190 final int reparseFlags; 2191 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2192 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2193 | PackageParser.PARSE_IS_SYSTEM_DIR 2194 | PackageParser.PARSE_IS_PRIVILEGED; 2195 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2196 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2197 | PackageParser.PARSE_IS_SYSTEM_DIR; 2198 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2199 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2200 | PackageParser.PARSE_IS_SYSTEM_DIR; 2201 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2202 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2203 | PackageParser.PARSE_IS_SYSTEM_DIR; 2204 } else { 2205 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2206 continue; 2207 } 2208 2209 mSettings.enableSystemPackageLPw(packageName); 2210 2211 try { 2212 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 2213 } catch (PackageManagerException e) { 2214 Slog.e(TAG, "Failed to parse original system package: " 2215 + e.getMessage()); 2216 } 2217 } 2218 } 2219 } 2220 mExpectingBetter.clear(); 2221 2222 // Now that we know all of the shared libraries, update all clients to have 2223 // the correct library paths. 2224 updateAllSharedLibrariesLPw(); 2225 2226 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2227 // NOTE: We ignore potential failures here during a system scan (like 2228 // the rest of the commands above) because there's precious little we 2229 // can do about it. A settings error is reported, though. 2230 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2231 false /* force dexopt */, false /* defer dexopt */); 2232 } 2233 2234 // Now that we know all the packages we are keeping, 2235 // read and update their last usage times. 2236 mPackageUsage.readLP(); 2237 2238 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2239 SystemClock.uptimeMillis()); 2240 Slog.i(TAG, "Time to scan packages: " 2241 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2242 + " seconds"); 2243 2244 // If the platform SDK has changed since the last time we booted, 2245 // we need to re-grant app permission to catch any new ones that 2246 // appear. This is really a hack, and means that apps can in some 2247 // cases get permissions that the user didn't initially explicitly 2248 // allow... it would be nice to have some better way to handle 2249 // this situation. 2250 final VersionInfo ver = mSettings.getInternalVersion(); 2251 2252 int updateFlags = UPDATE_PERMISSIONS_ALL; 2253 if (ver.sdkVersion != mSdkVersion) { 2254 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2255 + mSdkVersion + "; regranting permissions for internal storage"); 2256 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2257 } 2258 updatePermissionsLPw(null, null, updateFlags); 2259 ver.sdkVersion = mSdkVersion; 2260 2261 // If this is the first boot, and it is a normal boot, then 2262 // we need to initialize the default preferred apps. 2263 if (!mRestoredSettings && !onlyCore) { 2264 mSettings.applyDefaultPreferredAppsLPw(this, UserHandle.USER_OWNER); 2265 applyFactoryDefaultBrowserLPw(UserHandle.USER_OWNER); 2266 primeDomainVerificationsLPw(UserHandle.USER_OWNER); 2267 } 2268 2269 // If this is first boot after an OTA, and a normal boot, then 2270 // we need to clear code cache directories. 2271 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2272 if (mIsUpgrade && !onlyCore) { 2273 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2274 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2275 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2276 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2277 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2278 } 2279 } 2280 ver.fingerprint = Build.FINGERPRINT; 2281 } 2282 2283 checkDefaultBrowser(); 2284 2285 // All the changes are done during package scanning. 2286 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2287 2288 // can downgrade to reader 2289 mSettings.writeLPr(); 2290 2291 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2292 SystemClock.uptimeMillis()); 2293 2294 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2295 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2296 2297 mInstallerService = new PackageInstallerService(context, this); 2298 2299 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2300 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2301 mIntentFilterVerifierComponent); 2302 2303 } // synchronized (mPackages) 2304 } // synchronized (mInstallLock) 2305 2306 // Now after opening every single application zip, make sure they 2307 // are all flushed. Not really needed, but keeps things nice and 2308 // tidy. 2309 Runtime.getRuntime().gc(); 2310 2311 // Expose private service for system components to use. 2312 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2313 } 2314 2315 @Override 2316 public boolean isFirstBoot() { 2317 return !mRestoredSettings; 2318 } 2319 2320 @Override 2321 public boolean isOnlyCoreApps() { 2322 return mOnlyCore; 2323 } 2324 2325 @Override 2326 public boolean isUpgrade() { 2327 return mIsUpgrade; 2328 } 2329 2330 private String getRequiredVerifierLPr() { 2331 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2332 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2333 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 2334 2335 String requiredVerifier = null; 2336 2337 final int N = receivers.size(); 2338 for (int i = 0; i < N; i++) { 2339 final ResolveInfo info = receivers.get(i); 2340 2341 if (info.activityInfo == null) { 2342 continue; 2343 } 2344 2345 final String packageName = info.activityInfo.packageName; 2346 2347 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2348 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2349 continue; 2350 } 2351 2352 if (requiredVerifier != null) { 2353 throw new RuntimeException("There can be only one required verifier"); 2354 } 2355 2356 requiredVerifier = packageName; 2357 } 2358 2359 return requiredVerifier; 2360 } 2361 2362 private String getRequiredInstallerLPr() { 2363 Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2364 installerIntent.addCategory(Intent.CATEGORY_DEFAULT); 2365 installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2366 2367 final List<ResolveInfo> installers = queryIntentActivities(installerIntent, 2368 PACKAGE_MIME_TYPE, 0, 0); 2369 2370 String requiredInstaller = null; 2371 2372 final int N = installers.size(); 2373 for (int i = 0; i < N; i++) { 2374 final ResolveInfo info = installers.get(i); 2375 final String packageName = info.activityInfo.packageName; 2376 2377 if (!info.activityInfo.applicationInfo.isSystemApp()) { 2378 continue; 2379 } 2380 2381 if (requiredInstaller != null) { 2382 throw new RuntimeException("There must be one required installer"); 2383 } 2384 2385 requiredInstaller = packageName; 2386 } 2387 2388 if (requiredInstaller == null) { 2389 throw new RuntimeException("There must be one required installer"); 2390 } 2391 2392 return requiredInstaller; 2393 } 2394 2395 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2396 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2397 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2398 PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */); 2399 2400 ComponentName verifierComponentName = null; 2401 2402 int priority = -1000; 2403 final int N = receivers.size(); 2404 for (int i = 0; i < N; i++) { 2405 final ResolveInfo info = receivers.get(i); 2406 2407 if (info.activityInfo == null) { 2408 continue; 2409 } 2410 2411 final String packageName = info.activityInfo.packageName; 2412 2413 final PackageSetting ps = mSettings.mPackages.get(packageName); 2414 if (ps == null) { 2415 continue; 2416 } 2417 2418 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2419 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2420 continue; 2421 } 2422 2423 // Select the IntentFilterVerifier with the highest priority 2424 if (priority < info.priority) { 2425 priority = info.priority; 2426 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2427 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: " 2428 + verifierComponentName + " with priority: " + info.priority); 2429 } 2430 } 2431 2432 return verifierComponentName; 2433 } 2434 2435 private void primeDomainVerificationsLPw(int userId) { 2436 if (DEBUG_DOMAIN_VERIFICATION) { 2437 Slog.d(TAG, "Priming domain verifications in user " + userId); 2438 } 2439 2440 SystemConfig systemConfig = SystemConfig.getInstance(); 2441 ArraySet<String> packages = systemConfig.getLinkedApps(); 2442 ArraySet<String> domains = new ArraySet<String>(); 2443 2444 for (String packageName : packages) { 2445 PackageParser.Package pkg = mPackages.get(packageName); 2446 if (pkg != null) { 2447 if (!pkg.isSystemApp()) { 2448 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2449 continue; 2450 } 2451 2452 domains.clear(); 2453 for (PackageParser.Activity a : pkg.activities) { 2454 for (ActivityIntentInfo filter : a.intents) { 2455 if (hasValidDomains(filter)) { 2456 domains.addAll(filter.getHostsList()); 2457 } 2458 } 2459 } 2460 2461 if (domains.size() > 0) { 2462 if (DEBUG_DOMAIN_VERIFICATION) { 2463 Slog.v(TAG, " + " + packageName); 2464 } 2465 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2466 // state w.r.t. the formal app-linkage "no verification attempted" state; 2467 // and then 'always' in the per-user state actually used for intent resolution. 2468 final IntentFilterVerificationInfo ivi; 2469 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2470 new ArrayList<String>(domains)); 2471 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2472 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2473 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2474 } else { 2475 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2476 + "' does not handle web links"); 2477 } 2478 } else { 2479 Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>"); 2480 } 2481 } 2482 2483 scheduleWritePackageRestrictionsLocked(userId); 2484 scheduleWriteSettingsLocked(); 2485 } 2486 2487 private void applyFactoryDefaultBrowserLPw(int userId) { 2488 // The default browser app's package name is stored in a string resource, 2489 // with a product-specific overlay used for vendor customization. 2490 String browserPkg = mContext.getResources().getString( 2491 com.android.internal.R.string.default_browser); 2492 if (!TextUtils.isEmpty(browserPkg)) { 2493 // non-empty string => required to be a known package 2494 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2495 if (ps == null) { 2496 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2497 browserPkg = null; 2498 } else { 2499 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2500 } 2501 } 2502 2503 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2504 // default. If there's more than one, just leave everything alone. 2505 if (browserPkg == null) { 2506 calculateDefaultBrowserLPw(userId); 2507 } 2508 } 2509 2510 private void calculateDefaultBrowserLPw(int userId) { 2511 List<String> allBrowsers = resolveAllBrowserApps(userId); 2512 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2513 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2514 } 2515 2516 private List<String> resolveAllBrowserApps(int userId) { 2517 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2518 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2519 PackageManager.MATCH_ALL, userId); 2520 2521 final int count = list.size(); 2522 List<String> result = new ArrayList<String>(count); 2523 for (int i=0; i<count; i++) { 2524 ResolveInfo info = list.get(i); 2525 if (info.activityInfo == null 2526 || !info.handleAllWebDataURI 2527 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2528 || result.contains(info.activityInfo.packageName)) { 2529 continue; 2530 } 2531 result.add(info.activityInfo.packageName); 2532 } 2533 2534 return result; 2535 } 2536 2537 private boolean packageIsBrowser(String packageName, int userId) { 2538 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2539 PackageManager.MATCH_ALL, userId); 2540 final int N = list.size(); 2541 for (int i = 0; i < N; i++) { 2542 ResolveInfo info = list.get(i); 2543 if (packageName.equals(info.activityInfo.packageName)) { 2544 return true; 2545 } 2546 } 2547 return false; 2548 } 2549 2550 private void checkDefaultBrowser() { 2551 final int myUserId = UserHandle.myUserId(); 2552 final String packageName = getDefaultBrowserPackageName(myUserId); 2553 if (packageName != null) { 2554 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2555 if (info == null) { 2556 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2557 synchronized (mPackages) { 2558 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2559 } 2560 } 2561 } 2562 } 2563 2564 @Override 2565 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2566 throws RemoteException { 2567 try { 2568 return super.onTransact(code, data, reply, flags); 2569 } catch (RuntimeException e) { 2570 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2571 Slog.wtf(TAG, "Package Manager Crash", e); 2572 } 2573 throw e; 2574 } 2575 } 2576 2577 void cleanupInstallFailedPackage(PackageSetting ps) { 2578 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2579 2580 removeDataDirsLI(ps.volumeUuid, ps.name); 2581 if (ps.codePath != null) { 2582 if (ps.codePath.isDirectory()) { 2583 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2584 } else { 2585 ps.codePath.delete(); 2586 } 2587 } 2588 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2589 if (ps.resourcePath.isDirectory()) { 2590 FileUtils.deleteContents(ps.resourcePath); 2591 } 2592 ps.resourcePath.delete(); 2593 } 2594 mSettings.removePackageLPw(ps.name); 2595 } 2596 2597 static int[] appendInts(int[] cur, int[] add) { 2598 if (add == null) return cur; 2599 if (cur == null) return add; 2600 final int N = add.length; 2601 for (int i=0; i<N; i++) { 2602 cur = appendInt(cur, add[i]); 2603 } 2604 return cur; 2605 } 2606 2607 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2608 if (!sUserManager.exists(userId)) return null; 2609 final PackageSetting ps = (PackageSetting) p.mExtras; 2610 if (ps == null) { 2611 return null; 2612 } 2613 2614 final PermissionsState permissionsState = ps.getPermissionsState(); 2615 2616 final int[] gids = permissionsState.computeGids(userId); 2617 final Set<String> permissions = permissionsState.getPermissions(userId); 2618 final PackageUserState state = ps.readUserState(userId); 2619 2620 return PackageParser.generatePackageInfo(p, gids, flags, 2621 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2622 } 2623 2624 @Override 2625 public boolean isPackageFrozen(String packageName) { 2626 synchronized (mPackages) { 2627 final PackageSetting ps = mSettings.mPackages.get(packageName); 2628 if (ps != null) { 2629 return ps.frozen; 2630 } 2631 } 2632 Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen"); 2633 return true; 2634 } 2635 2636 @Override 2637 public boolean isPackageAvailable(String packageName, int userId) { 2638 if (!sUserManager.exists(userId)) return false; 2639 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2640 synchronized (mPackages) { 2641 PackageParser.Package p = mPackages.get(packageName); 2642 if (p != null) { 2643 final PackageSetting ps = (PackageSetting) p.mExtras; 2644 if (ps != null) { 2645 final PackageUserState state = ps.readUserState(userId); 2646 if (state != null) { 2647 return PackageParser.isAvailable(state); 2648 } 2649 } 2650 } 2651 } 2652 return false; 2653 } 2654 2655 @Override 2656 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2657 if (!sUserManager.exists(userId)) return null; 2658 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2659 // reader 2660 synchronized (mPackages) { 2661 PackageParser.Package p = mPackages.get(packageName); 2662 if (DEBUG_PACKAGE_INFO) 2663 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2664 if (p != null) { 2665 return generatePackageInfo(p, flags, userId); 2666 } 2667 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2668 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2669 } 2670 } 2671 return null; 2672 } 2673 2674 @Override 2675 public String[] currentToCanonicalPackageNames(String[] names) { 2676 String[] out = new String[names.length]; 2677 // reader 2678 synchronized (mPackages) { 2679 for (int i=names.length-1; i>=0; i--) { 2680 PackageSetting ps = mSettings.mPackages.get(names[i]); 2681 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2682 } 2683 } 2684 return out; 2685 } 2686 2687 @Override 2688 public String[] canonicalToCurrentPackageNames(String[] names) { 2689 String[] out = new String[names.length]; 2690 // reader 2691 synchronized (mPackages) { 2692 for (int i=names.length-1; i>=0; i--) { 2693 String cur = mSettings.mRenamedPackages.get(names[i]); 2694 out[i] = cur != null ? cur : names[i]; 2695 } 2696 } 2697 return out; 2698 } 2699 2700 @Override 2701 public int getPackageUid(String packageName, int userId) { 2702 if (!sUserManager.exists(userId)) return -1; 2703 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2704 2705 // reader 2706 synchronized (mPackages) { 2707 PackageParser.Package p = mPackages.get(packageName); 2708 if(p != null) { 2709 return UserHandle.getUid(userId, p.applicationInfo.uid); 2710 } 2711 PackageSetting ps = mSettings.mPackages.get(packageName); 2712 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2713 return -1; 2714 } 2715 p = ps.pkg; 2716 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2717 } 2718 } 2719 2720 @Override 2721 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2722 if (!sUserManager.exists(userId)) { 2723 return null; 2724 } 2725 2726 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2727 "getPackageGids"); 2728 2729 // reader 2730 synchronized (mPackages) { 2731 PackageParser.Package p = mPackages.get(packageName); 2732 if (DEBUG_PACKAGE_INFO) { 2733 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2734 } 2735 if (p != null) { 2736 PackageSetting ps = (PackageSetting) p.mExtras; 2737 return ps.getPermissionsState().computeGids(userId); 2738 } 2739 } 2740 2741 return null; 2742 } 2743 2744 static PermissionInfo generatePermissionInfo( 2745 BasePermission bp, int flags) { 2746 if (bp.perm != null) { 2747 return PackageParser.generatePermissionInfo(bp.perm, flags); 2748 } 2749 PermissionInfo pi = new PermissionInfo(); 2750 pi.name = bp.name; 2751 pi.packageName = bp.sourcePackage; 2752 pi.nonLocalizedLabel = bp.name; 2753 pi.protectionLevel = bp.protectionLevel; 2754 return pi; 2755 } 2756 2757 @Override 2758 public PermissionInfo getPermissionInfo(String name, int flags) { 2759 // reader 2760 synchronized (mPackages) { 2761 final BasePermission p = mSettings.mPermissions.get(name); 2762 if (p != null) { 2763 return generatePermissionInfo(p, flags); 2764 } 2765 return null; 2766 } 2767 } 2768 2769 @Override 2770 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2771 // reader 2772 synchronized (mPackages) { 2773 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2774 for (BasePermission p : mSettings.mPermissions.values()) { 2775 if (group == null) { 2776 if (p.perm == null || p.perm.info.group == null) { 2777 out.add(generatePermissionInfo(p, flags)); 2778 } 2779 } else { 2780 if (p.perm != null && group.equals(p.perm.info.group)) { 2781 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2782 } 2783 } 2784 } 2785 2786 if (out.size() > 0) { 2787 return out; 2788 } 2789 return mPermissionGroups.containsKey(group) ? out : null; 2790 } 2791 } 2792 2793 @Override 2794 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2795 // reader 2796 synchronized (mPackages) { 2797 return PackageParser.generatePermissionGroupInfo( 2798 mPermissionGroups.get(name), flags); 2799 } 2800 } 2801 2802 @Override 2803 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2804 // reader 2805 synchronized (mPackages) { 2806 final int N = mPermissionGroups.size(); 2807 ArrayList<PermissionGroupInfo> out 2808 = new ArrayList<PermissionGroupInfo>(N); 2809 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2810 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2811 } 2812 return out; 2813 } 2814 } 2815 2816 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2817 int userId) { 2818 if (!sUserManager.exists(userId)) return null; 2819 PackageSetting ps = mSettings.mPackages.get(packageName); 2820 if (ps != null) { 2821 if (ps.pkg == null) { 2822 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2823 flags, userId); 2824 if (pInfo != null) { 2825 return pInfo.applicationInfo; 2826 } 2827 return null; 2828 } 2829 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2830 ps.readUserState(userId), userId); 2831 } 2832 return null; 2833 } 2834 2835 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2836 int userId) { 2837 if (!sUserManager.exists(userId)) return null; 2838 PackageSetting ps = mSettings.mPackages.get(packageName); 2839 if (ps != null) { 2840 PackageParser.Package pkg = ps.pkg; 2841 if (pkg == null) { 2842 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2843 return null; 2844 } 2845 // Only data remains, so we aren't worried about code paths 2846 pkg = new PackageParser.Package(packageName); 2847 pkg.applicationInfo.packageName = packageName; 2848 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2849 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2850 pkg.applicationInfo.dataDir = Environment 2851 .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName) 2852 .getAbsolutePath(); 2853 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2854 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2855 } 2856 return generatePackageInfo(pkg, flags, userId); 2857 } 2858 return null; 2859 } 2860 2861 @Override 2862 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2863 if (!sUserManager.exists(userId)) return null; 2864 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2865 // writer 2866 synchronized (mPackages) { 2867 PackageParser.Package p = mPackages.get(packageName); 2868 if (DEBUG_PACKAGE_INFO) Log.v( 2869 TAG, "getApplicationInfo " + packageName 2870 + ": " + p); 2871 if (p != null) { 2872 PackageSetting ps = mSettings.mPackages.get(packageName); 2873 if (ps == null) return null; 2874 // Note: isEnabledLP() does not apply here - always return info 2875 return PackageParser.generateApplicationInfo( 2876 p, flags, ps.readUserState(userId), userId); 2877 } 2878 if ("android".equals(packageName)||"system".equals(packageName)) { 2879 return mAndroidApplication; 2880 } 2881 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2882 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2883 } 2884 } 2885 return null; 2886 } 2887 2888 @Override 2889 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2890 final IPackageDataObserver observer) { 2891 mContext.enforceCallingOrSelfPermission( 2892 android.Manifest.permission.CLEAR_APP_CACHE, null); 2893 // Queue up an async operation since clearing cache may take a little while. 2894 mHandler.post(new Runnable() { 2895 public void run() { 2896 mHandler.removeCallbacks(this); 2897 int retCode = -1; 2898 synchronized (mInstallLock) { 2899 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2900 if (retCode < 0) { 2901 Slog.w(TAG, "Couldn't clear application caches"); 2902 } 2903 } 2904 if (observer != null) { 2905 try { 2906 observer.onRemoveCompleted(null, (retCode >= 0)); 2907 } catch (RemoteException e) { 2908 Slog.w(TAG, "RemoveException when invoking call back"); 2909 } 2910 } 2911 } 2912 }); 2913 } 2914 2915 @Override 2916 public void freeStorage(final String volumeUuid, final long freeStorageSize, 2917 final IntentSender pi) { 2918 mContext.enforceCallingOrSelfPermission( 2919 android.Manifest.permission.CLEAR_APP_CACHE, null); 2920 // Queue up an async operation since clearing cache may take a little while. 2921 mHandler.post(new Runnable() { 2922 public void run() { 2923 mHandler.removeCallbacks(this); 2924 int retCode = -1; 2925 synchronized (mInstallLock) { 2926 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2927 if (retCode < 0) { 2928 Slog.w(TAG, "Couldn't clear application caches"); 2929 } 2930 } 2931 if(pi != null) { 2932 try { 2933 // Callback via pending intent 2934 int code = (retCode >= 0) ? 1 : 0; 2935 pi.sendIntent(null, code, null, 2936 null, null); 2937 } catch (SendIntentException e1) { 2938 Slog.i(TAG, "Failed to send pending intent"); 2939 } 2940 } 2941 } 2942 }); 2943 } 2944 2945 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 2946 synchronized (mInstallLock) { 2947 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 2948 throw new IOException("Failed to free enough space"); 2949 } 2950 } 2951 } 2952 2953 @Override 2954 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2955 if (!sUserManager.exists(userId)) return null; 2956 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2957 synchronized (mPackages) { 2958 PackageParser.Activity a = mActivities.mActivities.get(component); 2959 2960 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2961 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2962 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2963 if (ps == null) return null; 2964 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2965 userId); 2966 } 2967 if (mResolveComponentName.equals(component)) { 2968 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2969 new PackageUserState(), userId); 2970 } 2971 } 2972 return null; 2973 } 2974 2975 @Override 2976 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2977 String resolvedType) { 2978 synchronized (mPackages) { 2979 if (component.equals(mResolveComponentName)) { 2980 // The resolver supports EVERYTHING! 2981 return true; 2982 } 2983 PackageParser.Activity a = mActivities.mActivities.get(component); 2984 if (a == null) { 2985 return false; 2986 } 2987 for (int i=0; i<a.intents.size(); i++) { 2988 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2989 intent.getData(), intent.getCategories(), TAG) >= 0) { 2990 return true; 2991 } 2992 } 2993 return false; 2994 } 2995 } 2996 2997 @Override 2998 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2999 if (!sUserManager.exists(userId)) return null; 3000 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 3001 synchronized (mPackages) { 3002 PackageParser.Activity a = mReceivers.mActivities.get(component); 3003 if (DEBUG_PACKAGE_INFO) Log.v( 3004 TAG, "getReceiverInfo " + component + ": " + a); 3005 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 3006 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3007 if (ps == null) return null; 3008 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3009 userId); 3010 } 3011 } 3012 return null; 3013 } 3014 3015 @Override 3016 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3017 if (!sUserManager.exists(userId)) return null; 3018 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 3019 synchronized (mPackages) { 3020 PackageParser.Service s = mServices.mServices.get(component); 3021 if (DEBUG_PACKAGE_INFO) Log.v( 3022 TAG, "getServiceInfo " + component + ": " + s); 3023 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 3024 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3025 if (ps == null) return null; 3026 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3027 userId); 3028 } 3029 } 3030 return null; 3031 } 3032 3033 @Override 3034 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3035 if (!sUserManager.exists(userId)) return null; 3036 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 3037 synchronized (mPackages) { 3038 PackageParser.Provider p = mProviders.mProviders.get(component); 3039 if (DEBUG_PACKAGE_INFO) Log.v( 3040 TAG, "getProviderInfo " + component + ": " + p); 3041 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 3042 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3043 if (ps == null) return null; 3044 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3045 userId); 3046 } 3047 } 3048 return null; 3049 } 3050 3051 @Override 3052 public String[] getSystemSharedLibraryNames() { 3053 Set<String> libSet; 3054 synchronized (mPackages) { 3055 libSet = mSharedLibraries.keySet(); 3056 int size = libSet.size(); 3057 if (size > 0) { 3058 String[] libs = new String[size]; 3059 libSet.toArray(libs); 3060 return libs; 3061 } 3062 } 3063 return null; 3064 } 3065 3066 /** 3067 * @hide 3068 */ 3069 PackageParser.Package findSharedNonSystemLibrary(String libName) { 3070 synchronized (mPackages) { 3071 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 3072 if (lib != null && lib.apk != null) { 3073 return mPackages.get(lib.apk); 3074 } 3075 } 3076 return null; 3077 } 3078 3079 @Override 3080 public FeatureInfo[] getSystemAvailableFeatures() { 3081 Collection<FeatureInfo> featSet; 3082 synchronized (mPackages) { 3083 featSet = mAvailableFeatures.values(); 3084 int size = featSet.size(); 3085 if (size > 0) { 3086 FeatureInfo[] features = new FeatureInfo[size+1]; 3087 featSet.toArray(features); 3088 FeatureInfo fi = new FeatureInfo(); 3089 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3090 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3091 features[size] = fi; 3092 return features; 3093 } 3094 } 3095 return null; 3096 } 3097 3098 @Override 3099 public boolean hasSystemFeature(String name) { 3100 synchronized (mPackages) { 3101 return mAvailableFeatures.containsKey(name); 3102 } 3103 } 3104 3105 private void checkValidCaller(int uid, int userId) { 3106 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 3107 return; 3108 3109 throw new SecurityException("Caller uid=" + uid 3110 + " is not privileged to communicate with user=" + userId); 3111 } 3112 3113 @Override 3114 public int checkPermission(String permName, String pkgName, int userId) { 3115 if (!sUserManager.exists(userId)) { 3116 return PackageManager.PERMISSION_DENIED; 3117 } 3118 3119 synchronized (mPackages) { 3120 final PackageParser.Package p = mPackages.get(pkgName); 3121 if (p != null && p.mExtras != null) { 3122 final PackageSetting ps = (PackageSetting) p.mExtras; 3123 final PermissionsState permissionsState = ps.getPermissionsState(); 3124 if (permissionsState.hasPermission(permName, userId)) { 3125 return PackageManager.PERMISSION_GRANTED; 3126 } 3127 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3128 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3129 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3130 return PackageManager.PERMISSION_GRANTED; 3131 } 3132 } 3133 } 3134 3135 return PackageManager.PERMISSION_DENIED; 3136 } 3137 3138 @Override 3139 public int checkUidPermission(String permName, int uid) { 3140 final int userId = UserHandle.getUserId(uid); 3141 3142 if (!sUserManager.exists(userId)) { 3143 return PackageManager.PERMISSION_DENIED; 3144 } 3145 3146 synchronized (mPackages) { 3147 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3148 if (obj != null) { 3149 final SettingBase ps = (SettingBase) obj; 3150 final PermissionsState permissionsState = ps.getPermissionsState(); 3151 if (permissionsState.hasPermission(permName, userId)) { 3152 return PackageManager.PERMISSION_GRANTED; 3153 } 3154 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3155 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3156 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3157 return PackageManager.PERMISSION_GRANTED; 3158 } 3159 } else { 3160 ArraySet<String> perms = mSystemPermissions.get(uid); 3161 if (perms != null) { 3162 if (perms.contains(permName)) { 3163 return PackageManager.PERMISSION_GRANTED; 3164 } 3165 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3166 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3167 return PackageManager.PERMISSION_GRANTED; 3168 } 3169 } 3170 } 3171 } 3172 3173 return PackageManager.PERMISSION_DENIED; 3174 } 3175 3176 @Override 3177 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3178 if (UserHandle.getCallingUserId() != userId) { 3179 mContext.enforceCallingPermission( 3180 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3181 "isPermissionRevokedByPolicy for user " + userId); 3182 } 3183 3184 if (checkPermission(permission, packageName, userId) 3185 == PackageManager.PERMISSION_GRANTED) { 3186 return false; 3187 } 3188 3189 final long identity = Binder.clearCallingIdentity(); 3190 try { 3191 final int flags = getPermissionFlags(permission, packageName, userId); 3192 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3193 } finally { 3194 Binder.restoreCallingIdentity(identity); 3195 } 3196 } 3197 3198 @Override 3199 public String getPermissionControllerPackageName() { 3200 synchronized (mPackages) { 3201 return mRequiredInstallerPackage; 3202 } 3203 } 3204 3205 /** 3206 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3207 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3208 * @param checkShell TODO(yamasani): 3209 * @param message the message to log on security exception 3210 */ 3211 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3212 boolean checkShell, String message) { 3213 if (userId < 0) { 3214 throw new IllegalArgumentException("Invalid userId " + userId); 3215 } 3216 if (checkShell) { 3217 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3218 } 3219 if (userId == UserHandle.getUserId(callingUid)) return; 3220 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3221 if (requireFullPermission) { 3222 mContext.enforceCallingOrSelfPermission( 3223 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3224 } else { 3225 try { 3226 mContext.enforceCallingOrSelfPermission( 3227 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3228 } catch (SecurityException se) { 3229 mContext.enforceCallingOrSelfPermission( 3230 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3231 } 3232 } 3233 } 3234 } 3235 3236 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3237 if (callingUid == Process.SHELL_UID) { 3238 if (userHandle >= 0 3239 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3240 throw new SecurityException("Shell does not have permission to access user " 3241 + userHandle); 3242 } else if (userHandle < 0) { 3243 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3244 + Debug.getCallers(3)); 3245 } 3246 } 3247 } 3248 3249 private BasePermission findPermissionTreeLP(String permName) { 3250 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3251 if (permName.startsWith(bp.name) && 3252 permName.length() > bp.name.length() && 3253 permName.charAt(bp.name.length()) == '.') { 3254 return bp; 3255 } 3256 } 3257 return null; 3258 } 3259 3260 private BasePermission checkPermissionTreeLP(String permName) { 3261 if (permName != null) { 3262 BasePermission bp = findPermissionTreeLP(permName); 3263 if (bp != null) { 3264 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3265 return bp; 3266 } 3267 throw new SecurityException("Calling uid " 3268 + Binder.getCallingUid() 3269 + " is not allowed to add to permission tree " 3270 + bp.name + " owned by uid " + bp.uid); 3271 } 3272 } 3273 throw new SecurityException("No permission tree found for " + permName); 3274 } 3275 3276 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3277 if (s1 == null) { 3278 return s2 == null; 3279 } 3280 if (s2 == null) { 3281 return false; 3282 } 3283 if (s1.getClass() != s2.getClass()) { 3284 return false; 3285 } 3286 return s1.equals(s2); 3287 } 3288 3289 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3290 if (pi1.icon != pi2.icon) return false; 3291 if (pi1.logo != pi2.logo) return false; 3292 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3293 if (!compareStrings(pi1.name, pi2.name)) return false; 3294 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3295 // We'll take care of setting this one. 3296 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3297 // These are not currently stored in settings. 3298 //if (!compareStrings(pi1.group, pi2.group)) return false; 3299 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3300 //if (pi1.labelRes != pi2.labelRes) return false; 3301 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3302 return true; 3303 } 3304 3305 int permissionInfoFootprint(PermissionInfo info) { 3306 int size = info.name.length(); 3307 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3308 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3309 return size; 3310 } 3311 3312 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3313 int size = 0; 3314 for (BasePermission perm : mSettings.mPermissions.values()) { 3315 if (perm.uid == tree.uid) { 3316 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3317 } 3318 } 3319 return size; 3320 } 3321 3322 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3323 // We calculate the max size of permissions defined by this uid and throw 3324 // if that plus the size of 'info' would exceed our stated maximum. 3325 if (tree.uid != Process.SYSTEM_UID) { 3326 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3327 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3328 throw new SecurityException("Permission tree size cap exceeded"); 3329 } 3330 } 3331 } 3332 3333 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3334 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3335 throw new SecurityException("Label must be specified in permission"); 3336 } 3337 BasePermission tree = checkPermissionTreeLP(info.name); 3338 BasePermission bp = mSettings.mPermissions.get(info.name); 3339 boolean added = bp == null; 3340 boolean changed = true; 3341 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3342 if (added) { 3343 enforcePermissionCapLocked(info, tree); 3344 bp = new BasePermission(info.name, tree.sourcePackage, 3345 BasePermission.TYPE_DYNAMIC); 3346 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3347 throw new SecurityException( 3348 "Not allowed to modify non-dynamic permission " 3349 + info.name); 3350 } else { 3351 if (bp.protectionLevel == fixedLevel 3352 && bp.perm.owner.equals(tree.perm.owner) 3353 && bp.uid == tree.uid 3354 && comparePermissionInfos(bp.perm.info, info)) { 3355 changed = false; 3356 } 3357 } 3358 bp.protectionLevel = fixedLevel; 3359 info = new PermissionInfo(info); 3360 info.protectionLevel = fixedLevel; 3361 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3362 bp.perm.info.packageName = tree.perm.info.packageName; 3363 bp.uid = tree.uid; 3364 if (added) { 3365 mSettings.mPermissions.put(info.name, bp); 3366 } 3367 if (changed) { 3368 if (!async) { 3369 mSettings.writeLPr(); 3370 } else { 3371 scheduleWriteSettingsLocked(); 3372 } 3373 } 3374 return added; 3375 } 3376 3377 @Override 3378 public boolean addPermission(PermissionInfo info) { 3379 synchronized (mPackages) { 3380 return addPermissionLocked(info, false); 3381 } 3382 } 3383 3384 @Override 3385 public boolean addPermissionAsync(PermissionInfo info) { 3386 synchronized (mPackages) { 3387 return addPermissionLocked(info, true); 3388 } 3389 } 3390 3391 @Override 3392 public void removePermission(String name) { 3393 synchronized (mPackages) { 3394 checkPermissionTreeLP(name); 3395 BasePermission bp = mSettings.mPermissions.get(name); 3396 if (bp != null) { 3397 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3398 throw new SecurityException( 3399 "Not allowed to modify non-dynamic permission " 3400 + name); 3401 } 3402 mSettings.mPermissions.remove(name); 3403 mSettings.writeLPr(); 3404 } 3405 } 3406 } 3407 3408 private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg, 3409 BasePermission bp) { 3410 int index = pkg.requestedPermissions.indexOf(bp.name); 3411 if (index == -1) { 3412 throw new SecurityException("Package " + pkg.packageName 3413 + " has not requested permission " + bp.name); 3414 } 3415 if (!bp.isRuntime()) { 3416 throw new SecurityException("Permission " + bp.name 3417 + " is not a changeable permission type"); 3418 } 3419 } 3420 3421 @Override 3422 public void grantRuntimePermission(String packageName, String name, final int userId) { 3423 if (!sUserManager.exists(userId)) { 3424 Log.e(TAG, "No such user:" + userId); 3425 return; 3426 } 3427 3428 mContext.enforceCallingOrSelfPermission( 3429 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3430 "grantRuntimePermission"); 3431 3432 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3433 "grantRuntimePermission"); 3434 3435 final int uid; 3436 final SettingBase sb; 3437 3438 synchronized (mPackages) { 3439 final PackageParser.Package pkg = mPackages.get(packageName); 3440 if (pkg == null) { 3441 throw new IllegalArgumentException("Unknown package: " + packageName); 3442 } 3443 3444 final BasePermission bp = mSettings.mPermissions.get(name); 3445 if (bp == null) { 3446 throw new IllegalArgumentException("Unknown permission: " + name); 3447 } 3448 3449 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3450 3451 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3452 sb = (SettingBase) pkg.mExtras; 3453 if (sb == null) { 3454 throw new IllegalArgumentException("Unknown package: " + packageName); 3455 } 3456 3457 final PermissionsState permissionsState = sb.getPermissionsState(); 3458 3459 final int flags = permissionsState.getPermissionFlags(name, userId); 3460 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3461 throw new SecurityException("Cannot grant system fixed permission: " 3462 + name + " for package: " + packageName); 3463 } 3464 3465 final int result = permissionsState.grantRuntimePermission(bp, userId); 3466 switch (result) { 3467 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3468 return; 3469 } 3470 3471 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3472 mHandler.post(new Runnable() { 3473 @Override 3474 public void run() { 3475 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED); 3476 } 3477 }); 3478 } break; 3479 } 3480 3481 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3482 3483 // Not critical if that is lost - app has to request again. 3484 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3485 } 3486 3487 // Only need to do this if user is initialized. Otherwise it's a new user 3488 // and there are no processes running as the user yet and there's no need 3489 // to make an expensive call to remount processes for the changed permissions. 3490 if (READ_EXTERNAL_STORAGE.equals(name) 3491 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3492 final long token = Binder.clearCallingIdentity(); 3493 try { 3494 if (sUserManager.isInitialized(userId)) { 3495 MountServiceInternal mountServiceInternal = LocalServices.getService( 3496 MountServiceInternal.class); 3497 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 3498 } 3499 } finally { 3500 Binder.restoreCallingIdentity(token); 3501 } 3502 } 3503 } 3504 3505 @Override 3506 public void revokeRuntimePermission(String packageName, String name, int userId) { 3507 if (!sUserManager.exists(userId)) { 3508 Log.e(TAG, "No such user:" + userId); 3509 return; 3510 } 3511 3512 mContext.enforceCallingOrSelfPermission( 3513 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3514 "revokeRuntimePermission"); 3515 3516 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3517 "revokeRuntimePermission"); 3518 3519 final SettingBase sb; 3520 3521 synchronized (mPackages) { 3522 final PackageParser.Package pkg = mPackages.get(packageName); 3523 if (pkg == null) { 3524 throw new IllegalArgumentException("Unknown package: " + packageName); 3525 } 3526 3527 final BasePermission bp = mSettings.mPermissions.get(name); 3528 if (bp == null) { 3529 throw new IllegalArgumentException("Unknown permission: " + name); 3530 } 3531 3532 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3533 3534 sb = (SettingBase) pkg.mExtras; 3535 if (sb == null) { 3536 throw new IllegalArgumentException("Unknown package: " + packageName); 3537 } 3538 3539 final PermissionsState permissionsState = sb.getPermissionsState(); 3540 3541 final int flags = permissionsState.getPermissionFlags(name, userId); 3542 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3543 throw new SecurityException("Cannot revoke system fixed permission: " 3544 + name + " for package: " + packageName); 3545 } 3546 3547 if (permissionsState.revokeRuntimePermission(bp, userId) == 3548 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3549 return; 3550 } 3551 3552 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3553 3554 // Critical, after this call app should never have the permission. 3555 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3556 } 3557 3558 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3559 } 3560 3561 @Override 3562 public void resetRuntimePermissions() { 3563 mContext.enforceCallingOrSelfPermission( 3564 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3565 "revokeRuntimePermission"); 3566 3567 int callingUid = Binder.getCallingUid(); 3568 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3569 mContext.enforceCallingOrSelfPermission( 3570 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3571 "resetRuntimePermissions"); 3572 } 3573 3574 synchronized (mPackages) { 3575 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 3576 for (int userId : UserManagerService.getInstance().getUserIds()) { 3577 final int packageCount = mPackages.size(); 3578 for (int i = 0; i < packageCount; i++) { 3579 PackageParser.Package pkg = mPackages.valueAt(i); 3580 if (!(pkg.mExtras instanceof PackageSetting)) { 3581 continue; 3582 } 3583 PackageSetting ps = (PackageSetting) pkg.mExtras; 3584 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 3585 } 3586 } 3587 } 3588 } 3589 3590 @Override 3591 public int getPermissionFlags(String name, String packageName, int userId) { 3592 if (!sUserManager.exists(userId)) { 3593 return 0; 3594 } 3595 3596 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 3597 3598 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3599 "getPermissionFlags"); 3600 3601 synchronized (mPackages) { 3602 final PackageParser.Package pkg = mPackages.get(packageName); 3603 if (pkg == null) { 3604 throw new IllegalArgumentException("Unknown package: " + packageName); 3605 } 3606 3607 final BasePermission bp = mSettings.mPermissions.get(name); 3608 if (bp == null) { 3609 throw new IllegalArgumentException("Unknown permission: " + name); 3610 } 3611 3612 SettingBase sb = (SettingBase) pkg.mExtras; 3613 if (sb == null) { 3614 throw new IllegalArgumentException("Unknown package: " + packageName); 3615 } 3616 3617 PermissionsState permissionsState = sb.getPermissionsState(); 3618 return permissionsState.getPermissionFlags(name, userId); 3619 } 3620 } 3621 3622 @Override 3623 public void updatePermissionFlags(String name, String packageName, int flagMask, 3624 int flagValues, int userId) { 3625 if (!sUserManager.exists(userId)) { 3626 return; 3627 } 3628 3629 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 3630 3631 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3632 "updatePermissionFlags"); 3633 3634 // Only the system can change these flags and nothing else. 3635 if (getCallingUid() != Process.SYSTEM_UID) { 3636 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3637 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3638 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3639 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3640 } 3641 3642 synchronized (mPackages) { 3643 final PackageParser.Package pkg = mPackages.get(packageName); 3644 if (pkg == null) { 3645 throw new IllegalArgumentException("Unknown package: " + packageName); 3646 } 3647 3648 final BasePermission bp = mSettings.mPermissions.get(name); 3649 if (bp == null) { 3650 throw new IllegalArgumentException("Unknown permission: " + name); 3651 } 3652 3653 SettingBase sb = (SettingBase) pkg.mExtras; 3654 if (sb == null) { 3655 throw new IllegalArgumentException("Unknown package: " + packageName); 3656 } 3657 3658 PermissionsState permissionsState = sb.getPermissionsState(); 3659 3660 // Only the package manager can change flags for system component permissions. 3661 final int flags = permissionsState.getPermissionFlags(bp.name, userId); 3662 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3663 return; 3664 } 3665 3666 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 3667 3668 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3669 // Install and runtime permissions are stored in different places, 3670 // so figure out what permission changed and persist the change. 3671 if (permissionsState.getInstallPermissionState(name) != null) { 3672 scheduleWriteSettingsLocked(); 3673 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 3674 || hadState) { 3675 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3676 } 3677 } 3678 } 3679 } 3680 3681 /** 3682 * Update the permission flags for all packages and runtime permissions of a user in order 3683 * to allow device or profile owner to remove POLICY_FIXED. 3684 */ 3685 @Override 3686 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 3687 if (!sUserManager.exists(userId)) { 3688 return; 3689 } 3690 3691 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 3692 3693 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3694 "updatePermissionFlagsForAllApps"); 3695 3696 // Only the system can change system fixed flags. 3697 if (getCallingUid() != Process.SYSTEM_UID) { 3698 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3699 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3700 } 3701 3702 synchronized (mPackages) { 3703 boolean changed = false; 3704 final int packageCount = mPackages.size(); 3705 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 3706 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 3707 SettingBase sb = (SettingBase) pkg.mExtras; 3708 if (sb == null) { 3709 continue; 3710 } 3711 PermissionsState permissionsState = sb.getPermissionsState(); 3712 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 3713 userId, flagMask, flagValues); 3714 } 3715 if (changed) { 3716 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3717 } 3718 } 3719 } 3720 3721 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 3722 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 3723 != PackageManager.PERMISSION_GRANTED 3724 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 3725 != PackageManager.PERMISSION_GRANTED) { 3726 throw new SecurityException(message + " requires " 3727 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 3728 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 3729 } 3730 } 3731 3732 @Override 3733 public boolean shouldShowRequestPermissionRationale(String permissionName, 3734 String packageName, int userId) { 3735 if (UserHandle.getCallingUserId() != userId) { 3736 mContext.enforceCallingPermission( 3737 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3738 "canShowRequestPermissionRationale for user " + userId); 3739 } 3740 3741 final int uid = getPackageUid(packageName, userId); 3742 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 3743 return false; 3744 } 3745 3746 if (checkPermission(permissionName, packageName, userId) 3747 == PackageManager.PERMISSION_GRANTED) { 3748 return false; 3749 } 3750 3751 final int flags; 3752 3753 final long identity = Binder.clearCallingIdentity(); 3754 try { 3755 flags = getPermissionFlags(permissionName, 3756 packageName, userId); 3757 } finally { 3758 Binder.restoreCallingIdentity(identity); 3759 } 3760 3761 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 3762 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 3763 | PackageManager.FLAG_PERMISSION_USER_FIXED; 3764 3765 if ((flags & fixedFlags) != 0) { 3766 return false; 3767 } 3768 3769 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 3770 } 3771 3772 void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) { 3773 BasePermission bp = mSettings.mPermissions.get(permission); 3774 if (bp == null) { 3775 throw new SecurityException("Missing " + permission + " permission"); 3776 } 3777 3778 SettingBase sb = (SettingBase) pkg.mExtras; 3779 PermissionsState permissionsState = sb.getPermissionsState(); 3780 3781 if (permissionsState.grantInstallPermission(bp) != 3782 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3783 scheduleWriteSettingsLocked(); 3784 } 3785 } 3786 3787 @Override 3788 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3789 mContext.enforceCallingOrSelfPermission( 3790 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 3791 "addOnPermissionsChangeListener"); 3792 3793 synchronized (mPackages) { 3794 mOnPermissionChangeListeners.addListenerLocked(listener); 3795 } 3796 } 3797 3798 @Override 3799 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3800 synchronized (mPackages) { 3801 mOnPermissionChangeListeners.removeListenerLocked(listener); 3802 } 3803 } 3804 3805 @Override 3806 public boolean isProtectedBroadcast(String actionName) { 3807 synchronized (mPackages) { 3808 return mProtectedBroadcasts.contains(actionName); 3809 } 3810 } 3811 3812 @Override 3813 public int checkSignatures(String pkg1, String pkg2) { 3814 synchronized (mPackages) { 3815 final PackageParser.Package p1 = mPackages.get(pkg1); 3816 final PackageParser.Package p2 = mPackages.get(pkg2); 3817 if (p1 == null || p1.mExtras == null 3818 || p2 == null || p2.mExtras == null) { 3819 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3820 } 3821 return compareSignatures(p1.mSignatures, p2.mSignatures); 3822 } 3823 } 3824 3825 @Override 3826 public int checkUidSignatures(int uid1, int uid2) { 3827 // Map to base uids. 3828 uid1 = UserHandle.getAppId(uid1); 3829 uid2 = UserHandle.getAppId(uid2); 3830 // reader 3831 synchronized (mPackages) { 3832 Signature[] s1; 3833 Signature[] s2; 3834 Object obj = mSettings.getUserIdLPr(uid1); 3835 if (obj != null) { 3836 if (obj instanceof SharedUserSetting) { 3837 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3838 } else if (obj instanceof PackageSetting) { 3839 s1 = ((PackageSetting)obj).signatures.mSignatures; 3840 } else { 3841 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3842 } 3843 } else { 3844 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3845 } 3846 obj = mSettings.getUserIdLPr(uid2); 3847 if (obj != null) { 3848 if (obj instanceof SharedUserSetting) { 3849 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3850 } else if (obj instanceof PackageSetting) { 3851 s2 = ((PackageSetting)obj).signatures.mSignatures; 3852 } else { 3853 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3854 } 3855 } else { 3856 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3857 } 3858 return compareSignatures(s1, s2); 3859 } 3860 } 3861 3862 private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) { 3863 final long identity = Binder.clearCallingIdentity(); 3864 try { 3865 if (sb instanceof SharedUserSetting) { 3866 SharedUserSetting sus = (SharedUserSetting) sb; 3867 final int packageCount = sus.packages.size(); 3868 for (int i = 0; i < packageCount; i++) { 3869 PackageSetting susPs = sus.packages.valueAt(i); 3870 if (userId == UserHandle.USER_ALL) { 3871 killApplication(susPs.pkg.packageName, susPs.appId, reason); 3872 } else { 3873 final int uid = UserHandle.getUid(userId, susPs.appId); 3874 killUid(uid, reason); 3875 } 3876 } 3877 } else if (sb instanceof PackageSetting) { 3878 PackageSetting ps = (PackageSetting) sb; 3879 if (userId == UserHandle.USER_ALL) { 3880 killApplication(ps.pkg.packageName, ps.appId, reason); 3881 } else { 3882 final int uid = UserHandle.getUid(userId, ps.appId); 3883 killUid(uid, reason); 3884 } 3885 } 3886 } finally { 3887 Binder.restoreCallingIdentity(identity); 3888 } 3889 } 3890 3891 private static void killUid(int uid, String reason) { 3892 IActivityManager am = ActivityManagerNative.getDefault(); 3893 if (am != null) { 3894 try { 3895 am.killUid(uid, reason); 3896 } catch (RemoteException e) { 3897 /* ignore - same process */ 3898 } 3899 } 3900 } 3901 3902 /** 3903 * Compares two sets of signatures. Returns: 3904 * <br /> 3905 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3906 * <br /> 3907 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3908 * <br /> 3909 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3910 * <br /> 3911 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3912 * <br /> 3913 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3914 */ 3915 static int compareSignatures(Signature[] s1, Signature[] s2) { 3916 if (s1 == null) { 3917 return s2 == null 3918 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3919 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3920 } 3921 3922 if (s2 == null) { 3923 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3924 } 3925 3926 if (s1.length != s2.length) { 3927 return PackageManager.SIGNATURE_NO_MATCH; 3928 } 3929 3930 // Since both signature sets are of size 1, we can compare without HashSets. 3931 if (s1.length == 1) { 3932 return s1[0].equals(s2[0]) ? 3933 PackageManager.SIGNATURE_MATCH : 3934 PackageManager.SIGNATURE_NO_MATCH; 3935 } 3936 3937 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3938 for (Signature sig : s1) { 3939 set1.add(sig); 3940 } 3941 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3942 for (Signature sig : s2) { 3943 set2.add(sig); 3944 } 3945 // Make sure s2 contains all signatures in s1. 3946 if (set1.equals(set2)) { 3947 return PackageManager.SIGNATURE_MATCH; 3948 } 3949 return PackageManager.SIGNATURE_NO_MATCH; 3950 } 3951 3952 /** 3953 * If the database version for this type of package (internal storage or 3954 * external storage) is less than the version where package signatures 3955 * were updated, return true. 3956 */ 3957 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3958 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 3959 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 3960 } 3961 3962 /** 3963 * Used for backward compatibility to make sure any packages with 3964 * certificate chains get upgraded to the new style. {@code existingSigs} 3965 * will be in the old format (since they were stored on disk from before the 3966 * system upgrade) and {@code scannedSigs} will be in the newer format. 3967 */ 3968 private int compareSignaturesCompat(PackageSignatures existingSigs, 3969 PackageParser.Package scannedPkg) { 3970 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 3971 return PackageManager.SIGNATURE_NO_MATCH; 3972 } 3973 3974 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 3975 for (Signature sig : existingSigs.mSignatures) { 3976 existingSet.add(sig); 3977 } 3978 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 3979 for (Signature sig : scannedPkg.mSignatures) { 3980 try { 3981 Signature[] chainSignatures = sig.getChainSignatures(); 3982 for (Signature chainSig : chainSignatures) { 3983 scannedCompatSet.add(chainSig); 3984 } 3985 } catch (CertificateEncodingException e) { 3986 scannedCompatSet.add(sig); 3987 } 3988 } 3989 /* 3990 * Make sure the expanded scanned set contains all signatures in the 3991 * existing one. 3992 */ 3993 if (scannedCompatSet.equals(existingSet)) { 3994 // Migrate the old signatures to the new scheme. 3995 existingSigs.assignSignatures(scannedPkg.mSignatures); 3996 // The new KeySets will be re-added later in the scanning process. 3997 synchronized (mPackages) { 3998 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 3999 } 4000 return PackageManager.SIGNATURE_MATCH; 4001 } 4002 return PackageManager.SIGNATURE_NO_MATCH; 4003 } 4004 4005 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4006 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4007 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4008 } 4009 4010 private int compareSignaturesRecover(PackageSignatures existingSigs, 4011 PackageParser.Package scannedPkg) { 4012 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4013 return PackageManager.SIGNATURE_NO_MATCH; 4014 } 4015 4016 String msg = null; 4017 try { 4018 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4019 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4020 + scannedPkg.packageName); 4021 return PackageManager.SIGNATURE_MATCH; 4022 } 4023 } catch (CertificateException e) { 4024 msg = e.getMessage(); 4025 } 4026 4027 logCriticalInfo(Log.INFO, 4028 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4029 return PackageManager.SIGNATURE_NO_MATCH; 4030 } 4031 4032 @Override 4033 public String[] getPackagesForUid(int uid) { 4034 uid = UserHandle.getAppId(uid); 4035 // reader 4036 synchronized (mPackages) { 4037 Object obj = mSettings.getUserIdLPr(uid); 4038 if (obj instanceof SharedUserSetting) { 4039 final SharedUserSetting sus = (SharedUserSetting) obj; 4040 final int N = sus.packages.size(); 4041 final String[] res = new String[N]; 4042 final Iterator<PackageSetting> it = sus.packages.iterator(); 4043 int i = 0; 4044 while (it.hasNext()) { 4045 res[i++] = it.next().name; 4046 } 4047 return res; 4048 } else if (obj instanceof PackageSetting) { 4049 final PackageSetting ps = (PackageSetting) obj; 4050 return new String[] { ps.name }; 4051 } 4052 } 4053 return null; 4054 } 4055 4056 @Override 4057 public String getNameForUid(int uid) { 4058 // reader 4059 synchronized (mPackages) { 4060 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4061 if (obj instanceof SharedUserSetting) { 4062 final SharedUserSetting sus = (SharedUserSetting) obj; 4063 return sus.name + ":" + sus.userId; 4064 } else if (obj instanceof PackageSetting) { 4065 final PackageSetting ps = (PackageSetting) obj; 4066 return ps.name; 4067 } 4068 } 4069 return null; 4070 } 4071 4072 @Override 4073 public int getUidForSharedUser(String sharedUserName) { 4074 if(sharedUserName == null) { 4075 return -1; 4076 } 4077 // reader 4078 synchronized (mPackages) { 4079 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4080 if (suid == null) { 4081 return -1; 4082 } 4083 return suid.userId; 4084 } 4085 } 4086 4087 @Override 4088 public int getFlagsForUid(int uid) { 4089 synchronized (mPackages) { 4090 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4091 if (obj instanceof SharedUserSetting) { 4092 final SharedUserSetting sus = (SharedUserSetting) obj; 4093 return sus.pkgFlags; 4094 } else if (obj instanceof PackageSetting) { 4095 final PackageSetting ps = (PackageSetting) obj; 4096 return ps.pkgFlags; 4097 } 4098 } 4099 return 0; 4100 } 4101 4102 @Override 4103 public int getPrivateFlagsForUid(int uid) { 4104 synchronized (mPackages) { 4105 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4106 if (obj instanceof SharedUserSetting) { 4107 final SharedUserSetting sus = (SharedUserSetting) obj; 4108 return sus.pkgPrivateFlags; 4109 } else if (obj instanceof PackageSetting) { 4110 final PackageSetting ps = (PackageSetting) obj; 4111 return ps.pkgPrivateFlags; 4112 } 4113 } 4114 return 0; 4115 } 4116 4117 @Override 4118 public boolean isUidPrivileged(int uid) { 4119 uid = UserHandle.getAppId(uid); 4120 // reader 4121 synchronized (mPackages) { 4122 Object obj = mSettings.getUserIdLPr(uid); 4123 if (obj instanceof SharedUserSetting) { 4124 final SharedUserSetting sus = (SharedUserSetting) obj; 4125 final Iterator<PackageSetting> it = sus.packages.iterator(); 4126 while (it.hasNext()) { 4127 if (it.next().isPrivileged()) { 4128 return true; 4129 } 4130 } 4131 } else if (obj instanceof PackageSetting) { 4132 final PackageSetting ps = (PackageSetting) obj; 4133 return ps.isPrivileged(); 4134 } 4135 } 4136 return false; 4137 } 4138 4139 @Override 4140 public String[] getAppOpPermissionPackages(String permissionName) { 4141 synchronized (mPackages) { 4142 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4143 if (pkgs == null) { 4144 return null; 4145 } 4146 return pkgs.toArray(new String[pkgs.size()]); 4147 } 4148 } 4149 4150 @Override 4151 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4152 int flags, int userId) { 4153 if (!sUserManager.exists(userId)) return null; 4154 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 4155 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4156 return chooseBestActivity(intent, resolvedType, flags, query, userId); 4157 } 4158 4159 @Override 4160 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4161 IntentFilter filter, int match, ComponentName activity) { 4162 final int userId = UserHandle.getCallingUserId(); 4163 if (DEBUG_PREFERRED) { 4164 Log.v(TAG, "setLastChosenActivity intent=" + intent 4165 + " resolvedType=" + resolvedType 4166 + " flags=" + flags 4167 + " filter=" + filter 4168 + " match=" + match 4169 + " activity=" + activity); 4170 filter.dump(new PrintStreamPrinter(System.out), " "); 4171 } 4172 intent.setComponent(null); 4173 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4174 // Find any earlier preferred or last chosen entries and nuke them 4175 findPreferredActivity(intent, resolvedType, 4176 flags, query, 0, false, true, false, userId); 4177 // Add the new activity as the last chosen for this filter 4178 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4179 "Setting last chosen"); 4180 } 4181 4182 @Override 4183 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4184 final int userId = UserHandle.getCallingUserId(); 4185 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4186 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4187 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4188 false, false, false, userId); 4189 } 4190 4191 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4192 int flags, List<ResolveInfo> query, int userId) { 4193 if (query != null) { 4194 final int N = query.size(); 4195 if (N == 1) { 4196 return query.get(0); 4197 } else if (N > 1) { 4198 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4199 // If there is more than one activity with the same priority, 4200 // then let the user decide between them. 4201 ResolveInfo r0 = query.get(0); 4202 ResolveInfo r1 = query.get(1); 4203 if (DEBUG_INTENT_MATCHING || debug) { 4204 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4205 + r1.activityInfo.name + "=" + r1.priority); 4206 } 4207 // If the first activity has a higher priority, or a different 4208 // default, then it is always desireable to pick it. 4209 if (r0.priority != r1.priority 4210 || r0.preferredOrder != r1.preferredOrder 4211 || r0.isDefault != r1.isDefault) { 4212 return query.get(0); 4213 } 4214 // If we have saved a preference for a preferred activity for 4215 // this Intent, use that. 4216 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4217 flags, query, r0.priority, true, false, debug, userId); 4218 if (ri != null) { 4219 return ri; 4220 } 4221 if (userId != 0) { 4222 ri = new ResolveInfo(mResolveInfo); 4223 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4224 ri.activityInfo.applicationInfo = new ApplicationInfo( 4225 ri.activityInfo.applicationInfo); 4226 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4227 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4228 return ri; 4229 } 4230 return mResolveInfo; 4231 } 4232 } 4233 return null; 4234 } 4235 4236 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4237 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4238 final int N = query.size(); 4239 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4240 .get(userId); 4241 // Get the list of persistent preferred activities that handle the intent 4242 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4243 List<PersistentPreferredActivity> pprefs = ppir != null 4244 ? ppir.queryIntent(intent, resolvedType, 4245 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4246 : null; 4247 if (pprefs != null && pprefs.size() > 0) { 4248 final int M = pprefs.size(); 4249 for (int i=0; i<M; i++) { 4250 final PersistentPreferredActivity ppa = pprefs.get(i); 4251 if (DEBUG_PREFERRED || debug) { 4252 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4253 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4254 + "\n component=" + ppa.mComponent); 4255 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4256 } 4257 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4258 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4259 if (DEBUG_PREFERRED || debug) { 4260 Slog.v(TAG, "Found persistent preferred activity:"); 4261 if (ai != null) { 4262 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4263 } else { 4264 Slog.v(TAG, " null"); 4265 } 4266 } 4267 if (ai == null) { 4268 // This previously registered persistent preferred activity 4269 // component is no longer known. Ignore it and do NOT remove it. 4270 continue; 4271 } 4272 for (int j=0; j<N; j++) { 4273 final ResolveInfo ri = query.get(j); 4274 if (!ri.activityInfo.applicationInfo.packageName 4275 .equals(ai.applicationInfo.packageName)) { 4276 continue; 4277 } 4278 if (!ri.activityInfo.name.equals(ai.name)) { 4279 continue; 4280 } 4281 // Found a persistent preference that can handle the intent. 4282 if (DEBUG_PREFERRED || debug) { 4283 Slog.v(TAG, "Returning persistent preferred activity: " + 4284 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4285 } 4286 return ri; 4287 } 4288 } 4289 } 4290 return null; 4291 } 4292 4293 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4294 List<ResolveInfo> query, int priority, boolean always, 4295 boolean removeMatches, boolean debug, int userId) { 4296 if (!sUserManager.exists(userId)) return null; 4297 // writer 4298 synchronized (mPackages) { 4299 if (intent.getSelector() != null) { 4300 intent = intent.getSelector(); 4301 } 4302 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4303 4304 // Try to find a matching persistent preferred activity. 4305 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4306 debug, userId); 4307 4308 // If a persistent preferred activity matched, use it. 4309 if (pri != null) { 4310 return pri; 4311 } 4312 4313 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4314 // Get the list of preferred activities that handle the intent 4315 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4316 List<PreferredActivity> prefs = pir != null 4317 ? pir.queryIntent(intent, resolvedType, 4318 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4319 : null; 4320 if (prefs != null && prefs.size() > 0) { 4321 boolean changed = false; 4322 try { 4323 // First figure out how good the original match set is. 4324 // We will only allow preferred activities that came 4325 // from the same match quality. 4326 int match = 0; 4327 4328 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4329 4330 final int N = query.size(); 4331 for (int j=0; j<N; j++) { 4332 final ResolveInfo ri = query.get(j); 4333 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4334 + ": 0x" + Integer.toHexString(match)); 4335 if (ri.match > match) { 4336 match = ri.match; 4337 } 4338 } 4339 4340 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4341 + Integer.toHexString(match)); 4342 4343 match &= IntentFilter.MATCH_CATEGORY_MASK; 4344 final int M = prefs.size(); 4345 for (int i=0; i<M; i++) { 4346 final PreferredActivity pa = prefs.get(i); 4347 if (DEBUG_PREFERRED || debug) { 4348 Slog.v(TAG, "Checking PreferredActivity ds=" 4349 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4350 + "\n component=" + pa.mPref.mComponent); 4351 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4352 } 4353 if (pa.mPref.mMatch != match) { 4354 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4355 + Integer.toHexString(pa.mPref.mMatch)); 4356 continue; 4357 } 4358 // If it's not an "always" type preferred activity and that's what we're 4359 // looking for, skip it. 4360 if (always && !pa.mPref.mAlways) { 4361 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4362 continue; 4363 } 4364 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4365 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4366 if (DEBUG_PREFERRED || debug) { 4367 Slog.v(TAG, "Found preferred activity:"); 4368 if (ai != null) { 4369 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4370 } else { 4371 Slog.v(TAG, " null"); 4372 } 4373 } 4374 if (ai == null) { 4375 // This previously registered preferred activity 4376 // component is no longer known. Most likely an update 4377 // to the app was installed and in the new version this 4378 // component no longer exists. Clean it up by removing 4379 // it from the preferred activities list, and skip it. 4380 Slog.w(TAG, "Removing dangling preferred activity: " 4381 + pa.mPref.mComponent); 4382 pir.removeFilter(pa); 4383 changed = true; 4384 continue; 4385 } 4386 for (int j=0; j<N; j++) { 4387 final ResolveInfo ri = query.get(j); 4388 if (!ri.activityInfo.applicationInfo.packageName 4389 .equals(ai.applicationInfo.packageName)) { 4390 continue; 4391 } 4392 if (!ri.activityInfo.name.equals(ai.name)) { 4393 continue; 4394 } 4395 4396 if (removeMatches) { 4397 pir.removeFilter(pa); 4398 changed = true; 4399 if (DEBUG_PREFERRED) { 4400 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4401 } 4402 break; 4403 } 4404 4405 // Okay we found a previously set preferred or last chosen app. 4406 // If the result set is different from when this 4407 // was created, we need to clear it and re-ask the 4408 // user their preference, if we're looking for an "always" type entry. 4409 if (always && !pa.mPref.sameSet(query)) { 4410 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4411 + intent + " type " + resolvedType); 4412 if (DEBUG_PREFERRED) { 4413 Slog.v(TAG, "Removing preferred activity since set changed " 4414 + pa.mPref.mComponent); 4415 } 4416 pir.removeFilter(pa); 4417 // Re-add the filter as a "last chosen" entry (!always) 4418 PreferredActivity lastChosen = new PreferredActivity( 4419 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4420 pir.addFilter(lastChosen); 4421 changed = true; 4422 return null; 4423 } 4424 4425 // Yay! Either the set matched or we're looking for the last chosen 4426 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4427 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4428 return ri; 4429 } 4430 } 4431 } finally { 4432 if (changed) { 4433 if (DEBUG_PREFERRED) { 4434 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4435 } 4436 scheduleWritePackageRestrictionsLocked(userId); 4437 } 4438 } 4439 } 4440 } 4441 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4442 return null; 4443 } 4444 4445 /* 4446 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4447 */ 4448 @Override 4449 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4450 int targetUserId) { 4451 mContext.enforceCallingOrSelfPermission( 4452 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4453 List<CrossProfileIntentFilter> matches = 4454 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4455 if (matches != null) { 4456 int size = matches.size(); 4457 for (int i = 0; i < size; i++) { 4458 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4459 } 4460 } 4461 if (hasWebURI(intent)) { 4462 // cross-profile app linking works only towards the parent. 4463 final UserInfo parent = getProfileParent(sourceUserId); 4464 synchronized(mPackages) { 4465 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 4466 intent, resolvedType, 0, sourceUserId, parent.id); 4467 return xpDomainInfo != null; 4468 } 4469 } 4470 return false; 4471 } 4472 4473 private UserInfo getProfileParent(int userId) { 4474 final long identity = Binder.clearCallingIdentity(); 4475 try { 4476 return sUserManager.getProfileParent(userId); 4477 } finally { 4478 Binder.restoreCallingIdentity(identity); 4479 } 4480 } 4481 4482 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4483 String resolvedType, int userId) { 4484 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4485 if (resolver != null) { 4486 return resolver.queryIntent(intent, resolvedType, false, userId); 4487 } 4488 return null; 4489 } 4490 4491 @Override 4492 public List<ResolveInfo> queryIntentActivities(Intent intent, 4493 String resolvedType, int flags, int userId) { 4494 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4495 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4496 ComponentName comp = intent.getComponent(); 4497 if (comp == null) { 4498 if (intent.getSelector() != null) { 4499 intent = intent.getSelector(); 4500 comp = intent.getComponent(); 4501 } 4502 } 4503 4504 if (comp != null) { 4505 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4506 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4507 if (ai != null) { 4508 final ResolveInfo ri = new ResolveInfo(); 4509 ri.activityInfo = ai; 4510 list.add(ri); 4511 } 4512 return list; 4513 } 4514 4515 // reader 4516 synchronized (mPackages) { 4517 final String pkgName = intent.getPackage(); 4518 if (pkgName == null) { 4519 List<CrossProfileIntentFilter> matchingFilters = 4520 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4521 // Check for results that need to skip the current profile. 4522 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4523 resolvedType, flags, userId); 4524 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4525 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4526 result.add(xpResolveInfo); 4527 return filterIfNotPrimaryUser(result, userId); 4528 } 4529 4530 // Check for results in the current profile. 4531 List<ResolveInfo> result = mActivities.queryIntent( 4532 intent, resolvedType, flags, userId); 4533 4534 // Check for cross profile results. 4535 xpResolveInfo = queryCrossProfileIntents( 4536 matchingFilters, intent, resolvedType, flags, userId); 4537 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4538 result.add(xpResolveInfo); 4539 Collections.sort(result, mResolvePrioritySorter); 4540 } 4541 result = filterIfNotPrimaryUser(result, userId); 4542 if (hasWebURI(intent)) { 4543 CrossProfileDomainInfo xpDomainInfo = null; 4544 final UserInfo parent = getProfileParent(userId); 4545 if (parent != null) { 4546 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 4547 flags, userId, parent.id); 4548 } 4549 if (xpDomainInfo != null) { 4550 if (xpResolveInfo != null) { 4551 // If we didn't remove it, the cross-profile ResolveInfo would be twice 4552 // in the result. 4553 result.remove(xpResolveInfo); 4554 } 4555 if (result.size() == 0) { 4556 result.add(xpDomainInfo.resolveInfo); 4557 return result; 4558 } 4559 } else if (result.size() <= 1) { 4560 return result; 4561 } 4562 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 4563 xpDomainInfo, userId); 4564 Collections.sort(result, mResolvePrioritySorter); 4565 } 4566 return result; 4567 } 4568 final PackageParser.Package pkg = mPackages.get(pkgName); 4569 if (pkg != null) { 4570 return filterIfNotPrimaryUser( 4571 mActivities.queryIntentForPackage( 4572 intent, resolvedType, flags, pkg.activities, userId), 4573 userId); 4574 } 4575 return new ArrayList<ResolveInfo>(); 4576 } 4577 } 4578 4579 private static class CrossProfileDomainInfo { 4580 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 4581 ResolveInfo resolveInfo; 4582 /* Best domain verification status of the activities found in the other profile */ 4583 int bestDomainVerificationStatus; 4584 } 4585 4586 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 4587 String resolvedType, int flags, int sourceUserId, int parentUserId) { 4588 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 4589 sourceUserId)) { 4590 return null; 4591 } 4592 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4593 resolvedType, flags, parentUserId); 4594 4595 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 4596 return null; 4597 } 4598 CrossProfileDomainInfo result = null; 4599 int size = resultTargetUser.size(); 4600 for (int i = 0; i < size; i++) { 4601 ResolveInfo riTargetUser = resultTargetUser.get(i); 4602 // Intent filter verification is only for filters that specify a host. So don't return 4603 // those that handle all web uris. 4604 if (riTargetUser.handleAllWebDataURI) { 4605 continue; 4606 } 4607 String packageName = riTargetUser.activityInfo.packageName; 4608 PackageSetting ps = mSettings.mPackages.get(packageName); 4609 if (ps == null) { 4610 continue; 4611 } 4612 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 4613 int status = (int)(verificationState >> 32); 4614 if (result == null) { 4615 result = new CrossProfileDomainInfo(); 4616 result.resolveInfo = 4617 createForwardingResolveInfo(null, sourceUserId, parentUserId); 4618 result.bestDomainVerificationStatus = status; 4619 } else { 4620 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 4621 result.bestDomainVerificationStatus); 4622 } 4623 } 4624 // Don't consider matches with status NEVER across profiles. 4625 if (result != null && result.bestDomainVerificationStatus 4626 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4627 return null; 4628 } 4629 return result; 4630 } 4631 4632 /** 4633 * Verification statuses are ordered from the worse to the best, except for 4634 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 4635 */ 4636 private int bestDomainVerificationStatus(int status1, int status2) { 4637 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4638 return status2; 4639 } 4640 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4641 return status1; 4642 } 4643 return (int) MathUtils.max(status1, status2); 4644 } 4645 4646 private boolean isUserEnabled(int userId) { 4647 long callingId = Binder.clearCallingIdentity(); 4648 try { 4649 UserInfo userInfo = sUserManager.getUserInfo(userId); 4650 return userInfo != null && userInfo.isEnabled(); 4651 } finally { 4652 Binder.restoreCallingIdentity(callingId); 4653 } 4654 } 4655 4656 /** 4657 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 4658 * 4659 * @return filtered list 4660 */ 4661 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 4662 if (userId == UserHandle.USER_OWNER) { 4663 return resolveInfos; 4664 } 4665 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 4666 ResolveInfo info = resolveInfos.get(i); 4667 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 4668 resolveInfos.remove(i); 4669 } 4670 } 4671 return resolveInfos; 4672 } 4673 4674 private static boolean hasWebURI(Intent intent) { 4675 if (intent.getData() == null) { 4676 return false; 4677 } 4678 final String scheme = intent.getScheme(); 4679 if (TextUtils.isEmpty(scheme)) { 4680 return false; 4681 } 4682 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4683 } 4684 4685 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 4686 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 4687 int userId) { 4688 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 4689 4690 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4691 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 4692 candidates.size()); 4693 } 4694 4695 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4696 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 4697 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4698 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4699 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4700 4701 synchronized (mPackages) { 4702 final int count = candidates.size(); 4703 // First, try to use linked apps. Partition the candidates into four lists: 4704 // one for the final results, one for the "do not use ever", one for "undefined status" 4705 // and finally one for "browser app type". 4706 for (int n=0; n<count; n++) { 4707 ResolveInfo info = candidates.get(n); 4708 String packageName = info.activityInfo.packageName; 4709 PackageSetting ps = mSettings.mPackages.get(packageName); 4710 if (ps != null) { 4711 // Add to the special match all list (Browser use case) 4712 if (info.handleAllWebDataURI) { 4713 matchAllList.add(info); 4714 continue; 4715 } 4716 // Try to get the status from User settings first 4717 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4718 int status = (int)(packedStatus >> 32); 4719 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 4720 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4721 if (DEBUG_DOMAIN_VERIFICATION) { 4722 Slog.i(TAG, " + always: " + info.activityInfo.packageName 4723 + " : linkgen=" + linkGeneration); 4724 } 4725 // Use link-enabled generation as preferredOrder, i.e. 4726 // prefer newly-enabled over earlier-enabled. 4727 info.preferredOrder = linkGeneration; 4728 alwaysList.add(info); 4729 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4730 if (DEBUG_DOMAIN_VERIFICATION) { 4731 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 4732 } 4733 neverList.add(info); 4734 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 4735 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 4736 if (DEBUG_DOMAIN_VERIFICATION) { 4737 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 4738 } 4739 undefinedList.add(info); 4740 } 4741 } 4742 } 4743 // First try to add the "always" resolution(s) for the current user, if any 4744 if (alwaysList.size() > 0) { 4745 result.addAll(alwaysList); 4746 // if there is an "always" for the parent user, add it. 4747 } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus 4748 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4749 result.add(xpDomainInfo.resolveInfo); 4750 } else { 4751 // Add all undefined Apps as we want them to appear in the Disambiguation dialog. 4752 result.addAll(undefinedList); 4753 if (xpDomainInfo != null && ( 4754 xpDomainInfo.bestDomainVerificationStatus 4755 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 4756 || xpDomainInfo.bestDomainVerificationStatus 4757 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) { 4758 result.add(xpDomainInfo.resolveInfo); 4759 } 4760 // Also add Browsers (all of them or only the default one) 4761 if ((matchFlags & MATCH_ALL) != 0) { 4762 result.addAll(matchAllList); 4763 } else { 4764 // Browser/generic handling case. If there's a default browser, go straight 4765 // to that (but only if there is no other higher-priority match). 4766 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 4767 int maxMatchPrio = 0; 4768 ResolveInfo defaultBrowserMatch = null; 4769 final int numCandidates = matchAllList.size(); 4770 for (int n = 0; n < numCandidates; n++) { 4771 ResolveInfo info = matchAllList.get(n); 4772 // track the highest overall match priority... 4773 if (info.priority > maxMatchPrio) { 4774 maxMatchPrio = info.priority; 4775 } 4776 // ...and the highest-priority default browser match 4777 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4778 if (defaultBrowserMatch == null 4779 || (defaultBrowserMatch.priority < info.priority)) { 4780 if (debug) { 4781 Slog.v(TAG, "Considering default browser match " + info); 4782 } 4783 defaultBrowserMatch = info; 4784 } 4785 } 4786 } 4787 if (defaultBrowserMatch != null 4788 && defaultBrowserMatch.priority >= maxMatchPrio 4789 && !TextUtils.isEmpty(defaultBrowserPackageName)) 4790 { 4791 if (debug) { 4792 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 4793 } 4794 result.add(defaultBrowserMatch); 4795 } else { 4796 result.addAll(matchAllList); 4797 } 4798 } 4799 4800 // If there is nothing selected, add all candidates and remove the ones that the user 4801 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 4802 if (result.size() == 0) { 4803 result.addAll(candidates); 4804 result.removeAll(neverList); 4805 } 4806 } 4807 } 4808 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4809 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 4810 result.size()); 4811 for (ResolveInfo info : result) { 4812 Slog.v(TAG, " + " + info.activityInfo); 4813 } 4814 } 4815 return result; 4816 } 4817 4818 // Returns a packed value as a long: 4819 // 4820 // high 'int'-sized word: link status: undefined/ask/never/always. 4821 // low 'int'-sized word: relative priority among 'always' results. 4822 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4823 long result = ps.getDomainVerificationStatusForUser(userId); 4824 // if none available, get the master status 4825 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4826 if (ps.getIntentFilterVerificationInfo() != null) { 4827 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 4828 } 4829 } 4830 return result; 4831 } 4832 4833 private ResolveInfo querySkipCurrentProfileIntents( 4834 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4835 int flags, int sourceUserId) { 4836 if (matchingFilters != null) { 4837 int size = matchingFilters.size(); 4838 for (int i = 0; i < size; i ++) { 4839 CrossProfileIntentFilter filter = matchingFilters.get(i); 4840 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4841 // Checking if there are activities in the target user that can handle the 4842 // intent. 4843 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4844 flags, sourceUserId); 4845 if (resolveInfo != null) { 4846 return resolveInfo; 4847 } 4848 } 4849 } 4850 } 4851 return null; 4852 } 4853 4854 // Return matching ResolveInfo if any for skip current profile intent filters. 4855 private ResolveInfo queryCrossProfileIntents( 4856 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4857 int flags, int sourceUserId) { 4858 if (matchingFilters != null) { 4859 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4860 // match the same intent. For performance reasons, it is better not to 4861 // run queryIntent twice for the same userId 4862 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4863 int size = matchingFilters.size(); 4864 for (int i = 0; i < size; i++) { 4865 CrossProfileIntentFilter filter = matchingFilters.get(i); 4866 int targetUserId = filter.getTargetUserId(); 4867 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4868 && !alreadyTriedUserIds.get(targetUserId)) { 4869 // Checking if there are activities in the target user that can handle the 4870 // intent. 4871 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4872 flags, sourceUserId); 4873 if (resolveInfo != null) return resolveInfo; 4874 alreadyTriedUserIds.put(targetUserId, true); 4875 } 4876 } 4877 } 4878 return null; 4879 } 4880 4881 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 4882 String resolvedType, int flags, int sourceUserId) { 4883 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4884 resolvedType, flags, filter.getTargetUserId()); 4885 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4886 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4887 } 4888 return null; 4889 } 4890 4891 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4892 int sourceUserId, int targetUserId) { 4893 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4894 String className; 4895 if (targetUserId == UserHandle.USER_OWNER) { 4896 className = FORWARD_INTENT_TO_USER_OWNER; 4897 } else { 4898 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4899 } 4900 ComponentName forwardingActivityComponentName = new ComponentName( 4901 mAndroidApplication.packageName, className); 4902 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4903 sourceUserId); 4904 if (targetUserId == UserHandle.USER_OWNER) { 4905 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 4906 forwardingResolveInfo.noResourceId = true; 4907 } 4908 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4909 forwardingResolveInfo.priority = 0; 4910 forwardingResolveInfo.preferredOrder = 0; 4911 forwardingResolveInfo.match = 0; 4912 forwardingResolveInfo.isDefault = true; 4913 forwardingResolveInfo.filter = filter; 4914 forwardingResolveInfo.targetUserId = targetUserId; 4915 return forwardingResolveInfo; 4916 } 4917 4918 @Override 4919 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4920 Intent[] specifics, String[] specificTypes, Intent intent, 4921 String resolvedType, int flags, int userId) { 4922 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4923 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4924 false, "query intent activity options"); 4925 final String resultsAction = intent.getAction(); 4926 4927 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4928 | PackageManager.GET_RESOLVED_FILTER, userId); 4929 4930 if (DEBUG_INTENT_MATCHING) { 4931 Log.v(TAG, "Query " + intent + ": " + results); 4932 } 4933 4934 int specificsPos = 0; 4935 int N; 4936 4937 // todo: note that the algorithm used here is O(N^2). This 4938 // isn't a problem in our current environment, but if we start running 4939 // into situations where we have more than 5 or 10 matches then this 4940 // should probably be changed to something smarter... 4941 4942 // First we go through and resolve each of the specific items 4943 // that were supplied, taking care of removing any corresponding 4944 // duplicate items in the generic resolve list. 4945 if (specifics != null) { 4946 for (int i=0; i<specifics.length; i++) { 4947 final Intent sintent = specifics[i]; 4948 if (sintent == null) { 4949 continue; 4950 } 4951 4952 if (DEBUG_INTENT_MATCHING) { 4953 Log.v(TAG, "Specific #" + i + ": " + sintent); 4954 } 4955 4956 String action = sintent.getAction(); 4957 if (resultsAction != null && resultsAction.equals(action)) { 4958 // If this action was explicitly requested, then don't 4959 // remove things that have it. 4960 action = null; 4961 } 4962 4963 ResolveInfo ri = null; 4964 ActivityInfo ai = null; 4965 4966 ComponentName comp = sintent.getComponent(); 4967 if (comp == null) { 4968 ri = resolveIntent( 4969 sintent, 4970 specificTypes != null ? specificTypes[i] : null, 4971 flags, userId); 4972 if (ri == null) { 4973 continue; 4974 } 4975 if (ri == mResolveInfo) { 4976 // ACK! Must do something better with this. 4977 } 4978 ai = ri.activityInfo; 4979 comp = new ComponentName(ai.applicationInfo.packageName, 4980 ai.name); 4981 } else { 4982 ai = getActivityInfo(comp, flags, userId); 4983 if (ai == null) { 4984 continue; 4985 } 4986 } 4987 4988 // Look for any generic query activities that are duplicates 4989 // of this specific one, and remove them from the results. 4990 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 4991 N = results.size(); 4992 int j; 4993 for (j=specificsPos; j<N; j++) { 4994 ResolveInfo sri = results.get(j); 4995 if ((sri.activityInfo.name.equals(comp.getClassName()) 4996 && sri.activityInfo.applicationInfo.packageName.equals( 4997 comp.getPackageName())) 4998 || (action != null && sri.filter.matchAction(action))) { 4999 results.remove(j); 5000 if (DEBUG_INTENT_MATCHING) Log.v( 5001 TAG, "Removing duplicate item from " + j 5002 + " due to specific " + specificsPos); 5003 if (ri == null) { 5004 ri = sri; 5005 } 5006 j--; 5007 N--; 5008 } 5009 } 5010 5011 // Add this specific item to its proper place. 5012 if (ri == null) { 5013 ri = new ResolveInfo(); 5014 ri.activityInfo = ai; 5015 } 5016 results.add(specificsPos, ri); 5017 ri.specificIndex = i; 5018 specificsPos++; 5019 } 5020 } 5021 5022 // Now we go through the remaining generic results and remove any 5023 // duplicate actions that are found here. 5024 N = results.size(); 5025 for (int i=specificsPos; i<N-1; i++) { 5026 final ResolveInfo rii = results.get(i); 5027 if (rii.filter == null) { 5028 continue; 5029 } 5030 5031 // Iterate over all of the actions of this result's intent 5032 // filter... typically this should be just one. 5033 final Iterator<String> it = rii.filter.actionsIterator(); 5034 if (it == null) { 5035 continue; 5036 } 5037 while (it.hasNext()) { 5038 final String action = it.next(); 5039 if (resultsAction != null && resultsAction.equals(action)) { 5040 // If this action was explicitly requested, then don't 5041 // remove things that have it. 5042 continue; 5043 } 5044 for (int j=i+1; j<N; j++) { 5045 final ResolveInfo rij = results.get(j); 5046 if (rij.filter != null && rij.filter.hasAction(action)) { 5047 results.remove(j); 5048 if (DEBUG_INTENT_MATCHING) Log.v( 5049 TAG, "Removing duplicate item from " + j 5050 + " due to action " + action + " at " + i); 5051 j--; 5052 N--; 5053 } 5054 } 5055 } 5056 5057 // If the caller didn't request filter information, drop it now 5058 // so we don't have to marshall/unmarshall it. 5059 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5060 rii.filter = null; 5061 } 5062 } 5063 5064 // Filter out the caller activity if so requested. 5065 if (caller != null) { 5066 N = results.size(); 5067 for (int i=0; i<N; i++) { 5068 ActivityInfo ainfo = results.get(i).activityInfo; 5069 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5070 && caller.getClassName().equals(ainfo.name)) { 5071 results.remove(i); 5072 break; 5073 } 5074 } 5075 } 5076 5077 // If the caller didn't request filter information, 5078 // drop them now so we don't have to 5079 // marshall/unmarshall it. 5080 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5081 N = results.size(); 5082 for (int i=0; i<N; i++) { 5083 results.get(i).filter = null; 5084 } 5085 } 5086 5087 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5088 return results; 5089 } 5090 5091 @Override 5092 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 5093 int userId) { 5094 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5095 ComponentName comp = intent.getComponent(); 5096 if (comp == null) { 5097 if (intent.getSelector() != null) { 5098 intent = intent.getSelector(); 5099 comp = intent.getComponent(); 5100 } 5101 } 5102 if (comp != null) { 5103 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5104 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5105 if (ai != null) { 5106 ResolveInfo ri = new ResolveInfo(); 5107 ri.activityInfo = ai; 5108 list.add(ri); 5109 } 5110 return list; 5111 } 5112 5113 // reader 5114 synchronized (mPackages) { 5115 String pkgName = intent.getPackage(); 5116 if (pkgName == null) { 5117 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5118 } 5119 final PackageParser.Package pkg = mPackages.get(pkgName); 5120 if (pkg != null) { 5121 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5122 userId); 5123 } 5124 return null; 5125 } 5126 } 5127 5128 @Override 5129 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5130 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 5131 if (!sUserManager.exists(userId)) return null; 5132 if (query != null) { 5133 if (query.size() >= 1) { 5134 // If there is more than one service with the same priority, 5135 // just arbitrarily pick the first one. 5136 return query.get(0); 5137 } 5138 } 5139 return null; 5140 } 5141 5142 @Override 5143 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 5144 int userId) { 5145 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5146 ComponentName comp = intent.getComponent(); 5147 if (comp == null) { 5148 if (intent.getSelector() != null) { 5149 intent = intent.getSelector(); 5150 comp = intent.getComponent(); 5151 } 5152 } 5153 if (comp != null) { 5154 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5155 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5156 if (si != null) { 5157 final ResolveInfo ri = new ResolveInfo(); 5158 ri.serviceInfo = si; 5159 list.add(ri); 5160 } 5161 return list; 5162 } 5163 5164 // reader 5165 synchronized (mPackages) { 5166 String pkgName = intent.getPackage(); 5167 if (pkgName == null) { 5168 return mServices.queryIntent(intent, resolvedType, flags, userId); 5169 } 5170 final PackageParser.Package pkg = mPackages.get(pkgName); 5171 if (pkg != null) { 5172 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5173 userId); 5174 } 5175 return null; 5176 } 5177 } 5178 5179 @Override 5180 public List<ResolveInfo> queryIntentContentProviders( 5181 Intent intent, String resolvedType, int flags, int userId) { 5182 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5183 ComponentName comp = intent.getComponent(); 5184 if (comp == null) { 5185 if (intent.getSelector() != null) { 5186 intent = intent.getSelector(); 5187 comp = intent.getComponent(); 5188 } 5189 } 5190 if (comp != null) { 5191 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5192 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5193 if (pi != null) { 5194 final ResolveInfo ri = new ResolveInfo(); 5195 ri.providerInfo = pi; 5196 list.add(ri); 5197 } 5198 return list; 5199 } 5200 5201 // reader 5202 synchronized (mPackages) { 5203 String pkgName = intent.getPackage(); 5204 if (pkgName == null) { 5205 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5206 } 5207 final PackageParser.Package pkg = mPackages.get(pkgName); 5208 if (pkg != null) { 5209 return mProviders.queryIntentForPackage( 5210 intent, resolvedType, flags, pkg.providers, userId); 5211 } 5212 return null; 5213 } 5214 } 5215 5216 @Override 5217 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5218 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5219 5220 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 5221 5222 // writer 5223 synchronized (mPackages) { 5224 ArrayList<PackageInfo> list; 5225 if (listUninstalled) { 5226 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5227 for (PackageSetting ps : mSettings.mPackages.values()) { 5228 PackageInfo pi; 5229 if (ps.pkg != null) { 5230 pi = generatePackageInfo(ps.pkg, flags, userId); 5231 } else { 5232 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5233 } 5234 if (pi != null) { 5235 list.add(pi); 5236 } 5237 } 5238 } else { 5239 list = new ArrayList<PackageInfo>(mPackages.size()); 5240 for (PackageParser.Package p : mPackages.values()) { 5241 PackageInfo pi = generatePackageInfo(p, flags, userId); 5242 if (pi != null) { 5243 list.add(pi); 5244 } 5245 } 5246 } 5247 5248 return new ParceledListSlice<PackageInfo>(list); 5249 } 5250 } 5251 5252 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5253 String[] permissions, boolean[] tmp, int flags, int userId) { 5254 int numMatch = 0; 5255 final PermissionsState permissionsState = ps.getPermissionsState(); 5256 for (int i=0; i<permissions.length; i++) { 5257 final String permission = permissions[i]; 5258 if (permissionsState.hasPermission(permission, userId)) { 5259 tmp[i] = true; 5260 numMatch++; 5261 } else { 5262 tmp[i] = false; 5263 } 5264 } 5265 if (numMatch == 0) { 5266 return; 5267 } 5268 PackageInfo pi; 5269 if (ps.pkg != null) { 5270 pi = generatePackageInfo(ps.pkg, flags, userId); 5271 } else { 5272 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5273 } 5274 // The above might return null in cases of uninstalled apps or install-state 5275 // skew across users/profiles. 5276 if (pi != null) { 5277 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5278 if (numMatch == permissions.length) { 5279 pi.requestedPermissions = permissions; 5280 } else { 5281 pi.requestedPermissions = new String[numMatch]; 5282 numMatch = 0; 5283 for (int i=0; i<permissions.length; i++) { 5284 if (tmp[i]) { 5285 pi.requestedPermissions[numMatch] = permissions[i]; 5286 numMatch++; 5287 } 5288 } 5289 } 5290 } 5291 list.add(pi); 5292 } 5293 } 5294 5295 @Override 5296 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5297 String[] permissions, int flags, int userId) { 5298 if (!sUserManager.exists(userId)) return null; 5299 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5300 5301 // writer 5302 synchronized (mPackages) { 5303 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5304 boolean[] tmpBools = new boolean[permissions.length]; 5305 if (listUninstalled) { 5306 for (PackageSetting ps : mSettings.mPackages.values()) { 5307 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5308 } 5309 } else { 5310 for (PackageParser.Package pkg : mPackages.values()) { 5311 PackageSetting ps = (PackageSetting)pkg.mExtras; 5312 if (ps != null) { 5313 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5314 userId); 5315 } 5316 } 5317 } 5318 5319 return new ParceledListSlice<PackageInfo>(list); 5320 } 5321 } 5322 5323 @Override 5324 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5325 if (!sUserManager.exists(userId)) return null; 5326 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5327 5328 // writer 5329 synchronized (mPackages) { 5330 ArrayList<ApplicationInfo> list; 5331 if (listUninstalled) { 5332 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5333 for (PackageSetting ps : mSettings.mPackages.values()) { 5334 ApplicationInfo ai; 5335 if (ps.pkg != null) { 5336 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5337 ps.readUserState(userId), userId); 5338 } else { 5339 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5340 } 5341 if (ai != null) { 5342 list.add(ai); 5343 } 5344 } 5345 } else { 5346 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5347 for (PackageParser.Package p : mPackages.values()) { 5348 if (p.mExtras != null) { 5349 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5350 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5351 if (ai != null) { 5352 list.add(ai); 5353 } 5354 } 5355 } 5356 } 5357 5358 return new ParceledListSlice<ApplicationInfo>(list); 5359 } 5360 } 5361 5362 public List<ApplicationInfo> getPersistentApplications(int flags) { 5363 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 5364 5365 // reader 5366 synchronized (mPackages) { 5367 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 5368 final int userId = UserHandle.getCallingUserId(); 5369 while (i.hasNext()) { 5370 final PackageParser.Package p = i.next(); 5371 if (p.applicationInfo != null 5372 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 5373 && (!mSafeMode || isSystemApp(p))) { 5374 PackageSetting ps = mSettings.mPackages.get(p.packageName); 5375 if (ps != null) { 5376 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5377 ps.readUserState(userId), userId); 5378 if (ai != null) { 5379 finalList.add(ai); 5380 } 5381 } 5382 } 5383 } 5384 } 5385 5386 return finalList; 5387 } 5388 5389 @Override 5390 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 5391 if (!sUserManager.exists(userId)) return null; 5392 // reader 5393 synchronized (mPackages) { 5394 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 5395 PackageSetting ps = provider != null 5396 ? mSettings.mPackages.get(provider.owner.packageName) 5397 : null; 5398 return ps != null 5399 && mSettings.isEnabledLPr(provider.info, flags, userId) 5400 && (!mSafeMode || (provider.info.applicationInfo.flags 5401 &ApplicationInfo.FLAG_SYSTEM) != 0) 5402 ? PackageParser.generateProviderInfo(provider, flags, 5403 ps.readUserState(userId), userId) 5404 : null; 5405 } 5406 } 5407 5408 /** 5409 * @deprecated 5410 */ 5411 @Deprecated 5412 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 5413 // reader 5414 synchronized (mPackages) { 5415 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 5416 .entrySet().iterator(); 5417 final int userId = UserHandle.getCallingUserId(); 5418 while (i.hasNext()) { 5419 Map.Entry<String, PackageParser.Provider> entry = i.next(); 5420 PackageParser.Provider p = entry.getValue(); 5421 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5422 5423 if (ps != null && p.syncable 5424 && (!mSafeMode || (p.info.applicationInfo.flags 5425 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 5426 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 5427 ps.readUserState(userId), userId); 5428 if (info != null) { 5429 outNames.add(entry.getKey()); 5430 outInfo.add(info); 5431 } 5432 } 5433 } 5434 } 5435 } 5436 5437 @Override 5438 public List<ProviderInfo> queryContentProviders(String processName, 5439 int uid, int flags) { 5440 ArrayList<ProviderInfo> finalList = null; 5441 // reader 5442 synchronized (mPackages) { 5443 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 5444 final int userId = processName != null ? 5445 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 5446 while (i.hasNext()) { 5447 final PackageParser.Provider p = i.next(); 5448 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5449 if (ps != null && p.info.authority != null 5450 && (processName == null 5451 || (p.info.processName.equals(processName) 5452 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 5453 && mSettings.isEnabledLPr(p.info, flags, userId) 5454 && (!mSafeMode 5455 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 5456 if (finalList == null) { 5457 finalList = new ArrayList<ProviderInfo>(3); 5458 } 5459 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 5460 ps.readUserState(userId), userId); 5461 if (info != null) { 5462 finalList.add(info); 5463 } 5464 } 5465 } 5466 } 5467 5468 if (finalList != null) { 5469 Collections.sort(finalList, mProviderInitOrderSorter); 5470 } 5471 5472 return finalList; 5473 } 5474 5475 @Override 5476 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 5477 int flags) { 5478 // reader 5479 synchronized (mPackages) { 5480 final PackageParser.Instrumentation i = mInstrumentation.get(name); 5481 return PackageParser.generateInstrumentationInfo(i, flags); 5482 } 5483 } 5484 5485 @Override 5486 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 5487 int flags) { 5488 ArrayList<InstrumentationInfo> finalList = 5489 new ArrayList<InstrumentationInfo>(); 5490 5491 // reader 5492 synchronized (mPackages) { 5493 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 5494 while (i.hasNext()) { 5495 final PackageParser.Instrumentation p = i.next(); 5496 if (targetPackage == null 5497 || targetPackage.equals(p.info.targetPackage)) { 5498 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 5499 flags); 5500 if (ii != null) { 5501 finalList.add(ii); 5502 } 5503 } 5504 } 5505 } 5506 5507 return finalList; 5508 } 5509 5510 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 5511 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 5512 if (overlays == null) { 5513 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 5514 return; 5515 } 5516 for (PackageParser.Package opkg : overlays.values()) { 5517 // Not much to do if idmap fails: we already logged the error 5518 // and we certainly don't want to abort installation of pkg simply 5519 // because an overlay didn't fit properly. For these reasons, 5520 // ignore the return value of createIdmapForPackagePairLI. 5521 createIdmapForPackagePairLI(pkg, opkg); 5522 } 5523 } 5524 5525 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 5526 PackageParser.Package opkg) { 5527 if (!opkg.mTrustedOverlay) { 5528 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 5529 opkg.baseCodePath + ": overlay not trusted"); 5530 return false; 5531 } 5532 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 5533 if (overlaySet == null) { 5534 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 5535 opkg.baseCodePath + " but target package has no known overlays"); 5536 return false; 5537 } 5538 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 5539 // TODO: generate idmap for split APKs 5540 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 5541 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 5542 + opkg.baseCodePath); 5543 return false; 5544 } 5545 PackageParser.Package[] overlayArray = 5546 overlaySet.values().toArray(new PackageParser.Package[0]); 5547 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 5548 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 5549 return p1.mOverlayPriority - p2.mOverlayPriority; 5550 } 5551 }; 5552 Arrays.sort(overlayArray, cmp); 5553 5554 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 5555 int i = 0; 5556 for (PackageParser.Package p : overlayArray) { 5557 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 5558 } 5559 return true; 5560 } 5561 5562 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5563 final File[] files = dir.listFiles(); 5564 if (ArrayUtils.isEmpty(files)) { 5565 Log.d(TAG, "No files in app dir " + dir); 5566 return; 5567 } 5568 5569 if (DEBUG_PACKAGE_SCANNING) { 5570 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 5571 + " flags=0x" + Integer.toHexString(parseFlags)); 5572 } 5573 5574 for (File file : files) { 5575 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 5576 && !PackageInstallerService.isStageName(file.getName()); 5577 if (!isPackage) { 5578 // Ignore entries which are not packages 5579 continue; 5580 } 5581 try { 5582 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 5583 scanFlags, currentTime, null); 5584 } catch (PackageManagerException e) { 5585 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 5586 5587 // Delete invalid userdata apps 5588 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 5589 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 5590 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 5591 if (file.isDirectory()) { 5592 mInstaller.rmPackageDir(file.getAbsolutePath()); 5593 } else { 5594 file.delete(); 5595 } 5596 } 5597 } 5598 } 5599 } 5600 5601 private static File getSettingsProblemFile() { 5602 File dataDir = Environment.getDataDirectory(); 5603 File systemDir = new File(dataDir, "system"); 5604 File fname = new File(systemDir, "uiderrors.txt"); 5605 return fname; 5606 } 5607 5608 static void reportSettingsProblem(int priority, String msg) { 5609 logCriticalInfo(priority, msg); 5610 } 5611 5612 static void logCriticalInfo(int priority, String msg) { 5613 Slog.println(priority, TAG, msg); 5614 EventLogTags.writePmCriticalInfo(msg); 5615 try { 5616 File fname = getSettingsProblemFile(); 5617 FileOutputStream out = new FileOutputStream(fname, true); 5618 PrintWriter pw = new FastPrintWriter(out); 5619 SimpleDateFormat formatter = new SimpleDateFormat(); 5620 String dateString = formatter.format(new Date(System.currentTimeMillis())); 5621 pw.println(dateString + ": " + msg); 5622 pw.close(); 5623 FileUtils.setPermissions( 5624 fname.toString(), 5625 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 5626 -1, -1); 5627 } catch (java.io.IOException e) { 5628 } 5629 } 5630 5631 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 5632 PackageParser.Package pkg, File srcFile, int parseFlags) 5633 throws PackageManagerException { 5634 if (ps != null 5635 && ps.codePath.equals(srcFile) 5636 && ps.timeStamp == srcFile.lastModified() 5637 && !isCompatSignatureUpdateNeeded(pkg) 5638 && !isRecoverSignatureUpdateNeeded(pkg)) { 5639 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 5640 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5641 ArraySet<PublicKey> signingKs; 5642 synchronized (mPackages) { 5643 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 5644 } 5645 if (ps.signatures.mSignatures != null 5646 && ps.signatures.mSignatures.length != 0 5647 && signingKs != null) { 5648 // Optimization: reuse the existing cached certificates 5649 // if the package appears to be unchanged. 5650 pkg.mSignatures = ps.signatures.mSignatures; 5651 pkg.mSigningKeys = signingKs; 5652 return; 5653 } 5654 5655 Slog.w(TAG, "PackageSetting for " + ps.name 5656 + " is missing signatures. Collecting certs again to recover them."); 5657 } else { 5658 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 5659 } 5660 5661 try { 5662 pp.collectCertificates(pkg, parseFlags); 5663 pp.collectManifestDigest(pkg); 5664 } catch (PackageParserException e) { 5665 throw PackageManagerException.from(e); 5666 } 5667 } 5668 5669 /* 5670 * Scan a package and return the newly parsed package. 5671 * Returns null in case of errors and the error code is stored in mLastScanError 5672 */ 5673 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 5674 long currentTime, UserHandle user) throws PackageManagerException { 5675 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 5676 parseFlags |= mDefParseFlags; 5677 PackageParser pp = new PackageParser(); 5678 pp.setSeparateProcesses(mSeparateProcesses); 5679 pp.setOnlyCoreApps(mOnlyCore); 5680 pp.setDisplayMetrics(mMetrics); 5681 5682 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 5683 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 5684 } 5685 5686 final PackageParser.Package pkg; 5687 try { 5688 pkg = pp.parsePackage(scanFile, parseFlags); 5689 } catch (PackageParserException e) { 5690 throw PackageManagerException.from(e); 5691 } 5692 5693 PackageSetting ps = null; 5694 PackageSetting updatedPkg; 5695 // reader 5696 synchronized (mPackages) { 5697 // Look to see if we already know about this package. 5698 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 5699 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 5700 // This package has been renamed to its original name. Let's 5701 // use that. 5702 ps = mSettings.peekPackageLPr(oldName); 5703 } 5704 // If there was no original package, see one for the real package name. 5705 if (ps == null) { 5706 ps = mSettings.peekPackageLPr(pkg.packageName); 5707 } 5708 // Check to see if this package could be hiding/updating a system 5709 // package. Must look for it either under the original or real 5710 // package name depending on our state. 5711 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 5712 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 5713 } 5714 boolean updatedPkgBetter = false; 5715 // First check if this is a system package that may involve an update 5716 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5717 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5718 // it needs to drop FLAG_PRIVILEGED. 5719 if (locationIsPrivileged(scanFile)) { 5720 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5721 } else { 5722 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5723 } 5724 5725 if (ps != null && !ps.codePath.equals(scanFile)) { 5726 // The path has changed from what was last scanned... check the 5727 // version of the new path against what we have stored to determine 5728 // what to do. 5729 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5730 if (pkg.mVersionCode <= ps.versionCode) { 5731 // The system package has been updated and the code path does not match 5732 // Ignore entry. Skip it. 5733 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5734 + " ignored: updated version " + ps.versionCode 5735 + " better than this " + pkg.mVersionCode); 5736 if (!updatedPkg.codePath.equals(scanFile)) { 5737 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5738 + ps.name + " changing from " + updatedPkg.codePathString 5739 + " to " + scanFile); 5740 updatedPkg.codePath = scanFile; 5741 updatedPkg.codePathString = scanFile.toString(); 5742 updatedPkg.resourcePath = scanFile; 5743 updatedPkg.resourcePathString = scanFile.toString(); 5744 } 5745 updatedPkg.pkg = pkg; 5746 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5747 "Package " + ps.name + " at " + scanFile 5748 + " ignored: updated version " + ps.versionCode 5749 + " better than this " + pkg.mVersionCode); 5750 } else { 5751 // The current app on the system partition is better than 5752 // what we have updated to on the data partition; switch 5753 // back to the system partition version. 5754 // At this point, its safely assumed that package installation for 5755 // apps in system partition will go through. If not there won't be a working 5756 // version of the app 5757 // writer 5758 synchronized (mPackages) { 5759 // Just remove the loaded entries from package lists. 5760 mPackages.remove(ps.name); 5761 } 5762 5763 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5764 + " reverting from " + ps.codePathString 5765 + ": new version " + pkg.mVersionCode 5766 + " better than installed " + ps.versionCode); 5767 5768 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5769 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5770 synchronized (mInstallLock) { 5771 args.cleanUpResourcesLI(); 5772 } 5773 synchronized (mPackages) { 5774 mSettings.enableSystemPackageLPw(ps.name); 5775 } 5776 updatedPkgBetter = true; 5777 } 5778 } 5779 } 5780 5781 if (updatedPkg != null) { 5782 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5783 // initially 5784 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5785 5786 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5787 // flag set initially 5788 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5789 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5790 } 5791 } 5792 5793 // Verify certificates against what was last scanned 5794 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5795 5796 /* 5797 * A new system app appeared, but we already had a non-system one of the 5798 * same name installed earlier. 5799 */ 5800 boolean shouldHideSystemApp = false; 5801 if (updatedPkg == null && ps != null 5802 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5803 /* 5804 * Check to make sure the signatures match first. If they don't, 5805 * wipe the installed application and its data. 5806 */ 5807 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5808 != PackageManager.SIGNATURE_MATCH) { 5809 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5810 + " signatures don't match existing userdata copy; removing"); 5811 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5812 ps = null; 5813 } else { 5814 /* 5815 * If the newly-added system app is an older version than the 5816 * already installed version, hide it. It will be scanned later 5817 * and re-added like an update. 5818 */ 5819 if (pkg.mVersionCode <= ps.versionCode) { 5820 shouldHideSystemApp = true; 5821 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5822 + " but new version " + pkg.mVersionCode + " better than installed " 5823 + ps.versionCode + "; hiding system"); 5824 } else { 5825 /* 5826 * The newly found system app is a newer version that the 5827 * one previously installed. Simply remove the 5828 * already-installed application and replace it with our own 5829 * while keeping the application data. 5830 */ 5831 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5832 + " reverting from " + ps.codePathString + ": new version " 5833 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5834 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5835 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5836 synchronized (mInstallLock) { 5837 args.cleanUpResourcesLI(); 5838 } 5839 } 5840 } 5841 } 5842 5843 // The apk is forward locked (not public) if its code and resources 5844 // are kept in different files. (except for app in either system or 5845 // vendor path). 5846 // TODO grab this value from PackageSettings 5847 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5848 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5849 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5850 } 5851 } 5852 5853 // TODO: extend to support forward-locked splits 5854 String resourcePath = null; 5855 String baseResourcePath = null; 5856 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5857 if (ps != null && ps.resourcePathString != null) { 5858 resourcePath = ps.resourcePathString; 5859 baseResourcePath = ps.resourcePathString; 5860 } else { 5861 // Should not happen at all. Just log an error. 5862 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5863 } 5864 } else { 5865 resourcePath = pkg.codePath; 5866 baseResourcePath = pkg.baseCodePath; 5867 } 5868 5869 // Set application objects path explicitly. 5870 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5871 pkg.applicationInfo.setCodePath(pkg.codePath); 5872 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5873 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5874 pkg.applicationInfo.setResourcePath(resourcePath); 5875 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5876 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5877 5878 // Note that we invoke the following method only if we are about to unpack an application 5879 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5880 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5881 5882 /* 5883 * If the system app should be overridden by a previously installed 5884 * data, hide the system app now and let the /data/app scan pick it up 5885 * again. 5886 */ 5887 if (shouldHideSystemApp) { 5888 synchronized (mPackages) { 5889 /* 5890 * We have to grant systems permissions before we hide, because 5891 * grantPermissions will assume the package update is trying to 5892 * expand its permissions. 5893 */ 5894 grantPermissionsLPw(pkg, true, pkg.packageName); 5895 mSettings.disableSystemPackageLPw(pkg.packageName); 5896 } 5897 } 5898 5899 return scannedPkg; 5900 } 5901 5902 private static String fixProcessName(String defProcessName, 5903 String processName, int uid) { 5904 if (processName == null) { 5905 return defProcessName; 5906 } 5907 return processName; 5908 } 5909 5910 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 5911 throws PackageManagerException { 5912 if (pkgSetting.signatures.mSignatures != null) { 5913 // Already existing package. Make sure signatures match 5914 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 5915 == PackageManager.SIGNATURE_MATCH; 5916 if (!match) { 5917 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 5918 == PackageManager.SIGNATURE_MATCH; 5919 } 5920 if (!match) { 5921 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 5922 == PackageManager.SIGNATURE_MATCH; 5923 } 5924 if (!match) { 5925 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5926 + pkg.packageName + " signatures do not match the " 5927 + "previously installed version; ignoring!"); 5928 } 5929 } 5930 5931 // Check for shared user signatures 5932 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 5933 // Already existing package. Make sure signatures match 5934 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5935 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 5936 if (!match) { 5937 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 5938 == PackageManager.SIGNATURE_MATCH; 5939 } 5940 if (!match) { 5941 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 5942 == PackageManager.SIGNATURE_MATCH; 5943 } 5944 if (!match) { 5945 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 5946 "Package " + pkg.packageName 5947 + " has no signatures that match those in shared user " 5948 + pkgSetting.sharedUser.name + "; ignoring!"); 5949 } 5950 } 5951 } 5952 5953 /** 5954 * Enforces that only the system UID or root's UID can call a method exposed 5955 * via Binder. 5956 * 5957 * @param message used as message if SecurityException is thrown 5958 * @throws SecurityException if the caller is not system or root 5959 */ 5960 private static final void enforceSystemOrRoot(String message) { 5961 final int uid = Binder.getCallingUid(); 5962 if (uid != Process.SYSTEM_UID && uid != 0) { 5963 throw new SecurityException(message); 5964 } 5965 } 5966 5967 @Override 5968 public void performBootDexOpt() { 5969 enforceSystemOrRoot("Only the system can request dexopt be performed"); 5970 5971 // Before everything else, see whether we need to fstrim. 5972 try { 5973 IMountService ms = PackageHelper.getMountService(); 5974 if (ms != null) { 5975 final boolean isUpgrade = isUpgrade(); 5976 boolean doTrim = isUpgrade; 5977 if (doTrim) { 5978 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 5979 } else { 5980 final long interval = android.provider.Settings.Global.getLong( 5981 mContext.getContentResolver(), 5982 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 5983 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 5984 if (interval > 0) { 5985 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 5986 if (timeSinceLast > interval) { 5987 doTrim = true; 5988 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 5989 + "; running immediately"); 5990 } 5991 } 5992 } 5993 if (doTrim) { 5994 if (!isFirstBoot()) { 5995 try { 5996 ActivityManagerNative.getDefault().showBootMessage( 5997 mContext.getResources().getString( 5998 R.string.android_upgrading_fstrim), true); 5999 } catch (RemoteException e) { 6000 } 6001 } 6002 ms.runMaintenance(); 6003 } 6004 } else { 6005 Slog.e(TAG, "Mount service unavailable!"); 6006 } 6007 } catch (RemoteException e) { 6008 // Can't happen; MountService is local 6009 } 6010 6011 final ArraySet<PackageParser.Package> pkgs; 6012 synchronized (mPackages) { 6013 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 6014 } 6015 6016 if (pkgs != null) { 6017 // Sort apps by importance for dexopt ordering. Important apps are given more priority 6018 // in case the device runs out of space. 6019 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 6020 // Give priority to core apps. 6021 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6022 PackageParser.Package pkg = it.next(); 6023 if (pkg.coreApp) { 6024 if (DEBUG_DEXOPT) { 6025 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 6026 } 6027 sortedPkgs.add(pkg); 6028 it.remove(); 6029 } 6030 } 6031 // Give priority to system apps that listen for pre boot complete. 6032 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 6033 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 6034 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6035 PackageParser.Package pkg = it.next(); 6036 if (pkgNames.contains(pkg.packageName)) { 6037 if (DEBUG_DEXOPT) { 6038 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 6039 } 6040 sortedPkgs.add(pkg); 6041 it.remove(); 6042 } 6043 } 6044 // Give priority to system apps. 6045 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6046 PackageParser.Package pkg = it.next(); 6047 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 6048 if (DEBUG_DEXOPT) { 6049 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 6050 } 6051 sortedPkgs.add(pkg); 6052 it.remove(); 6053 } 6054 } 6055 // Give priority to updated system apps. 6056 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6057 PackageParser.Package pkg = it.next(); 6058 if (pkg.isUpdatedSystemApp()) { 6059 if (DEBUG_DEXOPT) { 6060 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 6061 } 6062 sortedPkgs.add(pkg); 6063 it.remove(); 6064 } 6065 } 6066 // Give priority to apps that listen for boot complete. 6067 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 6068 pkgNames = getPackageNamesForIntent(intent); 6069 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6070 PackageParser.Package pkg = it.next(); 6071 if (pkgNames.contains(pkg.packageName)) { 6072 if (DEBUG_DEXOPT) { 6073 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 6074 } 6075 sortedPkgs.add(pkg); 6076 it.remove(); 6077 } 6078 } 6079 // Filter out packages that aren't recently used. 6080 filterRecentlyUsedApps(pkgs); 6081 // Add all remaining apps. 6082 for (PackageParser.Package pkg : pkgs) { 6083 if (DEBUG_DEXOPT) { 6084 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 6085 } 6086 sortedPkgs.add(pkg); 6087 } 6088 6089 // If we want to be lazy, filter everything that wasn't recently used. 6090 if (mLazyDexOpt) { 6091 filterRecentlyUsedApps(sortedPkgs); 6092 } 6093 6094 int i = 0; 6095 int total = sortedPkgs.size(); 6096 File dataDir = Environment.getDataDirectory(); 6097 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 6098 if (lowThreshold == 0) { 6099 throw new IllegalStateException("Invalid low memory threshold"); 6100 } 6101 for (PackageParser.Package pkg : sortedPkgs) { 6102 long usableSpace = dataDir.getUsableSpace(); 6103 if (usableSpace < lowThreshold) { 6104 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 6105 break; 6106 } 6107 performBootDexOpt(pkg, ++i, total); 6108 } 6109 } 6110 } 6111 6112 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 6113 // Filter out packages that aren't recently used. 6114 // 6115 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 6116 // should do a full dexopt. 6117 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 6118 int total = pkgs.size(); 6119 int skipped = 0; 6120 long now = System.currentTimeMillis(); 6121 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 6122 PackageParser.Package pkg = i.next(); 6123 long then = pkg.mLastPackageUsageTimeInMills; 6124 if (then + mDexOptLRUThresholdInMills < now) { 6125 if (DEBUG_DEXOPT) { 6126 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 6127 ((then == 0) ? "never" : new Date(then))); 6128 } 6129 i.remove(); 6130 skipped++; 6131 } 6132 } 6133 if (DEBUG_DEXOPT) { 6134 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 6135 } 6136 } 6137 } 6138 6139 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 6140 List<ResolveInfo> ris = null; 6141 try { 6142 ris = AppGlobals.getPackageManager().queryIntentReceivers( 6143 intent, null, 0, UserHandle.USER_OWNER); 6144 } catch (RemoteException e) { 6145 } 6146 ArraySet<String> pkgNames = new ArraySet<String>(); 6147 if (ris != null) { 6148 for (ResolveInfo ri : ris) { 6149 pkgNames.add(ri.activityInfo.packageName); 6150 } 6151 } 6152 return pkgNames; 6153 } 6154 6155 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 6156 if (DEBUG_DEXOPT) { 6157 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 6158 } 6159 if (!isFirstBoot()) { 6160 try { 6161 ActivityManagerNative.getDefault().showBootMessage( 6162 mContext.getResources().getString(R.string.android_upgrading_apk, 6163 curr, total), true); 6164 } catch (RemoteException e) { 6165 } 6166 } 6167 PackageParser.Package p = pkg; 6168 synchronized (mInstallLock) { 6169 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 6170 false /* force dex */, false /* defer */, true /* include dependencies */); 6171 } 6172 } 6173 6174 @Override 6175 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6176 return performDexOpt(packageName, instructionSet, false); 6177 } 6178 6179 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 6180 boolean dexopt = mLazyDexOpt || backgroundDexopt; 6181 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 6182 if (!dexopt && !updateUsage) { 6183 // We aren't going to dexopt or update usage, so bail early. 6184 return false; 6185 } 6186 PackageParser.Package p; 6187 final String targetInstructionSet; 6188 synchronized (mPackages) { 6189 p = mPackages.get(packageName); 6190 if (p == null) { 6191 return false; 6192 } 6193 if (updateUsage) { 6194 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6195 } 6196 mPackageUsage.write(false); 6197 if (!dexopt) { 6198 // We aren't going to dexopt, so bail early. 6199 return false; 6200 } 6201 6202 targetInstructionSet = instructionSet != null ? instructionSet : 6203 getPrimaryInstructionSet(p.applicationInfo); 6204 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 6205 return false; 6206 } 6207 } 6208 long callingId = Binder.clearCallingIdentity(); 6209 try { 6210 synchronized (mInstallLock) { 6211 final String[] instructionSets = new String[] { targetInstructionSet }; 6212 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 6213 false /* forceDex */, false /* defer */, true /* inclDependencies */); 6214 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6215 } 6216 } finally { 6217 Binder.restoreCallingIdentity(callingId); 6218 } 6219 } 6220 6221 public ArraySet<String> getPackagesThatNeedDexOpt() { 6222 ArraySet<String> pkgs = null; 6223 synchronized (mPackages) { 6224 for (PackageParser.Package p : mPackages.values()) { 6225 if (DEBUG_DEXOPT) { 6226 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 6227 } 6228 if (!p.mDexOptPerformed.isEmpty()) { 6229 continue; 6230 } 6231 if (pkgs == null) { 6232 pkgs = new ArraySet<String>(); 6233 } 6234 pkgs.add(p.packageName); 6235 } 6236 } 6237 return pkgs; 6238 } 6239 6240 public void shutdown() { 6241 mPackageUsage.write(true); 6242 } 6243 6244 @Override 6245 public void forceDexOpt(String packageName) { 6246 enforceSystemOrRoot("forceDexOpt"); 6247 6248 PackageParser.Package pkg; 6249 synchronized (mPackages) { 6250 pkg = mPackages.get(packageName); 6251 if (pkg == null) { 6252 throw new IllegalArgumentException("Missing package: " + packageName); 6253 } 6254 } 6255 6256 synchronized (mInstallLock) { 6257 final String[] instructionSets = new String[] { 6258 getPrimaryInstructionSet(pkg.applicationInfo) }; 6259 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 6260 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 6261 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 6262 throw new IllegalStateException("Failed to dexopt: " + res); 6263 } 6264 } 6265 } 6266 6267 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 6268 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 6269 Slog.w(TAG, "Unable to update from " + oldPkg.name 6270 + " to " + newPkg.packageName 6271 + ": old package not in system partition"); 6272 return false; 6273 } else if (mPackages.get(oldPkg.name) != null) { 6274 Slog.w(TAG, "Unable to update from " + oldPkg.name 6275 + " to " + newPkg.packageName 6276 + ": old package still exists"); 6277 return false; 6278 } 6279 return true; 6280 } 6281 6282 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 6283 int[] users = sUserManager.getUserIds(); 6284 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 6285 if (res < 0) { 6286 return res; 6287 } 6288 for (int user : users) { 6289 if (user != 0) { 6290 res = mInstaller.createUserData(volumeUuid, packageName, 6291 UserHandle.getUid(user, uid), user, seinfo); 6292 if (res < 0) { 6293 return res; 6294 } 6295 } 6296 } 6297 return res; 6298 } 6299 6300 private int removeDataDirsLI(String volumeUuid, String packageName) { 6301 int[] users = sUserManager.getUserIds(); 6302 int res = 0; 6303 for (int user : users) { 6304 int resInner = mInstaller.remove(volumeUuid, packageName, user); 6305 if (resInner < 0) { 6306 res = resInner; 6307 } 6308 } 6309 6310 return res; 6311 } 6312 6313 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 6314 int[] users = sUserManager.getUserIds(); 6315 int res = 0; 6316 for (int user : users) { 6317 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 6318 if (resInner < 0) { 6319 res = resInner; 6320 } 6321 } 6322 return res; 6323 } 6324 6325 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 6326 PackageParser.Package changingLib) { 6327 if (file.path != null) { 6328 usesLibraryFiles.add(file.path); 6329 return; 6330 } 6331 PackageParser.Package p = mPackages.get(file.apk); 6332 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 6333 // If we are doing this while in the middle of updating a library apk, 6334 // then we need to make sure to use that new apk for determining the 6335 // dependencies here. (We haven't yet finished committing the new apk 6336 // to the package manager state.) 6337 if (p == null || p.packageName.equals(changingLib.packageName)) { 6338 p = changingLib; 6339 } 6340 } 6341 if (p != null) { 6342 usesLibraryFiles.addAll(p.getAllCodePaths()); 6343 } 6344 } 6345 6346 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 6347 PackageParser.Package changingLib) throws PackageManagerException { 6348 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 6349 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 6350 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 6351 for (int i=0; i<N; i++) { 6352 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 6353 if (file == null) { 6354 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 6355 "Package " + pkg.packageName + " requires unavailable shared library " 6356 + pkg.usesLibraries.get(i) + "; failing!"); 6357 } 6358 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6359 } 6360 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 6361 for (int i=0; i<N; i++) { 6362 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 6363 if (file == null) { 6364 Slog.w(TAG, "Package " + pkg.packageName 6365 + " desires unavailable shared library " 6366 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 6367 } else { 6368 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6369 } 6370 } 6371 N = usesLibraryFiles.size(); 6372 if (N > 0) { 6373 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 6374 } else { 6375 pkg.usesLibraryFiles = null; 6376 } 6377 } 6378 } 6379 6380 private static boolean hasString(List<String> list, List<String> which) { 6381 if (list == null) { 6382 return false; 6383 } 6384 for (int i=list.size()-1; i>=0; i--) { 6385 for (int j=which.size()-1; j>=0; j--) { 6386 if (which.get(j).equals(list.get(i))) { 6387 return true; 6388 } 6389 } 6390 } 6391 return false; 6392 } 6393 6394 private void updateAllSharedLibrariesLPw() { 6395 for (PackageParser.Package pkg : mPackages.values()) { 6396 try { 6397 updateSharedLibrariesLPw(pkg, null); 6398 } catch (PackageManagerException e) { 6399 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6400 } 6401 } 6402 } 6403 6404 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 6405 PackageParser.Package changingPkg) { 6406 ArrayList<PackageParser.Package> res = null; 6407 for (PackageParser.Package pkg : mPackages.values()) { 6408 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 6409 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 6410 if (res == null) { 6411 res = new ArrayList<PackageParser.Package>(); 6412 } 6413 res.add(pkg); 6414 try { 6415 updateSharedLibrariesLPw(pkg, changingPkg); 6416 } catch (PackageManagerException e) { 6417 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6418 } 6419 } 6420 } 6421 return res; 6422 } 6423 6424 /** 6425 * Derive the value of the {@code cpuAbiOverride} based on the provided 6426 * value and an optional stored value from the package settings. 6427 */ 6428 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 6429 String cpuAbiOverride = null; 6430 6431 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 6432 cpuAbiOverride = null; 6433 } else if (abiOverride != null) { 6434 cpuAbiOverride = abiOverride; 6435 } else if (settings != null) { 6436 cpuAbiOverride = settings.cpuAbiOverrideString; 6437 } 6438 6439 return cpuAbiOverride; 6440 } 6441 6442 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 6443 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6444 boolean success = false; 6445 try { 6446 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 6447 currentTime, user); 6448 success = true; 6449 return res; 6450 } finally { 6451 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 6452 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 6453 } 6454 } 6455 } 6456 6457 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 6458 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6459 final File scanFile = new File(pkg.codePath); 6460 if (pkg.applicationInfo.getCodePath() == null || 6461 pkg.applicationInfo.getResourcePath() == null) { 6462 // Bail out. The resource and code paths haven't been set. 6463 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 6464 "Code and resource paths haven't been set correctly"); 6465 } 6466 6467 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 6468 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 6469 } else { 6470 // Only allow system apps to be flagged as core apps. 6471 pkg.coreApp = false; 6472 } 6473 6474 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 6475 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6476 } 6477 6478 if (mCustomResolverComponentName != null && 6479 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 6480 setUpCustomResolverActivity(pkg); 6481 } 6482 6483 if (pkg.packageName.equals("android")) { 6484 synchronized (mPackages) { 6485 if (mAndroidApplication != null) { 6486 Slog.w(TAG, "*************************************************"); 6487 Slog.w(TAG, "Core android package being redefined. Skipping."); 6488 Slog.w(TAG, " file=" + scanFile); 6489 Slog.w(TAG, "*************************************************"); 6490 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6491 "Core android package being redefined. Skipping."); 6492 } 6493 6494 // Set up information for our fall-back user intent resolution activity. 6495 mPlatformPackage = pkg; 6496 pkg.mVersionCode = mSdkVersion; 6497 mAndroidApplication = pkg.applicationInfo; 6498 6499 if (!mResolverReplaced) { 6500 mResolveActivity.applicationInfo = mAndroidApplication; 6501 mResolveActivity.name = ResolverActivity.class.getName(); 6502 mResolveActivity.packageName = mAndroidApplication.packageName; 6503 mResolveActivity.processName = "system:ui"; 6504 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6505 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 6506 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 6507 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 6508 mResolveActivity.exported = true; 6509 mResolveActivity.enabled = true; 6510 mResolveInfo.activityInfo = mResolveActivity; 6511 mResolveInfo.priority = 0; 6512 mResolveInfo.preferredOrder = 0; 6513 mResolveInfo.match = 0; 6514 mResolveComponentName = new ComponentName( 6515 mAndroidApplication.packageName, mResolveActivity.name); 6516 } 6517 } 6518 } 6519 6520 if (DEBUG_PACKAGE_SCANNING) { 6521 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6522 Log.d(TAG, "Scanning package " + pkg.packageName); 6523 } 6524 6525 if (mPackages.containsKey(pkg.packageName) 6526 || mSharedLibraries.containsKey(pkg.packageName)) { 6527 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6528 "Application package " + pkg.packageName 6529 + " already installed. Skipping duplicate."); 6530 } 6531 6532 // If we're only installing presumed-existing packages, require that the 6533 // scanned APK is both already known and at the path previously established 6534 // for it. Previously unknown packages we pick up normally, but if we have an 6535 // a priori expectation about this package's install presence, enforce it. 6536 // With a singular exception for new system packages. When an OTA contains 6537 // a new system package, we allow the codepath to change from a system location 6538 // to the user-installed location. If we don't allow this change, any newer, 6539 // user-installed version of the application will be ignored. 6540 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 6541 if (mExpectingBetter.containsKey(pkg.packageName)) { 6542 logCriticalInfo(Log.WARN, 6543 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 6544 } else { 6545 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 6546 if (known != null) { 6547 if (DEBUG_PACKAGE_SCANNING) { 6548 Log.d(TAG, "Examining " + pkg.codePath 6549 + " and requiring known paths " + known.codePathString 6550 + " & " + known.resourcePathString); 6551 } 6552 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6553 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6554 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6555 "Application package " + pkg.packageName 6556 + " found at " + pkg.applicationInfo.getCodePath() 6557 + " but expected at " + known.codePathString + "; ignoring."); 6558 } 6559 } 6560 } 6561 } 6562 6563 // Initialize package source and resource directories 6564 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6565 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6566 6567 SharedUserSetting suid = null; 6568 PackageSetting pkgSetting = null; 6569 6570 if (!isSystemApp(pkg)) { 6571 // Only system apps can use these features. 6572 pkg.mOriginalPackages = null; 6573 pkg.mRealPackage = null; 6574 pkg.mAdoptPermissions = null; 6575 } 6576 6577 // writer 6578 synchronized (mPackages) { 6579 if (pkg.mSharedUserId != null) { 6580 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 6581 if (suid == null) { 6582 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6583 "Creating application package " + pkg.packageName 6584 + " for shared user failed"); 6585 } 6586 if (DEBUG_PACKAGE_SCANNING) { 6587 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6588 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 6589 + "): packages=" + suid.packages); 6590 } 6591 } 6592 6593 // Check if we are renaming from an original package name. 6594 PackageSetting origPackage = null; 6595 String realName = null; 6596 if (pkg.mOriginalPackages != null) { 6597 // This package may need to be renamed to a previously 6598 // installed name. Let's check on that... 6599 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 6600 if (pkg.mOriginalPackages.contains(renamed)) { 6601 // This package had originally been installed as the 6602 // original name, and we have already taken care of 6603 // transitioning to the new one. Just update the new 6604 // one to continue using the old name. 6605 realName = pkg.mRealPackage; 6606 if (!pkg.packageName.equals(renamed)) { 6607 // Callers into this function may have already taken 6608 // care of renaming the package; only do it here if 6609 // it is not already done. 6610 pkg.setPackageName(renamed); 6611 } 6612 6613 } else { 6614 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 6615 if ((origPackage = mSettings.peekPackageLPr( 6616 pkg.mOriginalPackages.get(i))) != null) { 6617 // We do have the package already installed under its 6618 // original name... should we use it? 6619 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 6620 // New package is not compatible with original. 6621 origPackage = null; 6622 continue; 6623 } else if (origPackage.sharedUser != null) { 6624 // Make sure uid is compatible between packages. 6625 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 6626 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 6627 + " to " + pkg.packageName + ": old uid " 6628 + origPackage.sharedUser.name 6629 + " differs from " + pkg.mSharedUserId); 6630 origPackage = null; 6631 continue; 6632 } 6633 } else { 6634 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6635 + pkg.packageName + " to old name " + origPackage.name); 6636 } 6637 break; 6638 } 6639 } 6640 } 6641 } 6642 6643 if (mTransferedPackages.contains(pkg.packageName)) { 6644 Slog.w(TAG, "Package " + pkg.packageName 6645 + " was transferred to another, but its .apk remains"); 6646 } 6647 6648 // Just create the setting, don't add it yet. For already existing packages 6649 // the PkgSetting exists already and doesn't have to be created. 6650 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6651 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6652 pkg.applicationInfo.primaryCpuAbi, 6653 pkg.applicationInfo.secondaryCpuAbi, 6654 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6655 user, false); 6656 if (pkgSetting == null) { 6657 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6658 "Creating application package " + pkg.packageName + " failed"); 6659 } 6660 6661 if (pkgSetting.origPackage != null) { 6662 // If we are first transitioning from an original package, 6663 // fix up the new package's name now. We need to do this after 6664 // looking up the package under its new name, so getPackageLP 6665 // can take care of fiddling things correctly. 6666 pkg.setPackageName(origPackage.name); 6667 6668 // File a report about this. 6669 String msg = "New package " + pkgSetting.realName 6670 + " renamed to replace old package " + pkgSetting.name; 6671 reportSettingsProblem(Log.WARN, msg); 6672 6673 // Make a note of it. 6674 mTransferedPackages.add(origPackage.name); 6675 6676 // No longer need to retain this. 6677 pkgSetting.origPackage = null; 6678 } 6679 6680 if (realName != null) { 6681 // Make a note of it. 6682 mTransferedPackages.add(pkg.packageName); 6683 } 6684 6685 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6686 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6687 } 6688 6689 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6690 // Check all shared libraries and map to their actual file path. 6691 // We only do this here for apps not on a system dir, because those 6692 // are the only ones that can fail an install due to this. We 6693 // will take care of the system apps by updating all of their 6694 // library paths after the scan is done. 6695 updateSharedLibrariesLPw(pkg, null); 6696 } 6697 6698 if (mFoundPolicyFile) { 6699 SELinuxMMAC.assignSeinfoValue(pkg); 6700 } 6701 6702 pkg.applicationInfo.uid = pkgSetting.appId; 6703 pkg.mExtras = pkgSetting; 6704 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 6705 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 6706 // We just determined the app is signed correctly, so bring 6707 // over the latest parsed certs. 6708 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6709 } else { 6710 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6711 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6712 "Package " + pkg.packageName + " upgrade keys do not match the " 6713 + "previously installed version"); 6714 } else { 6715 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6716 String msg = "System package " + pkg.packageName 6717 + " signature changed; retaining data."; 6718 reportSettingsProblem(Log.WARN, msg); 6719 } 6720 } 6721 } else { 6722 try { 6723 verifySignaturesLP(pkgSetting, pkg); 6724 // We just determined the app is signed correctly, so bring 6725 // over the latest parsed certs. 6726 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6727 } catch (PackageManagerException e) { 6728 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6729 throw e; 6730 } 6731 // The signature has changed, but this package is in the system 6732 // image... let's recover! 6733 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6734 // However... if this package is part of a shared user, but it 6735 // doesn't match the signature of the shared user, let's fail. 6736 // What this means is that you can't change the signatures 6737 // associated with an overall shared user, which doesn't seem all 6738 // that unreasonable. 6739 if (pkgSetting.sharedUser != null) { 6740 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6741 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 6742 throw new PackageManagerException( 6743 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6744 "Signature mismatch for shared user : " 6745 + pkgSetting.sharedUser); 6746 } 6747 } 6748 // File a report about this. 6749 String msg = "System package " + pkg.packageName 6750 + " signature changed; retaining data."; 6751 reportSettingsProblem(Log.WARN, msg); 6752 } 6753 } 6754 // Verify that this new package doesn't have any content providers 6755 // that conflict with existing packages. Only do this if the 6756 // package isn't already installed, since we don't want to break 6757 // things that are installed. 6758 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6759 final int N = pkg.providers.size(); 6760 int i; 6761 for (i=0; i<N; i++) { 6762 PackageParser.Provider p = pkg.providers.get(i); 6763 if (p.info.authority != null) { 6764 String names[] = p.info.authority.split(";"); 6765 for (int j = 0; j < names.length; j++) { 6766 if (mProvidersByAuthority.containsKey(names[j])) { 6767 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6768 final String otherPackageName = 6769 ((other != null && other.getComponentName() != null) ? 6770 other.getComponentName().getPackageName() : "?"); 6771 throw new PackageManagerException( 6772 INSTALL_FAILED_CONFLICTING_PROVIDER, 6773 "Can't install because provider name " + names[j] 6774 + " (in package " + pkg.applicationInfo.packageName 6775 + ") is already used by " + otherPackageName); 6776 } 6777 } 6778 } 6779 } 6780 } 6781 6782 if (pkg.mAdoptPermissions != null) { 6783 // This package wants to adopt ownership of permissions from 6784 // another package. 6785 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6786 final String origName = pkg.mAdoptPermissions.get(i); 6787 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6788 if (orig != null) { 6789 if (verifyPackageUpdateLPr(orig, pkg)) { 6790 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6791 + pkg.packageName); 6792 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6793 } 6794 } 6795 } 6796 } 6797 } 6798 6799 final String pkgName = pkg.packageName; 6800 6801 final long scanFileTime = scanFile.lastModified(); 6802 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6803 pkg.applicationInfo.processName = fixProcessName( 6804 pkg.applicationInfo.packageName, 6805 pkg.applicationInfo.processName, 6806 pkg.applicationInfo.uid); 6807 6808 File dataPath; 6809 if (mPlatformPackage == pkg) { 6810 // The system package is special. 6811 dataPath = new File(Environment.getDataDirectory(), "system"); 6812 6813 pkg.applicationInfo.dataDir = dataPath.getPath(); 6814 6815 } else { 6816 // This is a normal package, need to make its data directory. 6817 dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid, 6818 UserHandle.USER_OWNER, pkg.packageName); 6819 6820 boolean uidError = false; 6821 if (dataPath.exists()) { 6822 int currentUid = 0; 6823 try { 6824 StructStat stat = Os.stat(dataPath.getPath()); 6825 currentUid = stat.st_uid; 6826 } catch (ErrnoException e) { 6827 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6828 } 6829 6830 // If we have mismatched owners for the data path, we have a problem. 6831 if (currentUid != pkg.applicationInfo.uid) { 6832 boolean recovered = false; 6833 if (currentUid == 0) { 6834 // The directory somehow became owned by root. Wow. 6835 // This is probably because the system was stopped while 6836 // installd was in the middle of messing with its libs 6837 // directory. Ask installd to fix that. 6838 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6839 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6840 if (ret >= 0) { 6841 recovered = true; 6842 String msg = "Package " + pkg.packageName 6843 + " unexpectedly changed to uid 0; recovered to " + 6844 + pkg.applicationInfo.uid; 6845 reportSettingsProblem(Log.WARN, msg); 6846 } 6847 } 6848 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6849 || (scanFlags&SCAN_BOOTING) != 0)) { 6850 // If this is a system app, we can at least delete its 6851 // current data so the application will still work. 6852 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6853 if (ret >= 0) { 6854 // TODO: Kill the processes first 6855 // Old data gone! 6856 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6857 ? "System package " : "Third party package "; 6858 String msg = prefix + pkg.packageName 6859 + " has changed from uid: " 6860 + currentUid + " to " 6861 + pkg.applicationInfo.uid + "; old data erased"; 6862 reportSettingsProblem(Log.WARN, msg); 6863 recovered = true; 6864 6865 // And now re-install the app. 6866 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6867 pkg.applicationInfo.seinfo); 6868 if (ret == -1) { 6869 // Ack should not happen! 6870 msg = prefix + pkg.packageName 6871 + " could not have data directory re-created after delete."; 6872 reportSettingsProblem(Log.WARN, msg); 6873 throw new PackageManagerException( 6874 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6875 } 6876 } 6877 if (!recovered) { 6878 mHasSystemUidErrors = true; 6879 } 6880 } else if (!recovered) { 6881 // If we allow this install to proceed, we will be broken. 6882 // Abort, abort! 6883 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6884 "scanPackageLI"); 6885 } 6886 if (!recovered) { 6887 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6888 + pkg.applicationInfo.uid + "/fs_" 6889 + currentUid; 6890 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6891 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6892 String msg = "Package " + pkg.packageName 6893 + " has mismatched uid: " 6894 + currentUid + " on disk, " 6895 + pkg.applicationInfo.uid + " in settings"; 6896 // writer 6897 synchronized (mPackages) { 6898 mSettings.mReadMessages.append(msg); 6899 mSettings.mReadMessages.append('\n'); 6900 uidError = true; 6901 if (!pkgSetting.uidError) { 6902 reportSettingsProblem(Log.ERROR, msg); 6903 } 6904 } 6905 } 6906 } 6907 pkg.applicationInfo.dataDir = dataPath.getPath(); 6908 if (mShouldRestoreconData) { 6909 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6910 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 6911 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 6912 } 6913 } else { 6914 if (DEBUG_PACKAGE_SCANNING) { 6915 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6916 Log.v(TAG, "Want this data dir: " + dataPath); 6917 } 6918 //invoke installer to do the actual installation 6919 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6920 pkg.applicationInfo.seinfo); 6921 if (ret < 0) { 6922 // Error from installer 6923 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6924 "Unable to create data dirs [errorCode=" + ret + "]"); 6925 } 6926 6927 if (dataPath.exists()) { 6928 pkg.applicationInfo.dataDir = dataPath.getPath(); 6929 } else { 6930 Slog.w(TAG, "Unable to create data directory: " + dataPath); 6931 pkg.applicationInfo.dataDir = null; 6932 } 6933 } 6934 6935 pkgSetting.uidError = uidError; 6936 } 6937 6938 final String path = scanFile.getPath(); 6939 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6940 6941 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 6942 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 6943 6944 // Some system apps still use directory structure for native libraries 6945 // in which case we might end up not detecting abi solely based on apk 6946 // structure. Try to detect abi based on directory structure. 6947 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 6948 pkg.applicationInfo.primaryCpuAbi == null) { 6949 setBundledAppAbisAndRoots(pkg, pkgSetting); 6950 setNativeLibraryPaths(pkg); 6951 } 6952 6953 } else { 6954 if ((scanFlags & SCAN_MOVE) != 0) { 6955 // We haven't run dex-opt for this move (since we've moved the compiled output too) 6956 // but we already have this packages package info in the PackageSetting. We just 6957 // use that and derive the native library path based on the new codepath. 6958 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 6959 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 6960 } 6961 6962 // Set native library paths again. For moves, the path will be updated based on the 6963 // ABIs we've determined above. For non-moves, the path will be updated based on the 6964 // ABIs we determined during compilation, but the path will depend on the final 6965 // package path (after the rename away from the stage path). 6966 setNativeLibraryPaths(pkg); 6967 } 6968 6969 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 6970 final int[] userIds = sUserManager.getUserIds(); 6971 synchronized (mInstallLock) { 6972 // Make sure all user data directories are ready to roll; we're okay 6973 // if they already exist 6974 if (!TextUtils.isEmpty(pkg.volumeUuid)) { 6975 for (int userId : userIds) { 6976 if (userId != 0) { 6977 mInstaller.createUserData(pkg.volumeUuid, pkg.packageName, 6978 UserHandle.getUid(userId, pkg.applicationInfo.uid), userId, 6979 pkg.applicationInfo.seinfo); 6980 } 6981 } 6982 } 6983 6984 // Create a native library symlink only if we have native libraries 6985 // and if the native libraries are 32 bit libraries. We do not provide 6986 // this symlink for 64 bit libraries. 6987 if (pkg.applicationInfo.primaryCpuAbi != null && 6988 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 6989 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 6990 for (int userId : userIds) { 6991 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 6992 nativeLibPath, userId) < 0) { 6993 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6994 "Failed linking native library dir (user=" + userId + ")"); 6995 } 6996 } 6997 } 6998 } 6999 7000 // This is a special case for the "system" package, where the ABI is 7001 // dictated by the zygote configuration (and init.rc). We should keep track 7002 // of this ABI so that we can deal with "normal" applications that run under 7003 // the same UID correctly. 7004 if (mPlatformPackage == pkg) { 7005 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 7006 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 7007 } 7008 7009 // If there's a mismatch between the abi-override in the package setting 7010 // and the abiOverride specified for the install. Warn about this because we 7011 // would've already compiled the app without taking the package setting into 7012 // account. 7013 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 7014 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 7015 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 7016 " for package: " + pkg.packageName); 7017 } 7018 } 7019 7020 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7021 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7022 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 7023 7024 // Copy the derived override back to the parsed package, so that we can 7025 // update the package settings accordingly. 7026 pkg.cpuAbiOverride = cpuAbiOverride; 7027 7028 if (DEBUG_ABI_SELECTION) { 7029 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 7030 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 7031 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 7032 } 7033 7034 // Push the derived path down into PackageSettings so we know what to 7035 // clean up at uninstall time. 7036 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 7037 7038 if (DEBUG_ABI_SELECTION) { 7039 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 7040 " primary=" + pkg.applicationInfo.primaryCpuAbi + 7041 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 7042 } 7043 7044 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 7045 // We don't do this here during boot because we can do it all 7046 // at once after scanning all existing packages. 7047 // 7048 // We also do this *before* we perform dexopt on this package, so that 7049 // we can avoid redundant dexopts, and also to make sure we've got the 7050 // code and package path correct. 7051 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 7052 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 7053 } 7054 7055 if ((scanFlags & SCAN_NO_DEX) == 0) { 7056 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 7057 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 7058 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7059 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 7060 } 7061 } 7062 if (mFactoryTest && pkg.requestedPermissions.contains( 7063 android.Manifest.permission.FACTORY_TEST)) { 7064 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 7065 } 7066 7067 ArrayList<PackageParser.Package> clientLibPkgs = null; 7068 7069 // writer 7070 synchronized (mPackages) { 7071 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7072 // Only system apps can add new shared libraries. 7073 if (pkg.libraryNames != null) { 7074 for (int i=0; i<pkg.libraryNames.size(); i++) { 7075 String name = pkg.libraryNames.get(i); 7076 boolean allowed = false; 7077 if (pkg.isUpdatedSystemApp()) { 7078 // New library entries can only be added through the 7079 // system image. This is important to get rid of a lot 7080 // of nasty edge cases: for example if we allowed a non- 7081 // system update of the app to add a library, then uninstalling 7082 // the update would make the library go away, and assumptions 7083 // we made such as through app install filtering would now 7084 // have allowed apps on the device which aren't compatible 7085 // with it. Better to just have the restriction here, be 7086 // conservative, and create many fewer cases that can negatively 7087 // impact the user experience. 7088 final PackageSetting sysPs = mSettings 7089 .getDisabledSystemPkgLPr(pkg.packageName); 7090 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 7091 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 7092 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 7093 allowed = true; 7094 allowed = true; 7095 break; 7096 } 7097 } 7098 } 7099 } else { 7100 allowed = true; 7101 } 7102 if (allowed) { 7103 if (!mSharedLibraries.containsKey(name)) { 7104 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 7105 } else if (!name.equals(pkg.packageName)) { 7106 Slog.w(TAG, "Package " + pkg.packageName + " library " 7107 + name + " already exists; skipping"); 7108 } 7109 } else { 7110 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 7111 + name + " that is not declared on system image; skipping"); 7112 } 7113 } 7114 if ((scanFlags&SCAN_BOOTING) == 0) { 7115 // If we are not booting, we need to update any applications 7116 // that are clients of our shared library. If we are booting, 7117 // this will all be done once the scan is complete. 7118 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 7119 } 7120 } 7121 } 7122 } 7123 7124 // We also need to dexopt any apps that are dependent on this library. Note that 7125 // if these fail, we should abort the install since installing the library will 7126 // result in some apps being broken. 7127 if (clientLibPkgs != null) { 7128 if ((scanFlags & SCAN_NO_DEX) == 0) { 7129 for (int i = 0; i < clientLibPkgs.size(); i++) { 7130 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7131 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 7132 null /* instruction sets */, forceDex, 7133 (scanFlags & SCAN_DEFER_DEX) != 0, false); 7134 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7135 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 7136 "scanPackageLI failed to dexopt clientLibPkgs"); 7137 } 7138 } 7139 } 7140 } 7141 7142 // Request the ActivityManager to kill the process(only for existing packages) 7143 // so that we do not end up in a confused state while the user is still using the older 7144 // version of the application while the new one gets installed. 7145 if ((scanFlags & SCAN_REPLACING) != 0) { 7146 killApplication(pkg.applicationInfo.packageName, 7147 pkg.applicationInfo.uid, "replace pkg"); 7148 } 7149 7150 // Also need to kill any apps that are dependent on the library. 7151 if (clientLibPkgs != null) { 7152 for (int i=0; i<clientLibPkgs.size(); i++) { 7153 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7154 killApplication(clientPkg.applicationInfo.packageName, 7155 clientPkg.applicationInfo.uid, "update lib"); 7156 } 7157 } 7158 7159 // Make sure we're not adding any bogus keyset info 7160 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7161 ksms.assertScannedPackageValid(pkg); 7162 7163 // writer 7164 synchronized (mPackages) { 7165 // We don't expect installation to fail beyond this point 7166 7167 // Add the new setting to mSettings 7168 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 7169 // Add the new setting to mPackages 7170 mPackages.put(pkg.applicationInfo.packageName, pkg); 7171 // Make sure we don't accidentally delete its data. 7172 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 7173 while (iter.hasNext()) { 7174 PackageCleanItem item = iter.next(); 7175 if (pkgName.equals(item.packageName)) { 7176 iter.remove(); 7177 } 7178 } 7179 7180 // Take care of first install / last update times. 7181 if (currentTime != 0) { 7182 if (pkgSetting.firstInstallTime == 0) { 7183 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7184 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7185 pkgSetting.lastUpdateTime = currentTime; 7186 } 7187 } else if (pkgSetting.firstInstallTime == 0) { 7188 // We need *something*. Take time time stamp of the file. 7189 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7190 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7191 if (scanFileTime != pkgSetting.timeStamp) { 7192 // A package on the system image has changed; consider this 7193 // to be an update. 7194 pkgSetting.lastUpdateTime = scanFileTime; 7195 } 7196 } 7197 7198 // Add the package's KeySets to the global KeySetManagerService 7199 ksms.addScannedPackageLPw(pkg); 7200 7201 int N = pkg.providers.size(); 7202 StringBuilder r = null; 7203 int i; 7204 for (i=0; i<N; i++) { 7205 PackageParser.Provider p = pkg.providers.get(i); 7206 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7207 p.info.processName, pkg.applicationInfo.uid); 7208 mProviders.addProvider(p); 7209 p.syncable = p.info.isSyncable; 7210 if (p.info.authority != null) { 7211 String names[] = p.info.authority.split(";"); 7212 p.info.authority = null; 7213 for (int j = 0; j < names.length; j++) { 7214 if (j == 1 && p.syncable) { 7215 // We only want the first authority for a provider to possibly be 7216 // syncable, so if we already added this provider using a different 7217 // authority clear the syncable flag. We copy the provider before 7218 // changing it because the mProviders object contains a reference 7219 // to a provider that we don't want to change. 7220 // Only do this for the second authority since the resulting provider 7221 // object can be the same for all future authorities for this provider. 7222 p = new PackageParser.Provider(p); 7223 p.syncable = false; 7224 } 7225 if (!mProvidersByAuthority.containsKey(names[j])) { 7226 mProvidersByAuthority.put(names[j], p); 7227 if (p.info.authority == null) { 7228 p.info.authority = names[j]; 7229 } else { 7230 p.info.authority = p.info.authority + ";" + names[j]; 7231 } 7232 if (DEBUG_PACKAGE_SCANNING) { 7233 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7234 Log.d(TAG, "Registered content provider: " + names[j] 7235 + ", className = " + p.info.name + ", isSyncable = " 7236 + p.info.isSyncable); 7237 } 7238 } else { 7239 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7240 Slog.w(TAG, "Skipping provider name " + names[j] + 7241 " (in package " + pkg.applicationInfo.packageName + 7242 "): name already used by " 7243 + ((other != null && other.getComponentName() != null) 7244 ? other.getComponentName().getPackageName() : "?")); 7245 } 7246 } 7247 } 7248 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7249 if (r == null) { 7250 r = new StringBuilder(256); 7251 } else { 7252 r.append(' '); 7253 } 7254 r.append(p.info.name); 7255 } 7256 } 7257 if (r != null) { 7258 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7259 } 7260 7261 N = pkg.services.size(); 7262 r = null; 7263 for (i=0; i<N; i++) { 7264 PackageParser.Service s = pkg.services.get(i); 7265 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 7266 s.info.processName, pkg.applicationInfo.uid); 7267 mServices.addService(s); 7268 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7269 if (r == null) { 7270 r = new StringBuilder(256); 7271 } else { 7272 r.append(' '); 7273 } 7274 r.append(s.info.name); 7275 } 7276 } 7277 if (r != null) { 7278 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 7279 } 7280 7281 N = pkg.receivers.size(); 7282 r = null; 7283 for (i=0; i<N; i++) { 7284 PackageParser.Activity a = pkg.receivers.get(i); 7285 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7286 a.info.processName, pkg.applicationInfo.uid); 7287 mReceivers.addActivity(a, "receiver"); 7288 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7289 if (r == null) { 7290 r = new StringBuilder(256); 7291 } else { 7292 r.append(' '); 7293 } 7294 r.append(a.info.name); 7295 } 7296 } 7297 if (r != null) { 7298 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 7299 } 7300 7301 N = pkg.activities.size(); 7302 r = null; 7303 for (i=0; i<N; i++) { 7304 PackageParser.Activity a = pkg.activities.get(i); 7305 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7306 a.info.processName, pkg.applicationInfo.uid); 7307 mActivities.addActivity(a, "activity"); 7308 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7309 if (r == null) { 7310 r = new StringBuilder(256); 7311 } else { 7312 r.append(' '); 7313 } 7314 r.append(a.info.name); 7315 } 7316 } 7317 if (r != null) { 7318 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 7319 } 7320 7321 N = pkg.permissionGroups.size(); 7322 r = null; 7323 for (i=0; i<N; i++) { 7324 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 7325 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 7326 if (cur == null) { 7327 mPermissionGroups.put(pg.info.name, pg); 7328 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7329 if (r == null) { 7330 r = new StringBuilder(256); 7331 } else { 7332 r.append(' '); 7333 } 7334 r.append(pg.info.name); 7335 } 7336 } else { 7337 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 7338 + pg.info.packageName + " ignored: original from " 7339 + cur.info.packageName); 7340 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7341 if (r == null) { 7342 r = new StringBuilder(256); 7343 } else { 7344 r.append(' '); 7345 } 7346 r.append("DUP:"); 7347 r.append(pg.info.name); 7348 } 7349 } 7350 } 7351 if (r != null) { 7352 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 7353 } 7354 7355 N = pkg.permissions.size(); 7356 r = null; 7357 for (i=0; i<N; i++) { 7358 PackageParser.Permission p = pkg.permissions.get(i); 7359 7360 // Assume by default that we did not install this permission into the system. 7361 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 7362 7363 // Now that permission groups have a special meaning, we ignore permission 7364 // groups for legacy apps to prevent unexpected behavior. In particular, 7365 // permissions for one app being granted to someone just becuase they happen 7366 // to be in a group defined by another app (before this had no implications). 7367 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 7368 p.group = mPermissionGroups.get(p.info.group); 7369 // Warn for a permission in an unknown group. 7370 if (p.info.group != null && p.group == null) { 7371 Slog.w(TAG, "Permission " + p.info.name + " from package " 7372 + p.info.packageName + " in an unknown group " + p.info.group); 7373 } 7374 } 7375 7376 ArrayMap<String, BasePermission> permissionMap = 7377 p.tree ? mSettings.mPermissionTrees 7378 : mSettings.mPermissions; 7379 BasePermission bp = permissionMap.get(p.info.name); 7380 7381 // Allow system apps to redefine non-system permissions 7382 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 7383 final boolean currentOwnerIsSystem = (bp.perm != null 7384 && isSystemApp(bp.perm.owner)); 7385 if (isSystemApp(p.owner)) { 7386 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 7387 // It's a built-in permission and no owner, take ownership now 7388 bp.packageSetting = pkgSetting; 7389 bp.perm = p; 7390 bp.uid = pkg.applicationInfo.uid; 7391 bp.sourcePackage = p.info.packageName; 7392 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7393 } else if (!currentOwnerIsSystem) { 7394 String msg = "New decl " + p.owner + " of permission " 7395 + p.info.name + " is system; overriding " + bp.sourcePackage; 7396 reportSettingsProblem(Log.WARN, msg); 7397 bp = null; 7398 } 7399 } 7400 } 7401 7402 if (bp == null) { 7403 bp = new BasePermission(p.info.name, p.info.packageName, 7404 BasePermission.TYPE_NORMAL); 7405 permissionMap.put(p.info.name, bp); 7406 } 7407 7408 if (bp.perm == null) { 7409 if (bp.sourcePackage == null 7410 || bp.sourcePackage.equals(p.info.packageName)) { 7411 BasePermission tree = findPermissionTreeLP(p.info.name); 7412 if (tree == null 7413 || tree.sourcePackage.equals(p.info.packageName)) { 7414 bp.packageSetting = pkgSetting; 7415 bp.perm = p; 7416 bp.uid = pkg.applicationInfo.uid; 7417 bp.sourcePackage = p.info.packageName; 7418 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7419 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7420 if (r == null) { 7421 r = new StringBuilder(256); 7422 } else { 7423 r.append(' '); 7424 } 7425 r.append(p.info.name); 7426 } 7427 } else { 7428 Slog.w(TAG, "Permission " + p.info.name + " from package " 7429 + p.info.packageName + " ignored: base tree " 7430 + tree.name + " is from package " 7431 + tree.sourcePackage); 7432 } 7433 } else { 7434 Slog.w(TAG, "Permission " + p.info.name + " from package " 7435 + p.info.packageName + " ignored: original from " 7436 + bp.sourcePackage); 7437 } 7438 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7439 if (r == null) { 7440 r = new StringBuilder(256); 7441 } else { 7442 r.append(' '); 7443 } 7444 r.append("DUP:"); 7445 r.append(p.info.name); 7446 } 7447 if (bp.perm == p) { 7448 bp.protectionLevel = p.info.protectionLevel; 7449 } 7450 } 7451 7452 if (r != null) { 7453 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 7454 } 7455 7456 N = pkg.instrumentation.size(); 7457 r = null; 7458 for (i=0; i<N; i++) { 7459 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7460 a.info.packageName = pkg.applicationInfo.packageName; 7461 a.info.sourceDir = pkg.applicationInfo.sourceDir; 7462 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 7463 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 7464 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 7465 a.info.dataDir = pkg.applicationInfo.dataDir; 7466 7467 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 7468 // need other information about the application, like the ABI and what not ? 7469 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 7470 mInstrumentation.put(a.getComponentName(), a); 7471 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7472 if (r == null) { 7473 r = new StringBuilder(256); 7474 } else { 7475 r.append(' '); 7476 } 7477 r.append(a.info.name); 7478 } 7479 } 7480 if (r != null) { 7481 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 7482 } 7483 7484 if (pkg.protectedBroadcasts != null) { 7485 N = pkg.protectedBroadcasts.size(); 7486 for (i=0; i<N; i++) { 7487 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 7488 } 7489 } 7490 7491 pkgSetting.setTimeStamp(scanFileTime); 7492 7493 // Create idmap files for pairs of (packages, overlay packages). 7494 // Note: "android", ie framework-res.apk, is handled by native layers. 7495 if (pkg.mOverlayTarget != null) { 7496 // This is an overlay package. 7497 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 7498 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 7499 mOverlays.put(pkg.mOverlayTarget, 7500 new ArrayMap<String, PackageParser.Package>()); 7501 } 7502 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 7503 map.put(pkg.packageName, pkg); 7504 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 7505 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 7506 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7507 "scanPackageLI failed to createIdmap"); 7508 } 7509 } 7510 } else if (mOverlays.containsKey(pkg.packageName) && 7511 !pkg.packageName.equals("android")) { 7512 // This is a regular package, with one or more known overlay packages. 7513 createIdmapsForPackageLI(pkg); 7514 } 7515 } 7516 7517 return pkg; 7518 } 7519 7520 /** 7521 * Derive the ABI of a non-system package located at {@code scanFile}. This information 7522 * is derived purely on the basis of the contents of {@code scanFile} and 7523 * {@code cpuAbiOverride}. 7524 * 7525 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 7526 */ 7527 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 7528 String cpuAbiOverride, boolean extractLibs) 7529 throws PackageManagerException { 7530 // TODO: We can probably be smarter about this stuff. For installed apps, 7531 // we can calculate this information at install time once and for all. For 7532 // system apps, we can probably assume that this information doesn't change 7533 // after the first boot scan. As things stand, we do lots of unnecessary work. 7534 7535 // Give ourselves some initial paths; we'll come back for another 7536 // pass once we've determined ABI below. 7537 setNativeLibraryPaths(pkg); 7538 7539 // We would never need to extract libs for forward-locked and external packages, 7540 // since the container service will do it for us. We shouldn't attempt to 7541 // extract libs from system app when it was not updated. 7542 if (pkg.isForwardLocked() || isExternal(pkg) || 7543 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) { 7544 extractLibs = false; 7545 } 7546 7547 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7548 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7549 7550 NativeLibraryHelper.Handle handle = null; 7551 try { 7552 handle = NativeLibraryHelper.Handle.create(scanFile); 7553 // TODO(multiArch): This can be null for apps that didn't go through the 7554 // usual installation process. We can calculate it again, like we 7555 // do during install time. 7556 // 7557 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7558 // unnecessary. 7559 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7560 7561 // Null out the abis so that they can be recalculated. 7562 pkg.applicationInfo.primaryCpuAbi = null; 7563 pkg.applicationInfo.secondaryCpuAbi = null; 7564 if (isMultiArch(pkg.applicationInfo)) { 7565 // Warn if we've set an abiOverride for multi-lib packages.. 7566 // By definition, we need to copy both 32 and 64 bit libraries for 7567 // such packages. 7568 if (pkg.cpuAbiOverride != null 7569 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7570 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7571 } 7572 7573 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7574 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7575 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7576 if (extractLibs) { 7577 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7578 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7579 useIsaSpecificSubdirs); 7580 } else { 7581 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7582 } 7583 } 7584 7585 maybeThrowExceptionForMultiArchCopy( 7586 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7587 7588 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7589 if (extractLibs) { 7590 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7591 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7592 useIsaSpecificSubdirs); 7593 } else { 7594 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7595 } 7596 } 7597 7598 maybeThrowExceptionForMultiArchCopy( 7599 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7600 7601 if (abi64 >= 0) { 7602 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7603 } 7604 7605 if (abi32 >= 0) { 7606 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7607 if (abi64 >= 0) { 7608 pkg.applicationInfo.secondaryCpuAbi = abi; 7609 } else { 7610 pkg.applicationInfo.primaryCpuAbi = abi; 7611 } 7612 } 7613 } else { 7614 String[] abiList = (cpuAbiOverride != null) ? 7615 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7616 7617 // Enable gross and lame hacks for apps that are built with old 7618 // SDK tools. We must scan their APKs for renderscript bitcode and 7619 // not launch them if it's present. Don't bother checking on devices 7620 // that don't have 64 bit support. 7621 boolean needsRenderScriptOverride = false; 7622 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7623 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7624 abiList = Build.SUPPORTED_32_BIT_ABIS; 7625 needsRenderScriptOverride = true; 7626 } 7627 7628 final int copyRet; 7629 if (extractLibs) { 7630 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7631 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7632 } else { 7633 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7634 } 7635 7636 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7637 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7638 "Error unpackaging native libs for app, errorCode=" + copyRet); 7639 } 7640 7641 if (copyRet >= 0) { 7642 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7643 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7644 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7645 } else if (needsRenderScriptOverride) { 7646 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7647 } 7648 } 7649 } catch (IOException ioe) { 7650 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7651 } finally { 7652 IoUtils.closeQuietly(handle); 7653 } 7654 7655 // Now that we've calculated the ABIs and determined if it's an internal app, 7656 // we will go ahead and populate the nativeLibraryPath. 7657 setNativeLibraryPaths(pkg); 7658 } 7659 7660 /** 7661 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7662 * i.e, so that all packages can be run inside a single process if required. 7663 * 7664 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7665 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7666 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7667 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7668 * updating a package that belongs to a shared user. 7669 * 7670 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7671 * adds unnecessary complexity. 7672 */ 7673 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7674 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 7675 String requiredInstructionSet = null; 7676 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7677 requiredInstructionSet = VMRuntime.getInstructionSet( 7678 scannedPackage.applicationInfo.primaryCpuAbi); 7679 } 7680 7681 PackageSetting requirer = null; 7682 for (PackageSetting ps : packagesForUser) { 7683 // If packagesForUser contains scannedPackage, we skip it. This will happen 7684 // when scannedPackage is an update of an existing package. Without this check, 7685 // we will never be able to change the ABI of any package belonging to a shared 7686 // user, even if it's compatible with other packages. 7687 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7688 if (ps.primaryCpuAbiString == null) { 7689 continue; 7690 } 7691 7692 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7693 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7694 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7695 // this but there's not much we can do. 7696 String errorMessage = "Instruction set mismatch, " 7697 + ((requirer == null) ? "[caller]" : requirer) 7698 + " requires " + requiredInstructionSet + " whereas " + ps 7699 + " requires " + instructionSet; 7700 Slog.w(TAG, errorMessage); 7701 } 7702 7703 if (requiredInstructionSet == null) { 7704 requiredInstructionSet = instructionSet; 7705 requirer = ps; 7706 } 7707 } 7708 } 7709 7710 if (requiredInstructionSet != null) { 7711 String adjustedAbi; 7712 if (requirer != null) { 7713 // requirer != null implies that either scannedPackage was null or that scannedPackage 7714 // did not require an ABI, in which case we have to adjust scannedPackage to match 7715 // the ABI of the set (which is the same as requirer's ABI) 7716 adjustedAbi = requirer.primaryCpuAbiString; 7717 if (scannedPackage != null) { 7718 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7719 } 7720 } else { 7721 // requirer == null implies that we're updating all ABIs in the set to 7722 // match scannedPackage. 7723 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7724 } 7725 7726 for (PackageSetting ps : packagesForUser) { 7727 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7728 if (ps.primaryCpuAbiString != null) { 7729 continue; 7730 } 7731 7732 ps.primaryCpuAbiString = adjustedAbi; 7733 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7734 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7735 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7736 7737 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 7738 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 7739 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7740 ps.primaryCpuAbiString = null; 7741 ps.pkg.applicationInfo.primaryCpuAbi = null; 7742 return; 7743 } else { 7744 mInstaller.rmdex(ps.codePathString, 7745 getDexCodeInstructionSet(getPreferredInstructionSet())); 7746 } 7747 } 7748 } 7749 } 7750 } 7751 } 7752 7753 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7754 synchronized (mPackages) { 7755 mResolverReplaced = true; 7756 // Set up information for custom user intent resolution activity. 7757 mResolveActivity.applicationInfo = pkg.applicationInfo; 7758 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7759 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7760 mResolveActivity.processName = pkg.applicationInfo.packageName; 7761 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7762 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7763 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7764 mResolveActivity.theme = 0; 7765 mResolveActivity.exported = true; 7766 mResolveActivity.enabled = true; 7767 mResolveInfo.activityInfo = mResolveActivity; 7768 mResolveInfo.priority = 0; 7769 mResolveInfo.preferredOrder = 0; 7770 mResolveInfo.match = 0; 7771 mResolveComponentName = mCustomResolverComponentName; 7772 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7773 mResolveComponentName); 7774 } 7775 } 7776 7777 private static String calculateBundledApkRoot(final String codePathString) { 7778 final File codePath = new File(codePathString); 7779 final File codeRoot; 7780 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 7781 codeRoot = Environment.getRootDirectory(); 7782 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7783 codeRoot = Environment.getOemDirectory(); 7784 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7785 codeRoot = Environment.getVendorDirectory(); 7786 } else { 7787 // Unrecognized code path; take its top real segment as the apk root: 7788 // e.g. /something/app/blah.apk => /something 7789 try { 7790 File f = codePath.getCanonicalFile(); 7791 File parent = f.getParentFile(); // non-null because codePath is a file 7792 File tmp; 7793 while ((tmp = parent.getParentFile()) != null) { 7794 f = parent; 7795 parent = tmp; 7796 } 7797 codeRoot = f; 7798 Slog.w(TAG, "Unrecognized code path " 7799 + codePath + " - using " + codeRoot); 7800 } catch (IOException e) { 7801 // Can't canonicalize the code path -- shenanigans? 7802 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7803 return Environment.getRootDirectory().getPath(); 7804 } 7805 } 7806 return codeRoot.getPath(); 7807 } 7808 7809 /** 7810 * Derive and set the location of native libraries for the given package, 7811 * which varies depending on where and how the package was installed. 7812 */ 7813 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7814 final ApplicationInfo info = pkg.applicationInfo; 7815 final String codePath = pkg.codePath; 7816 final File codeFile = new File(codePath); 7817 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7818 final boolean asecApp = info.isForwardLocked() || isExternal(info); 7819 7820 info.nativeLibraryRootDir = null; 7821 info.nativeLibraryRootRequiresIsa = false; 7822 info.nativeLibraryDir = null; 7823 info.secondaryNativeLibraryDir = null; 7824 7825 if (isApkFile(codeFile)) { 7826 // Monolithic install 7827 if (bundledApp) { 7828 // If "/system/lib64/apkname" exists, assume that is the per-package 7829 // native library directory to use; otherwise use "/system/lib/apkname". 7830 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7831 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7832 getPrimaryInstructionSet(info)); 7833 7834 // This is a bundled system app so choose the path based on the ABI. 7835 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7836 // is just the default path. 7837 final String apkName = deriveCodePathName(codePath); 7838 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7839 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7840 apkName).getAbsolutePath(); 7841 7842 if (info.secondaryCpuAbi != null) { 7843 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7844 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7845 secondaryLibDir, apkName).getAbsolutePath(); 7846 } 7847 } else if (asecApp) { 7848 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 7849 .getAbsolutePath(); 7850 } else { 7851 final String apkName = deriveCodePathName(codePath); 7852 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 7853 .getAbsolutePath(); 7854 } 7855 7856 info.nativeLibraryRootRequiresIsa = false; 7857 info.nativeLibraryDir = info.nativeLibraryRootDir; 7858 } else { 7859 // Cluster install 7860 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 7861 info.nativeLibraryRootRequiresIsa = true; 7862 7863 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 7864 getPrimaryInstructionSet(info)).getAbsolutePath(); 7865 7866 if (info.secondaryCpuAbi != null) { 7867 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 7868 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 7869 } 7870 } 7871 } 7872 7873 /** 7874 * Calculate the abis and roots for a bundled app. These can uniquely 7875 * be determined from the contents of the system partition, i.e whether 7876 * it contains 64 or 32 bit shared libraries etc. We do not validate any 7877 * of this information, and instead assume that the system was built 7878 * sensibly. 7879 */ 7880 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 7881 PackageSetting pkgSetting) { 7882 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 7883 7884 // If "/system/lib64/apkname" exists, assume that is the per-package 7885 // native library directory to use; otherwise use "/system/lib/apkname". 7886 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 7887 setBundledAppAbi(pkg, apkRoot, apkName); 7888 // pkgSetting might be null during rescan following uninstall of updates 7889 // to a bundled app, so accommodate that possibility. The settings in 7890 // that case will be established later from the parsed package. 7891 // 7892 // If the settings aren't null, sync them up with what we've just derived. 7893 // note that apkRoot isn't stored in the package settings. 7894 if (pkgSetting != null) { 7895 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7896 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7897 } 7898 } 7899 7900 /** 7901 * Deduces the ABI of a bundled app and sets the relevant fields on the 7902 * parsed pkg object. 7903 * 7904 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 7905 * under which system libraries are installed. 7906 * @param apkName the name of the installed package. 7907 */ 7908 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 7909 final File codeFile = new File(pkg.codePath); 7910 7911 final boolean has64BitLibs; 7912 final boolean has32BitLibs; 7913 if (isApkFile(codeFile)) { 7914 // Monolithic install 7915 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 7916 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7917 } else { 7918 // Cluster install 7919 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7920 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7921 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7922 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7923 has64BitLibs = (new File(rootDir, isa)).exists(); 7924 } else { 7925 has64BitLibs = false; 7926 } 7927 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7928 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 7929 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 7930 has32BitLibs = (new File(rootDir, isa)).exists(); 7931 } else { 7932 has32BitLibs = false; 7933 } 7934 } 7935 7936 if (has64BitLibs && !has32BitLibs) { 7937 // The package has 64 bit libs, but not 32 bit libs. Its primary 7938 // ABI should be 64 bit. We can safely assume here that the bundled 7939 // native libraries correspond to the most preferred ABI in the list. 7940 7941 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7942 pkg.applicationInfo.secondaryCpuAbi = null; 7943 } else if (has32BitLibs && !has64BitLibs) { 7944 // The package has 32 bit libs but not 64 bit libs. Its primary 7945 // ABI should be 32 bit. 7946 7947 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7948 pkg.applicationInfo.secondaryCpuAbi = null; 7949 } else if (has32BitLibs && has64BitLibs) { 7950 // The application has both 64 and 32 bit bundled libraries. We check 7951 // here that the app declares multiArch support, and warn if it doesn't. 7952 // 7953 // We will be lenient here and record both ABIs. The primary will be the 7954 // ABI that's higher on the list, i.e, a device that's configured to prefer 7955 // 64 bit apps will see a 64 bit primary ABI, 7956 7957 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 7958 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 7959 } 7960 7961 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 7962 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7963 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7964 } else { 7965 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7966 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7967 } 7968 } else { 7969 pkg.applicationInfo.primaryCpuAbi = null; 7970 pkg.applicationInfo.secondaryCpuAbi = null; 7971 } 7972 } 7973 7974 private void killApplication(String pkgName, int appId, String reason) { 7975 // Request the ActivityManager to kill the process(only for existing packages) 7976 // so that we do not end up in a confused state while the user is still using the older 7977 // version of the application while the new one gets installed. 7978 IActivityManager am = ActivityManagerNative.getDefault(); 7979 if (am != null) { 7980 try { 7981 am.killApplicationWithAppId(pkgName, appId, reason); 7982 } catch (RemoteException e) { 7983 } 7984 } 7985 } 7986 7987 void removePackageLI(PackageSetting ps, boolean chatty) { 7988 if (DEBUG_INSTALL) { 7989 if (chatty) 7990 Log.d(TAG, "Removing package " + ps.name); 7991 } 7992 7993 // writer 7994 synchronized (mPackages) { 7995 mPackages.remove(ps.name); 7996 final PackageParser.Package pkg = ps.pkg; 7997 if (pkg != null) { 7998 cleanPackageDataStructuresLILPw(pkg, chatty); 7999 } 8000 } 8001 } 8002 8003 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 8004 if (DEBUG_INSTALL) { 8005 if (chatty) 8006 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 8007 } 8008 8009 // writer 8010 synchronized (mPackages) { 8011 mPackages.remove(pkg.applicationInfo.packageName); 8012 cleanPackageDataStructuresLILPw(pkg, chatty); 8013 } 8014 } 8015 8016 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 8017 int N = pkg.providers.size(); 8018 StringBuilder r = null; 8019 int i; 8020 for (i=0; i<N; i++) { 8021 PackageParser.Provider p = pkg.providers.get(i); 8022 mProviders.removeProvider(p); 8023 if (p.info.authority == null) { 8024 8025 /* There was another ContentProvider with this authority when 8026 * this app was installed so this authority is null, 8027 * Ignore it as we don't have to unregister the provider. 8028 */ 8029 continue; 8030 } 8031 String names[] = p.info.authority.split(";"); 8032 for (int j = 0; j < names.length; j++) { 8033 if (mProvidersByAuthority.get(names[j]) == p) { 8034 mProvidersByAuthority.remove(names[j]); 8035 if (DEBUG_REMOVE) { 8036 if (chatty) 8037 Log.d(TAG, "Unregistered content provider: " + names[j] 8038 + ", className = " + p.info.name + ", isSyncable = " 8039 + p.info.isSyncable); 8040 } 8041 } 8042 } 8043 if (DEBUG_REMOVE && chatty) { 8044 if (r == null) { 8045 r = new StringBuilder(256); 8046 } else { 8047 r.append(' '); 8048 } 8049 r.append(p.info.name); 8050 } 8051 } 8052 if (r != null) { 8053 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 8054 } 8055 8056 N = pkg.services.size(); 8057 r = null; 8058 for (i=0; i<N; i++) { 8059 PackageParser.Service s = pkg.services.get(i); 8060 mServices.removeService(s); 8061 if (chatty) { 8062 if (r == null) { 8063 r = new StringBuilder(256); 8064 } else { 8065 r.append(' '); 8066 } 8067 r.append(s.info.name); 8068 } 8069 } 8070 if (r != null) { 8071 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 8072 } 8073 8074 N = pkg.receivers.size(); 8075 r = null; 8076 for (i=0; i<N; i++) { 8077 PackageParser.Activity a = pkg.receivers.get(i); 8078 mReceivers.removeActivity(a, "receiver"); 8079 if (DEBUG_REMOVE && chatty) { 8080 if (r == null) { 8081 r = new StringBuilder(256); 8082 } else { 8083 r.append(' '); 8084 } 8085 r.append(a.info.name); 8086 } 8087 } 8088 if (r != null) { 8089 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 8090 } 8091 8092 N = pkg.activities.size(); 8093 r = null; 8094 for (i=0; i<N; i++) { 8095 PackageParser.Activity a = pkg.activities.get(i); 8096 mActivities.removeActivity(a, "activity"); 8097 if (DEBUG_REMOVE && chatty) { 8098 if (r == null) { 8099 r = new StringBuilder(256); 8100 } else { 8101 r.append(' '); 8102 } 8103 r.append(a.info.name); 8104 } 8105 } 8106 if (r != null) { 8107 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 8108 } 8109 8110 N = pkg.permissions.size(); 8111 r = null; 8112 for (i=0; i<N; i++) { 8113 PackageParser.Permission p = pkg.permissions.get(i); 8114 BasePermission bp = mSettings.mPermissions.get(p.info.name); 8115 if (bp == null) { 8116 bp = mSettings.mPermissionTrees.get(p.info.name); 8117 } 8118 if (bp != null && bp.perm == p) { 8119 bp.perm = null; 8120 if (DEBUG_REMOVE && chatty) { 8121 if (r == null) { 8122 r = new StringBuilder(256); 8123 } else { 8124 r.append(' '); 8125 } 8126 r.append(p.info.name); 8127 } 8128 } 8129 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8130 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 8131 if (appOpPerms != null) { 8132 appOpPerms.remove(pkg.packageName); 8133 } 8134 } 8135 } 8136 if (r != null) { 8137 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8138 } 8139 8140 N = pkg.requestedPermissions.size(); 8141 r = null; 8142 for (i=0; i<N; i++) { 8143 String perm = pkg.requestedPermissions.get(i); 8144 BasePermission bp = mSettings.mPermissions.get(perm); 8145 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8146 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 8147 if (appOpPerms != null) { 8148 appOpPerms.remove(pkg.packageName); 8149 if (appOpPerms.isEmpty()) { 8150 mAppOpPermissionPackages.remove(perm); 8151 } 8152 } 8153 } 8154 } 8155 if (r != null) { 8156 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8157 } 8158 8159 N = pkg.instrumentation.size(); 8160 r = null; 8161 for (i=0; i<N; i++) { 8162 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8163 mInstrumentation.remove(a.getComponentName()); 8164 if (DEBUG_REMOVE && chatty) { 8165 if (r == null) { 8166 r = new StringBuilder(256); 8167 } else { 8168 r.append(' '); 8169 } 8170 r.append(a.info.name); 8171 } 8172 } 8173 if (r != null) { 8174 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 8175 } 8176 8177 r = null; 8178 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8179 // Only system apps can hold shared libraries. 8180 if (pkg.libraryNames != null) { 8181 for (i=0; i<pkg.libraryNames.size(); i++) { 8182 String name = pkg.libraryNames.get(i); 8183 SharedLibraryEntry cur = mSharedLibraries.get(name); 8184 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 8185 mSharedLibraries.remove(name); 8186 if (DEBUG_REMOVE && chatty) { 8187 if (r == null) { 8188 r = new StringBuilder(256); 8189 } else { 8190 r.append(' '); 8191 } 8192 r.append(name); 8193 } 8194 } 8195 } 8196 } 8197 } 8198 if (r != null) { 8199 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 8200 } 8201 } 8202 8203 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 8204 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 8205 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 8206 return true; 8207 } 8208 } 8209 return false; 8210 } 8211 8212 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 8213 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 8214 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 8215 8216 private void updatePermissionsLPw(String changingPkg, 8217 PackageParser.Package pkgInfo, int flags) { 8218 // Make sure there are no dangling permission trees. 8219 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 8220 while (it.hasNext()) { 8221 final BasePermission bp = it.next(); 8222 if (bp.packageSetting == null) { 8223 // We may not yet have parsed the package, so just see if 8224 // we still know about its settings. 8225 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8226 } 8227 if (bp.packageSetting == null) { 8228 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 8229 + " from package " + bp.sourcePackage); 8230 it.remove(); 8231 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8232 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8233 Slog.i(TAG, "Removing old permission tree: " + bp.name 8234 + " from package " + bp.sourcePackage); 8235 flags |= UPDATE_PERMISSIONS_ALL; 8236 it.remove(); 8237 } 8238 } 8239 } 8240 8241 // Make sure all dynamic permissions have been assigned to a package, 8242 // and make sure there are no dangling permissions. 8243 it = mSettings.mPermissions.values().iterator(); 8244 while (it.hasNext()) { 8245 final BasePermission bp = it.next(); 8246 if (bp.type == BasePermission.TYPE_DYNAMIC) { 8247 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 8248 + bp.name + " pkg=" + bp.sourcePackage 8249 + " info=" + bp.pendingInfo); 8250 if (bp.packageSetting == null && bp.pendingInfo != null) { 8251 final BasePermission tree = findPermissionTreeLP(bp.name); 8252 if (tree != null && tree.perm != null) { 8253 bp.packageSetting = tree.packageSetting; 8254 bp.perm = new PackageParser.Permission(tree.perm.owner, 8255 new PermissionInfo(bp.pendingInfo)); 8256 bp.perm.info.packageName = tree.perm.info.packageName; 8257 bp.perm.info.name = bp.name; 8258 bp.uid = tree.uid; 8259 } 8260 } 8261 } 8262 if (bp.packageSetting == null) { 8263 // We may not yet have parsed the package, so just see if 8264 // we still know about its settings. 8265 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8266 } 8267 if (bp.packageSetting == null) { 8268 Slog.w(TAG, "Removing dangling permission: " + bp.name 8269 + " from package " + bp.sourcePackage); 8270 it.remove(); 8271 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8272 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8273 Slog.i(TAG, "Removing old permission: " + bp.name 8274 + " from package " + bp.sourcePackage); 8275 flags |= UPDATE_PERMISSIONS_ALL; 8276 it.remove(); 8277 } 8278 } 8279 } 8280 8281 // Now update the permissions for all packages, in particular 8282 // replace the granted permissions of the system packages. 8283 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 8284 for (PackageParser.Package pkg : mPackages.values()) { 8285 if (pkg != pkgInfo) { 8286 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 8287 changingPkg); 8288 } 8289 } 8290 } 8291 8292 if (pkgInfo != null) { 8293 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 8294 } 8295 } 8296 8297 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 8298 String packageOfInterest) { 8299 // IMPORTANT: There are two types of permissions: install and runtime. 8300 // Install time permissions are granted when the app is installed to 8301 // all device users and users added in the future. Runtime permissions 8302 // are granted at runtime explicitly to specific users. Normal and signature 8303 // protected permissions are install time permissions. Dangerous permissions 8304 // are install permissions if the app's target SDK is Lollipop MR1 or older, 8305 // otherwise they are runtime permissions. This function does not manage 8306 // runtime permissions except for the case an app targeting Lollipop MR1 8307 // being upgraded to target a newer SDK, in which case dangerous permissions 8308 // are transformed from install time to runtime ones. 8309 8310 final PackageSetting ps = (PackageSetting) pkg.mExtras; 8311 if (ps == null) { 8312 return; 8313 } 8314 8315 PermissionsState permissionsState = ps.getPermissionsState(); 8316 PermissionsState origPermissions = permissionsState; 8317 8318 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 8319 8320 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 8321 8322 boolean changedInstallPermission = false; 8323 8324 if (replace) { 8325 ps.installPermissionsFixed = false; 8326 if (!ps.isSharedUser()) { 8327 origPermissions = new PermissionsState(permissionsState); 8328 permissionsState.reset(); 8329 } 8330 } 8331 8332 permissionsState.setGlobalGids(mGlobalGids); 8333 8334 final int N = pkg.requestedPermissions.size(); 8335 for (int i=0; i<N; i++) { 8336 final String name = pkg.requestedPermissions.get(i); 8337 final BasePermission bp = mSettings.mPermissions.get(name); 8338 8339 if (DEBUG_INSTALL) { 8340 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 8341 } 8342 8343 if (bp == null || bp.packageSetting == null) { 8344 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8345 Slog.w(TAG, "Unknown permission " + name 8346 + " in package " + pkg.packageName); 8347 } 8348 continue; 8349 } 8350 8351 final String perm = bp.name; 8352 boolean allowedSig = false; 8353 int grant = GRANT_DENIED; 8354 8355 // Keep track of app op permissions. 8356 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8357 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 8358 if (pkgs == null) { 8359 pkgs = new ArraySet<>(); 8360 mAppOpPermissionPackages.put(bp.name, pkgs); 8361 } 8362 pkgs.add(pkg.packageName); 8363 } 8364 8365 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 8366 switch (level) { 8367 case PermissionInfo.PROTECTION_NORMAL: { 8368 // For all apps normal permissions are install time ones. 8369 grant = GRANT_INSTALL; 8370 } break; 8371 8372 case PermissionInfo.PROTECTION_DANGEROUS: { 8373 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 8374 // For legacy apps dangerous permissions are install time ones. 8375 grant = GRANT_INSTALL_LEGACY; 8376 } else if (origPermissions.hasInstallPermission(bp.name)) { 8377 // For legacy apps that became modern, install becomes runtime. 8378 grant = GRANT_UPGRADE; 8379 } else { 8380 // For modern apps keep runtime permissions unchanged. 8381 grant = GRANT_RUNTIME; 8382 } 8383 } break; 8384 8385 case PermissionInfo.PROTECTION_SIGNATURE: { 8386 // For all apps signature permissions are install time ones. 8387 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 8388 if (allowedSig) { 8389 grant = GRANT_INSTALL; 8390 } 8391 } break; 8392 } 8393 8394 if (DEBUG_INSTALL) { 8395 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 8396 } 8397 8398 if (grant != GRANT_DENIED) { 8399 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 8400 // If this is an existing, non-system package, then 8401 // we can't add any new permissions to it. 8402 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 8403 // Except... if this is a permission that was added 8404 // to the platform (note: need to only do this when 8405 // updating the platform). 8406 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 8407 grant = GRANT_DENIED; 8408 } 8409 } 8410 } 8411 8412 switch (grant) { 8413 case GRANT_INSTALL: { 8414 // Revoke this as runtime permission to handle the case of 8415 // a runtime permission being downgraded to an install one. 8416 for (int userId : UserManagerService.getInstance().getUserIds()) { 8417 if (origPermissions.getRuntimePermissionState( 8418 bp.name, userId) != null) { 8419 // Revoke the runtime permission and clear the flags. 8420 origPermissions.revokeRuntimePermission(bp, userId); 8421 origPermissions.updatePermissionFlags(bp, userId, 8422 PackageManager.MASK_PERMISSION_FLAGS, 0); 8423 // If we revoked a permission permission, we have to write. 8424 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8425 changedRuntimePermissionUserIds, userId); 8426 } 8427 } 8428 // Grant an install permission. 8429 if (permissionsState.grantInstallPermission(bp) != 8430 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8431 changedInstallPermission = true; 8432 } 8433 } break; 8434 8435 case GRANT_INSTALL_LEGACY: { 8436 // Grant an install permission. 8437 if (permissionsState.grantInstallPermission(bp) != 8438 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8439 changedInstallPermission = true; 8440 } 8441 } break; 8442 8443 case GRANT_RUNTIME: { 8444 // Grant previously granted runtime permissions. 8445 for (int userId : UserManagerService.getInstance().getUserIds()) { 8446 PermissionState permissionState = origPermissions 8447 .getRuntimePermissionState(bp.name, userId); 8448 final int flags = permissionState != null 8449 ? permissionState.getFlags() : 0; 8450 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8451 if (permissionsState.grantRuntimePermission(bp, userId) == 8452 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8453 // If we cannot put the permission as it was, we have to write. 8454 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8455 changedRuntimePermissionUserIds, userId); 8456 } 8457 } 8458 // Propagate the permission flags. 8459 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 8460 } 8461 } break; 8462 8463 case GRANT_UPGRADE: { 8464 // Grant runtime permissions for a previously held install permission. 8465 PermissionState permissionState = origPermissions 8466 .getInstallPermissionState(bp.name); 8467 final int flags = permissionState != null ? permissionState.getFlags() : 0; 8468 8469 if (origPermissions.revokeInstallPermission(bp) 8470 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 8471 // We will be transferring the permission flags, so clear them. 8472 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 8473 PackageManager.MASK_PERMISSION_FLAGS, 0); 8474 changedInstallPermission = true; 8475 } 8476 8477 // If the permission is not to be promoted to runtime we ignore it and 8478 // also its other flags as they are not applicable to install permissions. 8479 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 8480 for (int userId : currentUserIds) { 8481 if (permissionsState.grantRuntimePermission(bp, userId) != 8482 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8483 // Transfer the permission flags. 8484 permissionsState.updatePermissionFlags(bp, userId, 8485 flags, flags); 8486 // If we granted the permission, we have to write. 8487 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8488 changedRuntimePermissionUserIds, userId); 8489 } 8490 } 8491 } 8492 } break; 8493 8494 default: { 8495 if (packageOfInterest == null 8496 || packageOfInterest.equals(pkg.packageName)) { 8497 Slog.w(TAG, "Not granting permission " + perm 8498 + " to package " + pkg.packageName 8499 + " because it was previously installed without"); 8500 } 8501 } break; 8502 } 8503 } else { 8504 if (permissionsState.revokeInstallPermission(bp) != 8505 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8506 // Also drop the permission flags. 8507 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 8508 PackageManager.MASK_PERMISSION_FLAGS, 0); 8509 changedInstallPermission = true; 8510 Slog.i(TAG, "Un-granting permission " + perm 8511 + " from package " + pkg.packageName 8512 + " (protectionLevel=" + bp.protectionLevel 8513 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8514 + ")"); 8515 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 8516 // Don't print warning for app op permissions, since it is fine for them 8517 // not to be granted, there is a UI for the user to decide. 8518 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8519 Slog.w(TAG, "Not granting permission " + perm 8520 + " to package " + pkg.packageName 8521 + " (protectionLevel=" + bp.protectionLevel 8522 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8523 + ")"); 8524 } 8525 } 8526 } 8527 } 8528 8529 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 8530 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 8531 // This is the first that we have heard about this package, so the 8532 // permissions we have now selected are fixed until explicitly 8533 // changed. 8534 ps.installPermissionsFixed = true; 8535 } 8536 8537 // Persist the runtime permissions state for users with changes. 8538 for (int userId : changedRuntimePermissionUserIds) { 8539 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 8540 } 8541 } 8542 8543 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8544 boolean allowed = false; 8545 final int NP = PackageParser.NEW_PERMISSIONS.length; 8546 for (int ip=0; ip<NP; ip++) { 8547 final PackageParser.NewPermissionInfo npi 8548 = PackageParser.NEW_PERMISSIONS[ip]; 8549 if (npi.name.equals(perm) 8550 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8551 allowed = true; 8552 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8553 + pkg.packageName); 8554 break; 8555 } 8556 } 8557 return allowed; 8558 } 8559 8560 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 8561 BasePermission bp, PermissionsState origPermissions) { 8562 boolean allowed; 8563 allowed = (compareSignatures( 8564 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 8565 == PackageManager.SIGNATURE_MATCH) 8566 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 8567 == PackageManager.SIGNATURE_MATCH); 8568 if (!allowed && (bp.protectionLevel 8569 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 8570 if (isSystemApp(pkg)) { 8571 // For updated system applications, a system permission 8572 // is granted only if it had been defined by the original application. 8573 if (pkg.isUpdatedSystemApp()) { 8574 final PackageSetting sysPs = mSettings 8575 .getDisabledSystemPkgLPr(pkg.packageName); 8576 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 8577 // If the original was granted this permission, we take 8578 // that grant decision as read and propagate it to the 8579 // update. 8580 if (sysPs.isPrivileged()) { 8581 allowed = true; 8582 } 8583 } else { 8584 // The system apk may have been updated with an older 8585 // version of the one on the data partition, but which 8586 // granted a new system permission that it didn't have 8587 // before. In this case we do want to allow the app to 8588 // now get the new permission if the ancestral apk is 8589 // privileged to get it. 8590 if (sysPs.pkg != null && sysPs.isPrivileged()) { 8591 for (int j=0; 8592 j<sysPs.pkg.requestedPermissions.size(); j++) { 8593 if (perm.equals( 8594 sysPs.pkg.requestedPermissions.get(j))) { 8595 allowed = true; 8596 break; 8597 } 8598 } 8599 } 8600 } 8601 } else { 8602 allowed = isPrivilegedApp(pkg); 8603 } 8604 } 8605 } 8606 if (!allowed) { 8607 if (!allowed && (bp.protectionLevel 8608 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 8609 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.MNC) { 8610 // If this was a previously normal/dangerous permission that got moved 8611 // to a system permission as part of the runtime permission redesign, then 8612 // we still want to blindly grant it to old apps. 8613 allowed = true; 8614 } 8615 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 8616 && pkg.packageName.equals(mRequiredInstallerPackage)) { 8617 // If this permission is to be granted to the system installer and 8618 // this app is an installer, then it gets the permission. 8619 allowed = true; 8620 } 8621 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 8622 && pkg.packageName.equals(mRequiredVerifierPackage)) { 8623 // If this permission is to be granted to the system verifier and 8624 // this app is a verifier, then it gets the permission. 8625 allowed = true; 8626 } 8627 if (!allowed && (bp.protectionLevel 8628 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 8629 && isSystemApp(pkg)) { 8630 // Any pre-installed system app is allowed to get this permission. 8631 allowed = true; 8632 } 8633 if (!allowed && (bp.protectionLevel 8634 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 8635 // For development permissions, a development permission 8636 // is granted only if it was already granted. 8637 allowed = origPermissions.hasInstallPermission(perm); 8638 } 8639 } 8640 return allowed; 8641 } 8642 8643 final class ActivityIntentResolver 8644 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 8645 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8646 boolean defaultOnly, int userId) { 8647 if (!sUserManager.exists(userId)) return null; 8648 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8649 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8650 } 8651 8652 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8653 int userId) { 8654 if (!sUserManager.exists(userId)) return null; 8655 mFlags = flags; 8656 return super.queryIntent(intent, resolvedType, 8657 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8658 } 8659 8660 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8661 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 8662 if (!sUserManager.exists(userId)) return null; 8663 if (packageActivities == null) { 8664 return null; 8665 } 8666 mFlags = flags; 8667 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8668 final int N = packageActivities.size(); 8669 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 8670 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 8671 8672 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 8673 for (int i = 0; i < N; ++i) { 8674 intentFilters = packageActivities.get(i).intents; 8675 if (intentFilters != null && intentFilters.size() > 0) { 8676 PackageParser.ActivityIntentInfo[] array = 8677 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 8678 intentFilters.toArray(array); 8679 listCut.add(array); 8680 } 8681 } 8682 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8683 } 8684 8685 public final void addActivity(PackageParser.Activity a, String type) { 8686 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 8687 mActivities.put(a.getComponentName(), a); 8688 if (DEBUG_SHOW_INFO) 8689 Log.v( 8690 TAG, " " + type + " " + 8691 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 8692 if (DEBUG_SHOW_INFO) 8693 Log.v(TAG, " Class=" + a.info.name); 8694 final int NI = a.intents.size(); 8695 for (int j=0; j<NI; j++) { 8696 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8697 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 8698 intent.setPriority(0); 8699 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 8700 + a.className + " with priority > 0, forcing to 0"); 8701 } 8702 if (DEBUG_SHOW_INFO) { 8703 Log.v(TAG, " IntentFilter:"); 8704 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8705 } 8706 if (!intent.debugCheck()) { 8707 Log.w(TAG, "==> For Activity " + a.info.name); 8708 } 8709 addFilter(intent); 8710 } 8711 } 8712 8713 public final void removeActivity(PackageParser.Activity a, String type) { 8714 mActivities.remove(a.getComponentName()); 8715 if (DEBUG_SHOW_INFO) { 8716 Log.v(TAG, " " + type + " " 8717 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 8718 : a.info.name) + ":"); 8719 Log.v(TAG, " Class=" + a.info.name); 8720 } 8721 final int NI = a.intents.size(); 8722 for (int j=0; j<NI; j++) { 8723 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8724 if (DEBUG_SHOW_INFO) { 8725 Log.v(TAG, " IntentFilter:"); 8726 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8727 } 8728 removeFilter(intent); 8729 } 8730 } 8731 8732 @Override 8733 protected boolean allowFilterResult( 8734 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 8735 ActivityInfo filterAi = filter.activity.info; 8736 for (int i=dest.size()-1; i>=0; i--) { 8737 ActivityInfo destAi = dest.get(i).activityInfo; 8738 if (destAi.name == filterAi.name 8739 && destAi.packageName == filterAi.packageName) { 8740 return false; 8741 } 8742 } 8743 return true; 8744 } 8745 8746 @Override 8747 protected ActivityIntentInfo[] newArray(int size) { 8748 return new ActivityIntentInfo[size]; 8749 } 8750 8751 @Override 8752 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 8753 if (!sUserManager.exists(userId)) return true; 8754 PackageParser.Package p = filter.activity.owner; 8755 if (p != null) { 8756 PackageSetting ps = (PackageSetting)p.mExtras; 8757 if (ps != null) { 8758 // System apps are never considered stopped for purposes of 8759 // filtering, because there may be no way for the user to 8760 // actually re-launch them. 8761 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 8762 && ps.getStopped(userId); 8763 } 8764 } 8765 return false; 8766 } 8767 8768 @Override 8769 protected boolean isPackageForFilter(String packageName, 8770 PackageParser.ActivityIntentInfo info) { 8771 return packageName.equals(info.activity.owner.packageName); 8772 } 8773 8774 @Override 8775 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 8776 int match, int userId) { 8777 if (!sUserManager.exists(userId)) return null; 8778 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 8779 return null; 8780 } 8781 final PackageParser.Activity activity = info.activity; 8782 if (mSafeMode && (activity.info.applicationInfo.flags 8783 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8784 return null; 8785 } 8786 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 8787 if (ps == null) { 8788 return null; 8789 } 8790 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 8791 ps.readUserState(userId), userId); 8792 if (ai == null) { 8793 return null; 8794 } 8795 final ResolveInfo res = new ResolveInfo(); 8796 res.activityInfo = ai; 8797 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8798 res.filter = info; 8799 } 8800 if (info != null) { 8801 res.handleAllWebDataURI = info.handleAllWebDataURI(); 8802 } 8803 res.priority = info.getPriority(); 8804 res.preferredOrder = activity.owner.mPreferredOrder; 8805 //System.out.println("Result: " + res.activityInfo.className + 8806 // " = " + res.priority); 8807 res.match = match; 8808 res.isDefault = info.hasDefault; 8809 res.labelRes = info.labelRes; 8810 res.nonLocalizedLabel = info.nonLocalizedLabel; 8811 if (userNeedsBadging(userId)) { 8812 res.noResourceId = true; 8813 } else { 8814 res.icon = info.icon; 8815 } 8816 res.iconResourceId = info.icon; 8817 res.system = res.activityInfo.applicationInfo.isSystemApp(); 8818 return res; 8819 } 8820 8821 @Override 8822 protected void sortResults(List<ResolveInfo> results) { 8823 Collections.sort(results, mResolvePrioritySorter); 8824 } 8825 8826 @Override 8827 protected void dumpFilter(PrintWriter out, String prefix, 8828 PackageParser.ActivityIntentInfo filter) { 8829 out.print(prefix); out.print( 8830 Integer.toHexString(System.identityHashCode(filter.activity))); 8831 out.print(' '); 8832 filter.activity.printComponentShortName(out); 8833 out.print(" filter "); 8834 out.println(Integer.toHexString(System.identityHashCode(filter))); 8835 } 8836 8837 @Override 8838 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 8839 return filter.activity; 8840 } 8841 8842 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8843 PackageParser.Activity activity = (PackageParser.Activity)label; 8844 out.print(prefix); out.print( 8845 Integer.toHexString(System.identityHashCode(activity))); 8846 out.print(' '); 8847 activity.printComponentShortName(out); 8848 if (count > 1) { 8849 out.print(" ("); out.print(count); out.print(" filters)"); 8850 } 8851 out.println(); 8852 } 8853 8854// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8855// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8856// final List<ResolveInfo> retList = Lists.newArrayList(); 8857// while (i.hasNext()) { 8858// final ResolveInfo resolveInfo = i.next(); 8859// if (isEnabledLP(resolveInfo.activityInfo)) { 8860// retList.add(resolveInfo); 8861// } 8862// } 8863// return retList; 8864// } 8865 8866 // Keys are String (activity class name), values are Activity. 8867 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 8868 = new ArrayMap<ComponentName, PackageParser.Activity>(); 8869 private int mFlags; 8870 } 8871 8872 private final class ServiceIntentResolver 8873 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 8874 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8875 boolean defaultOnly, int userId) { 8876 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8877 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8878 } 8879 8880 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8881 int userId) { 8882 if (!sUserManager.exists(userId)) return null; 8883 mFlags = flags; 8884 return super.queryIntent(intent, resolvedType, 8885 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8886 } 8887 8888 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8889 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 8890 if (!sUserManager.exists(userId)) return null; 8891 if (packageServices == null) { 8892 return null; 8893 } 8894 mFlags = flags; 8895 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8896 final int N = packageServices.size(); 8897 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 8898 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 8899 8900 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 8901 for (int i = 0; i < N; ++i) { 8902 intentFilters = packageServices.get(i).intents; 8903 if (intentFilters != null && intentFilters.size() > 0) { 8904 PackageParser.ServiceIntentInfo[] array = 8905 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 8906 intentFilters.toArray(array); 8907 listCut.add(array); 8908 } 8909 } 8910 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8911 } 8912 8913 public final void addService(PackageParser.Service s) { 8914 mServices.put(s.getComponentName(), s); 8915 if (DEBUG_SHOW_INFO) { 8916 Log.v(TAG, " " 8917 + (s.info.nonLocalizedLabel != null 8918 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8919 Log.v(TAG, " Class=" + s.info.name); 8920 } 8921 final int NI = s.intents.size(); 8922 int j; 8923 for (j=0; j<NI; j++) { 8924 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8925 if (DEBUG_SHOW_INFO) { 8926 Log.v(TAG, " IntentFilter:"); 8927 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8928 } 8929 if (!intent.debugCheck()) { 8930 Log.w(TAG, "==> For Service " + s.info.name); 8931 } 8932 addFilter(intent); 8933 } 8934 } 8935 8936 public final void removeService(PackageParser.Service s) { 8937 mServices.remove(s.getComponentName()); 8938 if (DEBUG_SHOW_INFO) { 8939 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 8940 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8941 Log.v(TAG, " Class=" + s.info.name); 8942 } 8943 final int NI = s.intents.size(); 8944 int j; 8945 for (j=0; j<NI; j++) { 8946 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8947 if (DEBUG_SHOW_INFO) { 8948 Log.v(TAG, " IntentFilter:"); 8949 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8950 } 8951 removeFilter(intent); 8952 } 8953 } 8954 8955 @Override 8956 protected boolean allowFilterResult( 8957 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 8958 ServiceInfo filterSi = filter.service.info; 8959 for (int i=dest.size()-1; i>=0; i--) { 8960 ServiceInfo destAi = dest.get(i).serviceInfo; 8961 if (destAi.name == filterSi.name 8962 && destAi.packageName == filterSi.packageName) { 8963 return false; 8964 } 8965 } 8966 return true; 8967 } 8968 8969 @Override 8970 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 8971 return new PackageParser.ServiceIntentInfo[size]; 8972 } 8973 8974 @Override 8975 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 8976 if (!sUserManager.exists(userId)) return true; 8977 PackageParser.Package p = filter.service.owner; 8978 if (p != null) { 8979 PackageSetting ps = (PackageSetting)p.mExtras; 8980 if (ps != null) { 8981 // System apps are never considered stopped for purposes of 8982 // filtering, because there may be no way for the user to 8983 // actually re-launch them. 8984 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8985 && ps.getStopped(userId); 8986 } 8987 } 8988 return false; 8989 } 8990 8991 @Override 8992 protected boolean isPackageForFilter(String packageName, 8993 PackageParser.ServiceIntentInfo info) { 8994 return packageName.equals(info.service.owner.packageName); 8995 } 8996 8997 @Override 8998 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 8999 int match, int userId) { 9000 if (!sUserManager.exists(userId)) return null; 9001 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 9002 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 9003 return null; 9004 } 9005 final PackageParser.Service service = info.service; 9006 if (mSafeMode && (service.info.applicationInfo.flags 9007 &ApplicationInfo.FLAG_SYSTEM) == 0) { 9008 return null; 9009 } 9010 PackageSetting ps = (PackageSetting) service.owner.mExtras; 9011 if (ps == null) { 9012 return null; 9013 } 9014 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 9015 ps.readUserState(userId), userId); 9016 if (si == null) { 9017 return null; 9018 } 9019 final ResolveInfo res = new ResolveInfo(); 9020 res.serviceInfo = si; 9021 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9022 res.filter = filter; 9023 } 9024 res.priority = info.getPriority(); 9025 res.preferredOrder = service.owner.mPreferredOrder; 9026 res.match = match; 9027 res.isDefault = info.hasDefault; 9028 res.labelRes = info.labelRes; 9029 res.nonLocalizedLabel = info.nonLocalizedLabel; 9030 res.icon = info.icon; 9031 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 9032 return res; 9033 } 9034 9035 @Override 9036 protected void sortResults(List<ResolveInfo> results) { 9037 Collections.sort(results, mResolvePrioritySorter); 9038 } 9039 9040 @Override 9041 protected void dumpFilter(PrintWriter out, String prefix, 9042 PackageParser.ServiceIntentInfo filter) { 9043 out.print(prefix); out.print( 9044 Integer.toHexString(System.identityHashCode(filter.service))); 9045 out.print(' '); 9046 filter.service.printComponentShortName(out); 9047 out.print(" filter "); 9048 out.println(Integer.toHexString(System.identityHashCode(filter))); 9049 } 9050 9051 @Override 9052 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 9053 return filter.service; 9054 } 9055 9056 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9057 PackageParser.Service service = (PackageParser.Service)label; 9058 out.print(prefix); out.print( 9059 Integer.toHexString(System.identityHashCode(service))); 9060 out.print(' '); 9061 service.printComponentShortName(out); 9062 if (count > 1) { 9063 out.print(" ("); out.print(count); out.print(" filters)"); 9064 } 9065 out.println(); 9066 } 9067 9068// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9069// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9070// final List<ResolveInfo> retList = Lists.newArrayList(); 9071// while (i.hasNext()) { 9072// final ResolveInfo resolveInfo = (ResolveInfo) i; 9073// if (isEnabledLP(resolveInfo.serviceInfo)) { 9074// retList.add(resolveInfo); 9075// } 9076// } 9077// return retList; 9078// } 9079 9080 // Keys are String (activity class name), values are Activity. 9081 private final ArrayMap<ComponentName, PackageParser.Service> mServices 9082 = new ArrayMap<ComponentName, PackageParser.Service>(); 9083 private int mFlags; 9084 }; 9085 9086 private final class ProviderIntentResolver 9087 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 9088 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9089 boolean defaultOnly, int userId) { 9090 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9091 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9092 } 9093 9094 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9095 int userId) { 9096 if (!sUserManager.exists(userId)) 9097 return null; 9098 mFlags = flags; 9099 return super.queryIntent(intent, resolvedType, 9100 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9101 } 9102 9103 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9104 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 9105 if (!sUserManager.exists(userId)) 9106 return null; 9107 if (packageProviders == null) { 9108 return null; 9109 } 9110 mFlags = flags; 9111 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 9112 final int N = packageProviders.size(); 9113 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 9114 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 9115 9116 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 9117 for (int i = 0; i < N; ++i) { 9118 intentFilters = packageProviders.get(i).intents; 9119 if (intentFilters != null && intentFilters.size() > 0) { 9120 PackageParser.ProviderIntentInfo[] array = 9121 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 9122 intentFilters.toArray(array); 9123 listCut.add(array); 9124 } 9125 } 9126 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9127 } 9128 9129 public final void addProvider(PackageParser.Provider p) { 9130 if (mProviders.containsKey(p.getComponentName())) { 9131 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 9132 return; 9133 } 9134 9135 mProviders.put(p.getComponentName(), p); 9136 if (DEBUG_SHOW_INFO) { 9137 Log.v(TAG, " " 9138 + (p.info.nonLocalizedLabel != null 9139 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9140 Log.v(TAG, " Class=" + p.info.name); 9141 } 9142 final int NI = p.intents.size(); 9143 int j; 9144 for (j = 0; j < NI; j++) { 9145 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9146 if (DEBUG_SHOW_INFO) { 9147 Log.v(TAG, " IntentFilter:"); 9148 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9149 } 9150 if (!intent.debugCheck()) { 9151 Log.w(TAG, "==> For Provider " + p.info.name); 9152 } 9153 addFilter(intent); 9154 } 9155 } 9156 9157 public final void removeProvider(PackageParser.Provider p) { 9158 mProviders.remove(p.getComponentName()); 9159 if (DEBUG_SHOW_INFO) { 9160 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 9161 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9162 Log.v(TAG, " Class=" + p.info.name); 9163 } 9164 final int NI = p.intents.size(); 9165 int j; 9166 for (j = 0; j < NI; j++) { 9167 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9168 if (DEBUG_SHOW_INFO) { 9169 Log.v(TAG, " IntentFilter:"); 9170 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9171 } 9172 removeFilter(intent); 9173 } 9174 } 9175 9176 @Override 9177 protected boolean allowFilterResult( 9178 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 9179 ProviderInfo filterPi = filter.provider.info; 9180 for (int i = dest.size() - 1; i >= 0; i--) { 9181 ProviderInfo destPi = dest.get(i).providerInfo; 9182 if (destPi.name == filterPi.name 9183 && destPi.packageName == filterPi.packageName) { 9184 return false; 9185 } 9186 } 9187 return true; 9188 } 9189 9190 @Override 9191 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 9192 return new PackageParser.ProviderIntentInfo[size]; 9193 } 9194 9195 @Override 9196 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 9197 if (!sUserManager.exists(userId)) 9198 return true; 9199 PackageParser.Package p = filter.provider.owner; 9200 if (p != null) { 9201 PackageSetting ps = (PackageSetting) p.mExtras; 9202 if (ps != null) { 9203 // System apps are never considered stopped for purposes of 9204 // filtering, because there may be no way for the user to 9205 // actually re-launch them. 9206 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9207 && ps.getStopped(userId); 9208 } 9209 } 9210 return false; 9211 } 9212 9213 @Override 9214 protected boolean isPackageForFilter(String packageName, 9215 PackageParser.ProviderIntentInfo info) { 9216 return packageName.equals(info.provider.owner.packageName); 9217 } 9218 9219 @Override 9220 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 9221 int match, int userId) { 9222 if (!sUserManager.exists(userId)) 9223 return null; 9224 final PackageParser.ProviderIntentInfo info = filter; 9225 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 9226 return null; 9227 } 9228 final PackageParser.Provider provider = info.provider; 9229 if (mSafeMode && (provider.info.applicationInfo.flags 9230 & ApplicationInfo.FLAG_SYSTEM) == 0) { 9231 return null; 9232 } 9233 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 9234 if (ps == null) { 9235 return null; 9236 } 9237 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 9238 ps.readUserState(userId), userId); 9239 if (pi == null) { 9240 return null; 9241 } 9242 final ResolveInfo res = new ResolveInfo(); 9243 res.providerInfo = pi; 9244 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 9245 res.filter = filter; 9246 } 9247 res.priority = info.getPriority(); 9248 res.preferredOrder = provider.owner.mPreferredOrder; 9249 res.match = match; 9250 res.isDefault = info.hasDefault; 9251 res.labelRes = info.labelRes; 9252 res.nonLocalizedLabel = info.nonLocalizedLabel; 9253 res.icon = info.icon; 9254 res.system = res.providerInfo.applicationInfo.isSystemApp(); 9255 return res; 9256 } 9257 9258 @Override 9259 protected void sortResults(List<ResolveInfo> results) { 9260 Collections.sort(results, mResolvePrioritySorter); 9261 } 9262 9263 @Override 9264 protected void dumpFilter(PrintWriter out, String prefix, 9265 PackageParser.ProviderIntentInfo filter) { 9266 out.print(prefix); 9267 out.print( 9268 Integer.toHexString(System.identityHashCode(filter.provider))); 9269 out.print(' '); 9270 filter.provider.printComponentShortName(out); 9271 out.print(" filter "); 9272 out.println(Integer.toHexString(System.identityHashCode(filter))); 9273 } 9274 9275 @Override 9276 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 9277 return filter.provider; 9278 } 9279 9280 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9281 PackageParser.Provider provider = (PackageParser.Provider)label; 9282 out.print(prefix); out.print( 9283 Integer.toHexString(System.identityHashCode(provider))); 9284 out.print(' '); 9285 provider.printComponentShortName(out); 9286 if (count > 1) { 9287 out.print(" ("); out.print(count); out.print(" filters)"); 9288 } 9289 out.println(); 9290 } 9291 9292 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 9293 = new ArrayMap<ComponentName, PackageParser.Provider>(); 9294 private int mFlags; 9295 }; 9296 9297 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 9298 new Comparator<ResolveInfo>() { 9299 public int compare(ResolveInfo r1, ResolveInfo r2) { 9300 int v1 = r1.priority; 9301 int v2 = r2.priority; 9302 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 9303 if (v1 != v2) { 9304 return (v1 > v2) ? -1 : 1; 9305 } 9306 v1 = r1.preferredOrder; 9307 v2 = r2.preferredOrder; 9308 if (v1 != v2) { 9309 return (v1 > v2) ? -1 : 1; 9310 } 9311 if (r1.isDefault != r2.isDefault) { 9312 return r1.isDefault ? -1 : 1; 9313 } 9314 v1 = r1.match; 9315 v2 = r2.match; 9316 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 9317 if (v1 != v2) { 9318 return (v1 > v2) ? -1 : 1; 9319 } 9320 if (r1.system != r2.system) { 9321 return r1.system ? -1 : 1; 9322 } 9323 return 0; 9324 } 9325 }; 9326 9327 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 9328 new Comparator<ProviderInfo>() { 9329 public int compare(ProviderInfo p1, ProviderInfo p2) { 9330 final int v1 = p1.initOrder; 9331 final int v2 = p2.initOrder; 9332 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 9333 } 9334 }; 9335 9336 final void sendPackageBroadcast(final String action, final String pkg, 9337 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 9338 final int[] userIds) { 9339 mHandler.post(new Runnable() { 9340 @Override 9341 public void run() { 9342 try { 9343 final IActivityManager am = ActivityManagerNative.getDefault(); 9344 if (am == null) return; 9345 final int[] resolvedUserIds; 9346 if (userIds == null) { 9347 resolvedUserIds = am.getRunningUserIds(); 9348 } else { 9349 resolvedUserIds = userIds; 9350 } 9351 for (int id : resolvedUserIds) { 9352 final Intent intent = new Intent(action, 9353 pkg != null ? Uri.fromParts("package", pkg, null) : null); 9354 if (extras != null) { 9355 intent.putExtras(extras); 9356 } 9357 if (targetPkg != null) { 9358 intent.setPackage(targetPkg); 9359 } 9360 // Modify the UID when posting to other users 9361 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 9362 if (uid > 0 && UserHandle.getUserId(uid) != id) { 9363 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 9364 intent.putExtra(Intent.EXTRA_UID, uid); 9365 } 9366 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 9367 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 9368 if (DEBUG_BROADCASTS) { 9369 RuntimeException here = new RuntimeException("here"); 9370 here.fillInStackTrace(); 9371 Slog.d(TAG, "Sending to user " + id + ": " 9372 + intent.toShortString(false, true, false, false) 9373 + " " + intent.getExtras(), here); 9374 } 9375 am.broadcastIntent(null, intent, null, finishedReceiver, 9376 0, null, null, null, android.app.AppOpsManager.OP_NONE, 9377 null, finishedReceiver != null, false, id); 9378 } 9379 } catch (RemoteException ex) { 9380 } 9381 } 9382 }); 9383 } 9384 9385 /** 9386 * Check if the external storage media is available. This is true if there 9387 * is a mounted external storage medium or if the external storage is 9388 * emulated. 9389 */ 9390 private boolean isExternalMediaAvailable() { 9391 return mMediaMounted || Environment.isExternalStorageEmulated(); 9392 } 9393 9394 @Override 9395 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 9396 // writer 9397 synchronized (mPackages) { 9398 if (!isExternalMediaAvailable()) { 9399 // If the external storage is no longer mounted at this point, 9400 // the caller may not have been able to delete all of this 9401 // packages files and can not delete any more. Bail. 9402 return null; 9403 } 9404 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 9405 if (lastPackage != null) { 9406 pkgs.remove(lastPackage); 9407 } 9408 if (pkgs.size() > 0) { 9409 return pkgs.get(0); 9410 } 9411 } 9412 return null; 9413 } 9414 9415 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 9416 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 9417 userId, andCode ? 1 : 0, packageName); 9418 if (mSystemReady) { 9419 msg.sendToTarget(); 9420 } else { 9421 if (mPostSystemReadyMessages == null) { 9422 mPostSystemReadyMessages = new ArrayList<>(); 9423 } 9424 mPostSystemReadyMessages.add(msg); 9425 } 9426 } 9427 9428 void startCleaningPackages() { 9429 // reader 9430 synchronized (mPackages) { 9431 if (!isExternalMediaAvailable()) { 9432 return; 9433 } 9434 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 9435 return; 9436 } 9437 } 9438 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 9439 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 9440 IActivityManager am = ActivityManagerNative.getDefault(); 9441 if (am != null) { 9442 try { 9443 am.startService(null, intent, null, mContext.getOpPackageName(), 9444 UserHandle.USER_OWNER); 9445 } catch (RemoteException e) { 9446 } 9447 } 9448 } 9449 9450 @Override 9451 public void installPackage(String originPath, IPackageInstallObserver2 observer, 9452 int installFlags, String installerPackageName, VerificationParams verificationParams, 9453 String packageAbiOverride) { 9454 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 9455 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 9456 } 9457 9458 @Override 9459 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 9460 int installFlags, String installerPackageName, VerificationParams verificationParams, 9461 String packageAbiOverride, int userId) { 9462 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 9463 9464 final int callingUid = Binder.getCallingUid(); 9465 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 9466 9467 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9468 try { 9469 if (observer != null) { 9470 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 9471 } 9472 } catch (RemoteException re) { 9473 } 9474 return; 9475 } 9476 9477 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 9478 installFlags |= PackageManager.INSTALL_FROM_ADB; 9479 9480 } else { 9481 // Caller holds INSTALL_PACKAGES permission, so we're less strict 9482 // about installerPackageName. 9483 9484 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 9485 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 9486 } 9487 9488 UserHandle user; 9489 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 9490 user = UserHandle.ALL; 9491 } else { 9492 user = new UserHandle(userId); 9493 } 9494 9495 // Only system components can circumvent runtime permissions when installing. 9496 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 9497 && mContext.checkCallingOrSelfPermission(Manifest.permission 9498 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 9499 throw new SecurityException("You need the " 9500 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 9501 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 9502 } 9503 9504 verificationParams.setInstallerUid(callingUid); 9505 9506 final File originFile = new File(originPath); 9507 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 9508 9509 final Message msg = mHandler.obtainMessage(INIT_COPY); 9510 msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName, 9511 null, verificationParams, user, packageAbiOverride, null); 9512 mHandler.sendMessage(msg); 9513 } 9514 9515 void installStage(String packageName, File stagedDir, String stagedCid, 9516 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 9517 String installerPackageName, int installerUid, UserHandle user) { 9518 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 9519 params.referrerUri, installerUid, null); 9520 verifParams.setInstallerUid(installerUid); 9521 9522 final OriginInfo origin; 9523 if (stagedDir != null) { 9524 origin = OriginInfo.fromStagedFile(stagedDir); 9525 } else { 9526 origin = OriginInfo.fromStagedContainer(stagedCid); 9527 } 9528 9529 final Message msg = mHandler.obtainMessage(INIT_COPY); 9530 msg.obj = new InstallParams(origin, null, observer, params.installFlags, 9531 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride, 9532 params.grantedRuntimePermissions); 9533 mHandler.sendMessage(msg); 9534 } 9535 9536 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 9537 Bundle extras = new Bundle(1); 9538 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 9539 9540 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 9541 packageName, extras, null, null, new int[] {userId}); 9542 try { 9543 IActivityManager am = ActivityManagerNative.getDefault(); 9544 final boolean isSystem = 9545 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 9546 if (isSystem && am.isUserRunning(userId, false)) { 9547 // The just-installed/enabled app is bundled on the system, so presumed 9548 // to be able to run automatically without needing an explicit launch. 9549 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 9550 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 9551 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 9552 .setPackage(packageName); 9553 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 9554 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 9555 } 9556 } catch (RemoteException e) { 9557 // shouldn't happen 9558 Slog.w(TAG, "Unable to bootstrap installed package", e); 9559 } 9560 } 9561 9562 @Override 9563 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 9564 int userId) { 9565 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9566 PackageSetting pkgSetting; 9567 final int uid = Binder.getCallingUid(); 9568 enforceCrossUserPermission(uid, userId, true, true, 9569 "setApplicationHiddenSetting for user " + userId); 9570 9571 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 9572 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 9573 return false; 9574 } 9575 9576 long callingId = Binder.clearCallingIdentity(); 9577 try { 9578 boolean sendAdded = false; 9579 boolean sendRemoved = false; 9580 // writer 9581 synchronized (mPackages) { 9582 pkgSetting = mSettings.mPackages.get(packageName); 9583 if (pkgSetting == null) { 9584 return false; 9585 } 9586 if (pkgSetting.getHidden(userId) != hidden) { 9587 pkgSetting.setHidden(hidden, userId); 9588 mSettings.writePackageRestrictionsLPr(userId); 9589 if (hidden) { 9590 sendRemoved = true; 9591 } else { 9592 sendAdded = true; 9593 } 9594 } 9595 } 9596 if (sendAdded) { 9597 sendPackageAddedForUser(packageName, pkgSetting, userId); 9598 return true; 9599 } 9600 if (sendRemoved) { 9601 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 9602 "hiding pkg"); 9603 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 9604 } 9605 } finally { 9606 Binder.restoreCallingIdentity(callingId); 9607 } 9608 return false; 9609 } 9610 9611 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 9612 int userId) { 9613 final PackageRemovedInfo info = new PackageRemovedInfo(); 9614 info.removedPackage = packageName; 9615 info.removedUsers = new int[] {userId}; 9616 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 9617 info.sendBroadcast(false, false, false); 9618 } 9619 9620 /** 9621 * Returns true if application is not found or there was an error. Otherwise it returns 9622 * the hidden state of the package for the given user. 9623 */ 9624 @Override 9625 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 9626 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9627 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 9628 false, "getApplicationHidden for user " + userId); 9629 PackageSetting pkgSetting; 9630 long callingId = Binder.clearCallingIdentity(); 9631 try { 9632 // writer 9633 synchronized (mPackages) { 9634 pkgSetting = mSettings.mPackages.get(packageName); 9635 if (pkgSetting == null) { 9636 return true; 9637 } 9638 return pkgSetting.getHidden(userId); 9639 } 9640 } finally { 9641 Binder.restoreCallingIdentity(callingId); 9642 } 9643 } 9644 9645 /** 9646 * @hide 9647 */ 9648 @Override 9649 public int installExistingPackageAsUser(String packageName, int userId) { 9650 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 9651 null); 9652 PackageSetting pkgSetting; 9653 final int uid = Binder.getCallingUid(); 9654 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 9655 + userId); 9656 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9657 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 9658 } 9659 9660 long callingId = Binder.clearCallingIdentity(); 9661 try { 9662 boolean sendAdded = false; 9663 9664 // writer 9665 synchronized (mPackages) { 9666 pkgSetting = mSettings.mPackages.get(packageName); 9667 if (pkgSetting == null) { 9668 return PackageManager.INSTALL_FAILED_INVALID_URI; 9669 } 9670 if (!pkgSetting.getInstalled(userId)) { 9671 pkgSetting.setInstalled(true, userId); 9672 pkgSetting.setHidden(false, userId); 9673 mSettings.writePackageRestrictionsLPr(userId); 9674 sendAdded = true; 9675 } 9676 } 9677 9678 if (sendAdded) { 9679 sendPackageAddedForUser(packageName, pkgSetting, userId); 9680 } 9681 } finally { 9682 Binder.restoreCallingIdentity(callingId); 9683 } 9684 9685 return PackageManager.INSTALL_SUCCEEDED; 9686 } 9687 9688 boolean isUserRestricted(int userId, String restrictionKey) { 9689 Bundle restrictions = sUserManager.getUserRestrictions(userId); 9690 if (restrictions.getBoolean(restrictionKey, false)) { 9691 Log.w(TAG, "User is restricted: " + restrictionKey); 9692 return true; 9693 } 9694 return false; 9695 } 9696 9697 @Override 9698 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 9699 mContext.enforceCallingOrSelfPermission( 9700 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9701 "Only package verification agents can verify applications"); 9702 9703 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9704 final PackageVerificationResponse response = new PackageVerificationResponse( 9705 verificationCode, Binder.getCallingUid()); 9706 msg.arg1 = id; 9707 msg.obj = response; 9708 mHandler.sendMessage(msg); 9709 } 9710 9711 @Override 9712 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 9713 long millisecondsToDelay) { 9714 mContext.enforceCallingOrSelfPermission( 9715 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9716 "Only package verification agents can extend verification timeouts"); 9717 9718 final PackageVerificationState state = mPendingVerification.get(id); 9719 final PackageVerificationResponse response = new PackageVerificationResponse( 9720 verificationCodeAtTimeout, Binder.getCallingUid()); 9721 9722 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 9723 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 9724 } 9725 if (millisecondsToDelay < 0) { 9726 millisecondsToDelay = 0; 9727 } 9728 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 9729 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 9730 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 9731 } 9732 9733 if ((state != null) && !state.timeoutExtended()) { 9734 state.extendTimeout(); 9735 9736 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9737 msg.arg1 = id; 9738 msg.obj = response; 9739 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 9740 } 9741 } 9742 9743 private void broadcastPackageVerified(int verificationId, Uri packageUri, 9744 int verificationCode, UserHandle user) { 9745 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 9746 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 9747 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9748 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9749 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 9750 9751 mContext.sendBroadcastAsUser(intent, user, 9752 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 9753 } 9754 9755 private ComponentName matchComponentForVerifier(String packageName, 9756 List<ResolveInfo> receivers) { 9757 ActivityInfo targetReceiver = null; 9758 9759 final int NR = receivers.size(); 9760 for (int i = 0; i < NR; i++) { 9761 final ResolveInfo info = receivers.get(i); 9762 if (info.activityInfo == null) { 9763 continue; 9764 } 9765 9766 if (packageName.equals(info.activityInfo.packageName)) { 9767 targetReceiver = info.activityInfo; 9768 break; 9769 } 9770 } 9771 9772 if (targetReceiver == null) { 9773 return null; 9774 } 9775 9776 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 9777 } 9778 9779 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 9780 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 9781 if (pkgInfo.verifiers.length == 0) { 9782 return null; 9783 } 9784 9785 final int N = pkgInfo.verifiers.length; 9786 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 9787 for (int i = 0; i < N; i++) { 9788 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 9789 9790 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 9791 receivers); 9792 if (comp == null) { 9793 continue; 9794 } 9795 9796 final int verifierUid = getUidForVerifier(verifierInfo); 9797 if (verifierUid == -1) { 9798 continue; 9799 } 9800 9801 if (DEBUG_VERIFY) { 9802 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 9803 + " with the correct signature"); 9804 } 9805 sufficientVerifiers.add(comp); 9806 verificationState.addSufficientVerifier(verifierUid); 9807 } 9808 9809 return sufficientVerifiers; 9810 } 9811 9812 private int getUidForVerifier(VerifierInfo verifierInfo) { 9813 synchronized (mPackages) { 9814 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 9815 if (pkg == null) { 9816 return -1; 9817 } else if (pkg.mSignatures.length != 1) { 9818 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9819 + " has more than one signature; ignoring"); 9820 return -1; 9821 } 9822 9823 /* 9824 * If the public key of the package's signature does not match 9825 * our expected public key, then this is a different package and 9826 * we should skip. 9827 */ 9828 9829 final byte[] expectedPublicKey; 9830 try { 9831 final Signature verifierSig = pkg.mSignatures[0]; 9832 final PublicKey publicKey = verifierSig.getPublicKey(); 9833 expectedPublicKey = publicKey.getEncoded(); 9834 } catch (CertificateException e) { 9835 return -1; 9836 } 9837 9838 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 9839 9840 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 9841 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9842 + " does not have the expected public key; ignoring"); 9843 return -1; 9844 } 9845 9846 return pkg.applicationInfo.uid; 9847 } 9848 } 9849 9850 @Override 9851 public void finishPackageInstall(int token) { 9852 enforceSystemOrRoot("Only the system is allowed to finish installs"); 9853 9854 if (DEBUG_INSTALL) { 9855 Slog.v(TAG, "BM finishing package install for " + token); 9856 } 9857 9858 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9859 mHandler.sendMessage(msg); 9860 } 9861 9862 /** 9863 * Get the verification agent timeout. 9864 * 9865 * @return verification timeout in milliseconds 9866 */ 9867 private long getVerificationTimeout() { 9868 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 9869 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 9870 DEFAULT_VERIFICATION_TIMEOUT); 9871 } 9872 9873 /** 9874 * Get the default verification agent response code. 9875 * 9876 * @return default verification response code 9877 */ 9878 private int getDefaultVerificationResponse() { 9879 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9880 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 9881 DEFAULT_VERIFICATION_RESPONSE); 9882 } 9883 9884 /** 9885 * Check whether or not package verification has been enabled. 9886 * 9887 * @return true if verification should be performed 9888 */ 9889 private boolean isVerificationEnabled(int userId, int installFlags) { 9890 if (!DEFAULT_VERIFY_ENABLE) { 9891 return false; 9892 } 9893 9894 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 9895 9896 // Check if installing from ADB 9897 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 9898 // Do not run verification in a test harness environment 9899 if (ActivityManager.isRunningInTestHarness()) { 9900 return false; 9901 } 9902 if (ensureVerifyAppsEnabled) { 9903 return true; 9904 } 9905 // Check if the developer does not want package verification for ADB installs 9906 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9907 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 9908 return false; 9909 } 9910 } 9911 9912 if (ensureVerifyAppsEnabled) { 9913 return true; 9914 } 9915 9916 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9917 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 9918 } 9919 9920 @Override 9921 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 9922 throws RemoteException { 9923 mContext.enforceCallingOrSelfPermission( 9924 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 9925 "Only intentfilter verification agents can verify applications"); 9926 9927 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 9928 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 9929 Binder.getCallingUid(), verificationCode, failedDomains); 9930 msg.arg1 = id; 9931 msg.obj = response; 9932 mHandler.sendMessage(msg); 9933 } 9934 9935 @Override 9936 public int getIntentVerificationStatus(String packageName, int userId) { 9937 synchronized (mPackages) { 9938 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 9939 } 9940 } 9941 9942 @Override 9943 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 9944 mContext.enforceCallingOrSelfPermission( 9945 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 9946 9947 boolean result = false; 9948 synchronized (mPackages) { 9949 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 9950 } 9951 if (result) { 9952 scheduleWritePackageRestrictionsLocked(userId); 9953 } 9954 return result; 9955 } 9956 9957 @Override 9958 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 9959 synchronized (mPackages) { 9960 return mSettings.getIntentFilterVerificationsLPr(packageName); 9961 } 9962 } 9963 9964 @Override 9965 public List<IntentFilter> getAllIntentFilters(String packageName) { 9966 if (TextUtils.isEmpty(packageName)) { 9967 return Collections.<IntentFilter>emptyList(); 9968 } 9969 synchronized (mPackages) { 9970 PackageParser.Package pkg = mPackages.get(packageName); 9971 if (pkg == null || pkg.activities == null) { 9972 return Collections.<IntentFilter>emptyList(); 9973 } 9974 final int count = pkg.activities.size(); 9975 ArrayList<IntentFilter> result = new ArrayList<>(); 9976 for (int n=0; n<count; n++) { 9977 PackageParser.Activity activity = pkg.activities.get(n); 9978 if (activity.intents != null || activity.intents.size() > 0) { 9979 result.addAll(activity.intents); 9980 } 9981 } 9982 return result; 9983 } 9984 } 9985 9986 @Override 9987 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 9988 mContext.enforceCallingOrSelfPermission( 9989 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 9990 9991 synchronized (mPackages) { 9992 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 9993 if (packageName != null) { 9994 result |= updateIntentVerificationStatus(packageName, 9995 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 9996 userId); 9997 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 9998 packageName, userId); 9999 } 10000 return result; 10001 } 10002 } 10003 10004 @Override 10005 public String getDefaultBrowserPackageName(int userId) { 10006 synchronized (mPackages) { 10007 return mSettings.getDefaultBrowserPackageNameLPw(userId); 10008 } 10009 } 10010 10011 /** 10012 * Get the "allow unknown sources" setting. 10013 * 10014 * @return the current "allow unknown sources" setting 10015 */ 10016 private int getUnknownSourcesSettings() { 10017 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10018 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 10019 -1); 10020 } 10021 10022 @Override 10023 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 10024 final int uid = Binder.getCallingUid(); 10025 // writer 10026 synchronized (mPackages) { 10027 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 10028 if (targetPackageSetting == null) { 10029 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 10030 } 10031 10032 PackageSetting installerPackageSetting; 10033 if (installerPackageName != null) { 10034 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 10035 if (installerPackageSetting == null) { 10036 throw new IllegalArgumentException("Unknown installer package: " 10037 + installerPackageName); 10038 } 10039 } else { 10040 installerPackageSetting = null; 10041 } 10042 10043 Signature[] callerSignature; 10044 Object obj = mSettings.getUserIdLPr(uid); 10045 if (obj != null) { 10046 if (obj instanceof SharedUserSetting) { 10047 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 10048 } else if (obj instanceof PackageSetting) { 10049 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 10050 } else { 10051 throw new SecurityException("Bad object " + obj + " for uid " + uid); 10052 } 10053 } else { 10054 throw new SecurityException("Unknown calling uid " + uid); 10055 } 10056 10057 // Verify: can't set installerPackageName to a package that is 10058 // not signed with the same cert as the caller. 10059 if (installerPackageSetting != null) { 10060 if (compareSignatures(callerSignature, 10061 installerPackageSetting.signatures.mSignatures) 10062 != PackageManager.SIGNATURE_MATCH) { 10063 throw new SecurityException( 10064 "Caller does not have same cert as new installer package " 10065 + installerPackageName); 10066 } 10067 } 10068 10069 // Verify: if target already has an installer package, it must 10070 // be signed with the same cert as the caller. 10071 if (targetPackageSetting.installerPackageName != null) { 10072 PackageSetting setting = mSettings.mPackages.get( 10073 targetPackageSetting.installerPackageName); 10074 // If the currently set package isn't valid, then it's always 10075 // okay to change it. 10076 if (setting != null) { 10077 if (compareSignatures(callerSignature, 10078 setting.signatures.mSignatures) 10079 != PackageManager.SIGNATURE_MATCH) { 10080 throw new SecurityException( 10081 "Caller does not have same cert as old installer package " 10082 + targetPackageSetting.installerPackageName); 10083 } 10084 } 10085 } 10086 10087 // Okay! 10088 targetPackageSetting.installerPackageName = installerPackageName; 10089 scheduleWriteSettingsLocked(); 10090 } 10091 } 10092 10093 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 10094 // Queue up an async operation since the package installation may take a little while. 10095 mHandler.post(new Runnable() { 10096 public void run() { 10097 mHandler.removeCallbacks(this); 10098 // Result object to be returned 10099 PackageInstalledInfo res = new PackageInstalledInfo(); 10100 res.returnCode = currentStatus; 10101 res.uid = -1; 10102 res.pkg = null; 10103 res.removedInfo = new PackageRemovedInfo(); 10104 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10105 args.doPreInstall(res.returnCode); 10106 synchronized (mInstallLock) { 10107 installPackageLI(args, res); 10108 } 10109 args.doPostInstall(res.returnCode, res.uid); 10110 } 10111 10112 // A restore should be performed at this point if (a) the install 10113 // succeeded, (b) the operation is not an update, and (c) the new 10114 // package has not opted out of backup participation. 10115 final boolean update = res.removedInfo.removedPackage != null; 10116 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 10117 boolean doRestore = !update 10118 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 10119 10120 // Set up the post-install work request bookkeeping. This will be used 10121 // and cleaned up by the post-install event handling regardless of whether 10122 // there's a restore pass performed. Token values are >= 1. 10123 int token; 10124 if (mNextInstallToken < 0) mNextInstallToken = 1; 10125 token = mNextInstallToken++; 10126 10127 PostInstallData data = new PostInstallData(args, res); 10128 mRunningInstalls.put(token, data); 10129 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 10130 10131 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 10132 // Pass responsibility to the Backup Manager. It will perform a 10133 // restore if appropriate, then pass responsibility back to the 10134 // Package Manager to run the post-install observer callbacks 10135 // and broadcasts. 10136 IBackupManager bm = IBackupManager.Stub.asInterface( 10137 ServiceManager.getService(Context.BACKUP_SERVICE)); 10138 if (bm != null) { 10139 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 10140 + " to BM for possible restore"); 10141 try { 10142 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 10143 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 10144 } else { 10145 doRestore = false; 10146 } 10147 } catch (RemoteException e) { 10148 // can't happen; the backup manager is local 10149 } catch (Exception e) { 10150 Slog.e(TAG, "Exception trying to enqueue restore", e); 10151 doRestore = false; 10152 } 10153 } else { 10154 Slog.e(TAG, "Backup Manager not found!"); 10155 doRestore = false; 10156 } 10157 } 10158 10159 if (!doRestore) { 10160 // No restore possible, or the Backup Manager was mysteriously not 10161 // available -- just fire the post-install work request directly. 10162 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 10163 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10164 mHandler.sendMessage(msg); 10165 } 10166 } 10167 }); 10168 } 10169 10170 private abstract class HandlerParams { 10171 private static final int MAX_RETRIES = 4; 10172 10173 /** 10174 * Number of times startCopy() has been attempted and had a non-fatal 10175 * error. 10176 */ 10177 private int mRetries = 0; 10178 10179 /** User handle for the user requesting the information or installation. */ 10180 private final UserHandle mUser; 10181 10182 HandlerParams(UserHandle user) { 10183 mUser = user; 10184 } 10185 10186 UserHandle getUser() { 10187 return mUser; 10188 } 10189 10190 final boolean startCopy() { 10191 boolean res; 10192 try { 10193 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 10194 10195 if (++mRetries > MAX_RETRIES) { 10196 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 10197 mHandler.sendEmptyMessage(MCS_GIVE_UP); 10198 handleServiceError(); 10199 return false; 10200 } else { 10201 handleStartCopy(); 10202 res = true; 10203 } 10204 } catch (RemoteException e) { 10205 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 10206 mHandler.sendEmptyMessage(MCS_RECONNECT); 10207 res = false; 10208 } 10209 handleReturnCode(); 10210 return res; 10211 } 10212 10213 final void serviceError() { 10214 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 10215 handleServiceError(); 10216 handleReturnCode(); 10217 } 10218 10219 abstract void handleStartCopy() throws RemoteException; 10220 abstract void handleServiceError(); 10221 abstract void handleReturnCode(); 10222 } 10223 10224 class MeasureParams extends HandlerParams { 10225 private final PackageStats mStats; 10226 private boolean mSuccess; 10227 10228 private final IPackageStatsObserver mObserver; 10229 10230 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 10231 super(new UserHandle(stats.userHandle)); 10232 mObserver = observer; 10233 mStats = stats; 10234 } 10235 10236 @Override 10237 public String toString() { 10238 return "MeasureParams{" 10239 + Integer.toHexString(System.identityHashCode(this)) 10240 + " " + mStats.packageName + "}"; 10241 } 10242 10243 @Override 10244 void handleStartCopy() throws RemoteException { 10245 synchronized (mInstallLock) { 10246 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 10247 } 10248 10249 if (mSuccess) { 10250 final boolean mounted; 10251 if (Environment.isExternalStorageEmulated()) { 10252 mounted = true; 10253 } else { 10254 final String status = Environment.getExternalStorageState(); 10255 mounted = (Environment.MEDIA_MOUNTED.equals(status) 10256 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 10257 } 10258 10259 if (mounted) { 10260 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 10261 10262 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 10263 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 10264 10265 mStats.externalDataSize = calculateDirectorySize(mContainerService, 10266 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 10267 10268 // Always subtract cache size, since it's a subdirectory 10269 mStats.externalDataSize -= mStats.externalCacheSize; 10270 10271 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 10272 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 10273 10274 mStats.externalObbSize = calculateDirectorySize(mContainerService, 10275 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 10276 } 10277 } 10278 } 10279 10280 @Override 10281 void handleReturnCode() { 10282 if (mObserver != null) { 10283 try { 10284 mObserver.onGetStatsCompleted(mStats, mSuccess); 10285 } catch (RemoteException e) { 10286 Slog.i(TAG, "Observer no longer exists."); 10287 } 10288 } 10289 } 10290 10291 @Override 10292 void handleServiceError() { 10293 Slog.e(TAG, "Could not measure application " + mStats.packageName 10294 + " external storage"); 10295 } 10296 } 10297 10298 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 10299 throws RemoteException { 10300 long result = 0; 10301 for (File path : paths) { 10302 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 10303 } 10304 return result; 10305 } 10306 10307 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 10308 for (File path : paths) { 10309 try { 10310 mcs.clearDirectory(path.getAbsolutePath()); 10311 } catch (RemoteException e) { 10312 } 10313 } 10314 } 10315 10316 static class OriginInfo { 10317 /** 10318 * Location where install is coming from, before it has been 10319 * copied/renamed into place. This could be a single monolithic APK 10320 * file, or a cluster directory. This location may be untrusted. 10321 */ 10322 final File file; 10323 final String cid; 10324 10325 /** 10326 * Flag indicating that {@link #file} or {@link #cid} has already been 10327 * staged, meaning downstream users don't need to defensively copy the 10328 * contents. 10329 */ 10330 final boolean staged; 10331 10332 /** 10333 * Flag indicating that {@link #file} or {@link #cid} is an already 10334 * installed app that is being moved. 10335 */ 10336 final boolean existing; 10337 10338 final String resolvedPath; 10339 final File resolvedFile; 10340 10341 static OriginInfo fromNothing() { 10342 return new OriginInfo(null, null, false, false); 10343 } 10344 10345 static OriginInfo fromUntrustedFile(File file) { 10346 return new OriginInfo(file, null, false, false); 10347 } 10348 10349 static OriginInfo fromExistingFile(File file) { 10350 return new OriginInfo(file, null, false, true); 10351 } 10352 10353 static OriginInfo fromStagedFile(File file) { 10354 return new OriginInfo(file, null, true, false); 10355 } 10356 10357 static OriginInfo fromStagedContainer(String cid) { 10358 return new OriginInfo(null, cid, true, false); 10359 } 10360 10361 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 10362 this.file = file; 10363 this.cid = cid; 10364 this.staged = staged; 10365 this.existing = existing; 10366 10367 if (cid != null) { 10368 resolvedPath = PackageHelper.getSdDir(cid); 10369 resolvedFile = new File(resolvedPath); 10370 } else if (file != null) { 10371 resolvedPath = file.getAbsolutePath(); 10372 resolvedFile = file; 10373 } else { 10374 resolvedPath = null; 10375 resolvedFile = null; 10376 } 10377 } 10378 } 10379 10380 class MoveInfo { 10381 final int moveId; 10382 final String fromUuid; 10383 final String toUuid; 10384 final String packageName; 10385 final String dataAppName; 10386 final int appId; 10387 final String seinfo; 10388 10389 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 10390 String dataAppName, int appId, String seinfo) { 10391 this.moveId = moveId; 10392 this.fromUuid = fromUuid; 10393 this.toUuid = toUuid; 10394 this.packageName = packageName; 10395 this.dataAppName = dataAppName; 10396 this.appId = appId; 10397 this.seinfo = seinfo; 10398 } 10399 } 10400 10401 class InstallParams extends HandlerParams { 10402 final OriginInfo origin; 10403 final MoveInfo move; 10404 final IPackageInstallObserver2 observer; 10405 int installFlags; 10406 final String installerPackageName; 10407 final String volumeUuid; 10408 final VerificationParams verificationParams; 10409 private InstallArgs mArgs; 10410 private int mRet; 10411 final String packageAbiOverride; 10412 final String[] grantedRuntimePermissions; 10413 10414 10415 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10416 int installFlags, String installerPackageName, String volumeUuid, 10417 VerificationParams verificationParams, UserHandle user, String packageAbiOverride, 10418 String[] grantedPermissions) { 10419 super(user); 10420 this.origin = origin; 10421 this.move = move; 10422 this.observer = observer; 10423 this.installFlags = installFlags; 10424 this.installerPackageName = installerPackageName; 10425 this.volumeUuid = volumeUuid; 10426 this.verificationParams = verificationParams; 10427 this.packageAbiOverride = packageAbiOverride; 10428 this.grantedRuntimePermissions = grantedPermissions; 10429 } 10430 10431 @Override 10432 public String toString() { 10433 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 10434 + " file=" + origin.file + " cid=" + origin.cid + "}"; 10435 } 10436 10437 public ManifestDigest getManifestDigest() { 10438 if (verificationParams == null) { 10439 return null; 10440 } 10441 return verificationParams.getManifestDigest(); 10442 } 10443 10444 private int installLocationPolicy(PackageInfoLite pkgLite) { 10445 String packageName = pkgLite.packageName; 10446 int installLocation = pkgLite.installLocation; 10447 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10448 // reader 10449 synchronized (mPackages) { 10450 PackageParser.Package pkg = mPackages.get(packageName); 10451 if (pkg != null) { 10452 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10453 // Check for downgrading. 10454 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 10455 try { 10456 checkDowngrade(pkg, pkgLite); 10457 } catch (PackageManagerException e) { 10458 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 10459 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 10460 } 10461 } 10462 // Check for updated system application. 10463 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10464 if (onSd) { 10465 Slog.w(TAG, "Cannot install update to system app on sdcard"); 10466 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 10467 } 10468 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10469 } else { 10470 if (onSd) { 10471 // Install flag overrides everything. 10472 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10473 } 10474 // If current upgrade specifies particular preference 10475 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 10476 // Application explicitly specified internal. 10477 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10478 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 10479 // App explictly prefers external. Let policy decide 10480 } else { 10481 // Prefer previous location 10482 if (isExternal(pkg)) { 10483 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10484 } 10485 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10486 } 10487 } 10488 } else { 10489 // Invalid install. Return error code 10490 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 10491 } 10492 } 10493 } 10494 // All the special cases have been taken care of. 10495 // Return result based on recommended install location. 10496 if (onSd) { 10497 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10498 } 10499 return pkgLite.recommendedInstallLocation; 10500 } 10501 10502 /* 10503 * Invoke remote method to get package information and install 10504 * location values. Override install location based on default 10505 * policy if needed and then create install arguments based 10506 * on the install location. 10507 */ 10508 public void handleStartCopy() throws RemoteException { 10509 int ret = PackageManager.INSTALL_SUCCEEDED; 10510 10511 // If we're already staged, we've firmly committed to an install location 10512 if (origin.staged) { 10513 if (origin.file != null) { 10514 installFlags |= PackageManager.INSTALL_INTERNAL; 10515 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10516 } else if (origin.cid != null) { 10517 installFlags |= PackageManager.INSTALL_EXTERNAL; 10518 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10519 } else { 10520 throw new IllegalStateException("Invalid stage location"); 10521 } 10522 } 10523 10524 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10525 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 10526 10527 PackageInfoLite pkgLite = null; 10528 10529 if (onInt && onSd) { 10530 // Check if both bits are set. 10531 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 10532 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10533 } else { 10534 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 10535 packageAbiOverride); 10536 10537 /* 10538 * If we have too little free space, try to free cache 10539 * before giving up. 10540 */ 10541 if (!origin.staged && pkgLite.recommendedInstallLocation 10542 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10543 // TODO: focus freeing disk space on the target device 10544 final StorageManager storage = StorageManager.from(mContext); 10545 final long lowThreshold = storage.getStorageLowBytes( 10546 Environment.getDataDirectory()); 10547 10548 final long sizeBytes = mContainerService.calculateInstalledSize( 10549 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 10550 10551 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 10552 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 10553 installFlags, packageAbiOverride); 10554 } 10555 10556 /* 10557 * The cache free must have deleted the file we 10558 * downloaded to install. 10559 * 10560 * TODO: fix the "freeCache" call to not delete 10561 * the file we care about. 10562 */ 10563 if (pkgLite.recommendedInstallLocation 10564 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10565 pkgLite.recommendedInstallLocation 10566 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 10567 } 10568 } 10569 } 10570 10571 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10572 int loc = pkgLite.recommendedInstallLocation; 10573 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 10574 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10575 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 10576 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 10577 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10578 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10579 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 10580 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 10581 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10582 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 10583 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 10584 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 10585 } else { 10586 // Override with defaults if needed. 10587 loc = installLocationPolicy(pkgLite); 10588 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 10589 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 10590 } else if (!onSd && !onInt) { 10591 // Override install location with flags 10592 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 10593 // Set the flag to install on external media. 10594 installFlags |= PackageManager.INSTALL_EXTERNAL; 10595 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10596 } else { 10597 // Make sure the flag for installing on external 10598 // media is unset 10599 installFlags |= PackageManager.INSTALL_INTERNAL; 10600 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10601 } 10602 } 10603 } 10604 } 10605 10606 final InstallArgs args = createInstallArgs(this); 10607 mArgs = args; 10608 10609 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10610 /* 10611 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 10612 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 10613 */ 10614 int userIdentifier = getUser().getIdentifier(); 10615 if (userIdentifier == UserHandle.USER_ALL 10616 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 10617 userIdentifier = UserHandle.USER_OWNER; 10618 } 10619 10620 /* 10621 * Determine if we have any installed package verifiers. If we 10622 * do, then we'll defer to them to verify the packages. 10623 */ 10624 final int requiredUid = mRequiredVerifierPackage == null ? -1 10625 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 10626 if (!origin.existing && requiredUid != -1 10627 && isVerificationEnabled(userIdentifier, installFlags)) { 10628 final Intent verification = new Intent( 10629 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 10630 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 10631 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 10632 PACKAGE_MIME_TYPE); 10633 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10634 10635 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 10636 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 10637 0 /* TODO: Which userId? */); 10638 10639 if (DEBUG_VERIFY) { 10640 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 10641 + verification.toString() + " with " + pkgLite.verifiers.length 10642 + " optional verifiers"); 10643 } 10644 10645 final int verificationId = mPendingVerificationToken++; 10646 10647 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10648 10649 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 10650 installerPackageName); 10651 10652 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 10653 installFlags); 10654 10655 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 10656 pkgLite.packageName); 10657 10658 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 10659 pkgLite.versionCode); 10660 10661 if (verificationParams != null) { 10662 if (verificationParams.getVerificationURI() != null) { 10663 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 10664 verificationParams.getVerificationURI()); 10665 } 10666 if (verificationParams.getOriginatingURI() != null) { 10667 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 10668 verificationParams.getOriginatingURI()); 10669 } 10670 if (verificationParams.getReferrer() != null) { 10671 verification.putExtra(Intent.EXTRA_REFERRER, 10672 verificationParams.getReferrer()); 10673 } 10674 if (verificationParams.getOriginatingUid() >= 0) { 10675 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 10676 verificationParams.getOriginatingUid()); 10677 } 10678 if (verificationParams.getInstallerUid() >= 0) { 10679 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 10680 verificationParams.getInstallerUid()); 10681 } 10682 } 10683 10684 final PackageVerificationState verificationState = new PackageVerificationState( 10685 requiredUid, args); 10686 10687 mPendingVerification.append(verificationId, verificationState); 10688 10689 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 10690 receivers, verificationState); 10691 10692 // Apps installed for "all" users use the device owner to verify the app 10693 UserHandle verifierUser = getUser(); 10694 if (verifierUser == UserHandle.ALL) { 10695 verifierUser = UserHandle.OWNER; 10696 } 10697 10698 /* 10699 * If any sufficient verifiers were listed in the package 10700 * manifest, attempt to ask them. 10701 */ 10702 if (sufficientVerifiers != null) { 10703 final int N = sufficientVerifiers.size(); 10704 if (N == 0) { 10705 Slog.i(TAG, "Additional verifiers required, but none installed."); 10706 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 10707 } else { 10708 for (int i = 0; i < N; i++) { 10709 final ComponentName verifierComponent = sufficientVerifiers.get(i); 10710 10711 final Intent sufficientIntent = new Intent(verification); 10712 sufficientIntent.setComponent(verifierComponent); 10713 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 10714 } 10715 } 10716 } 10717 10718 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 10719 mRequiredVerifierPackage, receivers); 10720 if (ret == PackageManager.INSTALL_SUCCEEDED 10721 && mRequiredVerifierPackage != null) { 10722 /* 10723 * Send the intent to the required verification agent, 10724 * but only start the verification timeout after the 10725 * target BroadcastReceivers have run. 10726 */ 10727 verification.setComponent(requiredVerifierComponent); 10728 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 10729 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10730 new BroadcastReceiver() { 10731 @Override 10732 public void onReceive(Context context, Intent intent) { 10733 final Message msg = mHandler 10734 .obtainMessage(CHECK_PENDING_VERIFICATION); 10735 msg.arg1 = verificationId; 10736 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 10737 } 10738 }, null, 0, null, null); 10739 10740 /* 10741 * We don't want the copy to proceed until verification 10742 * succeeds, so null out this field. 10743 */ 10744 mArgs = null; 10745 } 10746 } else { 10747 /* 10748 * No package verification is enabled, so immediately start 10749 * the remote call to initiate copy using temporary file. 10750 */ 10751 ret = args.copyApk(mContainerService, true); 10752 } 10753 } 10754 10755 mRet = ret; 10756 } 10757 10758 @Override 10759 void handleReturnCode() { 10760 // If mArgs is null, then MCS couldn't be reached. When it 10761 // reconnects, it will try again to install. At that point, this 10762 // will succeed. 10763 if (mArgs != null) { 10764 processPendingInstall(mArgs, mRet); 10765 } 10766 } 10767 10768 @Override 10769 void handleServiceError() { 10770 mArgs = createInstallArgs(this); 10771 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10772 } 10773 10774 public boolean isForwardLocked() { 10775 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10776 } 10777 } 10778 10779 /** 10780 * Used during creation of InstallArgs 10781 * 10782 * @param installFlags package installation flags 10783 * @return true if should be installed on external storage 10784 */ 10785 private static boolean installOnExternalAsec(int installFlags) { 10786 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 10787 return false; 10788 } 10789 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 10790 return true; 10791 } 10792 return false; 10793 } 10794 10795 /** 10796 * Used during creation of InstallArgs 10797 * 10798 * @param installFlags package installation flags 10799 * @return true if should be installed as forward locked 10800 */ 10801 private static boolean installForwardLocked(int installFlags) { 10802 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10803 } 10804 10805 private InstallArgs createInstallArgs(InstallParams params) { 10806 if (params.move != null) { 10807 return new MoveInstallArgs(params); 10808 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 10809 return new AsecInstallArgs(params); 10810 } else { 10811 return new FileInstallArgs(params); 10812 } 10813 } 10814 10815 /** 10816 * Create args that describe an existing installed package. Typically used 10817 * when cleaning up old installs, or used as a move source. 10818 */ 10819 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 10820 String resourcePath, String[] instructionSets) { 10821 final boolean isInAsec; 10822 if (installOnExternalAsec(installFlags)) { 10823 /* Apps on SD card are always in ASEC containers. */ 10824 isInAsec = true; 10825 } else if (installForwardLocked(installFlags) 10826 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 10827 /* 10828 * Forward-locked apps are only in ASEC containers if they're the 10829 * new style 10830 */ 10831 isInAsec = true; 10832 } else { 10833 isInAsec = false; 10834 } 10835 10836 if (isInAsec) { 10837 return new AsecInstallArgs(codePath, instructionSets, 10838 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 10839 } else { 10840 return new FileInstallArgs(codePath, resourcePath, instructionSets); 10841 } 10842 } 10843 10844 static abstract class InstallArgs { 10845 /** @see InstallParams#origin */ 10846 final OriginInfo origin; 10847 /** @see InstallParams#move */ 10848 final MoveInfo move; 10849 10850 final IPackageInstallObserver2 observer; 10851 // Always refers to PackageManager flags only 10852 final int installFlags; 10853 final String installerPackageName; 10854 final String volumeUuid; 10855 final ManifestDigest manifestDigest; 10856 final UserHandle user; 10857 final String abiOverride; 10858 final String[] installGrantPermissions; 10859 10860 // The list of instruction sets supported by this app. This is currently 10861 // only used during the rmdex() phase to clean up resources. We can get rid of this 10862 // if we move dex files under the common app path. 10863 /* nullable */ String[] instructionSets; 10864 10865 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10866 int installFlags, String installerPackageName, String volumeUuid, 10867 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 10868 String abiOverride, String[] installGrantPermissions) { 10869 this.origin = origin; 10870 this.move = move; 10871 this.installFlags = installFlags; 10872 this.observer = observer; 10873 this.installerPackageName = installerPackageName; 10874 this.volumeUuid = volumeUuid; 10875 this.manifestDigest = manifestDigest; 10876 this.user = user; 10877 this.instructionSets = instructionSets; 10878 this.abiOverride = abiOverride; 10879 this.installGrantPermissions = installGrantPermissions; 10880 } 10881 10882 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 10883 abstract int doPreInstall(int status); 10884 10885 /** 10886 * Rename package into final resting place. All paths on the given 10887 * scanned package should be updated to reflect the rename. 10888 */ 10889 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 10890 abstract int doPostInstall(int status, int uid); 10891 10892 /** @see PackageSettingBase#codePathString */ 10893 abstract String getCodePath(); 10894 /** @see PackageSettingBase#resourcePathString */ 10895 abstract String getResourcePath(); 10896 10897 // Need installer lock especially for dex file removal. 10898 abstract void cleanUpResourcesLI(); 10899 abstract boolean doPostDeleteLI(boolean delete); 10900 10901 /** 10902 * Called before the source arguments are copied. This is used mostly 10903 * for MoveParams when it needs to read the source file to put it in the 10904 * destination. 10905 */ 10906 int doPreCopy() { 10907 return PackageManager.INSTALL_SUCCEEDED; 10908 } 10909 10910 /** 10911 * Called after the source arguments are copied. This is used mostly for 10912 * MoveParams when it needs to read the source file to put it in the 10913 * destination. 10914 * 10915 * @return 10916 */ 10917 int doPostCopy(int uid) { 10918 return PackageManager.INSTALL_SUCCEEDED; 10919 } 10920 10921 protected boolean isFwdLocked() { 10922 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10923 } 10924 10925 protected boolean isExternalAsec() { 10926 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10927 } 10928 10929 UserHandle getUser() { 10930 return user; 10931 } 10932 } 10933 10934 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 10935 if (!allCodePaths.isEmpty()) { 10936 if (instructionSets == null) { 10937 throw new IllegalStateException("instructionSet == null"); 10938 } 10939 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 10940 for (String codePath : allCodePaths) { 10941 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 10942 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 10943 if (retCode < 0) { 10944 Slog.w(TAG, "Couldn't remove dex file for package: " 10945 + " at location " + codePath + ", retcode=" + retCode); 10946 // we don't consider this to be a failure of the core package deletion 10947 } 10948 } 10949 } 10950 } 10951 } 10952 10953 /** 10954 * Logic to handle installation of non-ASEC applications, including copying 10955 * and renaming logic. 10956 */ 10957 class FileInstallArgs extends InstallArgs { 10958 private File codeFile; 10959 private File resourceFile; 10960 10961 // Example topology: 10962 // /data/app/com.example/base.apk 10963 // /data/app/com.example/split_foo.apk 10964 // /data/app/com.example/lib/arm/libfoo.so 10965 // /data/app/com.example/lib/arm64/libfoo.so 10966 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 10967 10968 /** New install */ 10969 FileInstallArgs(InstallParams params) { 10970 super(params.origin, params.move, params.observer, params.installFlags, 10971 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10972 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 10973 params.grantedRuntimePermissions); 10974 if (isFwdLocked()) { 10975 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 10976 } 10977 } 10978 10979 /** Existing install */ 10980 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 10981 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 10982 null, null); 10983 this.codeFile = (codePath != null) ? new File(codePath) : null; 10984 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 10985 } 10986 10987 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10988 if (origin.staged) { 10989 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 10990 codeFile = origin.file; 10991 resourceFile = origin.file; 10992 return PackageManager.INSTALL_SUCCEEDED; 10993 } 10994 10995 try { 10996 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 10997 codeFile = tempDir; 10998 resourceFile = tempDir; 10999 } catch (IOException e) { 11000 Slog.w(TAG, "Failed to create copy file: " + e); 11001 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11002 } 11003 11004 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 11005 @Override 11006 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 11007 if (!FileUtils.isValidExtFilename(name)) { 11008 throw new IllegalArgumentException("Invalid filename: " + name); 11009 } 11010 try { 11011 final File file = new File(codeFile, name); 11012 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 11013 O_RDWR | O_CREAT, 0644); 11014 Os.chmod(file.getAbsolutePath(), 0644); 11015 return new ParcelFileDescriptor(fd); 11016 } catch (ErrnoException e) { 11017 throw new RemoteException("Failed to open: " + e.getMessage()); 11018 } 11019 } 11020 }; 11021 11022 int ret = PackageManager.INSTALL_SUCCEEDED; 11023 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 11024 if (ret != PackageManager.INSTALL_SUCCEEDED) { 11025 Slog.e(TAG, "Failed to copy package"); 11026 return ret; 11027 } 11028 11029 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 11030 NativeLibraryHelper.Handle handle = null; 11031 try { 11032 handle = NativeLibraryHelper.Handle.create(codeFile); 11033 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 11034 abiOverride); 11035 } catch (IOException e) { 11036 Slog.e(TAG, "Copying native libraries failed", e); 11037 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11038 } finally { 11039 IoUtils.closeQuietly(handle); 11040 } 11041 11042 return ret; 11043 } 11044 11045 int doPreInstall(int status) { 11046 if (status != PackageManager.INSTALL_SUCCEEDED) { 11047 cleanUp(); 11048 } 11049 return status; 11050 } 11051 11052 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11053 if (status != PackageManager.INSTALL_SUCCEEDED) { 11054 cleanUp(); 11055 return false; 11056 } 11057 11058 final File targetDir = codeFile.getParentFile(); 11059 final File beforeCodeFile = codeFile; 11060 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 11061 11062 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 11063 try { 11064 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 11065 } catch (ErrnoException e) { 11066 Slog.w(TAG, "Failed to rename", e); 11067 return false; 11068 } 11069 11070 if (!SELinux.restoreconRecursive(afterCodeFile)) { 11071 Slog.w(TAG, "Failed to restorecon"); 11072 return false; 11073 } 11074 11075 // Reflect the rename internally 11076 codeFile = afterCodeFile; 11077 resourceFile = afterCodeFile; 11078 11079 // Reflect the rename in scanned details 11080 pkg.codePath = afterCodeFile.getAbsolutePath(); 11081 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11082 pkg.baseCodePath); 11083 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11084 pkg.splitCodePaths); 11085 11086 // Reflect the rename in app info 11087 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11088 pkg.applicationInfo.setCodePath(pkg.codePath); 11089 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11090 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11091 pkg.applicationInfo.setResourcePath(pkg.codePath); 11092 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11093 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11094 11095 return true; 11096 } 11097 11098 int doPostInstall(int status, int uid) { 11099 if (status != PackageManager.INSTALL_SUCCEEDED) { 11100 cleanUp(); 11101 } 11102 return status; 11103 } 11104 11105 @Override 11106 String getCodePath() { 11107 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11108 } 11109 11110 @Override 11111 String getResourcePath() { 11112 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11113 } 11114 11115 private boolean cleanUp() { 11116 if (codeFile == null || !codeFile.exists()) { 11117 return false; 11118 } 11119 11120 if (codeFile.isDirectory()) { 11121 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11122 } else { 11123 codeFile.delete(); 11124 } 11125 11126 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 11127 resourceFile.delete(); 11128 } 11129 11130 return true; 11131 } 11132 11133 void cleanUpResourcesLI() { 11134 // Try enumerating all code paths before deleting 11135 List<String> allCodePaths = Collections.EMPTY_LIST; 11136 if (codeFile != null && codeFile.exists()) { 11137 try { 11138 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11139 allCodePaths = pkg.getAllCodePaths(); 11140 } catch (PackageParserException e) { 11141 // Ignored; we tried our best 11142 } 11143 } 11144 11145 cleanUp(); 11146 removeDexFiles(allCodePaths, instructionSets); 11147 } 11148 11149 boolean doPostDeleteLI(boolean delete) { 11150 // XXX err, shouldn't we respect the delete flag? 11151 cleanUpResourcesLI(); 11152 return true; 11153 } 11154 } 11155 11156 private boolean isAsecExternal(String cid) { 11157 final String asecPath = PackageHelper.getSdFilesystem(cid); 11158 return !asecPath.startsWith(mAsecInternalPath); 11159 } 11160 11161 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 11162 PackageManagerException { 11163 if (copyRet < 0) { 11164 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 11165 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 11166 throw new PackageManagerException(copyRet, message); 11167 } 11168 } 11169 } 11170 11171 /** 11172 * Extract the MountService "container ID" from the full code path of an 11173 * .apk. 11174 */ 11175 static String cidFromCodePath(String fullCodePath) { 11176 int eidx = fullCodePath.lastIndexOf("/"); 11177 String subStr1 = fullCodePath.substring(0, eidx); 11178 int sidx = subStr1.lastIndexOf("/"); 11179 return subStr1.substring(sidx+1, eidx); 11180 } 11181 11182 /** 11183 * Logic to handle installation of ASEC applications, including copying and 11184 * renaming logic. 11185 */ 11186 class AsecInstallArgs extends InstallArgs { 11187 static final String RES_FILE_NAME = "pkg.apk"; 11188 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 11189 11190 String cid; 11191 String packagePath; 11192 String resourcePath; 11193 11194 /** New install */ 11195 AsecInstallArgs(InstallParams params) { 11196 super(params.origin, params.move, params.observer, params.installFlags, 11197 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11198 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11199 params.grantedRuntimePermissions); 11200 } 11201 11202 /** Existing install */ 11203 AsecInstallArgs(String fullCodePath, String[] instructionSets, 11204 boolean isExternal, boolean isForwardLocked) { 11205 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 11206 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11207 instructionSets, null, null); 11208 // Hackily pretend we're still looking at a full code path 11209 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 11210 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 11211 } 11212 11213 // Extract cid from fullCodePath 11214 int eidx = fullCodePath.lastIndexOf("/"); 11215 String subStr1 = fullCodePath.substring(0, eidx); 11216 int sidx = subStr1.lastIndexOf("/"); 11217 cid = subStr1.substring(sidx+1, eidx); 11218 setMountPath(subStr1); 11219 } 11220 11221 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 11222 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 11223 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11224 instructionSets, null, null); 11225 this.cid = cid; 11226 setMountPath(PackageHelper.getSdDir(cid)); 11227 } 11228 11229 void createCopyFile() { 11230 cid = mInstallerService.allocateExternalStageCidLegacy(); 11231 } 11232 11233 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11234 if (origin.staged) { 11235 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 11236 cid = origin.cid; 11237 setMountPath(PackageHelper.getSdDir(cid)); 11238 return PackageManager.INSTALL_SUCCEEDED; 11239 } 11240 11241 if (temp) { 11242 createCopyFile(); 11243 } else { 11244 /* 11245 * Pre-emptively destroy the container since it's destroyed if 11246 * copying fails due to it existing anyway. 11247 */ 11248 PackageHelper.destroySdDir(cid); 11249 } 11250 11251 final String newMountPath = imcs.copyPackageToContainer( 11252 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 11253 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 11254 11255 if (newMountPath != null) { 11256 setMountPath(newMountPath); 11257 return PackageManager.INSTALL_SUCCEEDED; 11258 } else { 11259 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11260 } 11261 } 11262 11263 @Override 11264 String getCodePath() { 11265 return packagePath; 11266 } 11267 11268 @Override 11269 String getResourcePath() { 11270 return resourcePath; 11271 } 11272 11273 int doPreInstall(int status) { 11274 if (status != PackageManager.INSTALL_SUCCEEDED) { 11275 // Destroy container 11276 PackageHelper.destroySdDir(cid); 11277 } else { 11278 boolean mounted = PackageHelper.isContainerMounted(cid); 11279 if (!mounted) { 11280 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 11281 Process.SYSTEM_UID); 11282 if (newMountPath != null) { 11283 setMountPath(newMountPath); 11284 } else { 11285 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11286 } 11287 } 11288 } 11289 return status; 11290 } 11291 11292 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11293 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 11294 String newMountPath = null; 11295 if (PackageHelper.isContainerMounted(cid)) { 11296 // Unmount the container 11297 if (!PackageHelper.unMountSdDir(cid)) { 11298 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 11299 return false; 11300 } 11301 } 11302 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11303 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 11304 " which might be stale. Will try to clean up."); 11305 // Clean up the stale container and proceed to recreate. 11306 if (!PackageHelper.destroySdDir(newCacheId)) { 11307 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 11308 return false; 11309 } 11310 // Successfully cleaned up stale container. Try to rename again. 11311 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11312 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 11313 + " inspite of cleaning it up."); 11314 return false; 11315 } 11316 } 11317 if (!PackageHelper.isContainerMounted(newCacheId)) { 11318 Slog.w(TAG, "Mounting container " + newCacheId); 11319 newMountPath = PackageHelper.mountSdDir(newCacheId, 11320 getEncryptKey(), Process.SYSTEM_UID); 11321 } else { 11322 newMountPath = PackageHelper.getSdDir(newCacheId); 11323 } 11324 if (newMountPath == null) { 11325 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 11326 return false; 11327 } 11328 Log.i(TAG, "Succesfully renamed " + cid + 11329 " to " + newCacheId + 11330 " at new path: " + newMountPath); 11331 cid = newCacheId; 11332 11333 final File beforeCodeFile = new File(packagePath); 11334 setMountPath(newMountPath); 11335 final File afterCodeFile = new File(packagePath); 11336 11337 // Reflect the rename in scanned details 11338 pkg.codePath = afterCodeFile.getAbsolutePath(); 11339 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11340 pkg.baseCodePath); 11341 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11342 pkg.splitCodePaths); 11343 11344 // Reflect the rename in app info 11345 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11346 pkg.applicationInfo.setCodePath(pkg.codePath); 11347 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11348 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11349 pkg.applicationInfo.setResourcePath(pkg.codePath); 11350 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11351 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11352 11353 return true; 11354 } 11355 11356 private void setMountPath(String mountPath) { 11357 final File mountFile = new File(mountPath); 11358 11359 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 11360 if (monolithicFile.exists()) { 11361 packagePath = monolithicFile.getAbsolutePath(); 11362 if (isFwdLocked()) { 11363 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 11364 } else { 11365 resourcePath = packagePath; 11366 } 11367 } else { 11368 packagePath = mountFile.getAbsolutePath(); 11369 resourcePath = packagePath; 11370 } 11371 } 11372 11373 int doPostInstall(int status, int uid) { 11374 if (status != PackageManager.INSTALL_SUCCEEDED) { 11375 cleanUp(); 11376 } else { 11377 final int groupOwner; 11378 final String protectedFile; 11379 if (isFwdLocked()) { 11380 groupOwner = UserHandle.getSharedAppGid(uid); 11381 protectedFile = RES_FILE_NAME; 11382 } else { 11383 groupOwner = -1; 11384 protectedFile = null; 11385 } 11386 11387 if (uid < Process.FIRST_APPLICATION_UID 11388 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 11389 Slog.e(TAG, "Failed to finalize " + cid); 11390 PackageHelper.destroySdDir(cid); 11391 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11392 } 11393 11394 boolean mounted = PackageHelper.isContainerMounted(cid); 11395 if (!mounted) { 11396 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 11397 } 11398 } 11399 return status; 11400 } 11401 11402 private void cleanUp() { 11403 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 11404 11405 // Destroy secure container 11406 PackageHelper.destroySdDir(cid); 11407 } 11408 11409 private List<String> getAllCodePaths() { 11410 final File codeFile = new File(getCodePath()); 11411 if (codeFile != null && codeFile.exists()) { 11412 try { 11413 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11414 return pkg.getAllCodePaths(); 11415 } catch (PackageParserException e) { 11416 // Ignored; we tried our best 11417 } 11418 } 11419 return Collections.EMPTY_LIST; 11420 } 11421 11422 void cleanUpResourcesLI() { 11423 // Enumerate all code paths before deleting 11424 cleanUpResourcesLI(getAllCodePaths()); 11425 } 11426 11427 private void cleanUpResourcesLI(List<String> allCodePaths) { 11428 cleanUp(); 11429 removeDexFiles(allCodePaths, instructionSets); 11430 } 11431 11432 String getPackageName() { 11433 return getAsecPackageName(cid); 11434 } 11435 11436 boolean doPostDeleteLI(boolean delete) { 11437 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 11438 final List<String> allCodePaths = getAllCodePaths(); 11439 boolean mounted = PackageHelper.isContainerMounted(cid); 11440 if (mounted) { 11441 // Unmount first 11442 if (PackageHelper.unMountSdDir(cid)) { 11443 mounted = false; 11444 } 11445 } 11446 if (!mounted && delete) { 11447 cleanUpResourcesLI(allCodePaths); 11448 } 11449 return !mounted; 11450 } 11451 11452 @Override 11453 int doPreCopy() { 11454 if (isFwdLocked()) { 11455 if (!PackageHelper.fixSdPermissions(cid, 11456 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 11457 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11458 } 11459 } 11460 11461 return PackageManager.INSTALL_SUCCEEDED; 11462 } 11463 11464 @Override 11465 int doPostCopy(int uid) { 11466 if (isFwdLocked()) { 11467 if (uid < Process.FIRST_APPLICATION_UID 11468 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 11469 RES_FILE_NAME)) { 11470 Slog.e(TAG, "Failed to finalize " + cid); 11471 PackageHelper.destroySdDir(cid); 11472 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11473 } 11474 } 11475 11476 return PackageManager.INSTALL_SUCCEEDED; 11477 } 11478 } 11479 11480 /** 11481 * Logic to handle movement of existing installed applications. 11482 */ 11483 class MoveInstallArgs extends InstallArgs { 11484 private File codeFile; 11485 private File resourceFile; 11486 11487 /** New install */ 11488 MoveInstallArgs(InstallParams params) { 11489 super(params.origin, params.move, params.observer, params.installFlags, 11490 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11491 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11492 params.grantedRuntimePermissions); 11493 } 11494 11495 int copyApk(IMediaContainerService imcs, boolean temp) { 11496 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 11497 + move.fromUuid + " to " + move.toUuid); 11498 synchronized (mInstaller) { 11499 if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName, 11500 move.dataAppName, move.appId, move.seinfo) != 0) { 11501 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11502 } 11503 } 11504 11505 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 11506 resourceFile = codeFile; 11507 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 11508 11509 return PackageManager.INSTALL_SUCCEEDED; 11510 } 11511 11512 int doPreInstall(int status) { 11513 if (status != PackageManager.INSTALL_SUCCEEDED) { 11514 cleanUp(move.toUuid); 11515 } 11516 return status; 11517 } 11518 11519 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11520 if (status != PackageManager.INSTALL_SUCCEEDED) { 11521 cleanUp(move.toUuid); 11522 return false; 11523 } 11524 11525 // Reflect the move in app info 11526 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11527 pkg.applicationInfo.setCodePath(pkg.codePath); 11528 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11529 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11530 pkg.applicationInfo.setResourcePath(pkg.codePath); 11531 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11532 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11533 11534 return true; 11535 } 11536 11537 int doPostInstall(int status, int uid) { 11538 if (status == PackageManager.INSTALL_SUCCEEDED) { 11539 cleanUp(move.fromUuid); 11540 } else { 11541 cleanUp(move.toUuid); 11542 } 11543 return status; 11544 } 11545 11546 @Override 11547 String getCodePath() { 11548 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11549 } 11550 11551 @Override 11552 String getResourcePath() { 11553 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11554 } 11555 11556 private boolean cleanUp(String volumeUuid) { 11557 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 11558 move.dataAppName); 11559 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 11560 synchronized (mInstallLock) { 11561 // Clean up both app data and code 11562 removeDataDirsLI(volumeUuid, move.packageName); 11563 if (codeFile.isDirectory()) { 11564 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11565 } else { 11566 codeFile.delete(); 11567 } 11568 } 11569 return true; 11570 } 11571 11572 void cleanUpResourcesLI() { 11573 throw new UnsupportedOperationException(); 11574 } 11575 11576 boolean doPostDeleteLI(boolean delete) { 11577 throw new UnsupportedOperationException(); 11578 } 11579 } 11580 11581 static String getAsecPackageName(String packageCid) { 11582 int idx = packageCid.lastIndexOf("-"); 11583 if (idx == -1) { 11584 return packageCid; 11585 } 11586 return packageCid.substring(0, idx); 11587 } 11588 11589 // Utility method used to create code paths based on package name and available index. 11590 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 11591 String idxStr = ""; 11592 int idx = 1; 11593 // Fall back to default value of idx=1 if prefix is not 11594 // part of oldCodePath 11595 if (oldCodePath != null) { 11596 String subStr = oldCodePath; 11597 // Drop the suffix right away 11598 if (suffix != null && subStr.endsWith(suffix)) { 11599 subStr = subStr.substring(0, subStr.length() - suffix.length()); 11600 } 11601 // If oldCodePath already contains prefix find out the 11602 // ending index to either increment or decrement. 11603 int sidx = subStr.lastIndexOf(prefix); 11604 if (sidx != -1) { 11605 subStr = subStr.substring(sidx + prefix.length()); 11606 if (subStr != null) { 11607 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 11608 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 11609 } 11610 try { 11611 idx = Integer.parseInt(subStr); 11612 if (idx <= 1) { 11613 idx++; 11614 } else { 11615 idx--; 11616 } 11617 } catch(NumberFormatException e) { 11618 } 11619 } 11620 } 11621 } 11622 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 11623 return prefix + idxStr; 11624 } 11625 11626 private File getNextCodePath(File targetDir, String packageName) { 11627 int suffix = 1; 11628 File result; 11629 do { 11630 result = new File(targetDir, packageName + "-" + suffix); 11631 suffix++; 11632 } while (result.exists()); 11633 return result; 11634 } 11635 11636 // Utility method that returns the relative package path with respect 11637 // to the installation directory. Like say for /data/data/com.test-1.apk 11638 // string com.test-1 is returned. 11639 static String deriveCodePathName(String codePath) { 11640 if (codePath == null) { 11641 return null; 11642 } 11643 final File codeFile = new File(codePath); 11644 final String name = codeFile.getName(); 11645 if (codeFile.isDirectory()) { 11646 return name; 11647 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 11648 final int lastDot = name.lastIndexOf('.'); 11649 return name.substring(0, lastDot); 11650 } else { 11651 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 11652 return null; 11653 } 11654 } 11655 11656 class PackageInstalledInfo { 11657 String name; 11658 int uid; 11659 // The set of users that originally had this package installed. 11660 int[] origUsers; 11661 // The set of users that now have this package installed. 11662 int[] newUsers; 11663 PackageParser.Package pkg; 11664 int returnCode; 11665 String returnMsg; 11666 PackageRemovedInfo removedInfo; 11667 11668 public void setError(int code, String msg) { 11669 returnCode = code; 11670 returnMsg = msg; 11671 Slog.w(TAG, msg); 11672 } 11673 11674 public void setError(String msg, PackageParserException e) { 11675 returnCode = e.error; 11676 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11677 Slog.w(TAG, msg, e); 11678 } 11679 11680 public void setError(String msg, PackageManagerException e) { 11681 returnCode = e.error; 11682 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11683 Slog.w(TAG, msg, e); 11684 } 11685 11686 // In some error cases we want to convey more info back to the observer 11687 String origPackage; 11688 String origPermission; 11689 } 11690 11691 /* 11692 * Install a non-existing package. 11693 */ 11694 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11695 UserHandle user, String installerPackageName, String volumeUuid, 11696 PackageInstalledInfo res) { 11697 // Remember this for later, in case we need to rollback this install 11698 String pkgName = pkg.packageName; 11699 11700 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 11701 final boolean dataDirExists = Environment 11702 .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists(); 11703 synchronized(mPackages) { 11704 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 11705 // A package with the same name is already installed, though 11706 // it has been renamed to an older name. The package we 11707 // are trying to install should be installed as an update to 11708 // the existing one, but that has not been requested, so bail. 11709 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11710 + " without first uninstalling package running as " 11711 + mSettings.mRenamedPackages.get(pkgName)); 11712 return; 11713 } 11714 if (mPackages.containsKey(pkgName)) { 11715 // Don't allow installation over an existing package with the same name. 11716 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11717 + " without first uninstalling."); 11718 return; 11719 } 11720 } 11721 11722 try { 11723 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 11724 System.currentTimeMillis(), user); 11725 11726 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 11727 // delete the partially installed application. the data directory will have to be 11728 // restored if it was already existing 11729 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11730 // remove package from internal structures. Note that we want deletePackageX to 11731 // delete the package data and cache directories that it created in 11732 // scanPackageLocked, unless those directories existed before we even tried to 11733 // install. 11734 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 11735 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 11736 res.removedInfo, true); 11737 } 11738 11739 } catch (PackageManagerException e) { 11740 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11741 } 11742 } 11743 11744 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 11745 // Can't rotate keys during boot or if sharedUser. 11746 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 11747 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 11748 return false; 11749 } 11750 // app is using upgradeKeySets; make sure all are valid 11751 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11752 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 11753 for (int i = 0; i < upgradeKeySets.length; i++) { 11754 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 11755 Slog.wtf(TAG, "Package " 11756 + (oldPs.name != null ? oldPs.name : "<null>") 11757 + " contains upgrade-key-set reference to unknown key-set: " 11758 + upgradeKeySets[i] 11759 + " reverting to signatures check."); 11760 return false; 11761 } 11762 } 11763 return true; 11764 } 11765 11766 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 11767 // Upgrade keysets are being used. Determine if new package has a superset of the 11768 // required keys. 11769 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 11770 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11771 for (int i = 0; i < upgradeKeySets.length; i++) { 11772 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 11773 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 11774 return true; 11775 } 11776 } 11777 return false; 11778 } 11779 11780 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11781 UserHandle user, String installerPackageName, String volumeUuid, 11782 PackageInstalledInfo res) { 11783 final PackageParser.Package oldPackage; 11784 final String pkgName = pkg.packageName; 11785 final int[] allUsers; 11786 final boolean[] perUserInstalled; 11787 11788 // First find the old package info and check signatures 11789 synchronized(mPackages) { 11790 oldPackage = mPackages.get(pkgName); 11791 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 11792 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11793 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 11794 if(!checkUpgradeKeySetLP(ps, pkg)) { 11795 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11796 "New package not signed by keys specified by upgrade-keysets: " 11797 + pkgName); 11798 return; 11799 } 11800 } else { 11801 // default to original signature matching 11802 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 11803 != PackageManager.SIGNATURE_MATCH) { 11804 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11805 "New package has a different signature: " + pkgName); 11806 return; 11807 } 11808 } 11809 11810 // In case of rollback, remember per-user/profile install state 11811 allUsers = sUserManager.getUserIds(); 11812 perUserInstalled = new boolean[allUsers.length]; 11813 for (int i = 0; i < allUsers.length; i++) { 11814 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11815 } 11816 } 11817 11818 boolean sysPkg = (isSystemApp(oldPackage)); 11819 if (sysPkg) { 11820 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11821 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11822 } else { 11823 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11824 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11825 } 11826 } 11827 11828 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 11829 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11830 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11831 String volumeUuid, PackageInstalledInfo res) { 11832 String pkgName = deletedPackage.packageName; 11833 boolean deletedPkg = true; 11834 boolean updatedSettings = false; 11835 11836 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 11837 + deletedPackage); 11838 long origUpdateTime; 11839 if (pkg.mExtras != null) { 11840 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 11841 } else { 11842 origUpdateTime = 0; 11843 } 11844 11845 // First delete the existing package while retaining the data directory 11846 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 11847 res.removedInfo, true)) { 11848 // If the existing package wasn't successfully deleted 11849 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 11850 deletedPkg = false; 11851 } else { 11852 // Successfully deleted the old package; proceed with replace. 11853 11854 // If deleted package lived in a container, give users a chance to 11855 // relinquish resources before killing. 11856 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 11857 if (DEBUG_INSTALL) { 11858 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 11859 } 11860 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 11861 final ArrayList<String> pkgList = new ArrayList<String>(1); 11862 pkgList.add(deletedPackage.applicationInfo.packageName); 11863 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 11864 } 11865 11866 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 11867 try { 11868 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 11869 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 11870 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11871 perUserInstalled, res, user); 11872 updatedSettings = true; 11873 } catch (PackageManagerException e) { 11874 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11875 } 11876 } 11877 11878 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11879 // remove package from internal structures. Note that we want deletePackageX to 11880 // delete the package data and cache directories that it created in 11881 // scanPackageLocked, unless those directories existed before we even tried to 11882 // install. 11883 if(updatedSettings) { 11884 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 11885 deletePackageLI( 11886 pkgName, null, true, allUsers, perUserInstalled, 11887 PackageManager.DELETE_KEEP_DATA, 11888 res.removedInfo, true); 11889 } 11890 // Since we failed to install the new package we need to restore the old 11891 // package that we deleted. 11892 if (deletedPkg) { 11893 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 11894 File restoreFile = new File(deletedPackage.codePath); 11895 // Parse old package 11896 boolean oldExternal = isExternal(deletedPackage); 11897 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 11898 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 11899 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11900 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 11901 try { 11902 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 11903 } catch (PackageManagerException e) { 11904 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 11905 + e.getMessage()); 11906 return; 11907 } 11908 // Restore of old package succeeded. Update permissions. 11909 // writer 11910 synchronized (mPackages) { 11911 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 11912 UPDATE_PERMISSIONS_ALL); 11913 // can downgrade to reader 11914 mSettings.writeLPr(); 11915 } 11916 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 11917 } 11918 } 11919 } 11920 11921 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 11922 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11923 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11924 String volumeUuid, PackageInstalledInfo res) { 11925 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 11926 + ", old=" + deletedPackage); 11927 boolean disabledSystem = false; 11928 boolean updatedSettings = false; 11929 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 11930 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 11931 != 0) { 11932 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11933 } 11934 String packageName = deletedPackage.packageName; 11935 if (packageName == null) { 11936 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11937 "Attempt to delete null packageName."); 11938 return; 11939 } 11940 PackageParser.Package oldPkg; 11941 PackageSetting oldPkgSetting; 11942 // reader 11943 synchronized (mPackages) { 11944 oldPkg = mPackages.get(packageName); 11945 oldPkgSetting = mSettings.mPackages.get(packageName); 11946 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 11947 (oldPkgSetting == null)) { 11948 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11949 "Couldn't find package:" + packageName + " information"); 11950 return; 11951 } 11952 } 11953 11954 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 11955 11956 res.removedInfo.uid = oldPkg.applicationInfo.uid; 11957 res.removedInfo.removedPackage = packageName; 11958 // Remove existing system package 11959 removePackageLI(oldPkgSetting, true); 11960 // writer 11961 synchronized (mPackages) { 11962 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 11963 if (!disabledSystem && deletedPackage != null) { 11964 // We didn't need to disable the .apk as a current system package, 11965 // which means we are replacing another update that is already 11966 // installed. We need to make sure to delete the older one's .apk. 11967 res.removedInfo.args = createInstallArgsForExisting(0, 11968 deletedPackage.applicationInfo.getCodePath(), 11969 deletedPackage.applicationInfo.getResourcePath(), 11970 getAppDexInstructionSets(deletedPackage.applicationInfo)); 11971 } else { 11972 res.removedInfo.args = null; 11973 } 11974 } 11975 11976 // Successfully disabled the old package. Now proceed with re-installation 11977 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 11978 11979 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11980 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 11981 11982 PackageParser.Package newPackage = null; 11983 try { 11984 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 11985 if (newPackage.mExtras != null) { 11986 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 11987 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 11988 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 11989 11990 // is the update attempting to change shared user? that isn't going to work... 11991 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 11992 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 11993 "Forbidding shared user change from " + oldPkgSetting.sharedUser 11994 + " to " + newPkgSetting.sharedUser); 11995 updatedSettings = true; 11996 } 11997 } 11998 11999 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12000 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12001 perUserInstalled, res, user); 12002 updatedSettings = true; 12003 } 12004 12005 } catch (PackageManagerException e) { 12006 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12007 } 12008 12009 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12010 // Re installation failed. Restore old information 12011 // Remove new pkg information 12012 if (newPackage != null) { 12013 removeInstalledPackageLI(newPackage, true); 12014 } 12015 // Add back the old system package 12016 try { 12017 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 12018 } catch (PackageManagerException e) { 12019 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 12020 } 12021 // Restore the old system information in Settings 12022 synchronized (mPackages) { 12023 if (disabledSystem) { 12024 mSettings.enableSystemPackageLPw(packageName); 12025 } 12026 if (updatedSettings) { 12027 mSettings.setInstallerPackageName(packageName, 12028 oldPkgSetting.installerPackageName); 12029 } 12030 mSettings.writeLPr(); 12031 } 12032 } 12033 } 12034 12035 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 12036 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 12037 UserHandle user) { 12038 String pkgName = newPackage.packageName; 12039 synchronized (mPackages) { 12040 //write settings. the installStatus will be incomplete at this stage. 12041 //note that the new package setting would have already been 12042 //added to mPackages. It hasn't been persisted yet. 12043 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 12044 mSettings.writeLPr(); 12045 } 12046 12047 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 12048 12049 synchronized (mPackages) { 12050 updatePermissionsLPw(newPackage.packageName, newPackage, 12051 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 12052 ? UPDATE_PERMISSIONS_ALL : 0)); 12053 // For system-bundled packages, we assume that installing an upgraded version 12054 // of the package implies that the user actually wants to run that new code, 12055 // so we enable the package. 12056 PackageSetting ps = mSettings.mPackages.get(pkgName); 12057 if (ps != null) { 12058 if (isSystemApp(newPackage)) { 12059 // NB: implicit assumption that system package upgrades apply to all users 12060 if (DEBUG_INSTALL) { 12061 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 12062 } 12063 if (res.origUsers != null) { 12064 for (int userHandle : res.origUsers) { 12065 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 12066 userHandle, installerPackageName); 12067 } 12068 } 12069 // Also convey the prior install/uninstall state 12070 if (allUsers != null && perUserInstalled != null) { 12071 for (int i = 0; i < allUsers.length; i++) { 12072 if (DEBUG_INSTALL) { 12073 Slog.d(TAG, " user " + allUsers[i] 12074 + " => " + perUserInstalled[i]); 12075 } 12076 ps.setInstalled(perUserInstalled[i], allUsers[i]); 12077 } 12078 // these install state changes will be persisted in the 12079 // upcoming call to mSettings.writeLPr(). 12080 } 12081 } 12082 // It's implied that when a user requests installation, they want the app to be 12083 // installed and enabled. 12084 int userId = user.getIdentifier(); 12085 if (userId != UserHandle.USER_ALL) { 12086 ps.setInstalled(true, userId); 12087 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 12088 } 12089 } 12090 res.name = pkgName; 12091 res.uid = newPackage.applicationInfo.uid; 12092 res.pkg = newPackage; 12093 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 12094 mSettings.setInstallerPackageName(pkgName, installerPackageName); 12095 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12096 //to update install status 12097 mSettings.writeLPr(); 12098 } 12099 } 12100 12101 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 12102 final int installFlags = args.installFlags; 12103 final String installerPackageName = args.installerPackageName; 12104 final String volumeUuid = args.volumeUuid; 12105 final File tmpPackageFile = new File(args.getCodePath()); 12106 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 12107 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 12108 || (args.volumeUuid != null)); 12109 boolean replace = false; 12110 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 12111 if (args.move != null) { 12112 // moving a complete application; perfom an initial scan on the new install location 12113 scanFlags |= SCAN_INITIAL; 12114 } 12115 // Result object to be returned 12116 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12117 12118 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 12119 // Retrieve PackageSettings and parse package 12120 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 12121 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 12122 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 12123 PackageParser pp = new PackageParser(); 12124 pp.setSeparateProcesses(mSeparateProcesses); 12125 pp.setDisplayMetrics(mMetrics); 12126 12127 final PackageParser.Package pkg; 12128 try { 12129 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 12130 } catch (PackageParserException e) { 12131 res.setError("Failed parse during installPackageLI", e); 12132 return; 12133 } 12134 12135 // Mark that we have an install time CPU ABI override. 12136 pkg.cpuAbiOverride = args.abiOverride; 12137 12138 String pkgName = res.name = pkg.packageName; 12139 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 12140 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 12141 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 12142 return; 12143 } 12144 } 12145 12146 try { 12147 pp.collectCertificates(pkg, parseFlags); 12148 pp.collectManifestDigest(pkg); 12149 } catch (PackageParserException e) { 12150 res.setError("Failed collect during installPackageLI", e); 12151 return; 12152 } 12153 12154 /* If the installer passed in a manifest digest, compare it now. */ 12155 if (args.manifestDigest != null) { 12156 if (DEBUG_INSTALL) { 12157 final String parsedManifest = pkg.manifestDigest == null ? "null" 12158 : pkg.manifestDigest.toString(); 12159 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 12160 + parsedManifest); 12161 } 12162 12163 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 12164 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 12165 return; 12166 } 12167 } else if (DEBUG_INSTALL) { 12168 final String parsedManifest = pkg.manifestDigest == null 12169 ? "null" : pkg.manifestDigest.toString(); 12170 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 12171 } 12172 12173 // Get rid of all references to package scan path via parser. 12174 pp = null; 12175 String oldCodePath = null; 12176 boolean systemApp = false; 12177 synchronized (mPackages) { 12178 // Check if installing already existing package 12179 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12180 String oldName = mSettings.mRenamedPackages.get(pkgName); 12181 if (pkg.mOriginalPackages != null 12182 && pkg.mOriginalPackages.contains(oldName) 12183 && mPackages.containsKey(oldName)) { 12184 // This package is derived from an original package, 12185 // and this device has been updating from that original 12186 // name. We must continue using the original name, so 12187 // rename the new package here. 12188 pkg.setPackageName(oldName); 12189 pkgName = pkg.packageName; 12190 replace = true; 12191 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 12192 + oldName + " pkgName=" + pkgName); 12193 } else if (mPackages.containsKey(pkgName)) { 12194 // This package, under its official name, already exists 12195 // on the device; we should replace it. 12196 replace = true; 12197 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 12198 } 12199 12200 // Prevent apps opting out from runtime permissions 12201 if (replace) { 12202 PackageParser.Package oldPackage = mPackages.get(pkgName); 12203 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 12204 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 12205 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 12206 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 12207 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 12208 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 12209 + " doesn't support runtime permissions but the old" 12210 + " target SDK " + oldTargetSdk + " does."); 12211 return; 12212 } 12213 } 12214 } 12215 12216 PackageSetting ps = mSettings.mPackages.get(pkgName); 12217 if (ps != null) { 12218 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 12219 12220 // Quick sanity check that we're signed correctly if updating; 12221 // we'll check this again later when scanning, but we want to 12222 // bail early here before tripping over redefined permissions. 12223 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12224 if (!checkUpgradeKeySetLP(ps, pkg)) { 12225 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 12226 + pkg.packageName + " upgrade keys do not match the " 12227 + "previously installed version"); 12228 return; 12229 } 12230 } else { 12231 try { 12232 verifySignaturesLP(ps, pkg); 12233 } catch (PackageManagerException e) { 12234 res.setError(e.error, e.getMessage()); 12235 return; 12236 } 12237 } 12238 12239 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 12240 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 12241 systemApp = (ps.pkg.applicationInfo.flags & 12242 ApplicationInfo.FLAG_SYSTEM) != 0; 12243 } 12244 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12245 } 12246 12247 // Check whether the newly-scanned package wants to define an already-defined perm 12248 int N = pkg.permissions.size(); 12249 for (int i = N-1; i >= 0; i--) { 12250 PackageParser.Permission perm = pkg.permissions.get(i); 12251 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 12252 if (bp != null) { 12253 // If the defining package is signed with our cert, it's okay. This 12254 // also includes the "updating the same package" case, of course. 12255 // "updating same package" could also involve key-rotation. 12256 final boolean sigsOk; 12257 if (bp.sourcePackage.equals(pkg.packageName) 12258 && (bp.packageSetting instanceof PackageSetting) 12259 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 12260 scanFlags))) { 12261 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 12262 } else { 12263 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 12264 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 12265 } 12266 if (!sigsOk) { 12267 // If the owning package is the system itself, we log but allow 12268 // install to proceed; we fail the install on all other permission 12269 // redefinitions. 12270 if (!bp.sourcePackage.equals("android")) { 12271 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 12272 + pkg.packageName + " attempting to redeclare permission " 12273 + perm.info.name + " already owned by " + bp.sourcePackage); 12274 res.origPermission = perm.info.name; 12275 res.origPackage = bp.sourcePackage; 12276 return; 12277 } else { 12278 Slog.w(TAG, "Package " + pkg.packageName 12279 + " attempting to redeclare system permission " 12280 + perm.info.name + "; ignoring new declaration"); 12281 pkg.permissions.remove(i); 12282 } 12283 } 12284 } 12285 } 12286 12287 } 12288 12289 if (systemApp && onExternal) { 12290 // Disable updates to system apps on sdcard 12291 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 12292 "Cannot install updates to system apps on sdcard"); 12293 return; 12294 } 12295 12296 if (args.move != null) { 12297 // We did an in-place move, so dex is ready to roll 12298 scanFlags |= SCAN_NO_DEX; 12299 scanFlags |= SCAN_MOVE; 12300 12301 synchronized (mPackages) { 12302 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12303 if (ps == null) { 12304 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 12305 "Missing settings for moved package " + pkgName); 12306 } 12307 12308 // We moved the entire application as-is, so bring over the 12309 // previously derived ABI information. 12310 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 12311 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 12312 } 12313 12314 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 12315 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 12316 scanFlags |= SCAN_NO_DEX; 12317 12318 try { 12319 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 12320 true /* extract libs */); 12321 } catch (PackageManagerException pme) { 12322 Slog.e(TAG, "Error deriving application ABI", pme); 12323 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 12324 return; 12325 } 12326 12327 // Run dexopt before old package gets removed, to minimize time when app is unavailable 12328 int result = mPackageDexOptimizer 12329 .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */, 12330 false /* defer */, false /* inclDependencies */); 12331 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 12332 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 12333 return; 12334 } 12335 } 12336 12337 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 12338 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 12339 return; 12340 } 12341 12342 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 12343 12344 if (replace) { 12345 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 12346 installerPackageName, volumeUuid, res); 12347 } else { 12348 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 12349 args.user, installerPackageName, volumeUuid, res); 12350 } 12351 synchronized (mPackages) { 12352 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12353 if (ps != null) { 12354 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12355 } 12356 } 12357 } 12358 12359 private void startIntentFilterVerifications(int userId, boolean replacing, 12360 PackageParser.Package pkg) { 12361 if (mIntentFilterVerifierComponent == null) { 12362 Slog.w(TAG, "No IntentFilter verification will not be done as " 12363 + "there is no IntentFilterVerifier available!"); 12364 return; 12365 } 12366 12367 final int verifierUid = getPackageUid( 12368 mIntentFilterVerifierComponent.getPackageName(), 12369 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 12370 12371 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 12372 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 12373 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 12374 mHandler.sendMessage(msg); 12375 } 12376 12377 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 12378 PackageParser.Package pkg) { 12379 int size = pkg.activities.size(); 12380 if (size == 0) { 12381 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12382 "No activity, so no need to verify any IntentFilter!"); 12383 return; 12384 } 12385 12386 final boolean hasDomainURLs = hasDomainURLs(pkg); 12387 if (!hasDomainURLs) { 12388 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12389 "No domain URLs, so no need to verify any IntentFilter!"); 12390 return; 12391 } 12392 12393 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 12394 + " if any IntentFilter from the " + size 12395 + " Activities needs verification ..."); 12396 12397 int count = 0; 12398 final String packageName = pkg.packageName; 12399 12400 synchronized (mPackages) { 12401 // If this is a new install and we see that we've already run verification for this 12402 // package, we have nothing to do: it means the state was restored from backup. 12403 if (!replacing) { 12404 IntentFilterVerificationInfo ivi = 12405 mSettings.getIntentFilterVerificationLPr(packageName); 12406 if (ivi != null) { 12407 if (DEBUG_DOMAIN_VERIFICATION) { 12408 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 12409 + ivi.getStatusString()); 12410 } 12411 return; 12412 } 12413 } 12414 12415 // If any filters need to be verified, then all need to be. 12416 boolean needToVerify = false; 12417 for (PackageParser.Activity a : pkg.activities) { 12418 for (ActivityIntentInfo filter : a.intents) { 12419 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 12420 if (DEBUG_DOMAIN_VERIFICATION) { 12421 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 12422 } 12423 needToVerify = true; 12424 break; 12425 } 12426 } 12427 } 12428 12429 if (needToVerify) { 12430 final int verificationId = mIntentFilterVerificationToken++; 12431 for (PackageParser.Activity a : pkg.activities) { 12432 for (ActivityIntentInfo filter : a.intents) { 12433 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 12434 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12435 "Verification needed for IntentFilter:" + filter.toString()); 12436 mIntentFilterVerifier.addOneIntentFilterVerification( 12437 verifierUid, userId, verificationId, filter, packageName); 12438 count++; 12439 } 12440 } 12441 } 12442 } 12443 } 12444 12445 if (count > 0) { 12446 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 12447 + " IntentFilter verification" + (count > 1 ? "s" : "") 12448 + " for userId:" + userId); 12449 mIntentFilterVerifier.startVerifications(userId); 12450 } else { 12451 if (DEBUG_DOMAIN_VERIFICATION) { 12452 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 12453 } 12454 } 12455 } 12456 12457 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 12458 final ComponentName cn = filter.activity.getComponentName(); 12459 final String packageName = cn.getPackageName(); 12460 12461 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 12462 packageName); 12463 if (ivi == null) { 12464 return true; 12465 } 12466 int status = ivi.getStatus(); 12467 switch (status) { 12468 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 12469 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 12470 return true; 12471 12472 default: 12473 // Nothing to do 12474 return false; 12475 } 12476 } 12477 12478 private static boolean isMultiArch(PackageSetting ps) { 12479 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12480 } 12481 12482 private static boolean isMultiArch(ApplicationInfo info) { 12483 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12484 } 12485 12486 private static boolean isExternal(PackageParser.Package pkg) { 12487 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12488 } 12489 12490 private static boolean isExternal(PackageSetting ps) { 12491 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12492 } 12493 12494 private static boolean isExternal(ApplicationInfo info) { 12495 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12496 } 12497 12498 private static boolean isSystemApp(PackageParser.Package pkg) { 12499 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 12500 } 12501 12502 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 12503 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 12504 } 12505 12506 private static boolean hasDomainURLs(PackageParser.Package pkg) { 12507 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 12508 } 12509 12510 private static boolean isSystemApp(PackageSetting ps) { 12511 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 12512 } 12513 12514 private static boolean isUpdatedSystemApp(PackageSetting ps) { 12515 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 12516 } 12517 12518 private int packageFlagsToInstallFlags(PackageSetting ps) { 12519 int installFlags = 0; 12520 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 12521 // This existing package was an external ASEC install when we have 12522 // the external flag without a UUID 12523 installFlags |= PackageManager.INSTALL_EXTERNAL; 12524 } 12525 if (ps.isForwardLocked()) { 12526 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12527 } 12528 return installFlags; 12529 } 12530 12531 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 12532 if (isExternal(pkg)) { 12533 if (TextUtils.isEmpty(pkg.volumeUuid)) { 12534 return mSettings.getExternalVersion(); 12535 } else { 12536 return mSettings.findOrCreateVersion(pkg.volumeUuid); 12537 } 12538 } else { 12539 return mSettings.getInternalVersion(); 12540 } 12541 } 12542 12543 private void deleteTempPackageFiles() { 12544 final FilenameFilter filter = new FilenameFilter() { 12545 public boolean accept(File dir, String name) { 12546 return name.startsWith("vmdl") && name.endsWith(".tmp"); 12547 } 12548 }; 12549 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 12550 file.delete(); 12551 } 12552 } 12553 12554 @Override 12555 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 12556 int flags) { 12557 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 12558 flags); 12559 } 12560 12561 @Override 12562 public void deletePackage(final String packageName, 12563 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 12564 mContext.enforceCallingOrSelfPermission( 12565 android.Manifest.permission.DELETE_PACKAGES, null); 12566 Preconditions.checkNotNull(packageName); 12567 Preconditions.checkNotNull(observer); 12568 final int uid = Binder.getCallingUid(); 12569 if (UserHandle.getUserId(uid) != userId) { 12570 mContext.enforceCallingPermission( 12571 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 12572 "deletePackage for user " + userId); 12573 } 12574 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 12575 try { 12576 observer.onPackageDeleted(packageName, 12577 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 12578 } catch (RemoteException re) { 12579 } 12580 return; 12581 } 12582 12583 boolean uninstallBlocked = false; 12584 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 12585 int[] users = sUserManager.getUserIds(); 12586 for (int i = 0; i < users.length; ++i) { 12587 if (getBlockUninstallForUser(packageName, users[i])) { 12588 uninstallBlocked = true; 12589 break; 12590 } 12591 } 12592 } else { 12593 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 12594 } 12595 if (uninstallBlocked) { 12596 try { 12597 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 12598 null); 12599 } catch (RemoteException re) { 12600 } 12601 return; 12602 } 12603 12604 if (DEBUG_REMOVE) { 12605 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 12606 } 12607 // Queue up an async operation since the package deletion may take a little while. 12608 mHandler.post(new Runnable() { 12609 public void run() { 12610 mHandler.removeCallbacks(this); 12611 final int returnCode = deletePackageX(packageName, userId, flags); 12612 if (observer != null) { 12613 try { 12614 observer.onPackageDeleted(packageName, returnCode, null); 12615 } catch (RemoteException e) { 12616 Log.i(TAG, "Observer no longer exists."); 12617 } //end catch 12618 } //end if 12619 } //end run 12620 }); 12621 } 12622 12623 private boolean isPackageDeviceAdmin(String packageName, int userId) { 12624 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 12625 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 12626 try { 12627 if (dpm != null) { 12628 if (dpm.isDeviceOwner(packageName)) { 12629 return true; 12630 } 12631 int[] users; 12632 if (userId == UserHandle.USER_ALL) { 12633 users = sUserManager.getUserIds(); 12634 } else { 12635 users = new int[]{userId}; 12636 } 12637 for (int i = 0; i < users.length; ++i) { 12638 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 12639 return true; 12640 } 12641 } 12642 } 12643 } catch (RemoteException e) { 12644 } 12645 return false; 12646 } 12647 12648 /** 12649 * This method is an internal method that could be get invoked either 12650 * to delete an installed package or to clean up a failed installation. 12651 * After deleting an installed package, a broadcast is sent to notify any 12652 * listeners that the package has been installed. For cleaning up a failed 12653 * installation, the broadcast is not necessary since the package's 12654 * installation wouldn't have sent the initial broadcast either 12655 * The key steps in deleting a package are 12656 * deleting the package information in internal structures like mPackages, 12657 * deleting the packages base directories through installd 12658 * updating mSettings to reflect current status 12659 * persisting settings for later use 12660 * sending a broadcast if necessary 12661 */ 12662 private int deletePackageX(String packageName, int userId, int flags) { 12663 final PackageRemovedInfo info = new PackageRemovedInfo(); 12664 final boolean res; 12665 12666 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 12667 ? UserHandle.ALL : new UserHandle(userId); 12668 12669 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 12670 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 12671 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 12672 } 12673 12674 boolean removedForAllUsers = false; 12675 boolean systemUpdate = false; 12676 12677 // for the uninstall-updates case and restricted profiles, remember the per- 12678 // userhandle installed state 12679 int[] allUsers; 12680 boolean[] perUserInstalled; 12681 synchronized (mPackages) { 12682 PackageSetting ps = mSettings.mPackages.get(packageName); 12683 allUsers = sUserManager.getUserIds(); 12684 perUserInstalled = new boolean[allUsers.length]; 12685 for (int i = 0; i < allUsers.length; i++) { 12686 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12687 } 12688 } 12689 12690 synchronized (mInstallLock) { 12691 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 12692 res = deletePackageLI(packageName, removeForUser, 12693 true, allUsers, perUserInstalled, 12694 flags | REMOVE_CHATTY, info, true); 12695 systemUpdate = info.isRemovedPackageSystemUpdate; 12696 if (res && !systemUpdate && mPackages.get(packageName) == null) { 12697 removedForAllUsers = true; 12698 } 12699 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 12700 + " removedForAllUsers=" + removedForAllUsers); 12701 } 12702 12703 if (res) { 12704 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 12705 12706 // If the removed package was a system update, the old system package 12707 // was re-enabled; we need to broadcast this information 12708 if (systemUpdate) { 12709 Bundle extras = new Bundle(1); 12710 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 12711 ? info.removedAppId : info.uid); 12712 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12713 12714 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 12715 extras, null, null, null); 12716 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 12717 extras, null, null, null); 12718 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 12719 null, packageName, null, null); 12720 } 12721 } 12722 // Force a gc here. 12723 Runtime.getRuntime().gc(); 12724 // Delete the resources here after sending the broadcast to let 12725 // other processes clean up before deleting resources. 12726 if (info.args != null) { 12727 synchronized (mInstallLock) { 12728 info.args.doPostDeleteLI(true); 12729 } 12730 } 12731 12732 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 12733 } 12734 12735 class PackageRemovedInfo { 12736 String removedPackage; 12737 int uid = -1; 12738 int removedAppId = -1; 12739 int[] removedUsers = null; 12740 boolean isRemovedPackageSystemUpdate = false; 12741 // Clean up resources deleted packages. 12742 InstallArgs args = null; 12743 12744 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 12745 Bundle extras = new Bundle(1); 12746 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 12747 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 12748 if (replacing) { 12749 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12750 } 12751 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 12752 if (removedPackage != null) { 12753 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 12754 extras, null, null, removedUsers); 12755 if (fullRemove && !replacing) { 12756 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 12757 extras, null, null, removedUsers); 12758 } 12759 } 12760 if (removedAppId >= 0) { 12761 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 12762 removedUsers); 12763 } 12764 } 12765 } 12766 12767 /* 12768 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 12769 * flag is not set, the data directory is removed as well. 12770 * make sure this flag is set for partially installed apps. If not its meaningless to 12771 * delete a partially installed application. 12772 */ 12773 private void removePackageDataLI(PackageSetting ps, 12774 int[] allUserHandles, boolean[] perUserInstalled, 12775 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 12776 String packageName = ps.name; 12777 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 12778 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 12779 // Retrieve object to delete permissions for shared user later on 12780 final PackageSetting deletedPs; 12781 // reader 12782 synchronized (mPackages) { 12783 deletedPs = mSettings.mPackages.get(packageName); 12784 if (outInfo != null) { 12785 outInfo.removedPackage = packageName; 12786 outInfo.removedUsers = deletedPs != null 12787 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 12788 : null; 12789 } 12790 } 12791 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12792 removeDataDirsLI(ps.volumeUuid, packageName); 12793 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 12794 } 12795 // writer 12796 synchronized (mPackages) { 12797 if (deletedPs != null) { 12798 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12799 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 12800 clearDefaultBrowserIfNeeded(packageName); 12801 if (outInfo != null) { 12802 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 12803 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 12804 } 12805 updatePermissionsLPw(deletedPs.name, null, 0); 12806 if (deletedPs.sharedUser != null) { 12807 // Remove permissions associated with package. Since runtime 12808 // permissions are per user we have to kill the removed package 12809 // or packages running under the shared user of the removed 12810 // package if revoking the permissions requested only by the removed 12811 // package is successful and this causes a change in gids. 12812 for (int userId : UserManagerService.getInstance().getUserIds()) { 12813 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 12814 userId); 12815 if (userIdToKill == UserHandle.USER_ALL 12816 || userIdToKill >= UserHandle.USER_OWNER) { 12817 // If gids changed for this user, kill all affected packages. 12818 mHandler.post(new Runnable() { 12819 @Override 12820 public void run() { 12821 // This has to happen with no lock held. 12822 killSettingPackagesForUser(deletedPs, userIdToKill, 12823 KILL_APP_REASON_GIDS_CHANGED); 12824 } 12825 }); 12826 break; 12827 } 12828 } 12829 } 12830 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 12831 } 12832 // make sure to preserve per-user disabled state if this removal was just 12833 // a downgrade of a system app to the factory package 12834 if (allUserHandles != null && perUserInstalled != null) { 12835 if (DEBUG_REMOVE) { 12836 Slog.d(TAG, "Propagating install state across downgrade"); 12837 } 12838 for (int i = 0; i < allUserHandles.length; i++) { 12839 if (DEBUG_REMOVE) { 12840 Slog.d(TAG, " user " + allUserHandles[i] 12841 + " => " + perUserInstalled[i]); 12842 } 12843 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12844 } 12845 } 12846 } 12847 // can downgrade to reader 12848 if (writeSettings) { 12849 // Save settings now 12850 mSettings.writeLPr(); 12851 } 12852 } 12853 if (outInfo != null) { 12854 // A user ID was deleted here. Go through all users and remove it 12855 // from KeyStore. 12856 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 12857 } 12858 } 12859 12860 static boolean locationIsPrivileged(File path) { 12861 try { 12862 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 12863 .getCanonicalPath(); 12864 return path.getCanonicalPath().startsWith(privilegedAppDir); 12865 } catch (IOException e) { 12866 Slog.e(TAG, "Unable to access code path " + path); 12867 } 12868 return false; 12869 } 12870 12871 /* 12872 * Tries to delete system package. 12873 */ 12874 private boolean deleteSystemPackageLI(PackageSetting newPs, 12875 int[] allUserHandles, boolean[] perUserInstalled, 12876 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 12877 final boolean applyUserRestrictions 12878 = (allUserHandles != null) && (perUserInstalled != null); 12879 PackageSetting disabledPs = null; 12880 // Confirm if the system package has been updated 12881 // An updated system app can be deleted. This will also have to restore 12882 // the system pkg from system partition 12883 // reader 12884 synchronized (mPackages) { 12885 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 12886 } 12887 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 12888 + " disabledPs=" + disabledPs); 12889 if (disabledPs == null) { 12890 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 12891 return false; 12892 } else if (DEBUG_REMOVE) { 12893 Slog.d(TAG, "Deleting system pkg from data partition"); 12894 } 12895 if (DEBUG_REMOVE) { 12896 if (applyUserRestrictions) { 12897 Slog.d(TAG, "Remembering install states:"); 12898 for (int i = 0; i < allUserHandles.length; i++) { 12899 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 12900 } 12901 } 12902 } 12903 // Delete the updated package 12904 outInfo.isRemovedPackageSystemUpdate = true; 12905 if (disabledPs.versionCode < newPs.versionCode) { 12906 // Delete data for downgrades 12907 flags &= ~PackageManager.DELETE_KEEP_DATA; 12908 } else { 12909 // Preserve data by setting flag 12910 flags |= PackageManager.DELETE_KEEP_DATA; 12911 } 12912 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 12913 allUserHandles, perUserInstalled, outInfo, writeSettings); 12914 if (!ret) { 12915 return false; 12916 } 12917 // writer 12918 synchronized (mPackages) { 12919 // Reinstate the old system package 12920 mSettings.enableSystemPackageLPw(newPs.name); 12921 // Remove any native libraries from the upgraded package. 12922 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 12923 } 12924 // Install the system package 12925 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 12926 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 12927 if (locationIsPrivileged(disabledPs.codePath)) { 12928 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12929 } 12930 12931 final PackageParser.Package newPkg; 12932 try { 12933 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 12934 } catch (PackageManagerException e) { 12935 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 12936 return false; 12937 } 12938 12939 // writer 12940 synchronized (mPackages) { 12941 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 12942 12943 updatePermissionsLPw(newPkg.packageName, newPkg, 12944 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 12945 12946 if (applyUserRestrictions) { 12947 if (DEBUG_REMOVE) { 12948 Slog.d(TAG, "Propagating install state across reinstall"); 12949 } 12950 for (int i = 0; i < allUserHandles.length; i++) { 12951 if (DEBUG_REMOVE) { 12952 Slog.d(TAG, " user " + allUserHandles[i] 12953 + " => " + perUserInstalled[i]); 12954 } 12955 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12956 12957 mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false); 12958 } 12959 // Regardless of writeSettings we need to ensure that this restriction 12960 // state propagation is persisted 12961 mSettings.writeAllUsersPackageRestrictionsLPr(); 12962 } 12963 // can downgrade to reader here 12964 if (writeSettings) { 12965 mSettings.writeLPr(); 12966 } 12967 } 12968 return true; 12969 } 12970 12971 private boolean deleteInstalledPackageLI(PackageSetting ps, 12972 boolean deleteCodeAndResources, int flags, 12973 int[] allUserHandles, boolean[] perUserInstalled, 12974 PackageRemovedInfo outInfo, boolean writeSettings) { 12975 if (outInfo != null) { 12976 outInfo.uid = ps.appId; 12977 } 12978 12979 // Delete package data from internal structures and also remove data if flag is set 12980 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 12981 12982 // Delete application code and resources 12983 if (deleteCodeAndResources && (outInfo != null)) { 12984 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 12985 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 12986 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 12987 } 12988 return true; 12989 } 12990 12991 @Override 12992 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 12993 int userId) { 12994 mContext.enforceCallingOrSelfPermission( 12995 android.Manifest.permission.DELETE_PACKAGES, null); 12996 synchronized (mPackages) { 12997 PackageSetting ps = mSettings.mPackages.get(packageName); 12998 if (ps == null) { 12999 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 13000 return false; 13001 } 13002 if (!ps.getInstalled(userId)) { 13003 // Can't block uninstall for an app that is not installed or enabled. 13004 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 13005 return false; 13006 } 13007 ps.setBlockUninstall(blockUninstall, userId); 13008 mSettings.writePackageRestrictionsLPr(userId); 13009 } 13010 return true; 13011 } 13012 13013 @Override 13014 public boolean getBlockUninstallForUser(String packageName, int userId) { 13015 synchronized (mPackages) { 13016 PackageSetting ps = mSettings.mPackages.get(packageName); 13017 if (ps == null) { 13018 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 13019 return false; 13020 } 13021 return ps.getBlockUninstall(userId); 13022 } 13023 } 13024 13025 /* 13026 * This method handles package deletion in general 13027 */ 13028 private boolean deletePackageLI(String packageName, UserHandle user, 13029 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 13030 int flags, PackageRemovedInfo outInfo, 13031 boolean writeSettings) { 13032 if (packageName == null) { 13033 Slog.w(TAG, "Attempt to delete null packageName."); 13034 return false; 13035 } 13036 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 13037 PackageSetting ps; 13038 boolean dataOnly = false; 13039 int removeUser = -1; 13040 int appId = -1; 13041 synchronized (mPackages) { 13042 ps = mSettings.mPackages.get(packageName); 13043 if (ps == null) { 13044 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13045 return false; 13046 } 13047 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 13048 && user.getIdentifier() != UserHandle.USER_ALL) { 13049 // The caller is asking that the package only be deleted for a single 13050 // user. To do this, we just mark its uninstalled state and delete 13051 // its data. If this is a system app, we only allow this to happen if 13052 // they have set the special DELETE_SYSTEM_APP which requests different 13053 // semantics than normal for uninstalling system apps. 13054 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 13055 ps.setUserState(user.getIdentifier(), 13056 COMPONENT_ENABLED_STATE_DEFAULT, 13057 false, //installed 13058 true, //stopped 13059 true, //notLaunched 13060 false, //hidden 13061 null, null, null, 13062 false, // blockUninstall 13063 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED, 0); 13064 if (!isSystemApp(ps)) { 13065 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 13066 // Other user still have this package installed, so all 13067 // we need to do is clear this user's data and save that 13068 // it is uninstalled. 13069 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 13070 removeUser = user.getIdentifier(); 13071 appId = ps.appId; 13072 scheduleWritePackageRestrictionsLocked(removeUser); 13073 } else { 13074 // We need to set it back to 'installed' so the uninstall 13075 // broadcasts will be sent correctly. 13076 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 13077 ps.setInstalled(true, user.getIdentifier()); 13078 } 13079 } else { 13080 // This is a system app, so we assume that the 13081 // other users still have this package installed, so all 13082 // we need to do is clear this user's data and save that 13083 // it is uninstalled. 13084 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 13085 removeUser = user.getIdentifier(); 13086 appId = ps.appId; 13087 scheduleWritePackageRestrictionsLocked(removeUser); 13088 } 13089 } 13090 } 13091 13092 if (removeUser >= 0) { 13093 // From above, we determined that we are deleting this only 13094 // for a single user. Continue the work here. 13095 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 13096 if (outInfo != null) { 13097 outInfo.removedPackage = packageName; 13098 outInfo.removedAppId = appId; 13099 outInfo.removedUsers = new int[] {removeUser}; 13100 } 13101 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 13102 removeKeystoreDataIfNeeded(removeUser, appId); 13103 schedulePackageCleaning(packageName, removeUser, false); 13104 synchronized (mPackages) { 13105 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 13106 scheduleWritePackageRestrictionsLocked(removeUser); 13107 } 13108 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser); 13109 } 13110 return true; 13111 } 13112 13113 if (dataOnly) { 13114 // Delete application data first 13115 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 13116 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 13117 return true; 13118 } 13119 13120 boolean ret = false; 13121 if (isSystemApp(ps)) { 13122 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 13123 // When an updated system application is deleted we delete the existing resources as well and 13124 // fall back to existing code in system partition 13125 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 13126 flags, outInfo, writeSettings); 13127 } else { 13128 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 13129 // Kill application pre-emptively especially for apps on sd. 13130 killApplication(packageName, ps.appId, "uninstall pkg"); 13131 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 13132 allUserHandles, perUserInstalled, 13133 outInfo, writeSettings); 13134 } 13135 13136 return ret; 13137 } 13138 13139 private final class ClearStorageConnection implements ServiceConnection { 13140 IMediaContainerService mContainerService; 13141 13142 @Override 13143 public void onServiceConnected(ComponentName name, IBinder service) { 13144 synchronized (this) { 13145 mContainerService = IMediaContainerService.Stub.asInterface(service); 13146 notifyAll(); 13147 } 13148 } 13149 13150 @Override 13151 public void onServiceDisconnected(ComponentName name) { 13152 } 13153 } 13154 13155 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 13156 final boolean mounted; 13157 if (Environment.isExternalStorageEmulated()) { 13158 mounted = true; 13159 } else { 13160 final String status = Environment.getExternalStorageState(); 13161 13162 mounted = status.equals(Environment.MEDIA_MOUNTED) 13163 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 13164 } 13165 13166 if (!mounted) { 13167 return; 13168 } 13169 13170 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 13171 int[] users; 13172 if (userId == UserHandle.USER_ALL) { 13173 users = sUserManager.getUserIds(); 13174 } else { 13175 users = new int[] { userId }; 13176 } 13177 final ClearStorageConnection conn = new ClearStorageConnection(); 13178 if (mContext.bindServiceAsUser( 13179 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 13180 try { 13181 for (int curUser : users) { 13182 long timeout = SystemClock.uptimeMillis() + 5000; 13183 synchronized (conn) { 13184 long now = SystemClock.uptimeMillis(); 13185 while (conn.mContainerService == null && now < timeout) { 13186 try { 13187 conn.wait(timeout - now); 13188 } catch (InterruptedException e) { 13189 } 13190 } 13191 } 13192 if (conn.mContainerService == null) { 13193 return; 13194 } 13195 13196 final UserEnvironment userEnv = new UserEnvironment(curUser); 13197 clearDirectory(conn.mContainerService, 13198 userEnv.buildExternalStorageAppCacheDirs(packageName)); 13199 if (allData) { 13200 clearDirectory(conn.mContainerService, 13201 userEnv.buildExternalStorageAppDataDirs(packageName)); 13202 clearDirectory(conn.mContainerService, 13203 userEnv.buildExternalStorageAppMediaDirs(packageName)); 13204 } 13205 } 13206 } finally { 13207 mContext.unbindService(conn); 13208 } 13209 } 13210 } 13211 13212 @Override 13213 public void clearApplicationUserData(final String packageName, 13214 final IPackageDataObserver observer, final int userId) { 13215 mContext.enforceCallingOrSelfPermission( 13216 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 13217 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 13218 // Queue up an async operation since the package deletion may take a little while. 13219 mHandler.post(new Runnable() { 13220 public void run() { 13221 mHandler.removeCallbacks(this); 13222 final boolean succeeded; 13223 synchronized (mInstallLock) { 13224 succeeded = clearApplicationUserDataLI(packageName, userId); 13225 } 13226 clearExternalStorageDataSync(packageName, userId, true); 13227 if (succeeded) { 13228 // invoke DeviceStorageMonitor's update method to clear any notifications 13229 DeviceStorageMonitorInternal 13230 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13231 if (dsm != null) { 13232 dsm.checkMemory(); 13233 } 13234 } 13235 if(observer != null) { 13236 try { 13237 observer.onRemoveCompleted(packageName, succeeded); 13238 } catch (RemoteException e) { 13239 Log.i(TAG, "Observer no longer exists."); 13240 } 13241 } //end if observer 13242 } //end run 13243 }); 13244 } 13245 13246 private boolean clearApplicationUserDataLI(String packageName, int userId) { 13247 if (packageName == null) { 13248 Slog.w(TAG, "Attempt to delete null packageName."); 13249 return false; 13250 } 13251 13252 // Try finding details about the requested package 13253 PackageParser.Package pkg; 13254 synchronized (mPackages) { 13255 pkg = mPackages.get(packageName); 13256 if (pkg == null) { 13257 final PackageSetting ps = mSettings.mPackages.get(packageName); 13258 if (ps != null) { 13259 pkg = ps.pkg; 13260 } 13261 } 13262 13263 if (pkg == null) { 13264 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13265 return false; 13266 } 13267 13268 PackageSetting ps = (PackageSetting) pkg.mExtras; 13269 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 13270 } 13271 13272 // Always delete data directories for package, even if we found no other 13273 // record of app. This helps users recover from UID mismatches without 13274 // resorting to a full data wipe. 13275 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 13276 if (retCode < 0) { 13277 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 13278 return false; 13279 } 13280 13281 final int appId = pkg.applicationInfo.uid; 13282 removeKeystoreDataIfNeeded(userId, appId); 13283 13284 // Create a native library symlink only if we have native libraries 13285 // and if the native libraries are 32 bit libraries. We do not provide 13286 // this symlink for 64 bit libraries. 13287 if (pkg.applicationInfo.primaryCpuAbi != null && 13288 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 13289 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 13290 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 13291 nativeLibPath, userId) < 0) { 13292 Slog.w(TAG, "Failed linking native library dir"); 13293 return false; 13294 } 13295 } 13296 13297 return true; 13298 } 13299 13300 /** 13301 * Reverts user permission state changes (permissions and flags) in 13302 * all packages for a given user. 13303 * 13304 * @param userId The device user for which to do a reset. 13305 */ 13306 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 13307 final int packageCount = mPackages.size(); 13308 for (int i = 0; i < packageCount; i++) { 13309 PackageParser.Package pkg = mPackages.valueAt(i); 13310 PackageSetting ps = (PackageSetting) pkg.mExtras; 13311 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 13312 } 13313 } 13314 13315 /** 13316 * Reverts user permission state changes (permissions and flags). 13317 * 13318 * @param ps The package for which to reset. 13319 * @param userId The device user for which to do a reset. 13320 */ 13321 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 13322 final PackageSetting ps, final int userId) { 13323 if (ps.pkg == null) { 13324 return; 13325 } 13326 13327 final int userSettableFlags = FLAG_PERMISSION_USER_SET 13328 | FLAG_PERMISSION_USER_FIXED 13329 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 13330 13331 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 13332 | FLAG_PERMISSION_POLICY_FIXED; 13333 13334 boolean writeInstallPermissions = false; 13335 boolean writeRuntimePermissions = false; 13336 13337 final int permissionCount = ps.pkg.requestedPermissions.size(); 13338 for (int i = 0; i < permissionCount; i++) { 13339 String permission = ps.pkg.requestedPermissions.get(i); 13340 13341 BasePermission bp = mSettings.mPermissions.get(permission); 13342 if (bp == null) { 13343 continue; 13344 } 13345 13346 // If shared user we just reset the state to which only this app contributed. 13347 if (ps.sharedUser != null) { 13348 boolean used = false; 13349 final int packageCount = ps.sharedUser.packages.size(); 13350 for (int j = 0; j < packageCount; j++) { 13351 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 13352 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 13353 && pkg.pkg.requestedPermissions.contains(permission)) { 13354 used = true; 13355 break; 13356 } 13357 } 13358 if (used) { 13359 continue; 13360 } 13361 } 13362 13363 PermissionsState permissionsState = ps.getPermissionsState(); 13364 13365 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 13366 13367 // Always clear the user settable flags. 13368 final boolean hasInstallState = permissionsState.getInstallPermissionState( 13369 bp.name) != null; 13370 if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) { 13371 if (hasInstallState) { 13372 writeInstallPermissions = true; 13373 } else { 13374 writeRuntimePermissions = true; 13375 } 13376 } 13377 13378 // Below is only runtime permission handling. 13379 if (!bp.isRuntime()) { 13380 continue; 13381 } 13382 13383 // Never clobber system or policy. 13384 if ((oldFlags & policyOrSystemFlags) != 0) { 13385 continue; 13386 } 13387 13388 // If this permission was granted by default, make sure it is. 13389 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 13390 if (permissionsState.grantRuntimePermission(bp, userId) 13391 != PERMISSION_OPERATION_FAILURE) { 13392 writeRuntimePermissions = true; 13393 } 13394 } else { 13395 // Otherwise, reset the permission. 13396 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 13397 switch (revokeResult) { 13398 case PERMISSION_OPERATION_SUCCESS: { 13399 writeRuntimePermissions = true; 13400 } break; 13401 13402 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 13403 writeRuntimePermissions = true; 13404 // If gids changed for this user, kill all affected packages. 13405 mHandler.post(new Runnable() { 13406 @Override 13407 public void run() { 13408 // This has to happen with no lock held. 13409 killSettingPackagesForUser(ps, userId, 13410 KILL_APP_REASON_GIDS_CHANGED); 13411 } 13412 }); 13413 } break; 13414 } 13415 } 13416 } 13417 13418 // Synchronously write as we are taking permissions away. 13419 if (writeRuntimePermissions) { 13420 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 13421 } 13422 13423 // Synchronously write as we are taking permissions away. 13424 if (writeInstallPermissions) { 13425 mSettings.writeLPr(); 13426 } 13427 } 13428 13429 /** 13430 * Remove entries from the keystore daemon. Will only remove it if the 13431 * {@code appId} is valid. 13432 */ 13433 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 13434 if (appId < 0) { 13435 return; 13436 } 13437 13438 final KeyStore keyStore = KeyStore.getInstance(); 13439 if (keyStore != null) { 13440 if (userId == UserHandle.USER_ALL) { 13441 for (final int individual : sUserManager.getUserIds()) { 13442 keyStore.clearUid(UserHandle.getUid(individual, appId)); 13443 } 13444 } else { 13445 keyStore.clearUid(UserHandle.getUid(userId, appId)); 13446 } 13447 } else { 13448 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 13449 } 13450 } 13451 13452 @Override 13453 public void deleteApplicationCacheFiles(final String packageName, 13454 final IPackageDataObserver observer) { 13455 mContext.enforceCallingOrSelfPermission( 13456 android.Manifest.permission.DELETE_CACHE_FILES, null); 13457 // Queue up an async operation since the package deletion may take a little while. 13458 final int userId = UserHandle.getCallingUserId(); 13459 mHandler.post(new Runnable() { 13460 public void run() { 13461 mHandler.removeCallbacks(this); 13462 final boolean succeded; 13463 synchronized (mInstallLock) { 13464 succeded = deleteApplicationCacheFilesLI(packageName, userId); 13465 } 13466 clearExternalStorageDataSync(packageName, userId, false); 13467 if (observer != null) { 13468 try { 13469 observer.onRemoveCompleted(packageName, succeded); 13470 } catch (RemoteException e) { 13471 Log.i(TAG, "Observer no longer exists."); 13472 } 13473 } //end if observer 13474 } //end run 13475 }); 13476 } 13477 13478 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 13479 if (packageName == null) { 13480 Slog.w(TAG, "Attempt to delete null packageName."); 13481 return false; 13482 } 13483 PackageParser.Package p; 13484 synchronized (mPackages) { 13485 p = mPackages.get(packageName); 13486 } 13487 if (p == null) { 13488 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13489 return false; 13490 } 13491 final ApplicationInfo applicationInfo = p.applicationInfo; 13492 if (applicationInfo == null) { 13493 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13494 return false; 13495 } 13496 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 13497 if (retCode < 0) { 13498 Slog.w(TAG, "Couldn't remove cache files for package: " 13499 + packageName + " u" + userId); 13500 return false; 13501 } 13502 return true; 13503 } 13504 13505 @Override 13506 public void getPackageSizeInfo(final String packageName, int userHandle, 13507 final IPackageStatsObserver observer) { 13508 mContext.enforceCallingOrSelfPermission( 13509 android.Manifest.permission.GET_PACKAGE_SIZE, null); 13510 if (packageName == null) { 13511 throw new IllegalArgumentException("Attempt to get size of null packageName"); 13512 } 13513 13514 PackageStats stats = new PackageStats(packageName, userHandle); 13515 13516 /* 13517 * Queue up an async operation since the package measurement may take a 13518 * little while. 13519 */ 13520 Message msg = mHandler.obtainMessage(INIT_COPY); 13521 msg.obj = new MeasureParams(stats, observer); 13522 mHandler.sendMessage(msg); 13523 } 13524 13525 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 13526 PackageStats pStats) { 13527 if (packageName == null) { 13528 Slog.w(TAG, "Attempt to get size of null packageName."); 13529 return false; 13530 } 13531 PackageParser.Package p; 13532 boolean dataOnly = false; 13533 String libDirRoot = null; 13534 String asecPath = null; 13535 PackageSetting ps = null; 13536 synchronized (mPackages) { 13537 p = mPackages.get(packageName); 13538 ps = mSettings.mPackages.get(packageName); 13539 if(p == null) { 13540 dataOnly = true; 13541 if((ps == null) || (ps.pkg == null)) { 13542 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13543 return false; 13544 } 13545 p = ps.pkg; 13546 } 13547 if (ps != null) { 13548 libDirRoot = ps.legacyNativeLibraryPathString; 13549 } 13550 if (p != null && (isExternal(p) || p.isForwardLocked())) { 13551 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 13552 if (secureContainerId != null) { 13553 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 13554 } 13555 } 13556 } 13557 String publicSrcDir = null; 13558 if(!dataOnly) { 13559 final ApplicationInfo applicationInfo = p.applicationInfo; 13560 if (applicationInfo == null) { 13561 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13562 return false; 13563 } 13564 if (p.isForwardLocked()) { 13565 publicSrcDir = applicationInfo.getBaseResourcePath(); 13566 } 13567 } 13568 // TODO: extend to measure size of split APKs 13569 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 13570 // not just the first level. 13571 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 13572 // just the primary. 13573 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 13574 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath, 13575 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 13576 if (res < 0) { 13577 return false; 13578 } 13579 13580 // Fix-up for forward-locked applications in ASEC containers. 13581 if (!isExternal(p)) { 13582 pStats.codeSize += pStats.externalCodeSize; 13583 pStats.externalCodeSize = 0L; 13584 } 13585 13586 return true; 13587 } 13588 13589 13590 @Override 13591 public void addPackageToPreferred(String packageName) { 13592 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 13593 } 13594 13595 @Override 13596 public void removePackageFromPreferred(String packageName) { 13597 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 13598 } 13599 13600 @Override 13601 public List<PackageInfo> getPreferredPackages(int flags) { 13602 return new ArrayList<PackageInfo>(); 13603 } 13604 13605 private int getUidTargetSdkVersionLockedLPr(int uid) { 13606 Object obj = mSettings.getUserIdLPr(uid); 13607 if (obj instanceof SharedUserSetting) { 13608 final SharedUserSetting sus = (SharedUserSetting) obj; 13609 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 13610 final Iterator<PackageSetting> it = sus.packages.iterator(); 13611 while (it.hasNext()) { 13612 final PackageSetting ps = it.next(); 13613 if (ps.pkg != null) { 13614 int v = ps.pkg.applicationInfo.targetSdkVersion; 13615 if (v < vers) vers = v; 13616 } 13617 } 13618 return vers; 13619 } else if (obj instanceof PackageSetting) { 13620 final PackageSetting ps = (PackageSetting) obj; 13621 if (ps.pkg != null) { 13622 return ps.pkg.applicationInfo.targetSdkVersion; 13623 } 13624 } 13625 return Build.VERSION_CODES.CUR_DEVELOPMENT; 13626 } 13627 13628 @Override 13629 public void addPreferredActivity(IntentFilter filter, int match, 13630 ComponentName[] set, ComponentName activity, int userId) { 13631 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13632 "Adding preferred"); 13633 } 13634 13635 private void addPreferredActivityInternal(IntentFilter filter, int match, 13636 ComponentName[] set, ComponentName activity, boolean always, int userId, 13637 String opname) { 13638 // writer 13639 int callingUid = Binder.getCallingUid(); 13640 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 13641 if (filter.countActions() == 0) { 13642 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13643 return; 13644 } 13645 synchronized (mPackages) { 13646 if (mContext.checkCallingOrSelfPermission( 13647 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13648 != PackageManager.PERMISSION_GRANTED) { 13649 if (getUidTargetSdkVersionLockedLPr(callingUid) 13650 < Build.VERSION_CODES.FROYO) { 13651 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 13652 + callingUid); 13653 return; 13654 } 13655 mContext.enforceCallingOrSelfPermission( 13656 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13657 } 13658 13659 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 13660 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 13661 + userId + ":"); 13662 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13663 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 13664 scheduleWritePackageRestrictionsLocked(userId); 13665 } 13666 } 13667 13668 @Override 13669 public void replacePreferredActivity(IntentFilter filter, int match, 13670 ComponentName[] set, ComponentName activity, int userId) { 13671 if (filter.countActions() != 1) { 13672 throw new IllegalArgumentException( 13673 "replacePreferredActivity expects filter to have only 1 action."); 13674 } 13675 if (filter.countDataAuthorities() != 0 13676 || filter.countDataPaths() != 0 13677 || filter.countDataSchemes() > 1 13678 || filter.countDataTypes() != 0) { 13679 throw new IllegalArgumentException( 13680 "replacePreferredActivity expects filter to have no data authorities, " + 13681 "paths, or types; and at most one scheme."); 13682 } 13683 13684 final int callingUid = Binder.getCallingUid(); 13685 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 13686 synchronized (mPackages) { 13687 if (mContext.checkCallingOrSelfPermission( 13688 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13689 != PackageManager.PERMISSION_GRANTED) { 13690 if (getUidTargetSdkVersionLockedLPr(callingUid) 13691 < Build.VERSION_CODES.FROYO) { 13692 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 13693 + Binder.getCallingUid()); 13694 return; 13695 } 13696 mContext.enforceCallingOrSelfPermission( 13697 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13698 } 13699 13700 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13701 if (pir != null) { 13702 // Get all of the existing entries that exactly match this filter. 13703 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 13704 if (existing != null && existing.size() == 1) { 13705 PreferredActivity cur = existing.get(0); 13706 if (DEBUG_PREFERRED) { 13707 Slog.i(TAG, "Checking replace of preferred:"); 13708 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13709 if (!cur.mPref.mAlways) { 13710 Slog.i(TAG, " -- CUR; not mAlways!"); 13711 } else { 13712 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 13713 Slog.i(TAG, " -- CUR: mSet=" 13714 + Arrays.toString(cur.mPref.mSetComponents)); 13715 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 13716 Slog.i(TAG, " -- NEW: mMatch=" 13717 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 13718 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 13719 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 13720 } 13721 } 13722 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 13723 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 13724 && cur.mPref.sameSet(set)) { 13725 // Setting the preferred activity to what it happens to be already 13726 if (DEBUG_PREFERRED) { 13727 Slog.i(TAG, "Replacing with same preferred activity " 13728 + cur.mPref.mShortComponent + " for user " 13729 + userId + ":"); 13730 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13731 } 13732 return; 13733 } 13734 } 13735 13736 if (existing != null) { 13737 if (DEBUG_PREFERRED) { 13738 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 13739 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13740 } 13741 for (int i = 0; i < existing.size(); i++) { 13742 PreferredActivity pa = existing.get(i); 13743 if (DEBUG_PREFERRED) { 13744 Slog.i(TAG, "Removing existing preferred activity " 13745 + pa.mPref.mComponent + ":"); 13746 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 13747 } 13748 pir.removeFilter(pa); 13749 } 13750 } 13751 } 13752 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13753 "Replacing preferred"); 13754 } 13755 } 13756 13757 @Override 13758 public void clearPackagePreferredActivities(String packageName) { 13759 final int uid = Binder.getCallingUid(); 13760 // writer 13761 synchronized (mPackages) { 13762 PackageParser.Package pkg = mPackages.get(packageName); 13763 if (pkg == null || pkg.applicationInfo.uid != uid) { 13764 if (mContext.checkCallingOrSelfPermission( 13765 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13766 != PackageManager.PERMISSION_GRANTED) { 13767 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 13768 < Build.VERSION_CODES.FROYO) { 13769 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 13770 + Binder.getCallingUid()); 13771 return; 13772 } 13773 mContext.enforceCallingOrSelfPermission( 13774 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13775 } 13776 } 13777 13778 int user = UserHandle.getCallingUserId(); 13779 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 13780 scheduleWritePackageRestrictionsLocked(user); 13781 } 13782 } 13783 } 13784 13785 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13786 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 13787 ArrayList<PreferredActivity> removed = null; 13788 boolean changed = false; 13789 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13790 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 13791 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13792 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 13793 continue; 13794 } 13795 Iterator<PreferredActivity> it = pir.filterIterator(); 13796 while (it.hasNext()) { 13797 PreferredActivity pa = it.next(); 13798 // Mark entry for removal only if it matches the package name 13799 // and the entry is of type "always". 13800 if (packageName == null || 13801 (pa.mPref.mComponent.getPackageName().equals(packageName) 13802 && pa.mPref.mAlways)) { 13803 if (removed == null) { 13804 removed = new ArrayList<PreferredActivity>(); 13805 } 13806 removed.add(pa); 13807 } 13808 } 13809 if (removed != null) { 13810 for (int j=0; j<removed.size(); j++) { 13811 PreferredActivity pa = removed.get(j); 13812 pir.removeFilter(pa); 13813 } 13814 changed = true; 13815 } 13816 } 13817 return changed; 13818 } 13819 13820 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13821 private void clearIntentFilterVerificationsLPw(int userId) { 13822 final int packageCount = mPackages.size(); 13823 for (int i = 0; i < packageCount; i++) { 13824 PackageParser.Package pkg = mPackages.valueAt(i); 13825 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 13826 } 13827 } 13828 13829 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13830 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 13831 if (userId == UserHandle.USER_ALL) { 13832 if (mSettings.removeIntentFilterVerificationLPw(packageName, 13833 sUserManager.getUserIds())) { 13834 for (int oneUserId : sUserManager.getUserIds()) { 13835 scheduleWritePackageRestrictionsLocked(oneUserId); 13836 } 13837 } 13838 } else { 13839 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 13840 scheduleWritePackageRestrictionsLocked(userId); 13841 } 13842 } 13843 } 13844 13845 void clearDefaultBrowserIfNeeded(String packageName) { 13846 for (int oneUserId : sUserManager.getUserIds()) { 13847 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 13848 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 13849 if (packageName.equals(defaultBrowserPackageName)) { 13850 setDefaultBrowserPackageName(null, oneUserId); 13851 } 13852 } 13853 } 13854 13855 @Override 13856 public void resetApplicationPreferences(int userId) { 13857 mContext.enforceCallingOrSelfPermission( 13858 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13859 // writer 13860 synchronized (mPackages) { 13861 final long identity = Binder.clearCallingIdentity(); 13862 try { 13863 clearPackagePreferredActivitiesLPw(null, userId); 13864 mSettings.applyDefaultPreferredAppsLPw(this, userId); 13865 // TODO: We have to reset the default SMS and Phone. This requires 13866 // significant refactoring to keep all default apps in the package 13867 // manager (cleaner but more work) or have the services provide 13868 // callbacks to the package manager to request a default app reset. 13869 applyFactoryDefaultBrowserLPw(userId); 13870 clearIntentFilterVerificationsLPw(userId); 13871 primeDomainVerificationsLPw(userId); 13872 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 13873 scheduleWritePackageRestrictionsLocked(userId); 13874 } finally { 13875 Binder.restoreCallingIdentity(identity); 13876 } 13877 } 13878 } 13879 13880 @Override 13881 public int getPreferredActivities(List<IntentFilter> outFilters, 13882 List<ComponentName> outActivities, String packageName) { 13883 13884 int num = 0; 13885 final int userId = UserHandle.getCallingUserId(); 13886 // reader 13887 synchronized (mPackages) { 13888 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13889 if (pir != null) { 13890 final Iterator<PreferredActivity> it = pir.filterIterator(); 13891 while (it.hasNext()) { 13892 final PreferredActivity pa = it.next(); 13893 if (packageName == null 13894 || (pa.mPref.mComponent.getPackageName().equals(packageName) 13895 && pa.mPref.mAlways)) { 13896 if (outFilters != null) { 13897 outFilters.add(new IntentFilter(pa)); 13898 } 13899 if (outActivities != null) { 13900 outActivities.add(pa.mPref.mComponent); 13901 } 13902 } 13903 } 13904 } 13905 } 13906 13907 return num; 13908 } 13909 13910 @Override 13911 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 13912 int userId) { 13913 int callingUid = Binder.getCallingUid(); 13914 if (callingUid != Process.SYSTEM_UID) { 13915 throw new SecurityException( 13916 "addPersistentPreferredActivity can only be run by the system"); 13917 } 13918 if (filter.countActions() == 0) { 13919 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13920 return; 13921 } 13922 synchronized (mPackages) { 13923 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 13924 " :"); 13925 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13926 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 13927 new PersistentPreferredActivity(filter, activity)); 13928 scheduleWritePackageRestrictionsLocked(userId); 13929 } 13930 } 13931 13932 @Override 13933 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 13934 int callingUid = Binder.getCallingUid(); 13935 if (callingUid != Process.SYSTEM_UID) { 13936 throw new SecurityException( 13937 "clearPackagePersistentPreferredActivities can only be run by the system"); 13938 } 13939 ArrayList<PersistentPreferredActivity> removed = null; 13940 boolean changed = false; 13941 synchronized (mPackages) { 13942 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 13943 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 13944 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 13945 .valueAt(i); 13946 if (userId != thisUserId) { 13947 continue; 13948 } 13949 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 13950 while (it.hasNext()) { 13951 PersistentPreferredActivity ppa = it.next(); 13952 // Mark entry for removal only if it matches the package name. 13953 if (ppa.mComponent.getPackageName().equals(packageName)) { 13954 if (removed == null) { 13955 removed = new ArrayList<PersistentPreferredActivity>(); 13956 } 13957 removed.add(ppa); 13958 } 13959 } 13960 if (removed != null) { 13961 for (int j=0; j<removed.size(); j++) { 13962 PersistentPreferredActivity ppa = removed.get(j); 13963 ppir.removeFilter(ppa); 13964 } 13965 changed = true; 13966 } 13967 } 13968 13969 if (changed) { 13970 scheduleWritePackageRestrictionsLocked(userId); 13971 } 13972 } 13973 } 13974 13975 /** 13976 * Common machinery for picking apart a restored XML blob and passing 13977 * it to a caller-supplied functor to be applied to the running system. 13978 */ 13979 private void restoreFromXml(XmlPullParser parser, int userId, 13980 String expectedStartTag, BlobXmlRestorer functor) 13981 throws IOException, XmlPullParserException { 13982 int type; 13983 while ((type = parser.next()) != XmlPullParser.START_TAG 13984 && type != XmlPullParser.END_DOCUMENT) { 13985 } 13986 if (type != XmlPullParser.START_TAG) { 13987 // oops didn't find a start tag?! 13988 if (DEBUG_BACKUP) { 13989 Slog.e(TAG, "Didn't find start tag during restore"); 13990 } 13991 return; 13992 } 13993 13994 // this is supposed to be TAG_PREFERRED_BACKUP 13995 if (!expectedStartTag.equals(parser.getName())) { 13996 if (DEBUG_BACKUP) { 13997 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 13998 } 13999 return; 14000 } 14001 14002 // skip interfering stuff, then we're aligned with the backing implementation 14003 while ((type = parser.next()) == XmlPullParser.TEXT) { } 14004 functor.apply(parser, userId); 14005 } 14006 14007 private interface BlobXmlRestorer { 14008 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 14009 } 14010 14011 /** 14012 * Non-Binder method, support for the backup/restore mechanism: write the 14013 * full set of preferred activities in its canonical XML format. Returns the 14014 * XML output as a byte array, or null if there is none. 14015 */ 14016 @Override 14017 public byte[] getPreferredActivityBackup(int userId) { 14018 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14019 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 14020 } 14021 14022 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14023 try { 14024 final XmlSerializer serializer = new FastXmlSerializer(); 14025 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14026 serializer.startDocument(null, true); 14027 serializer.startTag(null, TAG_PREFERRED_BACKUP); 14028 14029 synchronized (mPackages) { 14030 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 14031 } 14032 14033 serializer.endTag(null, TAG_PREFERRED_BACKUP); 14034 serializer.endDocument(); 14035 serializer.flush(); 14036 } catch (Exception e) { 14037 if (DEBUG_BACKUP) { 14038 Slog.e(TAG, "Unable to write preferred activities for backup", e); 14039 } 14040 return null; 14041 } 14042 14043 return dataStream.toByteArray(); 14044 } 14045 14046 @Override 14047 public void restorePreferredActivities(byte[] backup, int userId) { 14048 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14049 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14050 } 14051 14052 try { 14053 final XmlPullParser parser = Xml.newPullParser(); 14054 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14055 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 14056 new BlobXmlRestorer() { 14057 @Override 14058 public void apply(XmlPullParser parser, int userId) 14059 throws XmlPullParserException, IOException { 14060 synchronized (mPackages) { 14061 mSettings.readPreferredActivitiesLPw(parser, userId); 14062 } 14063 } 14064 } ); 14065 } catch (Exception e) { 14066 if (DEBUG_BACKUP) { 14067 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14068 } 14069 } 14070 } 14071 14072 /** 14073 * Non-Binder method, support for the backup/restore mechanism: write the 14074 * default browser (etc) settings in its canonical XML format. Returns the default 14075 * browser XML representation as a byte array, or null if there is none. 14076 */ 14077 @Override 14078 public byte[] getDefaultAppsBackup(int userId) { 14079 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14080 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 14081 } 14082 14083 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14084 try { 14085 final XmlSerializer serializer = new FastXmlSerializer(); 14086 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14087 serializer.startDocument(null, true); 14088 serializer.startTag(null, TAG_DEFAULT_APPS); 14089 14090 synchronized (mPackages) { 14091 mSettings.writeDefaultAppsLPr(serializer, userId); 14092 } 14093 14094 serializer.endTag(null, TAG_DEFAULT_APPS); 14095 serializer.endDocument(); 14096 serializer.flush(); 14097 } catch (Exception e) { 14098 if (DEBUG_BACKUP) { 14099 Slog.e(TAG, "Unable to write default apps for backup", e); 14100 } 14101 return null; 14102 } 14103 14104 return dataStream.toByteArray(); 14105 } 14106 14107 @Override 14108 public void restoreDefaultApps(byte[] backup, int userId) { 14109 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14110 throw new SecurityException("Only the system may call restoreDefaultApps()"); 14111 } 14112 14113 try { 14114 final XmlPullParser parser = Xml.newPullParser(); 14115 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14116 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 14117 new BlobXmlRestorer() { 14118 @Override 14119 public void apply(XmlPullParser parser, int userId) 14120 throws XmlPullParserException, IOException { 14121 synchronized (mPackages) { 14122 mSettings.readDefaultAppsLPw(parser, userId); 14123 } 14124 } 14125 } ); 14126 } catch (Exception e) { 14127 if (DEBUG_BACKUP) { 14128 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 14129 } 14130 } 14131 } 14132 14133 @Override 14134 public byte[] getIntentFilterVerificationBackup(int userId) { 14135 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14136 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 14137 } 14138 14139 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14140 try { 14141 final XmlSerializer serializer = new FastXmlSerializer(); 14142 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14143 serializer.startDocument(null, true); 14144 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 14145 14146 synchronized (mPackages) { 14147 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 14148 } 14149 14150 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 14151 serializer.endDocument(); 14152 serializer.flush(); 14153 } catch (Exception e) { 14154 if (DEBUG_BACKUP) { 14155 Slog.e(TAG, "Unable to write default apps for backup", e); 14156 } 14157 return null; 14158 } 14159 14160 return dataStream.toByteArray(); 14161 } 14162 14163 @Override 14164 public void restoreIntentFilterVerification(byte[] backup, int userId) { 14165 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14166 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14167 } 14168 14169 try { 14170 final XmlPullParser parser = Xml.newPullParser(); 14171 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14172 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 14173 new BlobXmlRestorer() { 14174 @Override 14175 public void apply(XmlPullParser parser, int userId) 14176 throws XmlPullParserException, IOException { 14177 synchronized (mPackages) { 14178 mSettings.readAllDomainVerificationsLPr(parser, userId); 14179 mSettings.writeLPr(); 14180 } 14181 } 14182 } ); 14183 } catch (Exception e) { 14184 if (DEBUG_BACKUP) { 14185 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14186 } 14187 } 14188 } 14189 14190 @Override 14191 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 14192 int sourceUserId, int targetUserId, int flags) { 14193 mContext.enforceCallingOrSelfPermission( 14194 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14195 int callingUid = Binder.getCallingUid(); 14196 enforceOwnerRights(ownerPackage, callingUid); 14197 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14198 if (intentFilter.countActions() == 0) { 14199 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 14200 return; 14201 } 14202 synchronized (mPackages) { 14203 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 14204 ownerPackage, targetUserId, flags); 14205 CrossProfileIntentResolver resolver = 14206 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14207 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 14208 // We have all those whose filter is equal. Now checking if the rest is equal as well. 14209 if (existing != null) { 14210 int size = existing.size(); 14211 for (int i = 0; i < size; i++) { 14212 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 14213 return; 14214 } 14215 } 14216 } 14217 resolver.addFilter(newFilter); 14218 scheduleWritePackageRestrictionsLocked(sourceUserId); 14219 } 14220 } 14221 14222 @Override 14223 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 14224 mContext.enforceCallingOrSelfPermission( 14225 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14226 int callingUid = Binder.getCallingUid(); 14227 enforceOwnerRights(ownerPackage, callingUid); 14228 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14229 synchronized (mPackages) { 14230 CrossProfileIntentResolver resolver = 14231 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14232 ArraySet<CrossProfileIntentFilter> set = 14233 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 14234 for (CrossProfileIntentFilter filter : set) { 14235 if (filter.getOwnerPackage().equals(ownerPackage)) { 14236 resolver.removeFilter(filter); 14237 } 14238 } 14239 scheduleWritePackageRestrictionsLocked(sourceUserId); 14240 } 14241 } 14242 14243 // Enforcing that callingUid is owning pkg on userId 14244 private void enforceOwnerRights(String pkg, int callingUid) { 14245 // The system owns everything. 14246 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 14247 return; 14248 } 14249 int callingUserId = UserHandle.getUserId(callingUid); 14250 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 14251 if (pi == null) { 14252 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 14253 + callingUserId); 14254 } 14255 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 14256 throw new SecurityException("Calling uid " + callingUid 14257 + " does not own package " + pkg); 14258 } 14259 } 14260 14261 @Override 14262 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 14263 Intent intent = new Intent(Intent.ACTION_MAIN); 14264 intent.addCategory(Intent.CATEGORY_HOME); 14265 14266 final int callingUserId = UserHandle.getCallingUserId(); 14267 List<ResolveInfo> list = queryIntentActivities(intent, null, 14268 PackageManager.GET_META_DATA, callingUserId); 14269 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 14270 true, false, false, callingUserId); 14271 14272 allHomeCandidates.clear(); 14273 if (list != null) { 14274 for (ResolveInfo ri : list) { 14275 allHomeCandidates.add(ri); 14276 } 14277 } 14278 return (preferred == null || preferred.activityInfo == null) 14279 ? null 14280 : new ComponentName(preferred.activityInfo.packageName, 14281 preferred.activityInfo.name); 14282 } 14283 14284 @Override 14285 public void setApplicationEnabledSetting(String appPackageName, 14286 int newState, int flags, int userId, String callingPackage) { 14287 if (!sUserManager.exists(userId)) return; 14288 if (callingPackage == null) { 14289 callingPackage = Integer.toString(Binder.getCallingUid()); 14290 } 14291 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 14292 } 14293 14294 @Override 14295 public void setComponentEnabledSetting(ComponentName componentName, 14296 int newState, int flags, int userId) { 14297 if (!sUserManager.exists(userId)) return; 14298 setEnabledSetting(componentName.getPackageName(), 14299 componentName.getClassName(), newState, flags, userId, null); 14300 } 14301 14302 private void setEnabledSetting(final String packageName, String className, int newState, 14303 final int flags, int userId, String callingPackage) { 14304 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 14305 || newState == COMPONENT_ENABLED_STATE_ENABLED 14306 || newState == COMPONENT_ENABLED_STATE_DISABLED 14307 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 14308 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 14309 throw new IllegalArgumentException("Invalid new component state: " 14310 + newState); 14311 } 14312 PackageSetting pkgSetting; 14313 final int uid = Binder.getCallingUid(); 14314 final int permission = mContext.checkCallingOrSelfPermission( 14315 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14316 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 14317 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14318 boolean sendNow = false; 14319 boolean isApp = (className == null); 14320 String componentName = isApp ? packageName : className; 14321 int packageUid = -1; 14322 ArrayList<String> components; 14323 14324 // writer 14325 synchronized (mPackages) { 14326 pkgSetting = mSettings.mPackages.get(packageName); 14327 if (pkgSetting == null) { 14328 if (className == null) { 14329 throw new IllegalArgumentException( 14330 "Unknown package: " + packageName); 14331 } 14332 throw new IllegalArgumentException( 14333 "Unknown component: " + packageName 14334 + "/" + className); 14335 } 14336 // Allow root and verify that userId is not being specified by a different user 14337 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 14338 throw new SecurityException( 14339 "Permission Denial: attempt to change component state from pid=" 14340 + Binder.getCallingPid() 14341 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 14342 } 14343 if (className == null) { 14344 // We're dealing with an application/package level state change 14345 if (pkgSetting.getEnabled(userId) == newState) { 14346 // Nothing to do 14347 return; 14348 } 14349 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 14350 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 14351 // Don't care about who enables an app. 14352 callingPackage = null; 14353 } 14354 pkgSetting.setEnabled(newState, userId, callingPackage); 14355 // pkgSetting.pkg.mSetEnabled = newState; 14356 } else { 14357 // We're dealing with a component level state change 14358 // First, verify that this is a valid class name. 14359 PackageParser.Package pkg = pkgSetting.pkg; 14360 if (pkg == null || !pkg.hasComponentClassName(className)) { 14361 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 14362 throw new IllegalArgumentException("Component class " + className 14363 + " does not exist in " + packageName); 14364 } else { 14365 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 14366 + className + " does not exist in " + packageName); 14367 } 14368 } 14369 switch (newState) { 14370 case COMPONENT_ENABLED_STATE_ENABLED: 14371 if (!pkgSetting.enableComponentLPw(className, userId)) { 14372 return; 14373 } 14374 break; 14375 case COMPONENT_ENABLED_STATE_DISABLED: 14376 if (!pkgSetting.disableComponentLPw(className, userId)) { 14377 return; 14378 } 14379 break; 14380 case COMPONENT_ENABLED_STATE_DEFAULT: 14381 if (!pkgSetting.restoreComponentLPw(className, userId)) { 14382 return; 14383 } 14384 break; 14385 default: 14386 Slog.e(TAG, "Invalid new component state: " + newState); 14387 return; 14388 } 14389 } 14390 scheduleWritePackageRestrictionsLocked(userId); 14391 components = mPendingBroadcasts.get(userId, packageName); 14392 final boolean newPackage = components == null; 14393 if (newPackage) { 14394 components = new ArrayList<String>(); 14395 } 14396 if (!components.contains(componentName)) { 14397 components.add(componentName); 14398 } 14399 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 14400 sendNow = true; 14401 // Purge entry from pending broadcast list if another one exists already 14402 // since we are sending one right away. 14403 mPendingBroadcasts.remove(userId, packageName); 14404 } else { 14405 if (newPackage) { 14406 mPendingBroadcasts.put(userId, packageName, components); 14407 } 14408 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 14409 // Schedule a message 14410 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 14411 } 14412 } 14413 } 14414 14415 long callingId = Binder.clearCallingIdentity(); 14416 try { 14417 if (sendNow) { 14418 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 14419 sendPackageChangedBroadcast(packageName, 14420 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 14421 } 14422 } finally { 14423 Binder.restoreCallingIdentity(callingId); 14424 } 14425 } 14426 14427 private void sendPackageChangedBroadcast(String packageName, 14428 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 14429 if (DEBUG_INSTALL) 14430 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 14431 + componentNames); 14432 Bundle extras = new Bundle(4); 14433 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 14434 String nameList[] = new String[componentNames.size()]; 14435 componentNames.toArray(nameList); 14436 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 14437 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 14438 extras.putInt(Intent.EXTRA_UID, packageUid); 14439 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 14440 new int[] {UserHandle.getUserId(packageUid)}); 14441 } 14442 14443 @Override 14444 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 14445 if (!sUserManager.exists(userId)) return; 14446 final int uid = Binder.getCallingUid(); 14447 final int permission = mContext.checkCallingOrSelfPermission( 14448 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14449 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14450 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 14451 // writer 14452 synchronized (mPackages) { 14453 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 14454 allowedByPermission, uid, userId)) { 14455 scheduleWritePackageRestrictionsLocked(userId); 14456 } 14457 } 14458 } 14459 14460 @Override 14461 public String getInstallerPackageName(String packageName) { 14462 // reader 14463 synchronized (mPackages) { 14464 return mSettings.getInstallerPackageNameLPr(packageName); 14465 } 14466 } 14467 14468 @Override 14469 public int getApplicationEnabledSetting(String packageName, int userId) { 14470 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14471 int uid = Binder.getCallingUid(); 14472 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 14473 // reader 14474 synchronized (mPackages) { 14475 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 14476 } 14477 } 14478 14479 @Override 14480 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 14481 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14482 int uid = Binder.getCallingUid(); 14483 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 14484 // reader 14485 synchronized (mPackages) { 14486 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 14487 } 14488 } 14489 14490 @Override 14491 public void enterSafeMode() { 14492 enforceSystemOrRoot("Only the system can request entering safe mode"); 14493 14494 if (!mSystemReady) { 14495 mSafeMode = true; 14496 } 14497 } 14498 14499 @Override 14500 public void systemReady() { 14501 mSystemReady = true; 14502 14503 // Read the compatibilty setting when the system is ready. 14504 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 14505 mContext.getContentResolver(), 14506 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 14507 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 14508 if (DEBUG_SETTINGS) { 14509 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 14510 } 14511 14512 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 14513 14514 synchronized (mPackages) { 14515 // Verify that all of the preferred activity components actually 14516 // exist. It is possible for applications to be updated and at 14517 // that point remove a previously declared activity component that 14518 // had been set as a preferred activity. We try to clean this up 14519 // the next time we encounter that preferred activity, but it is 14520 // possible for the user flow to never be able to return to that 14521 // situation so here we do a sanity check to make sure we haven't 14522 // left any junk around. 14523 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 14524 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14525 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14526 removed.clear(); 14527 for (PreferredActivity pa : pir.filterSet()) { 14528 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 14529 removed.add(pa); 14530 } 14531 } 14532 if (removed.size() > 0) { 14533 for (int r=0; r<removed.size(); r++) { 14534 PreferredActivity pa = removed.get(r); 14535 Slog.w(TAG, "Removing dangling preferred activity: " 14536 + pa.mPref.mComponent); 14537 pir.removeFilter(pa); 14538 } 14539 mSettings.writePackageRestrictionsLPr( 14540 mSettings.mPreferredActivities.keyAt(i)); 14541 } 14542 } 14543 14544 for (int userId : UserManagerService.getInstance().getUserIds()) { 14545 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 14546 grantPermissionsUserIds = ArrayUtils.appendInt( 14547 grantPermissionsUserIds, userId); 14548 } 14549 } 14550 } 14551 sUserManager.systemReady(); 14552 14553 // If we upgraded grant all default permissions before kicking off. 14554 for (int userId : grantPermissionsUserIds) { 14555 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 14556 } 14557 14558 // Kick off any messages waiting for system ready 14559 if (mPostSystemReadyMessages != null) { 14560 for (Message msg : mPostSystemReadyMessages) { 14561 msg.sendToTarget(); 14562 } 14563 mPostSystemReadyMessages = null; 14564 } 14565 14566 // Watch for external volumes that come and go over time 14567 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14568 storage.registerListener(mStorageListener); 14569 14570 mInstallerService.systemReady(); 14571 mPackageDexOptimizer.systemReady(); 14572 14573 MountServiceInternal mountServiceInternal = LocalServices.getService( 14574 MountServiceInternal.class); 14575 mountServiceInternal.addExternalStoragePolicy( 14576 new MountServiceInternal.ExternalStorageMountPolicy() { 14577 @Override 14578 public int getMountMode(int uid, String packageName) { 14579 if (Process.isIsolated(uid)) { 14580 return Zygote.MOUNT_EXTERNAL_NONE; 14581 } 14582 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 14583 return Zygote.MOUNT_EXTERNAL_DEFAULT; 14584 } 14585 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 14586 return Zygote.MOUNT_EXTERNAL_DEFAULT; 14587 } 14588 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 14589 return Zygote.MOUNT_EXTERNAL_READ; 14590 } 14591 return Zygote.MOUNT_EXTERNAL_WRITE; 14592 } 14593 14594 @Override 14595 public boolean hasExternalStorage(int uid, String packageName) { 14596 return true; 14597 } 14598 }); 14599 } 14600 14601 @Override 14602 public boolean isSafeMode() { 14603 return mSafeMode; 14604 } 14605 14606 @Override 14607 public boolean hasSystemUidErrors() { 14608 return mHasSystemUidErrors; 14609 } 14610 14611 static String arrayToString(int[] array) { 14612 StringBuffer buf = new StringBuffer(128); 14613 buf.append('['); 14614 if (array != null) { 14615 for (int i=0; i<array.length; i++) { 14616 if (i > 0) buf.append(", "); 14617 buf.append(array[i]); 14618 } 14619 } 14620 buf.append(']'); 14621 return buf.toString(); 14622 } 14623 14624 static class DumpState { 14625 public static final int DUMP_LIBS = 1 << 0; 14626 public static final int DUMP_FEATURES = 1 << 1; 14627 public static final int DUMP_RESOLVERS = 1 << 2; 14628 public static final int DUMP_PERMISSIONS = 1 << 3; 14629 public static final int DUMP_PACKAGES = 1 << 4; 14630 public static final int DUMP_SHARED_USERS = 1 << 5; 14631 public static final int DUMP_MESSAGES = 1 << 6; 14632 public static final int DUMP_PROVIDERS = 1 << 7; 14633 public static final int DUMP_VERIFIERS = 1 << 8; 14634 public static final int DUMP_PREFERRED = 1 << 9; 14635 public static final int DUMP_PREFERRED_XML = 1 << 10; 14636 public static final int DUMP_KEYSETS = 1 << 11; 14637 public static final int DUMP_VERSION = 1 << 12; 14638 public static final int DUMP_INSTALLS = 1 << 13; 14639 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 14640 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 14641 14642 public static final int OPTION_SHOW_FILTERS = 1 << 0; 14643 14644 private int mTypes; 14645 14646 private int mOptions; 14647 14648 private boolean mTitlePrinted; 14649 14650 private SharedUserSetting mSharedUser; 14651 14652 public boolean isDumping(int type) { 14653 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 14654 return true; 14655 } 14656 14657 return (mTypes & type) != 0; 14658 } 14659 14660 public void setDump(int type) { 14661 mTypes |= type; 14662 } 14663 14664 public boolean isOptionEnabled(int option) { 14665 return (mOptions & option) != 0; 14666 } 14667 14668 public void setOptionEnabled(int option) { 14669 mOptions |= option; 14670 } 14671 14672 public boolean onTitlePrinted() { 14673 final boolean printed = mTitlePrinted; 14674 mTitlePrinted = true; 14675 return printed; 14676 } 14677 14678 public boolean getTitlePrinted() { 14679 return mTitlePrinted; 14680 } 14681 14682 public void setTitlePrinted(boolean enabled) { 14683 mTitlePrinted = enabled; 14684 } 14685 14686 public SharedUserSetting getSharedUser() { 14687 return mSharedUser; 14688 } 14689 14690 public void setSharedUser(SharedUserSetting user) { 14691 mSharedUser = user; 14692 } 14693 } 14694 14695 @Override 14696 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 14697 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 14698 != PackageManager.PERMISSION_GRANTED) { 14699 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 14700 + Binder.getCallingPid() 14701 + ", uid=" + Binder.getCallingUid() 14702 + " without permission " 14703 + android.Manifest.permission.DUMP); 14704 return; 14705 } 14706 14707 DumpState dumpState = new DumpState(); 14708 boolean fullPreferred = false; 14709 boolean checkin = false; 14710 14711 String packageName = null; 14712 ArraySet<String> permissionNames = null; 14713 14714 int opti = 0; 14715 while (opti < args.length) { 14716 String opt = args[opti]; 14717 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 14718 break; 14719 } 14720 opti++; 14721 14722 if ("-a".equals(opt)) { 14723 // Right now we only know how to print all. 14724 } else if ("-h".equals(opt)) { 14725 pw.println("Package manager dump options:"); 14726 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 14727 pw.println(" --checkin: dump for a checkin"); 14728 pw.println(" -f: print details of intent filters"); 14729 pw.println(" -h: print this help"); 14730 pw.println(" cmd may be one of:"); 14731 pw.println(" l[ibraries]: list known shared libraries"); 14732 pw.println(" f[ibraries]: list device features"); 14733 pw.println(" k[eysets]: print known keysets"); 14734 pw.println(" r[esolvers]: dump intent resolvers"); 14735 pw.println(" perm[issions]: dump permissions"); 14736 pw.println(" permission [name ...]: dump declaration and use of given permission"); 14737 pw.println(" pref[erred]: print preferred package settings"); 14738 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 14739 pw.println(" prov[iders]: dump content providers"); 14740 pw.println(" p[ackages]: dump installed packages"); 14741 pw.println(" s[hared-users]: dump shared user IDs"); 14742 pw.println(" m[essages]: print collected runtime messages"); 14743 pw.println(" v[erifiers]: print package verifier info"); 14744 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 14745 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 14746 pw.println(" version: print database version info"); 14747 pw.println(" write: write current settings now"); 14748 pw.println(" installs: details about install sessions"); 14749 pw.println(" <package.name>: info about given package"); 14750 return; 14751 } else if ("--checkin".equals(opt)) { 14752 checkin = true; 14753 } else if ("-f".equals(opt)) { 14754 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14755 } else { 14756 pw.println("Unknown argument: " + opt + "; use -h for help"); 14757 } 14758 } 14759 14760 // Is the caller requesting to dump a particular piece of data? 14761 if (opti < args.length) { 14762 String cmd = args[opti]; 14763 opti++; 14764 // Is this a package name? 14765 if ("android".equals(cmd) || cmd.contains(".")) { 14766 packageName = cmd; 14767 // When dumping a single package, we always dump all of its 14768 // filter information since the amount of data will be reasonable. 14769 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14770 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 14771 dumpState.setDump(DumpState.DUMP_LIBS); 14772 } else if ("f".equals(cmd) || "features".equals(cmd)) { 14773 dumpState.setDump(DumpState.DUMP_FEATURES); 14774 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 14775 dumpState.setDump(DumpState.DUMP_RESOLVERS); 14776 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 14777 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 14778 } else if ("permission".equals(cmd)) { 14779 if (opti >= args.length) { 14780 pw.println("Error: permission requires permission name"); 14781 return; 14782 } 14783 permissionNames = new ArraySet<>(); 14784 while (opti < args.length) { 14785 permissionNames.add(args[opti]); 14786 opti++; 14787 } 14788 dumpState.setDump(DumpState.DUMP_PERMISSIONS 14789 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 14790 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 14791 dumpState.setDump(DumpState.DUMP_PREFERRED); 14792 } else if ("preferred-xml".equals(cmd)) { 14793 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 14794 if (opti < args.length && "--full".equals(args[opti])) { 14795 fullPreferred = true; 14796 opti++; 14797 } 14798 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 14799 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 14800 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 14801 dumpState.setDump(DumpState.DUMP_PACKAGES); 14802 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 14803 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 14804 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 14805 dumpState.setDump(DumpState.DUMP_PROVIDERS); 14806 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 14807 dumpState.setDump(DumpState.DUMP_MESSAGES); 14808 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 14809 dumpState.setDump(DumpState.DUMP_VERIFIERS); 14810 } else if ("i".equals(cmd) || "ifv".equals(cmd) 14811 || "intent-filter-verifiers".equals(cmd)) { 14812 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 14813 } else if ("version".equals(cmd)) { 14814 dumpState.setDump(DumpState.DUMP_VERSION); 14815 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 14816 dumpState.setDump(DumpState.DUMP_KEYSETS); 14817 } else if ("installs".equals(cmd)) { 14818 dumpState.setDump(DumpState.DUMP_INSTALLS); 14819 } else if ("write".equals(cmd)) { 14820 synchronized (mPackages) { 14821 mSettings.writeLPr(); 14822 pw.println("Settings written."); 14823 return; 14824 } 14825 } 14826 } 14827 14828 if (checkin) { 14829 pw.println("vers,1"); 14830 } 14831 14832 // reader 14833 synchronized (mPackages) { 14834 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 14835 if (!checkin) { 14836 if (dumpState.onTitlePrinted()) 14837 pw.println(); 14838 pw.println("Database versions:"); 14839 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 14840 } 14841 } 14842 14843 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 14844 if (!checkin) { 14845 if (dumpState.onTitlePrinted()) 14846 pw.println(); 14847 pw.println("Verifiers:"); 14848 pw.print(" Required: "); 14849 pw.print(mRequiredVerifierPackage); 14850 pw.print(" (uid="); 14851 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 14852 pw.println(")"); 14853 } else if (mRequiredVerifierPackage != null) { 14854 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 14855 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 14856 } 14857 } 14858 14859 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 14860 packageName == null) { 14861 if (mIntentFilterVerifierComponent != null) { 14862 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 14863 if (!checkin) { 14864 if (dumpState.onTitlePrinted()) 14865 pw.println(); 14866 pw.println("Intent Filter Verifier:"); 14867 pw.print(" Using: "); 14868 pw.print(verifierPackageName); 14869 pw.print(" (uid="); 14870 pw.print(getPackageUid(verifierPackageName, 0)); 14871 pw.println(")"); 14872 } else if (verifierPackageName != null) { 14873 pw.print("ifv,"); pw.print(verifierPackageName); 14874 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 14875 } 14876 } else { 14877 pw.println(); 14878 pw.println("No Intent Filter Verifier available!"); 14879 } 14880 } 14881 14882 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 14883 boolean printedHeader = false; 14884 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 14885 while (it.hasNext()) { 14886 String name = it.next(); 14887 SharedLibraryEntry ent = mSharedLibraries.get(name); 14888 if (!checkin) { 14889 if (!printedHeader) { 14890 if (dumpState.onTitlePrinted()) 14891 pw.println(); 14892 pw.println("Libraries:"); 14893 printedHeader = true; 14894 } 14895 pw.print(" "); 14896 } else { 14897 pw.print("lib,"); 14898 } 14899 pw.print(name); 14900 if (!checkin) { 14901 pw.print(" -> "); 14902 } 14903 if (ent.path != null) { 14904 if (!checkin) { 14905 pw.print("(jar) "); 14906 pw.print(ent.path); 14907 } else { 14908 pw.print(",jar,"); 14909 pw.print(ent.path); 14910 } 14911 } else { 14912 if (!checkin) { 14913 pw.print("(apk) "); 14914 pw.print(ent.apk); 14915 } else { 14916 pw.print(",apk,"); 14917 pw.print(ent.apk); 14918 } 14919 } 14920 pw.println(); 14921 } 14922 } 14923 14924 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 14925 if (dumpState.onTitlePrinted()) 14926 pw.println(); 14927 if (!checkin) { 14928 pw.println("Features:"); 14929 } 14930 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 14931 while (it.hasNext()) { 14932 String name = it.next(); 14933 if (!checkin) { 14934 pw.print(" "); 14935 } else { 14936 pw.print("feat,"); 14937 } 14938 pw.println(name); 14939 } 14940 } 14941 14942 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 14943 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 14944 : "Activity Resolver Table:", " ", packageName, 14945 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14946 dumpState.setTitlePrinted(true); 14947 } 14948 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 14949 : "Receiver Resolver Table:", " ", packageName, 14950 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14951 dumpState.setTitlePrinted(true); 14952 } 14953 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 14954 : "Service Resolver Table:", " ", packageName, 14955 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14956 dumpState.setTitlePrinted(true); 14957 } 14958 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 14959 : "Provider Resolver Table:", " ", packageName, 14960 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14961 dumpState.setTitlePrinted(true); 14962 } 14963 } 14964 14965 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 14966 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14967 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14968 int user = mSettings.mPreferredActivities.keyAt(i); 14969 if (pir.dump(pw, 14970 dumpState.getTitlePrinted() 14971 ? "\nPreferred Activities User " + user + ":" 14972 : "Preferred Activities User " + user + ":", " ", 14973 packageName, true, false)) { 14974 dumpState.setTitlePrinted(true); 14975 } 14976 } 14977 } 14978 14979 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 14980 pw.flush(); 14981 FileOutputStream fout = new FileOutputStream(fd); 14982 BufferedOutputStream str = new BufferedOutputStream(fout); 14983 XmlSerializer serializer = new FastXmlSerializer(); 14984 try { 14985 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 14986 serializer.startDocument(null, true); 14987 serializer.setFeature( 14988 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 14989 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 14990 serializer.endDocument(); 14991 serializer.flush(); 14992 } catch (IllegalArgumentException e) { 14993 pw.println("Failed writing: " + e); 14994 } catch (IllegalStateException e) { 14995 pw.println("Failed writing: " + e); 14996 } catch (IOException e) { 14997 pw.println("Failed writing: " + e); 14998 } 14999 } 15000 15001 if (!checkin 15002 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 15003 && packageName == null) { 15004 pw.println(); 15005 int count = mSettings.mPackages.size(); 15006 if (count == 0) { 15007 pw.println("No applications!"); 15008 pw.println(); 15009 } else { 15010 final String prefix = " "; 15011 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 15012 if (allPackageSettings.size() == 0) { 15013 pw.println("No domain preferred apps!"); 15014 pw.println(); 15015 } else { 15016 pw.println("App verification status:"); 15017 pw.println(); 15018 count = 0; 15019 for (PackageSetting ps : allPackageSettings) { 15020 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 15021 if (ivi == null || ivi.getPackageName() == null) continue; 15022 pw.println(prefix + "Package: " + ivi.getPackageName()); 15023 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 15024 pw.println(prefix + "Status: " + ivi.getStatusString()); 15025 pw.println(); 15026 count++; 15027 } 15028 if (count == 0) { 15029 pw.println(prefix + "No app verification established."); 15030 pw.println(); 15031 } 15032 for (int userId : sUserManager.getUserIds()) { 15033 pw.println("App linkages for user " + userId + ":"); 15034 pw.println(); 15035 count = 0; 15036 for (PackageSetting ps : allPackageSettings) { 15037 final long status = ps.getDomainVerificationStatusForUser(userId); 15038 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 15039 continue; 15040 } 15041 pw.println(prefix + "Package: " + ps.name); 15042 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 15043 String statusStr = IntentFilterVerificationInfo. 15044 getStatusStringFromValue(status); 15045 pw.println(prefix + "Status: " + statusStr); 15046 pw.println(); 15047 count++; 15048 } 15049 if (count == 0) { 15050 pw.println(prefix + "No configured app linkages."); 15051 pw.println(); 15052 } 15053 } 15054 } 15055 } 15056 } 15057 15058 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 15059 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 15060 if (packageName == null && permissionNames == null) { 15061 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 15062 if (iperm == 0) { 15063 if (dumpState.onTitlePrinted()) 15064 pw.println(); 15065 pw.println("AppOp Permissions:"); 15066 } 15067 pw.print(" AppOp Permission "); 15068 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 15069 pw.println(":"); 15070 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 15071 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 15072 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 15073 } 15074 } 15075 } 15076 } 15077 15078 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 15079 boolean printedSomething = false; 15080 for (PackageParser.Provider p : mProviders.mProviders.values()) { 15081 if (packageName != null && !packageName.equals(p.info.packageName)) { 15082 continue; 15083 } 15084 if (!printedSomething) { 15085 if (dumpState.onTitlePrinted()) 15086 pw.println(); 15087 pw.println("Registered ContentProviders:"); 15088 printedSomething = true; 15089 } 15090 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 15091 pw.print(" "); pw.println(p.toString()); 15092 } 15093 printedSomething = false; 15094 for (Map.Entry<String, PackageParser.Provider> entry : 15095 mProvidersByAuthority.entrySet()) { 15096 PackageParser.Provider p = entry.getValue(); 15097 if (packageName != null && !packageName.equals(p.info.packageName)) { 15098 continue; 15099 } 15100 if (!printedSomething) { 15101 if (dumpState.onTitlePrinted()) 15102 pw.println(); 15103 pw.println("ContentProvider Authorities:"); 15104 printedSomething = true; 15105 } 15106 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 15107 pw.print(" "); pw.println(p.toString()); 15108 if (p.info != null && p.info.applicationInfo != null) { 15109 final String appInfo = p.info.applicationInfo.toString(); 15110 pw.print(" applicationInfo="); pw.println(appInfo); 15111 } 15112 } 15113 } 15114 15115 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 15116 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 15117 } 15118 15119 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 15120 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 15121 } 15122 15123 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 15124 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 15125 } 15126 15127 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 15128 // XXX should handle packageName != null by dumping only install data that 15129 // the given package is involved with. 15130 if (dumpState.onTitlePrinted()) pw.println(); 15131 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 15132 } 15133 15134 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 15135 if (dumpState.onTitlePrinted()) pw.println(); 15136 mSettings.dumpReadMessagesLPr(pw, dumpState); 15137 15138 pw.println(); 15139 pw.println("Package warning messages:"); 15140 BufferedReader in = null; 15141 String line = null; 15142 try { 15143 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15144 while ((line = in.readLine()) != null) { 15145 if (line.contains("ignored: updated version")) continue; 15146 pw.println(line); 15147 } 15148 } catch (IOException ignored) { 15149 } finally { 15150 IoUtils.closeQuietly(in); 15151 } 15152 } 15153 15154 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 15155 BufferedReader in = null; 15156 String line = null; 15157 try { 15158 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15159 while ((line = in.readLine()) != null) { 15160 if (line.contains("ignored: updated version")) continue; 15161 pw.print("msg,"); 15162 pw.println(line); 15163 } 15164 } catch (IOException ignored) { 15165 } finally { 15166 IoUtils.closeQuietly(in); 15167 } 15168 } 15169 } 15170 } 15171 15172 private String dumpDomainString(String packageName) { 15173 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName); 15174 List<IntentFilter> filters = getAllIntentFilters(packageName); 15175 15176 ArraySet<String> result = new ArraySet<>(); 15177 if (iviList.size() > 0) { 15178 for (IntentFilterVerificationInfo ivi : iviList) { 15179 for (String host : ivi.getDomains()) { 15180 result.add(host); 15181 } 15182 } 15183 } 15184 if (filters != null && filters.size() > 0) { 15185 for (IntentFilter filter : filters) { 15186 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 15187 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 15188 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 15189 result.addAll(filter.getHostsList()); 15190 } 15191 } 15192 } 15193 15194 StringBuilder sb = new StringBuilder(result.size() * 16); 15195 for (String domain : result) { 15196 if (sb.length() > 0) sb.append(" "); 15197 sb.append(domain); 15198 } 15199 return sb.toString(); 15200 } 15201 15202 // ------- apps on sdcard specific code ------- 15203 static final boolean DEBUG_SD_INSTALL = false; 15204 15205 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 15206 15207 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 15208 15209 private boolean mMediaMounted = false; 15210 15211 static String getEncryptKey() { 15212 try { 15213 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 15214 SD_ENCRYPTION_KEYSTORE_NAME); 15215 if (sdEncKey == null) { 15216 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 15217 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 15218 if (sdEncKey == null) { 15219 Slog.e(TAG, "Failed to create encryption keys"); 15220 return null; 15221 } 15222 } 15223 return sdEncKey; 15224 } catch (NoSuchAlgorithmException nsae) { 15225 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 15226 return null; 15227 } catch (IOException ioe) { 15228 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 15229 return null; 15230 } 15231 } 15232 15233 /* 15234 * Update media status on PackageManager. 15235 */ 15236 @Override 15237 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 15238 int callingUid = Binder.getCallingUid(); 15239 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 15240 throw new SecurityException("Media status can only be updated by the system"); 15241 } 15242 // reader; this apparently protects mMediaMounted, but should probably 15243 // be a different lock in that case. 15244 synchronized (mPackages) { 15245 Log.i(TAG, "Updating external media status from " 15246 + (mMediaMounted ? "mounted" : "unmounted") + " to " 15247 + (mediaStatus ? "mounted" : "unmounted")); 15248 if (DEBUG_SD_INSTALL) 15249 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 15250 + ", mMediaMounted=" + mMediaMounted); 15251 if (mediaStatus == mMediaMounted) { 15252 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 15253 : 0, -1); 15254 mHandler.sendMessage(msg); 15255 return; 15256 } 15257 mMediaMounted = mediaStatus; 15258 } 15259 // Queue up an async operation since the package installation may take a 15260 // little while. 15261 mHandler.post(new Runnable() { 15262 public void run() { 15263 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 15264 } 15265 }); 15266 } 15267 15268 /** 15269 * Called by MountService when the initial ASECs to scan are available. 15270 * Should block until all the ASEC containers are finished being scanned. 15271 */ 15272 public void scanAvailableAsecs() { 15273 updateExternalMediaStatusInner(true, false, false); 15274 if (mShouldRestoreconData) { 15275 SELinuxMMAC.setRestoreconDone(); 15276 mShouldRestoreconData = false; 15277 } 15278 } 15279 15280 /* 15281 * Collect information of applications on external media, map them against 15282 * existing containers and update information based on current mount status. 15283 * Please note that we always have to report status if reportStatus has been 15284 * set to true especially when unloading packages. 15285 */ 15286 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 15287 boolean externalStorage) { 15288 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 15289 int[] uidArr = EmptyArray.INT; 15290 15291 final String[] list = PackageHelper.getSecureContainerList(); 15292 if (ArrayUtils.isEmpty(list)) { 15293 Log.i(TAG, "No secure containers found"); 15294 } else { 15295 // Process list of secure containers and categorize them 15296 // as active or stale based on their package internal state. 15297 15298 // reader 15299 synchronized (mPackages) { 15300 for (String cid : list) { 15301 // Leave stages untouched for now; installer service owns them 15302 if (PackageInstallerService.isStageName(cid)) continue; 15303 15304 if (DEBUG_SD_INSTALL) 15305 Log.i(TAG, "Processing container " + cid); 15306 String pkgName = getAsecPackageName(cid); 15307 if (pkgName == null) { 15308 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 15309 continue; 15310 } 15311 if (DEBUG_SD_INSTALL) 15312 Log.i(TAG, "Looking for pkg : " + pkgName); 15313 15314 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15315 if (ps == null) { 15316 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 15317 continue; 15318 } 15319 15320 /* 15321 * Skip packages that are not external if we're unmounting 15322 * external storage. 15323 */ 15324 if (externalStorage && !isMounted && !isExternal(ps)) { 15325 continue; 15326 } 15327 15328 final AsecInstallArgs args = new AsecInstallArgs(cid, 15329 getAppDexInstructionSets(ps), ps.isForwardLocked()); 15330 // The package status is changed only if the code path 15331 // matches between settings and the container id. 15332 if (ps.codePathString != null 15333 && ps.codePathString.startsWith(args.getCodePath())) { 15334 if (DEBUG_SD_INSTALL) { 15335 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 15336 + " at code path: " + ps.codePathString); 15337 } 15338 15339 // We do have a valid package installed on sdcard 15340 processCids.put(args, ps.codePathString); 15341 final int uid = ps.appId; 15342 if (uid != -1) { 15343 uidArr = ArrayUtils.appendInt(uidArr, uid); 15344 } 15345 } else { 15346 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 15347 + ps.codePathString); 15348 } 15349 } 15350 } 15351 15352 Arrays.sort(uidArr); 15353 } 15354 15355 // Process packages with valid entries. 15356 if (isMounted) { 15357 if (DEBUG_SD_INSTALL) 15358 Log.i(TAG, "Loading packages"); 15359 loadMediaPackages(processCids, uidArr); 15360 startCleaningPackages(); 15361 mInstallerService.onSecureContainersAvailable(); 15362 } else { 15363 if (DEBUG_SD_INSTALL) 15364 Log.i(TAG, "Unloading packages"); 15365 unloadMediaPackages(processCids, uidArr, reportStatus); 15366 } 15367 } 15368 15369 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15370 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 15371 final int size = infos.size(); 15372 final String[] packageNames = new String[size]; 15373 final int[] packageUids = new int[size]; 15374 for (int i = 0; i < size; i++) { 15375 final ApplicationInfo info = infos.get(i); 15376 packageNames[i] = info.packageName; 15377 packageUids[i] = info.uid; 15378 } 15379 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 15380 finishedReceiver); 15381 } 15382 15383 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15384 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15385 sendResourcesChangedBroadcast(mediaStatus, replacing, 15386 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 15387 } 15388 15389 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15390 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15391 int size = pkgList.length; 15392 if (size > 0) { 15393 // Send broadcasts here 15394 Bundle extras = new Bundle(); 15395 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 15396 if (uidArr != null) { 15397 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 15398 } 15399 if (replacing) { 15400 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 15401 } 15402 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 15403 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 15404 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 15405 } 15406 } 15407 15408 /* 15409 * Look at potentially valid container ids from processCids If package 15410 * information doesn't match the one on record or package scanning fails, 15411 * the cid is added to list of removeCids. We currently don't delete stale 15412 * containers. 15413 */ 15414 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 15415 ArrayList<String> pkgList = new ArrayList<String>(); 15416 Set<AsecInstallArgs> keys = processCids.keySet(); 15417 15418 for (AsecInstallArgs args : keys) { 15419 String codePath = processCids.get(args); 15420 if (DEBUG_SD_INSTALL) 15421 Log.i(TAG, "Loading container : " + args.cid); 15422 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15423 try { 15424 // Make sure there are no container errors first. 15425 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 15426 Slog.e(TAG, "Failed to mount cid : " + args.cid 15427 + " when installing from sdcard"); 15428 continue; 15429 } 15430 // Check code path here. 15431 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 15432 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 15433 + " does not match one in settings " + codePath); 15434 continue; 15435 } 15436 // Parse package 15437 int parseFlags = mDefParseFlags; 15438 if (args.isExternalAsec()) { 15439 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 15440 } 15441 if (args.isFwdLocked()) { 15442 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 15443 } 15444 15445 synchronized (mInstallLock) { 15446 PackageParser.Package pkg = null; 15447 try { 15448 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 15449 } catch (PackageManagerException e) { 15450 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 15451 } 15452 // Scan the package 15453 if (pkg != null) { 15454 /* 15455 * TODO why is the lock being held? doPostInstall is 15456 * called in other places without the lock. This needs 15457 * to be straightened out. 15458 */ 15459 // writer 15460 synchronized (mPackages) { 15461 retCode = PackageManager.INSTALL_SUCCEEDED; 15462 pkgList.add(pkg.packageName); 15463 // Post process args 15464 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 15465 pkg.applicationInfo.uid); 15466 } 15467 } else { 15468 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 15469 } 15470 } 15471 15472 } finally { 15473 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 15474 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 15475 } 15476 } 15477 } 15478 // writer 15479 synchronized (mPackages) { 15480 // If the platform SDK has changed since the last time we booted, 15481 // we need to re-grant app permission to catch any new ones that 15482 // appear. This is really a hack, and means that apps can in some 15483 // cases get permissions that the user didn't initially explicitly 15484 // allow... it would be nice to have some better way to handle 15485 // this situation. 15486 final VersionInfo ver = mSettings.getExternalVersion(); 15487 15488 int updateFlags = UPDATE_PERMISSIONS_ALL; 15489 if (ver.sdkVersion != mSdkVersion) { 15490 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 15491 + mSdkVersion + "; regranting permissions for external"); 15492 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 15493 } 15494 updatePermissionsLPw(null, null, updateFlags); 15495 15496 // Yay, everything is now upgraded 15497 ver.forceCurrent(); 15498 15499 // can downgrade to reader 15500 // Persist settings 15501 mSettings.writeLPr(); 15502 } 15503 // Send a broadcast to let everyone know we are done processing 15504 if (pkgList.size() > 0) { 15505 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 15506 } 15507 } 15508 15509 /* 15510 * Utility method to unload a list of specified containers 15511 */ 15512 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 15513 // Just unmount all valid containers. 15514 for (AsecInstallArgs arg : cidArgs) { 15515 synchronized (mInstallLock) { 15516 arg.doPostDeleteLI(false); 15517 } 15518 } 15519 } 15520 15521 /* 15522 * Unload packages mounted on external media. This involves deleting package 15523 * data from internal structures, sending broadcasts about diabled packages, 15524 * gc'ing to free up references, unmounting all secure containers 15525 * corresponding to packages on external media, and posting a 15526 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 15527 * that we always have to post this message if status has been requested no 15528 * matter what. 15529 */ 15530 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 15531 final boolean reportStatus) { 15532 if (DEBUG_SD_INSTALL) 15533 Log.i(TAG, "unloading media packages"); 15534 ArrayList<String> pkgList = new ArrayList<String>(); 15535 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 15536 final Set<AsecInstallArgs> keys = processCids.keySet(); 15537 for (AsecInstallArgs args : keys) { 15538 String pkgName = args.getPackageName(); 15539 if (DEBUG_SD_INSTALL) 15540 Log.i(TAG, "Trying to unload pkg : " + pkgName); 15541 // Delete package internally 15542 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15543 synchronized (mInstallLock) { 15544 boolean res = deletePackageLI(pkgName, null, false, null, null, 15545 PackageManager.DELETE_KEEP_DATA, outInfo, false); 15546 if (res) { 15547 pkgList.add(pkgName); 15548 } else { 15549 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 15550 failedList.add(args); 15551 } 15552 } 15553 } 15554 15555 // reader 15556 synchronized (mPackages) { 15557 // We didn't update the settings after removing each package; 15558 // write them now for all packages. 15559 mSettings.writeLPr(); 15560 } 15561 15562 // We have to absolutely send UPDATED_MEDIA_STATUS only 15563 // after confirming that all the receivers processed the ordered 15564 // broadcast when packages get disabled, force a gc to clean things up. 15565 // and unload all the containers. 15566 if (pkgList.size() > 0) { 15567 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 15568 new IIntentReceiver.Stub() { 15569 public void performReceive(Intent intent, int resultCode, String data, 15570 Bundle extras, boolean ordered, boolean sticky, 15571 int sendingUser) throws RemoteException { 15572 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 15573 reportStatus ? 1 : 0, 1, keys); 15574 mHandler.sendMessage(msg); 15575 } 15576 }); 15577 } else { 15578 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 15579 keys); 15580 mHandler.sendMessage(msg); 15581 } 15582 } 15583 15584 private void loadPrivatePackages(VolumeInfo vol) { 15585 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 15586 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 15587 synchronized (mInstallLock) { 15588 synchronized (mPackages) { 15589 final VersionInfo ver = mSettings.findOrCreateVersion(vol.fsUuid); 15590 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15591 for (PackageSetting ps : packages) { 15592 final PackageParser.Package pkg; 15593 try { 15594 pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null); 15595 loaded.add(pkg.applicationInfo); 15596 } catch (PackageManagerException e) { 15597 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 15598 } 15599 15600 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 15601 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 15602 } 15603 } 15604 15605 int updateFlags = UPDATE_PERMISSIONS_ALL; 15606 if (ver.sdkVersion != mSdkVersion) { 15607 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 15608 + mSdkVersion + "; regranting permissions for " + vol.fsUuid); 15609 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 15610 } 15611 updatePermissionsLPw(null, null, updateFlags); 15612 15613 // Yay, everything is now upgraded 15614 ver.forceCurrent(); 15615 15616 mSettings.writeLPr(); 15617 } 15618 } 15619 15620 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 15621 sendResourcesChangedBroadcast(true, false, loaded, null); 15622 } 15623 15624 private void unloadPrivatePackages(VolumeInfo vol) { 15625 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 15626 synchronized (mInstallLock) { 15627 synchronized (mPackages) { 15628 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15629 for (PackageSetting ps : packages) { 15630 if (ps.pkg == null) continue; 15631 15632 final ApplicationInfo info = ps.pkg.applicationInfo; 15633 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15634 if (deletePackageLI(ps.name, null, false, null, null, 15635 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 15636 unloaded.add(info); 15637 } else { 15638 Slog.w(TAG, "Failed to unload " + ps.codePath); 15639 } 15640 } 15641 15642 mSettings.writeLPr(); 15643 } 15644 } 15645 15646 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 15647 sendResourcesChangedBroadcast(false, false, unloaded, null); 15648 } 15649 15650 /** 15651 * Examine all users present on given mounted volume, and destroy data 15652 * belonging to users that are no longer valid, or whose user ID has been 15653 * recycled. 15654 */ 15655 private void reconcileUsers(String volumeUuid) { 15656 final File[] files = FileUtils 15657 .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid)); 15658 for (File file : files) { 15659 if (!file.isDirectory()) continue; 15660 15661 final int userId; 15662 final UserInfo info; 15663 try { 15664 userId = Integer.parseInt(file.getName()); 15665 info = sUserManager.getUserInfo(userId); 15666 } catch (NumberFormatException e) { 15667 Slog.w(TAG, "Invalid user directory " + file); 15668 continue; 15669 } 15670 15671 boolean destroyUser = false; 15672 if (info == null) { 15673 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15674 + " because no matching user was found"); 15675 destroyUser = true; 15676 } else { 15677 try { 15678 UserManagerService.enforceSerialNumber(file, info.serialNumber); 15679 } catch (IOException e) { 15680 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15681 + " because we failed to enforce serial number: " + e); 15682 destroyUser = true; 15683 } 15684 } 15685 15686 if (destroyUser) { 15687 synchronized (mInstallLock) { 15688 mInstaller.removeUserDataDirs(volumeUuid, userId); 15689 } 15690 } 15691 } 15692 15693 final UserManager um = mContext.getSystemService(UserManager.class); 15694 for (UserInfo user : um.getUsers()) { 15695 final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id); 15696 if (userDir.exists()) continue; 15697 15698 try { 15699 UserManagerService.prepareUserDirectory(userDir); 15700 UserManagerService.enforceSerialNumber(userDir, user.serialNumber); 15701 } catch (IOException e) { 15702 Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e); 15703 } 15704 } 15705 } 15706 15707 /** 15708 * Examine all apps present on given mounted volume, and destroy apps that 15709 * aren't expected, either due to uninstallation or reinstallation on 15710 * another volume. 15711 */ 15712 private void reconcileApps(String volumeUuid) { 15713 final File[] files = FileUtils 15714 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 15715 for (File file : files) { 15716 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 15717 && !PackageInstallerService.isStageName(file.getName()); 15718 if (!isPackage) { 15719 // Ignore entries which are not packages 15720 continue; 15721 } 15722 15723 boolean destroyApp = false; 15724 String packageName = null; 15725 try { 15726 final PackageLite pkg = PackageParser.parsePackageLite(file, 15727 PackageParser.PARSE_MUST_BE_APK); 15728 packageName = pkg.packageName; 15729 15730 synchronized (mPackages) { 15731 final PackageSetting ps = mSettings.mPackages.get(packageName); 15732 if (ps == null) { 15733 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + " 15734 + volumeUuid + " because we found no install record"); 15735 destroyApp = true; 15736 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 15737 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on " 15738 + volumeUuid + " because we expected it on " + ps.volumeUuid); 15739 destroyApp = true; 15740 } 15741 } 15742 15743 } catch (PackageParserException e) { 15744 logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e); 15745 destroyApp = true; 15746 } 15747 15748 if (destroyApp) { 15749 synchronized (mInstallLock) { 15750 if (packageName != null) { 15751 removeDataDirsLI(volumeUuid, packageName); 15752 } 15753 if (file.isDirectory()) { 15754 mInstaller.rmPackageDir(file.getAbsolutePath()); 15755 } else { 15756 file.delete(); 15757 } 15758 } 15759 } 15760 } 15761 } 15762 15763 private void unfreezePackage(String packageName) { 15764 synchronized (mPackages) { 15765 final PackageSetting ps = mSettings.mPackages.get(packageName); 15766 if (ps != null) { 15767 ps.frozen = false; 15768 } 15769 } 15770 } 15771 15772 @Override 15773 public int movePackage(final String packageName, final String volumeUuid) { 15774 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15775 15776 final int moveId = mNextMoveId.getAndIncrement(); 15777 try { 15778 movePackageInternal(packageName, volumeUuid, moveId); 15779 } catch (PackageManagerException e) { 15780 Slog.w(TAG, "Failed to move " + packageName, e); 15781 mMoveCallbacks.notifyStatusChanged(moveId, 15782 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15783 } 15784 return moveId; 15785 } 15786 15787 private void movePackageInternal(final String packageName, final String volumeUuid, 15788 final int moveId) throws PackageManagerException { 15789 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 15790 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15791 final PackageManager pm = mContext.getPackageManager(); 15792 15793 final boolean currentAsec; 15794 final String currentVolumeUuid; 15795 final File codeFile; 15796 final String installerPackageName; 15797 final String packageAbiOverride; 15798 final int appId; 15799 final String seinfo; 15800 final String label; 15801 15802 // reader 15803 synchronized (mPackages) { 15804 final PackageParser.Package pkg = mPackages.get(packageName); 15805 final PackageSetting ps = mSettings.mPackages.get(packageName); 15806 if (pkg == null || ps == null) { 15807 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 15808 } 15809 15810 if (pkg.applicationInfo.isSystemApp()) { 15811 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 15812 "Cannot move system application"); 15813 } 15814 15815 if (Objects.equals(ps.volumeUuid, volumeUuid)) { 15816 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15817 "Package already moved to " + volumeUuid); 15818 } 15819 15820 final File probe = new File(pkg.codePath); 15821 final File probeOat = new File(probe, "oat"); 15822 if (!probe.isDirectory() || !probeOat.isDirectory()) { 15823 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15824 "Move only supported for modern cluster style installs"); 15825 } 15826 15827 if (ps.frozen) { 15828 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 15829 "Failed to move already frozen package"); 15830 } 15831 ps.frozen = true; 15832 15833 currentAsec = pkg.applicationInfo.isForwardLocked() 15834 || pkg.applicationInfo.isExternalAsec(); 15835 currentVolumeUuid = ps.volumeUuid; 15836 codeFile = new File(pkg.codePath); 15837 installerPackageName = ps.installerPackageName; 15838 packageAbiOverride = ps.cpuAbiOverrideString; 15839 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 15840 seinfo = pkg.applicationInfo.seinfo; 15841 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 15842 } 15843 15844 // Now that we're guarded by frozen state, kill app during move 15845 final long token = Binder.clearCallingIdentity(); 15846 try { 15847 killApplication(packageName, appId, "move pkg"); 15848 } finally { 15849 Binder.restoreCallingIdentity(token); 15850 } 15851 15852 final Bundle extras = new Bundle(); 15853 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 15854 extras.putString(Intent.EXTRA_TITLE, label); 15855 mMoveCallbacks.notifyCreated(moveId, extras); 15856 15857 int installFlags; 15858 final boolean moveCompleteApp; 15859 final File measurePath; 15860 15861 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 15862 installFlags = INSTALL_INTERNAL; 15863 moveCompleteApp = !currentAsec; 15864 measurePath = Environment.getDataAppDirectory(volumeUuid); 15865 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 15866 installFlags = INSTALL_EXTERNAL; 15867 moveCompleteApp = false; 15868 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 15869 } else { 15870 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 15871 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 15872 || !volume.isMountedWritable()) { 15873 unfreezePackage(packageName); 15874 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15875 "Move location not mounted private volume"); 15876 } 15877 15878 Preconditions.checkState(!currentAsec); 15879 15880 installFlags = INSTALL_INTERNAL; 15881 moveCompleteApp = true; 15882 measurePath = Environment.getDataAppDirectory(volumeUuid); 15883 } 15884 15885 final PackageStats stats = new PackageStats(null, -1); 15886 synchronized (mInstaller) { 15887 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 15888 unfreezePackage(packageName); 15889 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15890 "Failed to measure package size"); 15891 } 15892 } 15893 15894 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 15895 + stats.dataSize); 15896 15897 final long startFreeBytes = measurePath.getFreeSpace(); 15898 final long sizeBytes; 15899 if (moveCompleteApp) { 15900 sizeBytes = stats.codeSize + stats.dataSize; 15901 } else { 15902 sizeBytes = stats.codeSize; 15903 } 15904 15905 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 15906 unfreezePackage(packageName); 15907 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15908 "Not enough free space to move"); 15909 } 15910 15911 mMoveCallbacks.notifyStatusChanged(moveId, 10); 15912 15913 final CountDownLatch installedLatch = new CountDownLatch(1); 15914 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 15915 @Override 15916 public void onUserActionRequired(Intent intent) throws RemoteException { 15917 throw new IllegalStateException(); 15918 } 15919 15920 @Override 15921 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 15922 Bundle extras) throws RemoteException { 15923 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 15924 + PackageManager.installStatusToString(returnCode, msg)); 15925 15926 installedLatch.countDown(); 15927 15928 // Regardless of success or failure of the move operation, 15929 // always unfreeze the package 15930 unfreezePackage(packageName); 15931 15932 final int status = PackageManager.installStatusToPublicStatus(returnCode); 15933 switch (status) { 15934 case PackageInstaller.STATUS_SUCCESS: 15935 mMoveCallbacks.notifyStatusChanged(moveId, 15936 PackageManager.MOVE_SUCCEEDED); 15937 break; 15938 case PackageInstaller.STATUS_FAILURE_STORAGE: 15939 mMoveCallbacks.notifyStatusChanged(moveId, 15940 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 15941 break; 15942 default: 15943 mMoveCallbacks.notifyStatusChanged(moveId, 15944 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15945 break; 15946 } 15947 } 15948 }; 15949 15950 final MoveInfo move; 15951 if (moveCompleteApp) { 15952 // Kick off a thread to report progress estimates 15953 new Thread() { 15954 @Override 15955 public void run() { 15956 while (true) { 15957 try { 15958 if (installedLatch.await(1, TimeUnit.SECONDS)) { 15959 break; 15960 } 15961 } catch (InterruptedException ignored) { 15962 } 15963 15964 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 15965 final int progress = 10 + (int) MathUtils.constrain( 15966 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 15967 mMoveCallbacks.notifyStatusChanged(moveId, progress); 15968 } 15969 } 15970 }.start(); 15971 15972 final String dataAppName = codeFile.getName(); 15973 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 15974 dataAppName, appId, seinfo); 15975 } else { 15976 move = null; 15977 } 15978 15979 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 15980 15981 final Message msg = mHandler.obtainMessage(INIT_COPY); 15982 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 15983 msg.obj = new InstallParams(origin, move, installObserver, installFlags, 15984 installerPackageName, volumeUuid, null, user, packageAbiOverride, null); 15985 mHandler.sendMessage(msg); 15986 } 15987 15988 @Override 15989 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 15990 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15991 15992 final int realMoveId = mNextMoveId.getAndIncrement(); 15993 final Bundle extras = new Bundle(); 15994 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 15995 mMoveCallbacks.notifyCreated(realMoveId, extras); 15996 15997 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 15998 @Override 15999 public void onCreated(int moveId, Bundle extras) { 16000 // Ignored 16001 } 16002 16003 @Override 16004 public void onStatusChanged(int moveId, int status, long estMillis) { 16005 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 16006 } 16007 }; 16008 16009 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16010 storage.setPrimaryStorageUuid(volumeUuid, callback); 16011 return realMoveId; 16012 } 16013 16014 @Override 16015 public int getMoveStatus(int moveId) { 16016 mContext.enforceCallingOrSelfPermission( 16017 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16018 return mMoveCallbacks.mLastStatus.get(moveId); 16019 } 16020 16021 @Override 16022 public void registerMoveCallback(IPackageMoveObserver callback) { 16023 mContext.enforceCallingOrSelfPermission( 16024 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16025 mMoveCallbacks.register(callback); 16026 } 16027 16028 @Override 16029 public void unregisterMoveCallback(IPackageMoveObserver callback) { 16030 mContext.enforceCallingOrSelfPermission( 16031 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16032 mMoveCallbacks.unregister(callback); 16033 } 16034 16035 @Override 16036 public boolean setInstallLocation(int loc) { 16037 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 16038 null); 16039 if (getInstallLocation() == loc) { 16040 return true; 16041 } 16042 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 16043 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 16044 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 16045 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 16046 return true; 16047 } 16048 return false; 16049 } 16050 16051 @Override 16052 public int getInstallLocation() { 16053 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 16054 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 16055 PackageHelper.APP_INSTALL_AUTO); 16056 } 16057 16058 /** Called by UserManagerService */ 16059 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 16060 mDirtyUsers.remove(userHandle); 16061 mSettings.removeUserLPw(userHandle); 16062 mPendingBroadcasts.remove(userHandle); 16063 if (mInstaller != null) { 16064 // Technically, we shouldn't be doing this with the package lock 16065 // held. However, this is very rare, and there is already so much 16066 // other disk I/O going on, that we'll let it slide for now. 16067 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16068 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 16069 final String volumeUuid = vol.getFsUuid(); 16070 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 16071 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 16072 } 16073 } 16074 mUserNeedsBadging.delete(userHandle); 16075 removeUnusedPackagesLILPw(userManager, userHandle); 16076 } 16077 16078 /** 16079 * We're removing userHandle and would like to remove any downloaded packages 16080 * that are no longer in use by any other user. 16081 * @param userHandle the user being removed 16082 */ 16083 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 16084 final boolean DEBUG_CLEAN_APKS = false; 16085 int [] users = userManager.getUserIdsLPr(); 16086 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 16087 while (psit.hasNext()) { 16088 PackageSetting ps = psit.next(); 16089 if (ps.pkg == null) { 16090 continue; 16091 } 16092 final String packageName = ps.pkg.packageName; 16093 // Skip over if system app 16094 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 16095 continue; 16096 } 16097 if (DEBUG_CLEAN_APKS) { 16098 Slog.i(TAG, "Checking package " + packageName); 16099 } 16100 boolean keep = false; 16101 for (int i = 0; i < users.length; i++) { 16102 if (users[i] != userHandle && ps.getInstalled(users[i])) { 16103 keep = true; 16104 if (DEBUG_CLEAN_APKS) { 16105 Slog.i(TAG, " Keeping package " + packageName + " for user " 16106 + users[i]); 16107 } 16108 break; 16109 } 16110 } 16111 if (!keep) { 16112 if (DEBUG_CLEAN_APKS) { 16113 Slog.i(TAG, " Removing package " + packageName); 16114 } 16115 mHandler.post(new Runnable() { 16116 public void run() { 16117 deletePackageX(packageName, userHandle, 0); 16118 } //end run 16119 }); 16120 } 16121 } 16122 } 16123 16124 /** Called by UserManagerService */ 16125 void createNewUserLILPw(int userHandle) { 16126 if (mInstaller != null) { 16127 mInstaller.createUserConfig(userHandle); 16128 mSettings.createNewUserLILPw(this, mInstaller, userHandle); 16129 applyFactoryDefaultBrowserLPw(userHandle); 16130 primeDomainVerificationsLPw(userHandle); 16131 } 16132 } 16133 16134 void newUserCreated(final int userHandle) { 16135 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 16136 } 16137 16138 @Override 16139 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 16140 mContext.enforceCallingOrSelfPermission( 16141 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 16142 "Only package verification agents can read the verifier device identity"); 16143 16144 synchronized (mPackages) { 16145 return mSettings.getVerifierDeviceIdentityLPw(); 16146 } 16147 } 16148 16149 @Override 16150 public void setPermissionEnforced(String permission, boolean enforced) { 16151 // TODO: Now that we no longer change GID for storage, this should to away. 16152 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 16153 "setPermissionEnforced"); 16154 if (READ_EXTERNAL_STORAGE.equals(permission)) { 16155 synchronized (mPackages) { 16156 if (mSettings.mReadExternalStorageEnforced == null 16157 || mSettings.mReadExternalStorageEnforced != enforced) { 16158 mSettings.mReadExternalStorageEnforced = enforced; 16159 mSettings.writeLPr(); 16160 } 16161 } 16162 // kill any non-foreground processes so we restart them and 16163 // grant/revoke the GID. 16164 final IActivityManager am = ActivityManagerNative.getDefault(); 16165 if (am != null) { 16166 final long token = Binder.clearCallingIdentity(); 16167 try { 16168 am.killProcessesBelowForeground("setPermissionEnforcement"); 16169 } catch (RemoteException e) { 16170 } finally { 16171 Binder.restoreCallingIdentity(token); 16172 } 16173 } 16174 } else { 16175 throw new IllegalArgumentException("No selective enforcement for " + permission); 16176 } 16177 } 16178 16179 @Override 16180 @Deprecated 16181 public boolean isPermissionEnforced(String permission) { 16182 return true; 16183 } 16184 16185 @Override 16186 public boolean isStorageLow() { 16187 final long token = Binder.clearCallingIdentity(); 16188 try { 16189 final DeviceStorageMonitorInternal 16190 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 16191 if (dsm != null) { 16192 return dsm.isMemoryLow(); 16193 } else { 16194 return false; 16195 } 16196 } finally { 16197 Binder.restoreCallingIdentity(token); 16198 } 16199 } 16200 16201 @Override 16202 public IPackageInstaller getPackageInstaller() { 16203 return mInstallerService; 16204 } 16205 16206 private boolean userNeedsBadging(int userId) { 16207 int index = mUserNeedsBadging.indexOfKey(userId); 16208 if (index < 0) { 16209 final UserInfo userInfo; 16210 final long token = Binder.clearCallingIdentity(); 16211 try { 16212 userInfo = sUserManager.getUserInfo(userId); 16213 } finally { 16214 Binder.restoreCallingIdentity(token); 16215 } 16216 final boolean b; 16217 if (userInfo != null && userInfo.isManagedProfile()) { 16218 b = true; 16219 } else { 16220 b = false; 16221 } 16222 mUserNeedsBadging.put(userId, b); 16223 return b; 16224 } 16225 return mUserNeedsBadging.valueAt(index); 16226 } 16227 16228 @Override 16229 public KeySet getKeySetByAlias(String packageName, String alias) { 16230 if (packageName == null || alias == null) { 16231 return null; 16232 } 16233 synchronized(mPackages) { 16234 final PackageParser.Package pkg = mPackages.get(packageName); 16235 if (pkg == null) { 16236 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16237 throw new IllegalArgumentException("Unknown package: " + packageName); 16238 } 16239 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16240 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 16241 } 16242 } 16243 16244 @Override 16245 public KeySet getSigningKeySet(String packageName) { 16246 if (packageName == null) { 16247 return null; 16248 } 16249 synchronized(mPackages) { 16250 final PackageParser.Package pkg = mPackages.get(packageName); 16251 if (pkg == null) { 16252 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16253 throw new IllegalArgumentException("Unknown package: " + packageName); 16254 } 16255 if (pkg.applicationInfo.uid != Binder.getCallingUid() 16256 && Process.SYSTEM_UID != Binder.getCallingUid()) { 16257 throw new SecurityException("May not access signing KeySet of other apps."); 16258 } 16259 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16260 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 16261 } 16262 } 16263 16264 @Override 16265 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 16266 if (packageName == null || ks == null) { 16267 return false; 16268 } 16269 synchronized(mPackages) { 16270 final PackageParser.Package pkg = mPackages.get(packageName); 16271 if (pkg == null) { 16272 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16273 throw new IllegalArgumentException("Unknown package: " + packageName); 16274 } 16275 IBinder ksh = ks.getToken(); 16276 if (ksh instanceof KeySetHandle) { 16277 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16278 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 16279 } 16280 return false; 16281 } 16282 } 16283 16284 @Override 16285 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 16286 if (packageName == null || ks == null) { 16287 return false; 16288 } 16289 synchronized(mPackages) { 16290 final PackageParser.Package pkg = mPackages.get(packageName); 16291 if (pkg == null) { 16292 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16293 throw new IllegalArgumentException("Unknown package: " + packageName); 16294 } 16295 IBinder ksh = ks.getToken(); 16296 if (ksh instanceof KeySetHandle) { 16297 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16298 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 16299 } 16300 return false; 16301 } 16302 } 16303 16304 public void getUsageStatsIfNoPackageUsageInfo() { 16305 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 16306 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 16307 if (usm == null) { 16308 throw new IllegalStateException("UsageStatsManager must be initialized"); 16309 } 16310 long now = System.currentTimeMillis(); 16311 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 16312 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 16313 String packageName = entry.getKey(); 16314 PackageParser.Package pkg = mPackages.get(packageName); 16315 if (pkg == null) { 16316 continue; 16317 } 16318 UsageStats usage = entry.getValue(); 16319 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 16320 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 16321 } 16322 } 16323 } 16324 16325 /** 16326 * Check and throw if the given before/after packages would be considered a 16327 * downgrade. 16328 */ 16329 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 16330 throws PackageManagerException { 16331 if (after.versionCode < before.mVersionCode) { 16332 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16333 "Update version code " + after.versionCode + " is older than current " 16334 + before.mVersionCode); 16335 } else if (after.versionCode == before.mVersionCode) { 16336 if (after.baseRevisionCode < before.baseRevisionCode) { 16337 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16338 "Update base revision code " + after.baseRevisionCode 16339 + " is older than current " + before.baseRevisionCode); 16340 } 16341 16342 if (!ArrayUtils.isEmpty(after.splitNames)) { 16343 for (int i = 0; i < after.splitNames.length; i++) { 16344 final String splitName = after.splitNames[i]; 16345 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 16346 if (j != -1) { 16347 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 16348 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16349 "Update split " + splitName + " revision code " 16350 + after.splitRevisionCodes[i] + " is older than current " 16351 + before.splitRevisionCodes[j]); 16352 } 16353 } 16354 } 16355 } 16356 } 16357 } 16358 16359 private static class MoveCallbacks extends Handler { 16360 private static final int MSG_CREATED = 1; 16361 private static final int MSG_STATUS_CHANGED = 2; 16362 16363 private final RemoteCallbackList<IPackageMoveObserver> 16364 mCallbacks = new RemoteCallbackList<>(); 16365 16366 private final SparseIntArray mLastStatus = new SparseIntArray(); 16367 16368 public MoveCallbacks(Looper looper) { 16369 super(looper); 16370 } 16371 16372 public void register(IPackageMoveObserver callback) { 16373 mCallbacks.register(callback); 16374 } 16375 16376 public void unregister(IPackageMoveObserver callback) { 16377 mCallbacks.unregister(callback); 16378 } 16379 16380 @Override 16381 public void handleMessage(Message msg) { 16382 final SomeArgs args = (SomeArgs) msg.obj; 16383 final int n = mCallbacks.beginBroadcast(); 16384 for (int i = 0; i < n; i++) { 16385 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 16386 try { 16387 invokeCallback(callback, msg.what, args); 16388 } catch (RemoteException ignored) { 16389 } 16390 } 16391 mCallbacks.finishBroadcast(); 16392 args.recycle(); 16393 } 16394 16395 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 16396 throws RemoteException { 16397 switch (what) { 16398 case MSG_CREATED: { 16399 callback.onCreated(args.argi1, (Bundle) args.arg2); 16400 break; 16401 } 16402 case MSG_STATUS_CHANGED: { 16403 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 16404 break; 16405 } 16406 } 16407 } 16408 16409 private void notifyCreated(int moveId, Bundle extras) { 16410 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 16411 16412 final SomeArgs args = SomeArgs.obtain(); 16413 args.argi1 = moveId; 16414 args.arg2 = extras; 16415 obtainMessage(MSG_CREATED, args).sendToTarget(); 16416 } 16417 16418 private void notifyStatusChanged(int moveId, int status) { 16419 notifyStatusChanged(moveId, status, -1); 16420 } 16421 16422 private void notifyStatusChanged(int moveId, int status, long estMillis) { 16423 Slog.v(TAG, "Move " + moveId + " status " + status); 16424 16425 final SomeArgs args = SomeArgs.obtain(); 16426 args.argi1 = moveId; 16427 args.argi2 = status; 16428 args.arg3 = estMillis; 16429 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 16430 16431 synchronized (mLastStatus) { 16432 mLastStatus.put(moveId, status); 16433 } 16434 } 16435 } 16436 16437 private final class OnPermissionChangeListeners extends Handler { 16438 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 16439 16440 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 16441 new RemoteCallbackList<>(); 16442 16443 public OnPermissionChangeListeners(Looper looper) { 16444 super(looper); 16445 } 16446 16447 @Override 16448 public void handleMessage(Message msg) { 16449 switch (msg.what) { 16450 case MSG_ON_PERMISSIONS_CHANGED: { 16451 final int uid = msg.arg1; 16452 handleOnPermissionsChanged(uid); 16453 } break; 16454 } 16455 } 16456 16457 public void addListenerLocked(IOnPermissionsChangeListener listener) { 16458 mPermissionListeners.register(listener); 16459 16460 } 16461 16462 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 16463 mPermissionListeners.unregister(listener); 16464 } 16465 16466 public void onPermissionsChanged(int uid) { 16467 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 16468 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 16469 } 16470 } 16471 16472 private void handleOnPermissionsChanged(int uid) { 16473 final int count = mPermissionListeners.beginBroadcast(); 16474 try { 16475 for (int i = 0; i < count; i++) { 16476 IOnPermissionsChangeListener callback = mPermissionListeners 16477 .getBroadcastItem(i); 16478 try { 16479 callback.onPermissionsChanged(uid); 16480 } catch (RemoteException e) { 16481 Log.e(TAG, "Permission listener is dead", e); 16482 } 16483 } 16484 } finally { 16485 mPermissionListeners.finishBroadcast(); 16486 } 16487 } 16488 } 16489 16490 private class PackageManagerInternalImpl extends PackageManagerInternal { 16491 @Override 16492 public void setLocationPackagesProvider(PackagesProvider provider) { 16493 synchronized (mPackages) { 16494 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 16495 } 16496 } 16497 16498 @Override 16499 public void setImePackagesProvider(PackagesProvider provider) { 16500 synchronized (mPackages) { 16501 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 16502 } 16503 } 16504 16505 @Override 16506 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 16507 synchronized (mPackages) { 16508 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 16509 } 16510 } 16511 16512 @Override 16513 public void setSmsAppPackagesProvider(PackagesProvider provider) { 16514 synchronized (mPackages) { 16515 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 16516 } 16517 } 16518 16519 @Override 16520 public void setDialerAppPackagesProvider(PackagesProvider provider) { 16521 synchronized (mPackages) { 16522 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 16523 } 16524 } 16525 16526 @Override 16527 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 16528 synchronized (mPackages) { 16529 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 16530 } 16531 } 16532 16533 @Override 16534 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 16535 synchronized (mPackages) { 16536 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 16537 } 16538 } 16539 16540 @Override 16541 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 16542 synchronized (mPackages) { 16543 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 16544 packageName, userId); 16545 } 16546 } 16547 16548 @Override 16549 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 16550 synchronized (mPackages) { 16551 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 16552 packageName, userId); 16553 } 16554 } 16555 @Override 16556 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 16557 synchronized (mPackages) { 16558 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 16559 packageName, userId); 16560 } 16561 } 16562 } 16563 16564 @Override 16565 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 16566 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 16567 synchronized (mPackages) { 16568 final long identity = Binder.clearCallingIdentity(); 16569 try { 16570 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 16571 packageNames, userId); 16572 } finally { 16573 Binder.restoreCallingIdentity(identity); 16574 } 16575 } 16576 } 16577 16578 private static void enforceSystemOrPhoneCaller(String tag) { 16579 int callingUid = Binder.getCallingUid(); 16580 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 16581 throw new SecurityException( 16582 "Cannot call " + tag + " from UID " + callingUid); 16583 } 16584 } 16585} 16586