PackageManagerService.java revision d7d1ea45984efdb6a514e97312045ac5b67ccb22
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 = Build.IS_DEBUGGABLE; 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_REQUIRE_KNOWN = 1<<12; 327 static final int SCAN_MOVE = 1<<13; 328 static final int SCAN_INITIAL = 1<<14; 329 330 static final int REMOVE_CHATTY = 1<<16; 331 332 private static final int[] EMPTY_INT_ARRAY = new int[0]; 333 334 /** 335 * Timeout (in milliseconds) after which the watchdog should declare that 336 * our handler thread is wedged. The usual default for such things is one 337 * minute but we sometimes do very lengthy I/O operations on this thread, 338 * such as installing multi-gigabyte applications, so ours needs to be longer. 339 */ 340 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 341 342 /** 343 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 344 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 345 * settings entry if available, otherwise we use the hardcoded default. If it's been 346 * more than this long since the last fstrim, we force one during the boot sequence. 347 * 348 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 349 * one gets run at the next available charging+idle time. This final mandatory 350 * no-fstrim check kicks in only of the other scheduling criteria is never met. 351 */ 352 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 353 354 /** 355 * Whether verification is enabled by default. 356 */ 357 private static final boolean DEFAULT_VERIFY_ENABLE = true; 358 359 /** 360 * The default maximum time to wait for the verification agent to return in 361 * milliseconds. 362 */ 363 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 364 365 /** 366 * The default response for package verification timeout. 367 * 368 * This can be either PackageManager.VERIFICATION_ALLOW or 369 * PackageManager.VERIFICATION_REJECT. 370 */ 371 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 372 373 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 374 375 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 376 DEFAULT_CONTAINER_PACKAGE, 377 "com.android.defcontainer.DefaultContainerService"); 378 379 private static final String KILL_APP_REASON_GIDS_CHANGED = 380 "permission grant or revoke changed gids"; 381 382 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 383 "permissions revoked"; 384 385 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 386 387 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 388 389 /** Permission grant: not grant the permission. */ 390 private static final int GRANT_DENIED = 1; 391 392 /** Permission grant: grant the permission as an install permission. */ 393 private static final int GRANT_INSTALL = 2; 394 395 /** Permission grant: grant the permission as an install permission for a legacy app. */ 396 private static final int GRANT_INSTALL_LEGACY = 3; 397 398 /** Permission grant: grant the permission as a runtime one. */ 399 private static final int GRANT_RUNTIME = 4; 400 401 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 402 private static final int GRANT_UPGRADE = 5; 403 404 /** Canonical intent used to identify what counts as a "web browser" app */ 405 private static final Intent sBrowserIntent; 406 static { 407 sBrowserIntent = new Intent(); 408 sBrowserIntent.setAction(Intent.ACTION_VIEW); 409 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 410 sBrowserIntent.setData(Uri.parse("http:")); 411 } 412 413 final ServiceThread mHandlerThread; 414 415 final PackageHandler mHandler; 416 417 /** 418 * Messages for {@link #mHandler} that need to wait for system ready before 419 * being dispatched. 420 */ 421 private ArrayList<Message> mPostSystemReadyMessages; 422 423 final int mSdkVersion = Build.VERSION.SDK_INT; 424 425 final Context mContext; 426 final boolean mFactoryTest; 427 final boolean mOnlyCore; 428 final boolean mLazyDexOpt; 429 final long mDexOptLRUThresholdInMills; 430 final DisplayMetrics mMetrics; 431 final int mDefParseFlags; 432 final String[] mSeparateProcesses; 433 final boolean mIsUpgrade; 434 435 // This is where all application persistent data goes. 436 final File mAppDataDir; 437 438 // This is where all application persistent data goes for secondary users. 439 final File mUserAppDataDir; 440 441 /** The location for ASEC container files on internal storage. */ 442 final String mAsecInternalPath; 443 444 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 445 // LOCK HELD. Can be called with mInstallLock held. 446 @GuardedBy("mInstallLock") 447 final Installer mInstaller; 448 449 /** Directory where installed third-party apps stored */ 450 final File mAppInstallDir; 451 452 /** 453 * Directory to which applications installed internally have their 454 * 32 bit native libraries copied. 455 */ 456 private File mAppLib32InstallDir; 457 458 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 459 // apps. 460 final File mDrmAppPrivateInstallDir; 461 462 // ---------------------------------------------------------------- 463 464 // Lock for state used when installing and doing other long running 465 // operations. Methods that must be called with this lock held have 466 // the suffix "LI". 467 final Object mInstallLock = new Object(); 468 469 // ---------------------------------------------------------------- 470 471 // Keys are String (package name), values are Package. This also serves 472 // as the lock for the global state. Methods that must be called with 473 // this lock held have the prefix "LP". 474 @GuardedBy("mPackages") 475 final ArrayMap<String, PackageParser.Package> mPackages = 476 new ArrayMap<String, PackageParser.Package>(); 477 478 // Tracks available target package names -> overlay package paths. 479 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 480 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 481 482 /** 483 * Tracks new system packages [receiving in an OTA] that we expect to 484 * find updated user-installed versions. Keys are package name, values 485 * are package location. 486 */ 487 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 488 489 final Settings mSettings; 490 boolean mRestoredSettings; 491 492 // System configuration read by SystemConfig. 493 final int[] mGlobalGids; 494 final SparseArray<ArraySet<String>> mSystemPermissions; 495 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 496 497 // If mac_permissions.xml was found for seinfo labeling. 498 boolean mFoundPolicyFile; 499 500 // If a recursive restorecon of /data/data/<pkg> is needed. 501 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 502 503 public static final class SharedLibraryEntry { 504 public final String path; 505 public final String apk; 506 507 SharedLibraryEntry(String _path, String _apk) { 508 path = _path; 509 apk = _apk; 510 } 511 } 512 513 // Currently known shared libraries. 514 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 515 new ArrayMap<String, SharedLibraryEntry>(); 516 517 // All available activities, for your resolving pleasure. 518 final ActivityIntentResolver mActivities = 519 new ActivityIntentResolver(); 520 521 // All available receivers, for your resolving pleasure. 522 final ActivityIntentResolver mReceivers = 523 new ActivityIntentResolver(); 524 525 // All available services, for your resolving pleasure. 526 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 527 528 // All available providers, for your resolving pleasure. 529 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 530 531 // Mapping from provider base names (first directory in content URI codePath) 532 // to the provider information. 533 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 534 new ArrayMap<String, PackageParser.Provider>(); 535 536 // Mapping from instrumentation class names to info about them. 537 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 538 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 539 540 // Mapping from permission names to info about them. 541 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 542 new ArrayMap<String, PackageParser.PermissionGroup>(); 543 544 // Packages whose data we have transfered into another package, thus 545 // should no longer exist. 546 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 547 548 // Broadcast actions that are only available to the system. 549 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 550 551 /** List of packages waiting for verification. */ 552 final SparseArray<PackageVerificationState> mPendingVerification 553 = new SparseArray<PackageVerificationState>(); 554 555 /** Set of packages associated with each app op permission. */ 556 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 557 558 final PackageInstallerService mInstallerService; 559 560 private final PackageDexOptimizer mPackageDexOptimizer; 561 562 private AtomicInteger mNextMoveId = new AtomicInteger(); 563 private final MoveCallbacks mMoveCallbacks; 564 565 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 566 567 // Cache of users who need badging. 568 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 569 570 /** Token for keys in mPendingVerification. */ 571 private int mPendingVerificationToken = 0; 572 573 volatile boolean mSystemReady; 574 volatile boolean mSafeMode; 575 volatile boolean mHasSystemUidErrors; 576 577 ApplicationInfo mAndroidApplication; 578 final ActivityInfo mResolveActivity = new ActivityInfo(); 579 final ResolveInfo mResolveInfo = new ResolveInfo(); 580 ComponentName mResolveComponentName; 581 PackageParser.Package mPlatformPackage; 582 ComponentName mCustomResolverComponentName; 583 584 boolean mResolverReplaced = false; 585 586 private final ComponentName mIntentFilterVerifierComponent; 587 private int mIntentFilterVerificationToken = 0; 588 589 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 590 = new SparseArray<IntentFilterVerificationState>(); 591 592 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 593 new DefaultPermissionGrantPolicy(this); 594 595 private static class IFVerificationParams { 596 PackageParser.Package pkg; 597 boolean replacing; 598 int userId; 599 int verifierUid; 600 601 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 602 int _userId, int _verifierUid) { 603 pkg = _pkg; 604 replacing = _replacing; 605 userId = _userId; 606 replacing = _replacing; 607 verifierUid = _verifierUid; 608 } 609 } 610 611 private interface IntentFilterVerifier<T extends IntentFilter> { 612 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 613 T filter, String packageName); 614 void startVerifications(int userId); 615 void receiveVerificationResponse(int verificationId); 616 } 617 618 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 619 private Context mContext; 620 private ComponentName mIntentFilterVerifierComponent; 621 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 622 623 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 624 mContext = context; 625 mIntentFilterVerifierComponent = verifierComponent; 626 } 627 628 private String getDefaultScheme() { 629 return IntentFilter.SCHEME_HTTPS; 630 } 631 632 @Override 633 public void startVerifications(int userId) { 634 // Launch verifications requests 635 int count = mCurrentIntentFilterVerifications.size(); 636 for (int n=0; n<count; n++) { 637 int verificationId = mCurrentIntentFilterVerifications.get(n); 638 final IntentFilterVerificationState ivs = 639 mIntentFilterVerificationStates.get(verificationId); 640 641 String packageName = ivs.getPackageName(); 642 643 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 644 final int filterCount = filters.size(); 645 ArraySet<String> domainsSet = new ArraySet<>(); 646 for (int m=0; m<filterCount; m++) { 647 PackageParser.ActivityIntentInfo filter = filters.get(m); 648 domainsSet.addAll(filter.getHostsList()); 649 } 650 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 651 synchronized (mPackages) { 652 if (mSettings.createIntentFilterVerificationIfNeededLPw( 653 packageName, domainsList) != null) { 654 scheduleWriteSettingsLocked(); 655 } 656 } 657 sendVerificationRequest(userId, verificationId, ivs); 658 } 659 mCurrentIntentFilterVerifications.clear(); 660 } 661 662 private void sendVerificationRequest(int userId, int verificationId, 663 IntentFilterVerificationState ivs) { 664 665 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 666 verificationIntent.putExtra( 667 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 668 verificationId); 669 verificationIntent.putExtra( 670 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 671 getDefaultScheme()); 672 verificationIntent.putExtra( 673 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 674 ivs.getHostsString()); 675 verificationIntent.putExtra( 676 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 677 ivs.getPackageName()); 678 verificationIntent.setComponent(mIntentFilterVerifierComponent); 679 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 680 681 UserHandle user = new UserHandle(userId); 682 mContext.sendBroadcastAsUser(verificationIntent, user); 683 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 684 "Sending IntentFilter verification broadcast"); 685 } 686 687 public void receiveVerificationResponse(int verificationId) { 688 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 689 690 final boolean verified = ivs.isVerified(); 691 692 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 693 final int count = filters.size(); 694 if (DEBUG_DOMAIN_VERIFICATION) { 695 Slog.i(TAG, "Received verification response " + verificationId 696 + " for " + count + " filters, verified=" + verified); 697 } 698 for (int n=0; n<count; n++) { 699 PackageParser.ActivityIntentInfo filter = filters.get(n); 700 filter.setVerified(verified); 701 702 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 703 + " verified with result:" + verified + " and hosts:" 704 + ivs.getHostsString()); 705 } 706 707 mIntentFilterVerificationStates.remove(verificationId); 708 709 final String packageName = ivs.getPackageName(); 710 IntentFilterVerificationInfo ivi = null; 711 712 synchronized (mPackages) { 713 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 714 } 715 if (ivi == null) { 716 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 717 + verificationId + " packageName:" + packageName); 718 return; 719 } 720 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 721 "Updating IntentFilterVerificationInfo for package " + packageName 722 +" verificationId:" + verificationId); 723 724 synchronized (mPackages) { 725 if (verified) { 726 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 727 } else { 728 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 729 } 730 scheduleWriteSettingsLocked(); 731 732 final int userId = ivs.getUserId(); 733 if (userId != UserHandle.USER_ALL) { 734 final int userStatus = 735 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 736 737 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 738 boolean needUpdate = false; 739 740 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 741 // already been set by the User thru the Disambiguation dialog 742 switch (userStatus) { 743 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 744 if (verified) { 745 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 746 } else { 747 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 748 } 749 needUpdate = true; 750 break; 751 752 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 753 if (verified) { 754 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 755 needUpdate = true; 756 } 757 break; 758 759 default: 760 // Nothing to do 761 } 762 763 if (needUpdate) { 764 mSettings.updateIntentFilterVerificationStatusLPw( 765 packageName, updatedStatus, userId); 766 scheduleWritePackageRestrictionsLocked(userId); 767 } 768 } 769 } 770 } 771 772 @Override 773 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 774 ActivityIntentInfo filter, String packageName) { 775 if (!hasValidDomains(filter)) { 776 return false; 777 } 778 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 779 if (ivs == null) { 780 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 781 packageName); 782 } 783 if (DEBUG_DOMAIN_VERIFICATION) { 784 Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter); 785 } 786 ivs.addFilter(filter); 787 return true; 788 } 789 790 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 791 int userId, int verificationId, String packageName) { 792 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 793 verifierUid, userId, packageName); 794 ivs.setPendingState(); 795 synchronized (mPackages) { 796 mIntentFilterVerificationStates.append(verificationId, ivs); 797 mCurrentIntentFilterVerifications.add(verificationId); 798 } 799 return ivs; 800 } 801 } 802 803 private static boolean hasValidDomains(ActivityIntentInfo filter) { 804 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 805 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 806 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 807 } 808 809 private IntentFilterVerifier mIntentFilterVerifier; 810 811 // Set of pending broadcasts for aggregating enable/disable of components. 812 static class PendingPackageBroadcasts { 813 // for each user id, a map of <package name -> components within that package> 814 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 815 816 public PendingPackageBroadcasts() { 817 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 818 } 819 820 public ArrayList<String> get(int userId, String packageName) { 821 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 822 return packages.get(packageName); 823 } 824 825 public void put(int userId, String packageName, ArrayList<String> components) { 826 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 827 packages.put(packageName, components); 828 } 829 830 public void remove(int userId, String packageName) { 831 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 832 if (packages != null) { 833 packages.remove(packageName); 834 } 835 } 836 837 public void remove(int userId) { 838 mUidMap.remove(userId); 839 } 840 841 public int userIdCount() { 842 return mUidMap.size(); 843 } 844 845 public int userIdAt(int n) { 846 return mUidMap.keyAt(n); 847 } 848 849 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 850 return mUidMap.get(userId); 851 } 852 853 public int size() { 854 // total number of pending broadcast entries across all userIds 855 int num = 0; 856 for (int i = 0; i< mUidMap.size(); i++) { 857 num += mUidMap.valueAt(i).size(); 858 } 859 return num; 860 } 861 862 public void clear() { 863 mUidMap.clear(); 864 } 865 866 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 867 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 868 if (map == null) { 869 map = new ArrayMap<String, ArrayList<String>>(); 870 mUidMap.put(userId, map); 871 } 872 return map; 873 } 874 } 875 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 876 877 // Service Connection to remote media container service to copy 878 // package uri's from external media onto secure containers 879 // or internal storage. 880 private IMediaContainerService mContainerService = null; 881 882 static final int SEND_PENDING_BROADCAST = 1; 883 static final int MCS_BOUND = 3; 884 static final int END_COPY = 4; 885 static final int INIT_COPY = 5; 886 static final int MCS_UNBIND = 6; 887 static final int START_CLEANING_PACKAGE = 7; 888 static final int FIND_INSTALL_LOC = 8; 889 static final int POST_INSTALL = 9; 890 static final int MCS_RECONNECT = 10; 891 static final int MCS_GIVE_UP = 11; 892 static final int UPDATED_MEDIA_STATUS = 12; 893 static final int WRITE_SETTINGS = 13; 894 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 895 static final int PACKAGE_VERIFIED = 15; 896 static final int CHECK_PENDING_VERIFICATION = 16; 897 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 898 static final int INTENT_FILTER_VERIFIED = 18; 899 900 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 901 902 // Delay time in millisecs 903 static final int BROADCAST_DELAY = 10 * 1000; 904 905 static UserManagerService sUserManager; 906 907 // Stores a list of users whose package restrictions file needs to be updated 908 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 909 910 final private DefaultContainerConnection mDefContainerConn = 911 new DefaultContainerConnection(); 912 class DefaultContainerConnection implements ServiceConnection { 913 public void onServiceConnected(ComponentName name, IBinder service) { 914 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 915 IMediaContainerService imcs = 916 IMediaContainerService.Stub.asInterface(service); 917 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 918 } 919 920 public void onServiceDisconnected(ComponentName name) { 921 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 922 } 923 } 924 925 // Recordkeeping of restore-after-install operations that are currently in flight 926 // between the Package Manager and the Backup Manager 927 class PostInstallData { 928 public InstallArgs args; 929 public PackageInstalledInfo res; 930 931 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 932 args = _a; 933 res = _r; 934 } 935 } 936 937 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 938 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 939 940 // XML tags for backup/restore of various bits of state 941 private static final String TAG_PREFERRED_BACKUP = "pa"; 942 private static final String TAG_DEFAULT_APPS = "da"; 943 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 944 945 final String mRequiredVerifierPackage; 946 final String mRequiredInstallerPackage; 947 948 private final PackageUsage mPackageUsage = new PackageUsage(); 949 950 private class PackageUsage { 951 private static final int WRITE_INTERVAL 952 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 953 954 private final Object mFileLock = new Object(); 955 private final AtomicLong mLastWritten = new AtomicLong(0); 956 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 957 958 private boolean mIsHistoricalPackageUsageAvailable = true; 959 960 boolean isHistoricalPackageUsageAvailable() { 961 return mIsHistoricalPackageUsageAvailable; 962 } 963 964 void write(boolean force) { 965 if (force) { 966 writeInternal(); 967 return; 968 } 969 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 970 && !DEBUG_DEXOPT) { 971 return; 972 } 973 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 974 new Thread("PackageUsage_DiskWriter") { 975 @Override 976 public void run() { 977 try { 978 writeInternal(); 979 } finally { 980 mBackgroundWriteRunning.set(false); 981 } 982 } 983 }.start(); 984 } 985 } 986 987 private void writeInternal() { 988 synchronized (mPackages) { 989 synchronized (mFileLock) { 990 AtomicFile file = getFile(); 991 FileOutputStream f = null; 992 try { 993 f = file.startWrite(); 994 BufferedOutputStream out = new BufferedOutputStream(f); 995 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 996 StringBuilder sb = new StringBuilder(); 997 for (PackageParser.Package pkg : mPackages.values()) { 998 if (pkg.mLastPackageUsageTimeInMills == 0) { 999 continue; 1000 } 1001 sb.setLength(0); 1002 sb.append(pkg.packageName); 1003 sb.append(' '); 1004 sb.append((long)pkg.mLastPackageUsageTimeInMills); 1005 sb.append('\n'); 1006 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1007 } 1008 out.flush(); 1009 file.finishWrite(f); 1010 } catch (IOException e) { 1011 if (f != null) { 1012 file.failWrite(f); 1013 } 1014 Log.e(TAG, "Failed to write package usage times", e); 1015 } 1016 } 1017 } 1018 mLastWritten.set(SystemClock.elapsedRealtime()); 1019 } 1020 1021 void readLP() { 1022 synchronized (mFileLock) { 1023 AtomicFile file = getFile(); 1024 BufferedInputStream in = null; 1025 try { 1026 in = new BufferedInputStream(file.openRead()); 1027 StringBuffer sb = new StringBuffer(); 1028 while (true) { 1029 String packageName = readToken(in, sb, ' '); 1030 if (packageName == null) { 1031 break; 1032 } 1033 String timeInMillisString = readToken(in, sb, '\n'); 1034 if (timeInMillisString == null) { 1035 throw new IOException("Failed to find last usage time for package " 1036 + packageName); 1037 } 1038 PackageParser.Package pkg = mPackages.get(packageName); 1039 if (pkg == null) { 1040 continue; 1041 } 1042 long timeInMillis; 1043 try { 1044 timeInMillis = Long.parseLong(timeInMillisString.toString()); 1045 } catch (NumberFormatException e) { 1046 throw new IOException("Failed to parse " + timeInMillisString 1047 + " as a long.", e); 1048 } 1049 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1050 } 1051 } catch (FileNotFoundException expected) { 1052 mIsHistoricalPackageUsageAvailable = false; 1053 } catch (IOException e) { 1054 Log.w(TAG, "Failed to read package usage times", e); 1055 } finally { 1056 IoUtils.closeQuietly(in); 1057 } 1058 } 1059 mLastWritten.set(SystemClock.elapsedRealtime()); 1060 } 1061 1062 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1063 throws IOException { 1064 sb.setLength(0); 1065 while (true) { 1066 int ch = in.read(); 1067 if (ch == -1) { 1068 if (sb.length() == 0) { 1069 return null; 1070 } 1071 throw new IOException("Unexpected EOF"); 1072 } 1073 if (ch == endOfToken) { 1074 return sb.toString(); 1075 } 1076 sb.append((char)ch); 1077 } 1078 } 1079 1080 private AtomicFile getFile() { 1081 File dataDir = Environment.getDataDirectory(); 1082 File systemDir = new File(dataDir, "system"); 1083 File fname = new File(systemDir, "package-usage.list"); 1084 return new AtomicFile(fname); 1085 } 1086 } 1087 1088 class PackageHandler extends Handler { 1089 private boolean mBound = false; 1090 final ArrayList<HandlerParams> mPendingInstalls = 1091 new ArrayList<HandlerParams>(); 1092 1093 private boolean connectToService() { 1094 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1095 " DefaultContainerService"); 1096 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1097 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1098 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1099 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 1100 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1101 mBound = true; 1102 return true; 1103 } 1104 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1105 return false; 1106 } 1107 1108 private void disconnectService() { 1109 mContainerService = null; 1110 mBound = false; 1111 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1112 mContext.unbindService(mDefContainerConn); 1113 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1114 } 1115 1116 PackageHandler(Looper looper) { 1117 super(looper); 1118 } 1119 1120 public void handleMessage(Message msg) { 1121 try { 1122 doHandleMessage(msg); 1123 } finally { 1124 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1125 } 1126 } 1127 1128 void doHandleMessage(Message msg) { 1129 switch (msg.what) { 1130 case INIT_COPY: { 1131 HandlerParams params = (HandlerParams) msg.obj; 1132 int idx = mPendingInstalls.size(); 1133 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1134 // If a bind was already initiated we dont really 1135 // need to do anything. The pending install 1136 // will be processed later on. 1137 if (!mBound) { 1138 // If this is the only one pending we might 1139 // have to bind to the service again. 1140 if (!connectToService()) { 1141 Slog.e(TAG, "Failed to bind to media container service"); 1142 params.serviceError(); 1143 return; 1144 } else { 1145 // Once we bind to the service, the first 1146 // pending request will be processed. 1147 mPendingInstalls.add(idx, params); 1148 } 1149 } else { 1150 mPendingInstalls.add(idx, params); 1151 // Already bound to the service. Just make 1152 // sure we trigger off processing the first request. 1153 if (idx == 0) { 1154 mHandler.sendEmptyMessage(MCS_BOUND); 1155 } 1156 } 1157 break; 1158 } 1159 case MCS_BOUND: { 1160 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1161 if (msg.obj != null) { 1162 mContainerService = (IMediaContainerService) msg.obj; 1163 } 1164 if (mContainerService == null) { 1165 if (!mBound) { 1166 // Something seriously wrong since we are not bound and we are not 1167 // waiting for connection. Bail out. 1168 Slog.e(TAG, "Cannot bind to media container service"); 1169 for (HandlerParams params : mPendingInstalls) { 1170 // Indicate service bind error 1171 params.serviceError(); 1172 } 1173 mPendingInstalls.clear(); 1174 } else { 1175 Slog.w(TAG, "Waiting to connect to media container service"); 1176 } 1177 } else if (mPendingInstalls.size() > 0) { 1178 HandlerParams params = mPendingInstalls.get(0); 1179 if (params != null) { 1180 if (params.startCopy()) { 1181 // We are done... look for more work or to 1182 // go idle. 1183 if (DEBUG_SD_INSTALL) Log.i(TAG, 1184 "Checking for more work or unbind..."); 1185 // Delete pending install 1186 if (mPendingInstalls.size() > 0) { 1187 mPendingInstalls.remove(0); 1188 } 1189 if (mPendingInstalls.size() == 0) { 1190 if (mBound) { 1191 if (DEBUG_SD_INSTALL) Log.i(TAG, 1192 "Posting delayed MCS_UNBIND"); 1193 removeMessages(MCS_UNBIND); 1194 Message ubmsg = obtainMessage(MCS_UNBIND); 1195 // Unbind after a little delay, to avoid 1196 // continual thrashing. 1197 sendMessageDelayed(ubmsg, 10000); 1198 } 1199 } else { 1200 // There are more pending requests in queue. 1201 // Just post MCS_BOUND message to trigger processing 1202 // of next pending install. 1203 if (DEBUG_SD_INSTALL) Log.i(TAG, 1204 "Posting MCS_BOUND for next work"); 1205 mHandler.sendEmptyMessage(MCS_BOUND); 1206 } 1207 } 1208 } 1209 } else { 1210 // Should never happen ideally. 1211 Slog.w(TAG, "Empty queue"); 1212 } 1213 break; 1214 } 1215 case MCS_RECONNECT: { 1216 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1217 if (mPendingInstalls.size() > 0) { 1218 if (mBound) { 1219 disconnectService(); 1220 } 1221 if (!connectToService()) { 1222 Slog.e(TAG, "Failed to bind to media container service"); 1223 for (HandlerParams params : mPendingInstalls) { 1224 // Indicate service bind error 1225 params.serviceError(); 1226 } 1227 mPendingInstalls.clear(); 1228 } 1229 } 1230 break; 1231 } 1232 case MCS_UNBIND: { 1233 // If there is no actual work left, then time to unbind. 1234 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1235 1236 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1237 if (mBound) { 1238 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1239 1240 disconnectService(); 1241 } 1242 } else if (mPendingInstalls.size() > 0) { 1243 // There are more pending requests in queue. 1244 // Just post MCS_BOUND message to trigger processing 1245 // of next pending install. 1246 mHandler.sendEmptyMessage(MCS_BOUND); 1247 } 1248 1249 break; 1250 } 1251 case MCS_GIVE_UP: { 1252 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1253 mPendingInstalls.remove(0); 1254 break; 1255 } 1256 case SEND_PENDING_BROADCAST: { 1257 String packages[]; 1258 ArrayList<String> components[]; 1259 int size = 0; 1260 int uids[]; 1261 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1262 synchronized (mPackages) { 1263 if (mPendingBroadcasts == null) { 1264 return; 1265 } 1266 size = mPendingBroadcasts.size(); 1267 if (size <= 0) { 1268 // Nothing to be done. Just return 1269 return; 1270 } 1271 packages = new String[size]; 1272 components = new ArrayList[size]; 1273 uids = new int[size]; 1274 int i = 0; // filling out the above arrays 1275 1276 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1277 int packageUserId = mPendingBroadcasts.userIdAt(n); 1278 Iterator<Map.Entry<String, ArrayList<String>>> it 1279 = mPendingBroadcasts.packagesForUserId(packageUserId) 1280 .entrySet().iterator(); 1281 while (it.hasNext() && i < size) { 1282 Map.Entry<String, ArrayList<String>> ent = it.next(); 1283 packages[i] = ent.getKey(); 1284 components[i] = ent.getValue(); 1285 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1286 uids[i] = (ps != null) 1287 ? UserHandle.getUid(packageUserId, ps.appId) 1288 : -1; 1289 i++; 1290 } 1291 } 1292 size = i; 1293 mPendingBroadcasts.clear(); 1294 } 1295 // Send broadcasts 1296 for (int i = 0; i < size; i++) { 1297 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1298 } 1299 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1300 break; 1301 } 1302 case START_CLEANING_PACKAGE: { 1303 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1304 final String packageName = (String)msg.obj; 1305 final int userId = msg.arg1; 1306 final boolean andCode = msg.arg2 != 0; 1307 synchronized (mPackages) { 1308 if (userId == UserHandle.USER_ALL) { 1309 int[] users = sUserManager.getUserIds(); 1310 for (int user : users) { 1311 mSettings.addPackageToCleanLPw( 1312 new PackageCleanItem(user, packageName, andCode)); 1313 } 1314 } else { 1315 mSettings.addPackageToCleanLPw( 1316 new PackageCleanItem(userId, packageName, andCode)); 1317 } 1318 } 1319 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1320 startCleaningPackages(); 1321 } break; 1322 case POST_INSTALL: { 1323 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1324 PostInstallData data = mRunningInstalls.get(msg.arg1); 1325 mRunningInstalls.delete(msg.arg1); 1326 boolean deleteOld = false; 1327 1328 if (data != null) { 1329 InstallArgs args = data.args; 1330 PackageInstalledInfo res = data.res; 1331 1332 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1333 final String packageName = res.pkg.applicationInfo.packageName; 1334 res.removedInfo.sendBroadcast(false, true, false); 1335 Bundle extras = new Bundle(1); 1336 extras.putInt(Intent.EXTRA_UID, res.uid); 1337 1338 // Now that we successfully installed the package, grant runtime 1339 // permissions if requested before broadcasting the install. 1340 if ((args.installFlags 1341 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1342 grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(), 1343 args.installGrantPermissions); 1344 } 1345 1346 // Determine the set of users who are adding this 1347 // package for the first time vs. those who are seeing 1348 // an update. 1349 int[] firstUsers; 1350 int[] updateUsers = new int[0]; 1351 if (res.origUsers == null || res.origUsers.length == 0) { 1352 firstUsers = res.newUsers; 1353 } else { 1354 firstUsers = new int[0]; 1355 for (int i=0; i<res.newUsers.length; i++) { 1356 int user = res.newUsers[i]; 1357 boolean isNew = true; 1358 for (int j=0; j<res.origUsers.length; j++) { 1359 if (res.origUsers[j] == user) { 1360 isNew = false; 1361 break; 1362 } 1363 } 1364 if (isNew) { 1365 int[] newFirst = new int[firstUsers.length+1]; 1366 System.arraycopy(firstUsers, 0, newFirst, 0, 1367 firstUsers.length); 1368 newFirst[firstUsers.length] = user; 1369 firstUsers = newFirst; 1370 } else { 1371 int[] newUpdate = new int[updateUsers.length+1]; 1372 System.arraycopy(updateUsers, 0, newUpdate, 0, 1373 updateUsers.length); 1374 newUpdate[updateUsers.length] = user; 1375 updateUsers = newUpdate; 1376 } 1377 } 1378 } 1379 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1380 packageName, extras, null, null, firstUsers); 1381 final boolean update = res.removedInfo.removedPackage != null; 1382 if (update) { 1383 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1384 } 1385 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1386 packageName, extras, null, null, updateUsers); 1387 if (update) { 1388 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1389 packageName, extras, null, null, updateUsers); 1390 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1391 null, null, packageName, null, updateUsers); 1392 1393 // treat asec-hosted packages like removable media on upgrade 1394 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1395 if (DEBUG_INSTALL) { 1396 Slog.i(TAG, "upgrading pkg " + res.pkg 1397 + " is ASEC-hosted -> AVAILABLE"); 1398 } 1399 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1400 ArrayList<String> pkgList = new ArrayList<String>(1); 1401 pkgList.add(packageName); 1402 sendResourcesChangedBroadcast(true, true, 1403 pkgList,uidArray, null); 1404 } 1405 } 1406 if (res.removedInfo.args != null) { 1407 // Remove the replaced package's older resources safely now 1408 deleteOld = true; 1409 } 1410 1411 // If this app is a browser and it's newly-installed for some 1412 // users, clear any default-browser state in those users 1413 if (firstUsers.length > 0) { 1414 // the app's nature doesn't depend on the user, so we can just 1415 // check its browser nature in any user and generalize. 1416 if (packageIsBrowser(packageName, firstUsers[0])) { 1417 synchronized (mPackages) { 1418 for (int userId : firstUsers) { 1419 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1420 } 1421 } 1422 } 1423 } 1424 // Log current value of "unknown sources" setting 1425 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1426 getUnknownSourcesSettings()); 1427 } 1428 // Force a gc to clear up things 1429 Runtime.getRuntime().gc(); 1430 // We delete after a gc for applications on sdcard. 1431 if (deleteOld) { 1432 synchronized (mInstallLock) { 1433 res.removedInfo.args.doPostDeleteLI(true); 1434 } 1435 } 1436 if (args.observer != null) { 1437 try { 1438 Bundle extras = extrasForInstallResult(res); 1439 args.observer.onPackageInstalled(res.name, res.returnCode, 1440 res.returnMsg, extras); 1441 } catch (RemoteException e) { 1442 Slog.i(TAG, "Observer no longer exists."); 1443 } 1444 } 1445 } else { 1446 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1447 } 1448 } break; 1449 case UPDATED_MEDIA_STATUS: { 1450 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1451 boolean reportStatus = msg.arg1 == 1; 1452 boolean doGc = msg.arg2 == 1; 1453 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1454 if (doGc) { 1455 // Force a gc to clear up stale containers. 1456 Runtime.getRuntime().gc(); 1457 } 1458 if (msg.obj != null) { 1459 @SuppressWarnings("unchecked") 1460 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1461 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1462 // Unload containers 1463 unloadAllContainers(args); 1464 } 1465 if (reportStatus) { 1466 try { 1467 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1468 PackageHelper.getMountService().finishMediaUpdate(); 1469 } catch (RemoteException e) { 1470 Log.e(TAG, "MountService not running?"); 1471 } 1472 } 1473 } break; 1474 case WRITE_SETTINGS: { 1475 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1476 synchronized (mPackages) { 1477 removeMessages(WRITE_SETTINGS); 1478 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1479 mSettings.writeLPr(); 1480 mDirtyUsers.clear(); 1481 } 1482 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1483 } break; 1484 case WRITE_PACKAGE_RESTRICTIONS: { 1485 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1486 synchronized (mPackages) { 1487 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1488 for (int userId : mDirtyUsers) { 1489 mSettings.writePackageRestrictionsLPr(userId); 1490 } 1491 mDirtyUsers.clear(); 1492 } 1493 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1494 } break; 1495 case CHECK_PENDING_VERIFICATION: { 1496 final int verificationId = msg.arg1; 1497 final PackageVerificationState state = mPendingVerification.get(verificationId); 1498 1499 if ((state != null) && !state.timeoutExtended()) { 1500 final InstallArgs args = state.getInstallArgs(); 1501 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1502 1503 Slog.i(TAG, "Verification timed out for " + originUri); 1504 mPendingVerification.remove(verificationId); 1505 1506 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1507 1508 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1509 Slog.i(TAG, "Continuing with installation of " + originUri); 1510 state.setVerifierResponse(Binder.getCallingUid(), 1511 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1512 broadcastPackageVerified(verificationId, originUri, 1513 PackageManager.VERIFICATION_ALLOW, 1514 state.getInstallArgs().getUser()); 1515 try { 1516 ret = args.copyApk(mContainerService, true); 1517 } catch (RemoteException e) { 1518 Slog.e(TAG, "Could not contact the ContainerService"); 1519 } 1520 } else { 1521 broadcastPackageVerified(verificationId, originUri, 1522 PackageManager.VERIFICATION_REJECT, 1523 state.getInstallArgs().getUser()); 1524 } 1525 1526 processPendingInstall(args, ret); 1527 mHandler.sendEmptyMessage(MCS_UNBIND); 1528 } 1529 break; 1530 } 1531 case PACKAGE_VERIFIED: { 1532 final int verificationId = msg.arg1; 1533 1534 final PackageVerificationState state = mPendingVerification.get(verificationId); 1535 if (state == null) { 1536 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1537 break; 1538 } 1539 1540 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1541 1542 state.setVerifierResponse(response.callerUid, response.code); 1543 1544 if (state.isVerificationComplete()) { 1545 mPendingVerification.remove(verificationId); 1546 1547 final InstallArgs args = state.getInstallArgs(); 1548 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1549 1550 int ret; 1551 if (state.isInstallAllowed()) { 1552 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1553 broadcastPackageVerified(verificationId, originUri, 1554 response.code, state.getInstallArgs().getUser()); 1555 try { 1556 ret = args.copyApk(mContainerService, true); 1557 } catch (RemoteException e) { 1558 Slog.e(TAG, "Could not contact the ContainerService"); 1559 } 1560 } else { 1561 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1562 } 1563 1564 processPendingInstall(args, ret); 1565 1566 mHandler.sendEmptyMessage(MCS_UNBIND); 1567 } 1568 1569 break; 1570 } 1571 case START_INTENT_FILTER_VERIFICATIONS: { 1572 IFVerificationParams params = (IFVerificationParams) msg.obj; 1573 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1574 params.replacing, params.pkg); 1575 break; 1576 } 1577 case INTENT_FILTER_VERIFIED: { 1578 final int verificationId = msg.arg1; 1579 1580 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1581 verificationId); 1582 if (state == null) { 1583 Slog.w(TAG, "Invalid IntentFilter verification token " 1584 + verificationId + " received"); 1585 break; 1586 } 1587 1588 final int userId = state.getUserId(); 1589 1590 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1591 "Processing IntentFilter verification with token:" 1592 + verificationId + " and userId:" + userId); 1593 1594 final IntentFilterVerificationResponse response = 1595 (IntentFilterVerificationResponse) msg.obj; 1596 1597 state.setVerifierResponse(response.callerUid, response.code); 1598 1599 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1600 "IntentFilter verification with token:" + verificationId 1601 + " and userId:" + userId 1602 + " is settings verifier response with response code:" 1603 + response.code); 1604 1605 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1606 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1607 + response.getFailedDomainsString()); 1608 } 1609 1610 if (state.isVerificationComplete()) { 1611 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1612 } else { 1613 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1614 "IntentFilter verification with token:" + verificationId 1615 + " was not said to be complete"); 1616 } 1617 1618 break; 1619 } 1620 } 1621 } 1622 } 1623 1624 private StorageEventListener mStorageListener = new StorageEventListener() { 1625 @Override 1626 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1627 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1628 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1629 final String volumeUuid = vol.getFsUuid(); 1630 1631 // Clean up any users or apps that were removed or recreated 1632 // while this volume was missing 1633 reconcileUsers(volumeUuid); 1634 reconcileApps(volumeUuid); 1635 1636 // Clean up any install sessions that expired or were 1637 // cancelled while this volume was missing 1638 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1639 1640 loadPrivatePackages(vol); 1641 1642 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1643 unloadPrivatePackages(vol); 1644 } 1645 } 1646 1647 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1648 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1649 updateExternalMediaStatus(true, false); 1650 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1651 updateExternalMediaStatus(false, false); 1652 } 1653 } 1654 } 1655 1656 @Override 1657 public void onVolumeForgotten(String fsUuid) { 1658 if (TextUtils.isEmpty(fsUuid)) { 1659 Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1660 return; 1661 } 1662 1663 // Remove any apps installed on the forgotten volume 1664 synchronized (mPackages) { 1665 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1666 for (PackageSetting ps : packages) { 1667 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1668 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1669 UserHandle.USER_OWNER, PackageManager.DELETE_ALL_USERS); 1670 } 1671 1672 mSettings.onVolumeForgotten(fsUuid); 1673 mSettings.writeLPr(); 1674 } 1675 } 1676 }; 1677 1678 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId, 1679 String[] grantedPermissions) { 1680 if (userId >= UserHandle.USER_OWNER) { 1681 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1682 } else if (userId == UserHandle.USER_ALL) { 1683 final int[] userIds; 1684 synchronized (mPackages) { 1685 userIds = UserManagerService.getInstance().getUserIds(); 1686 } 1687 for (int someUserId : userIds) { 1688 grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions); 1689 } 1690 } 1691 1692 // We could have touched GID membership, so flush out packages.list 1693 synchronized (mPackages) { 1694 mSettings.writePackageListLPr(); 1695 } 1696 } 1697 1698 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1699 String[] grantedPermissions) { 1700 SettingBase sb = (SettingBase) pkg.mExtras; 1701 if (sb == null) { 1702 return; 1703 } 1704 1705 PermissionsState permissionsState = sb.getPermissionsState(); 1706 1707 for (String permission : pkg.requestedPermissions) { 1708 BasePermission bp = mSettings.mPermissions.get(permission); 1709 if (bp != null && bp.isRuntime() && (grantedPermissions == null 1710 || ArrayUtils.contains(grantedPermissions, permission))) { 1711 permissionsState.grantRuntimePermission(bp, userId); 1712 } 1713 } 1714 } 1715 1716 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1717 Bundle extras = null; 1718 switch (res.returnCode) { 1719 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1720 extras = new Bundle(); 1721 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1722 res.origPermission); 1723 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1724 res.origPackage); 1725 break; 1726 } 1727 case PackageManager.INSTALL_SUCCEEDED: { 1728 extras = new Bundle(); 1729 extras.putBoolean(Intent.EXTRA_REPLACING, 1730 res.removedInfo != null && res.removedInfo.removedPackage != null); 1731 break; 1732 } 1733 } 1734 return extras; 1735 } 1736 1737 void scheduleWriteSettingsLocked() { 1738 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1739 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1740 } 1741 } 1742 1743 void scheduleWritePackageRestrictionsLocked(int userId) { 1744 if (!sUserManager.exists(userId)) return; 1745 mDirtyUsers.add(userId); 1746 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1747 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1748 } 1749 } 1750 1751 public static PackageManagerService main(Context context, Installer installer, 1752 boolean factoryTest, boolean onlyCore) { 1753 PackageManagerService m = new PackageManagerService(context, installer, 1754 factoryTest, onlyCore); 1755 ServiceManager.addService("package", m); 1756 return m; 1757 } 1758 1759 static String[] splitString(String str, char sep) { 1760 int count = 1; 1761 int i = 0; 1762 while ((i=str.indexOf(sep, i)) >= 0) { 1763 count++; 1764 i++; 1765 } 1766 1767 String[] res = new String[count]; 1768 i=0; 1769 count = 0; 1770 int lastI=0; 1771 while ((i=str.indexOf(sep, i)) >= 0) { 1772 res[count] = str.substring(lastI, i); 1773 count++; 1774 i++; 1775 lastI = i; 1776 } 1777 res[count] = str.substring(lastI, str.length()); 1778 return res; 1779 } 1780 1781 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1782 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1783 Context.DISPLAY_SERVICE); 1784 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1785 } 1786 1787 public PackageManagerService(Context context, Installer installer, 1788 boolean factoryTest, boolean onlyCore) { 1789 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1790 SystemClock.uptimeMillis()); 1791 1792 if (mSdkVersion <= 0) { 1793 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1794 } 1795 1796 mContext = context; 1797 mFactoryTest = factoryTest; 1798 mOnlyCore = onlyCore; 1799 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1800 mMetrics = new DisplayMetrics(); 1801 mSettings = new Settings(mPackages); 1802 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1803 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1804 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1805 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1806 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1807 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1808 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1809 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1810 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1811 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1812 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1813 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1814 1815 // TODO: add a property to control this? 1816 long dexOptLRUThresholdInMinutes; 1817 if (mLazyDexOpt) { 1818 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1819 } else { 1820 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1821 } 1822 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1823 1824 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1825 if (separateProcesses != null && separateProcesses.length() > 0) { 1826 if ("*".equals(separateProcesses)) { 1827 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1828 mSeparateProcesses = null; 1829 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1830 } else { 1831 mDefParseFlags = 0; 1832 mSeparateProcesses = separateProcesses.split(","); 1833 Slog.w(TAG, "Running with debug.separate_processes: " 1834 + separateProcesses); 1835 } 1836 } else { 1837 mDefParseFlags = 0; 1838 mSeparateProcesses = null; 1839 } 1840 1841 mInstaller = installer; 1842 mPackageDexOptimizer = new PackageDexOptimizer(this); 1843 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1844 1845 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 1846 FgThread.get().getLooper()); 1847 1848 getDefaultDisplayMetrics(context, mMetrics); 1849 1850 SystemConfig systemConfig = SystemConfig.getInstance(); 1851 mGlobalGids = systemConfig.getGlobalGids(); 1852 mSystemPermissions = systemConfig.getSystemPermissions(); 1853 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1854 1855 synchronized (mInstallLock) { 1856 // writer 1857 synchronized (mPackages) { 1858 mHandlerThread = new ServiceThread(TAG, 1859 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1860 mHandlerThread.start(); 1861 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1862 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1863 1864 File dataDir = Environment.getDataDirectory(); 1865 mAppDataDir = new File(dataDir, "data"); 1866 mAppInstallDir = new File(dataDir, "app"); 1867 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1868 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1869 mUserAppDataDir = new File(dataDir, "user"); 1870 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1871 1872 sUserManager = new UserManagerService(context, this, 1873 mInstallLock, mPackages); 1874 1875 // Propagate permission configuration in to package manager. 1876 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1877 = systemConfig.getPermissions(); 1878 for (int i=0; i<permConfig.size(); i++) { 1879 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1880 BasePermission bp = mSettings.mPermissions.get(perm.name); 1881 if (bp == null) { 1882 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1883 mSettings.mPermissions.put(perm.name, bp); 1884 } 1885 if (perm.gids != null) { 1886 bp.setGids(perm.gids, perm.perUser); 1887 } 1888 } 1889 1890 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1891 for (int i=0; i<libConfig.size(); i++) { 1892 mSharedLibraries.put(libConfig.keyAt(i), 1893 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1894 } 1895 1896 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1897 1898 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1899 mSdkVersion, mOnlyCore); 1900 1901 String customResolverActivity = Resources.getSystem().getString( 1902 R.string.config_customResolverActivity); 1903 if (TextUtils.isEmpty(customResolverActivity)) { 1904 customResolverActivity = null; 1905 } else { 1906 mCustomResolverComponentName = ComponentName.unflattenFromString( 1907 customResolverActivity); 1908 } 1909 1910 long startTime = SystemClock.uptimeMillis(); 1911 1912 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1913 startTime); 1914 1915 // Set flag to monitor and not change apk file paths when 1916 // scanning install directories. 1917 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 1918 1919 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1920 1921 /** 1922 * Add everything in the in the boot class path to the 1923 * list of process files because dexopt will have been run 1924 * if necessary during zygote startup. 1925 */ 1926 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1927 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1928 1929 if (bootClassPath != null) { 1930 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1931 for (String element : bootClassPathElements) { 1932 alreadyDexOpted.add(element); 1933 } 1934 } else { 1935 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1936 } 1937 1938 if (systemServerClassPath != null) { 1939 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1940 for (String element : systemServerClassPathElements) { 1941 alreadyDexOpted.add(element); 1942 } 1943 } else { 1944 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1945 } 1946 1947 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1948 final String[] dexCodeInstructionSets = 1949 getDexCodeInstructionSets( 1950 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1951 1952 /** 1953 * Ensure all external libraries have had dexopt run on them. 1954 */ 1955 if (mSharedLibraries.size() > 0) { 1956 // NOTE: For now, we're compiling these system "shared libraries" 1957 // (and framework jars) into all available architectures. It's possible 1958 // to compile them only when we come across an app that uses them (there's 1959 // already logic for that in scanPackageLI) but that adds some complexity. 1960 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1961 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1962 final String lib = libEntry.path; 1963 if (lib == null) { 1964 continue; 1965 } 1966 1967 try { 1968 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 1969 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1970 alreadyDexOpted.add(lib); 1971 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1972 } 1973 } catch (FileNotFoundException e) { 1974 Slog.w(TAG, "Library not found: " + lib); 1975 } catch (IOException e) { 1976 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1977 + e.getMessage()); 1978 } 1979 } 1980 } 1981 } 1982 1983 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1984 1985 // Gross hack for now: we know this file doesn't contain any 1986 // code, so don't dexopt it to avoid the resulting log spew. 1987 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1988 1989 // Gross hack for now: we know this file is only part of 1990 // the boot class path for art, so don't dexopt it to 1991 // avoid the resulting log spew. 1992 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1993 1994 /** 1995 * There are a number of commands implemented in Java, which 1996 * we currently need to do the dexopt on so that they can be 1997 * run from a non-root shell. 1998 */ 1999 String[] frameworkFiles = frameworkDir.list(); 2000 if (frameworkFiles != null) { 2001 // TODO: We could compile these only for the most preferred ABI. We should 2002 // first double check that the dex files for these commands are not referenced 2003 // by other system apps. 2004 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2005 for (int i=0; i<frameworkFiles.length; i++) { 2006 File libPath = new File(frameworkDir, frameworkFiles[i]); 2007 String path = libPath.getPath(); 2008 // Skip the file if we already did it. 2009 if (alreadyDexOpted.contains(path)) { 2010 continue; 2011 } 2012 // Skip the file if it is not a type we want to dexopt. 2013 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 2014 continue; 2015 } 2016 try { 2017 int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false); 2018 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2019 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 2020 } 2021 } catch (FileNotFoundException e) { 2022 Slog.w(TAG, "Jar not found: " + path); 2023 } catch (IOException e) { 2024 Slog.w(TAG, "Exception reading jar: " + path, e); 2025 } 2026 } 2027 } 2028 } 2029 2030 // Collect vendor overlay packages. 2031 // (Do this before scanning any apps.) 2032 // For security and version matching reason, only consider 2033 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2034 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2035 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2036 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2037 2038 // Find base frameworks (resource packages without code). 2039 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2040 | PackageParser.PARSE_IS_SYSTEM_DIR 2041 | PackageParser.PARSE_IS_PRIVILEGED, 2042 scanFlags | SCAN_NO_DEX, 0); 2043 2044 // Collected privileged system packages. 2045 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2046 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2047 | PackageParser.PARSE_IS_SYSTEM_DIR 2048 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2049 2050 // Collect ordinary system packages. 2051 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2052 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2053 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2054 2055 // Collect all vendor packages. 2056 File vendorAppDir = new File("/vendor/app"); 2057 try { 2058 vendorAppDir = vendorAppDir.getCanonicalFile(); 2059 } catch (IOException e) { 2060 // failed to look up canonical path, continue with original one 2061 } 2062 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2063 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2064 2065 // Collect all OEM packages. 2066 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2067 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2068 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2069 2070 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 2071 mInstaller.moveFiles(); 2072 2073 // Prune any system packages that no longer exist. 2074 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2075 if (!mOnlyCore) { 2076 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2077 while (psit.hasNext()) { 2078 PackageSetting ps = psit.next(); 2079 2080 /* 2081 * If this is not a system app, it can't be a 2082 * disable system app. 2083 */ 2084 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2085 continue; 2086 } 2087 2088 /* 2089 * If the package is scanned, it's not erased. 2090 */ 2091 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2092 if (scannedPkg != null) { 2093 /* 2094 * If the system app is both scanned and in the 2095 * disabled packages list, then it must have been 2096 * added via OTA. Remove it from the currently 2097 * scanned package so the previously user-installed 2098 * application can be scanned. 2099 */ 2100 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2101 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2102 + ps.name + "; removing system app. Last known codePath=" 2103 + ps.codePathString + ", installStatus=" + ps.installStatus 2104 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2105 + scannedPkg.mVersionCode); 2106 removePackageLI(ps, true); 2107 mExpectingBetter.put(ps.name, ps.codePath); 2108 } 2109 2110 continue; 2111 } 2112 2113 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2114 psit.remove(); 2115 logCriticalInfo(Log.WARN, "System package " + ps.name 2116 + " no longer exists; wiping its data"); 2117 removeDataDirsLI(null, ps.name); 2118 } else { 2119 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2120 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2121 possiblyDeletedUpdatedSystemApps.add(ps.name); 2122 } 2123 } 2124 } 2125 } 2126 2127 //look for any incomplete package installations 2128 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2129 //clean up list 2130 for(int i = 0; i < deletePkgsList.size(); i++) { 2131 //clean up here 2132 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2133 } 2134 //delete tmp files 2135 deleteTempPackageFiles(); 2136 2137 // Remove any shared userIDs that have no associated packages 2138 mSettings.pruneSharedUsersLPw(); 2139 2140 if (!mOnlyCore) { 2141 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2142 SystemClock.uptimeMillis()); 2143 scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2144 2145 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2146 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2147 2148 /** 2149 * Remove disable package settings for any updated system 2150 * apps that were removed via an OTA. If they're not a 2151 * previously-updated app, remove them completely. 2152 * Otherwise, just revoke their system-level permissions. 2153 */ 2154 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2155 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2156 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2157 2158 String msg; 2159 if (deletedPkg == null) { 2160 msg = "Updated system package " + deletedAppName 2161 + " no longer exists; wiping its data"; 2162 removeDataDirsLI(null, deletedAppName); 2163 } else { 2164 msg = "Updated system app + " + deletedAppName 2165 + " no longer present; removing system privileges for " 2166 + deletedAppName; 2167 2168 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2169 2170 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2171 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2172 } 2173 logCriticalInfo(Log.WARN, msg); 2174 } 2175 2176 /** 2177 * Make sure all system apps that we expected to appear on 2178 * the userdata partition actually showed up. If they never 2179 * appeared, crawl back and revive the system version. 2180 */ 2181 for (int i = 0; i < mExpectingBetter.size(); i++) { 2182 final String packageName = mExpectingBetter.keyAt(i); 2183 if (!mPackages.containsKey(packageName)) { 2184 final File scanFile = mExpectingBetter.valueAt(i); 2185 2186 logCriticalInfo(Log.WARN, "Expected better " + packageName 2187 + " but never showed up; reverting to system"); 2188 2189 final int reparseFlags; 2190 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2191 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2192 | PackageParser.PARSE_IS_SYSTEM_DIR 2193 | PackageParser.PARSE_IS_PRIVILEGED; 2194 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2195 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2196 | PackageParser.PARSE_IS_SYSTEM_DIR; 2197 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2198 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2199 | PackageParser.PARSE_IS_SYSTEM_DIR; 2200 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2201 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2202 | PackageParser.PARSE_IS_SYSTEM_DIR; 2203 } else { 2204 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2205 continue; 2206 } 2207 2208 mSettings.enableSystemPackageLPw(packageName); 2209 2210 try { 2211 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 2212 } catch (PackageManagerException e) { 2213 Slog.e(TAG, "Failed to parse original system package: " 2214 + e.getMessage()); 2215 } 2216 } 2217 } 2218 } 2219 mExpectingBetter.clear(); 2220 2221 // Now that we know all of the shared libraries, update all clients to have 2222 // the correct library paths. 2223 updateAllSharedLibrariesLPw(); 2224 2225 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2226 // NOTE: We ignore potential failures here during a system scan (like 2227 // the rest of the commands above) because there's precious little we 2228 // can do about it. A settings error is reported, though. 2229 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2230 false /* force dexopt */, false /* defer dexopt */); 2231 } 2232 2233 // Now that we know all the packages we are keeping, 2234 // read and update their last usage times. 2235 mPackageUsage.readLP(); 2236 2237 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2238 SystemClock.uptimeMillis()); 2239 Slog.i(TAG, "Time to scan packages: " 2240 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2241 + " seconds"); 2242 2243 // If the platform SDK has changed since the last time we booted, 2244 // we need to re-grant app permission to catch any new ones that 2245 // appear. This is really a hack, and means that apps can in some 2246 // cases get permissions that the user didn't initially explicitly 2247 // allow... it would be nice to have some better way to handle 2248 // this situation. 2249 final VersionInfo ver = mSettings.getInternalVersion(); 2250 2251 int updateFlags = UPDATE_PERMISSIONS_ALL; 2252 if (ver.sdkVersion != mSdkVersion) { 2253 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2254 + mSdkVersion + "; regranting permissions for internal storage"); 2255 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2256 } 2257 updatePermissionsLPw(null, null, updateFlags); 2258 ver.sdkVersion = mSdkVersion; 2259 2260 // If this is the first boot, and it is a normal boot, then 2261 // we need to initialize the default preferred apps. 2262 if (!mRestoredSettings && !onlyCore) { 2263 mSettings.applyDefaultPreferredAppsLPw(this, UserHandle.USER_OWNER); 2264 applyFactoryDefaultBrowserLPw(UserHandle.USER_OWNER); 2265 primeDomainVerificationsLPw(UserHandle.USER_OWNER); 2266 } 2267 2268 // If this is first boot after an OTA, and a normal boot, then 2269 // we need to clear code cache directories. 2270 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2271 if (mIsUpgrade && !onlyCore) { 2272 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2273 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2274 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2275 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2276 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2277 } 2278 } 2279 ver.fingerprint = Build.FINGERPRINT; 2280 } 2281 2282 checkDefaultBrowser(); 2283 2284 // All the changes are done during package scanning. 2285 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2286 2287 // can downgrade to reader 2288 mSettings.writeLPr(); 2289 2290 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2291 SystemClock.uptimeMillis()); 2292 2293 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2294 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2295 2296 mInstallerService = new PackageInstallerService(context, this); 2297 2298 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2299 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2300 mIntentFilterVerifierComponent); 2301 2302 } // synchronized (mPackages) 2303 } // synchronized (mInstallLock) 2304 2305 // Now after opening every single application zip, make sure they 2306 // are all flushed. Not really needed, but keeps things nice and 2307 // tidy. 2308 Runtime.getRuntime().gc(); 2309 2310 // Expose private service for system components to use. 2311 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2312 } 2313 2314 @Override 2315 public boolean isFirstBoot() { 2316 return !mRestoredSettings; 2317 } 2318 2319 @Override 2320 public boolean isOnlyCoreApps() { 2321 return mOnlyCore; 2322 } 2323 2324 @Override 2325 public boolean isUpgrade() { 2326 return mIsUpgrade; 2327 } 2328 2329 private String getRequiredVerifierLPr() { 2330 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2331 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2332 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 2333 2334 String requiredVerifier = null; 2335 2336 final int N = receivers.size(); 2337 for (int i = 0; i < N; i++) { 2338 final ResolveInfo info = receivers.get(i); 2339 2340 if (info.activityInfo == null) { 2341 continue; 2342 } 2343 2344 final String packageName = info.activityInfo.packageName; 2345 2346 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2347 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2348 continue; 2349 } 2350 2351 if (requiredVerifier != null) { 2352 throw new RuntimeException("There can be only one required verifier"); 2353 } 2354 2355 requiredVerifier = packageName; 2356 } 2357 2358 return requiredVerifier; 2359 } 2360 2361 private String getRequiredInstallerLPr() { 2362 Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2363 installerIntent.addCategory(Intent.CATEGORY_DEFAULT); 2364 installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2365 2366 final List<ResolveInfo> installers = queryIntentActivities(installerIntent, 2367 PACKAGE_MIME_TYPE, 0, 0); 2368 2369 String requiredInstaller = null; 2370 2371 final int N = installers.size(); 2372 for (int i = 0; i < N; i++) { 2373 final ResolveInfo info = installers.get(i); 2374 final String packageName = info.activityInfo.packageName; 2375 2376 if (!info.activityInfo.applicationInfo.isSystemApp()) { 2377 continue; 2378 } 2379 2380 if (requiredInstaller != null) { 2381 throw new RuntimeException("There must be one required installer"); 2382 } 2383 2384 requiredInstaller = packageName; 2385 } 2386 2387 if (requiredInstaller == null) { 2388 throw new RuntimeException("There must be one required installer"); 2389 } 2390 2391 return requiredInstaller; 2392 } 2393 2394 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2395 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2396 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2397 PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */); 2398 2399 ComponentName verifierComponentName = null; 2400 2401 int priority = -1000; 2402 final int N = receivers.size(); 2403 for (int i = 0; i < N; i++) { 2404 final ResolveInfo info = receivers.get(i); 2405 2406 if (info.activityInfo == null) { 2407 continue; 2408 } 2409 2410 final String packageName = info.activityInfo.packageName; 2411 2412 final PackageSetting ps = mSettings.mPackages.get(packageName); 2413 if (ps == null) { 2414 continue; 2415 } 2416 2417 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2418 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2419 continue; 2420 } 2421 2422 // Select the IntentFilterVerifier with the highest priority 2423 if (priority < info.priority) { 2424 priority = info.priority; 2425 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2426 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: " 2427 + verifierComponentName + " with priority: " + info.priority); 2428 } 2429 } 2430 2431 return verifierComponentName; 2432 } 2433 2434 private void primeDomainVerificationsLPw(int userId) { 2435 if (DEBUG_DOMAIN_VERIFICATION) { 2436 Slog.d(TAG, "Priming domain verifications in user " + userId); 2437 } 2438 2439 SystemConfig systemConfig = SystemConfig.getInstance(); 2440 ArraySet<String> packages = systemConfig.getLinkedApps(); 2441 ArraySet<String> domains = new ArraySet<String>(); 2442 2443 for (String packageName : packages) { 2444 PackageParser.Package pkg = mPackages.get(packageName); 2445 if (pkg != null) { 2446 if (!pkg.isSystemApp()) { 2447 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2448 continue; 2449 } 2450 2451 domains.clear(); 2452 for (PackageParser.Activity a : pkg.activities) { 2453 for (ActivityIntentInfo filter : a.intents) { 2454 if (hasValidDomains(filter)) { 2455 domains.addAll(filter.getHostsList()); 2456 } 2457 } 2458 } 2459 2460 if (domains.size() > 0) { 2461 if (DEBUG_DOMAIN_VERIFICATION) { 2462 Slog.v(TAG, " + " + packageName); 2463 } 2464 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2465 // state w.r.t. the formal app-linkage "no verification attempted" state; 2466 // and then 'always' in the per-user state actually used for intent resolution. 2467 final IntentFilterVerificationInfo ivi; 2468 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2469 new ArrayList<String>(domains)); 2470 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2471 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2472 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2473 } else { 2474 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2475 + "' does not handle web links"); 2476 } 2477 } else { 2478 Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>"); 2479 } 2480 } 2481 2482 scheduleWritePackageRestrictionsLocked(userId); 2483 scheduleWriteSettingsLocked(); 2484 } 2485 2486 private void applyFactoryDefaultBrowserLPw(int userId) { 2487 // The default browser app's package name is stored in a string resource, 2488 // with a product-specific overlay used for vendor customization. 2489 String browserPkg = mContext.getResources().getString( 2490 com.android.internal.R.string.default_browser); 2491 if (!TextUtils.isEmpty(browserPkg)) { 2492 // non-empty string => required to be a known package 2493 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2494 if (ps == null) { 2495 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2496 browserPkg = null; 2497 } else { 2498 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2499 } 2500 } 2501 2502 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2503 // default. If there's more than one, just leave everything alone. 2504 if (browserPkg == null) { 2505 calculateDefaultBrowserLPw(userId); 2506 } 2507 } 2508 2509 private void calculateDefaultBrowserLPw(int userId) { 2510 List<String> allBrowsers = resolveAllBrowserApps(userId); 2511 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2512 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2513 } 2514 2515 private List<String> resolveAllBrowserApps(int userId) { 2516 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2517 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2518 PackageManager.MATCH_ALL, userId); 2519 2520 final int count = list.size(); 2521 List<String> result = new ArrayList<String>(count); 2522 for (int i=0; i<count; i++) { 2523 ResolveInfo info = list.get(i); 2524 if (info.activityInfo == null 2525 || !info.handleAllWebDataURI 2526 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2527 || result.contains(info.activityInfo.packageName)) { 2528 continue; 2529 } 2530 result.add(info.activityInfo.packageName); 2531 } 2532 2533 return result; 2534 } 2535 2536 private boolean packageIsBrowser(String packageName, int userId) { 2537 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2538 PackageManager.MATCH_ALL, userId); 2539 final int N = list.size(); 2540 for (int i = 0; i < N; i++) { 2541 ResolveInfo info = list.get(i); 2542 if (packageName.equals(info.activityInfo.packageName)) { 2543 return true; 2544 } 2545 } 2546 return false; 2547 } 2548 2549 private void checkDefaultBrowser() { 2550 final int myUserId = UserHandle.myUserId(); 2551 final String packageName = getDefaultBrowserPackageName(myUserId); 2552 if (packageName != null) { 2553 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2554 if (info == null) { 2555 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2556 synchronized (mPackages) { 2557 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2558 } 2559 } 2560 } 2561 } 2562 2563 @Override 2564 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2565 throws RemoteException { 2566 try { 2567 return super.onTransact(code, data, reply, flags); 2568 } catch (RuntimeException e) { 2569 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2570 Slog.wtf(TAG, "Package Manager Crash", e); 2571 } 2572 throw e; 2573 } 2574 } 2575 2576 void cleanupInstallFailedPackage(PackageSetting ps) { 2577 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2578 2579 removeDataDirsLI(ps.volumeUuid, ps.name); 2580 if (ps.codePath != null) { 2581 if (ps.codePath.isDirectory()) { 2582 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2583 } else { 2584 ps.codePath.delete(); 2585 } 2586 } 2587 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2588 if (ps.resourcePath.isDirectory()) { 2589 FileUtils.deleteContents(ps.resourcePath); 2590 } 2591 ps.resourcePath.delete(); 2592 } 2593 mSettings.removePackageLPw(ps.name); 2594 } 2595 2596 static int[] appendInts(int[] cur, int[] add) { 2597 if (add == null) return cur; 2598 if (cur == null) return add; 2599 final int N = add.length; 2600 for (int i=0; i<N; i++) { 2601 cur = appendInt(cur, add[i]); 2602 } 2603 return cur; 2604 } 2605 2606 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2607 if (!sUserManager.exists(userId)) return null; 2608 final PackageSetting ps = (PackageSetting) p.mExtras; 2609 if (ps == null) { 2610 return null; 2611 } 2612 2613 final PermissionsState permissionsState = ps.getPermissionsState(); 2614 2615 final int[] gids = permissionsState.computeGids(userId); 2616 final Set<String> permissions = permissionsState.getPermissions(userId); 2617 final PackageUserState state = ps.readUserState(userId); 2618 2619 return PackageParser.generatePackageInfo(p, gids, flags, 2620 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2621 } 2622 2623 @Override 2624 public boolean isPackageFrozen(String packageName) { 2625 synchronized (mPackages) { 2626 final PackageSetting ps = mSettings.mPackages.get(packageName); 2627 if (ps != null) { 2628 return ps.frozen; 2629 } 2630 } 2631 Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen"); 2632 return true; 2633 } 2634 2635 @Override 2636 public boolean isPackageAvailable(String packageName, int userId) { 2637 if (!sUserManager.exists(userId)) return false; 2638 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2639 synchronized (mPackages) { 2640 PackageParser.Package p = mPackages.get(packageName); 2641 if (p != null) { 2642 final PackageSetting ps = (PackageSetting) p.mExtras; 2643 if (ps != null) { 2644 final PackageUserState state = ps.readUserState(userId); 2645 if (state != null) { 2646 return PackageParser.isAvailable(state); 2647 } 2648 } 2649 } 2650 } 2651 return false; 2652 } 2653 2654 @Override 2655 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2656 if (!sUserManager.exists(userId)) return null; 2657 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2658 // reader 2659 synchronized (mPackages) { 2660 PackageParser.Package p = mPackages.get(packageName); 2661 if (DEBUG_PACKAGE_INFO) 2662 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2663 if (p != null) { 2664 return generatePackageInfo(p, flags, userId); 2665 } 2666 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2667 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2668 } 2669 } 2670 return null; 2671 } 2672 2673 @Override 2674 public String[] currentToCanonicalPackageNames(String[] names) { 2675 String[] out = new String[names.length]; 2676 // reader 2677 synchronized (mPackages) { 2678 for (int i=names.length-1; i>=0; i--) { 2679 PackageSetting ps = mSettings.mPackages.get(names[i]); 2680 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2681 } 2682 } 2683 return out; 2684 } 2685 2686 @Override 2687 public String[] canonicalToCurrentPackageNames(String[] names) { 2688 String[] out = new String[names.length]; 2689 // reader 2690 synchronized (mPackages) { 2691 for (int i=names.length-1; i>=0; i--) { 2692 String cur = mSettings.mRenamedPackages.get(names[i]); 2693 out[i] = cur != null ? cur : names[i]; 2694 } 2695 } 2696 return out; 2697 } 2698 2699 @Override 2700 public int getPackageUid(String packageName, int userId) { 2701 if (!sUserManager.exists(userId)) return -1; 2702 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2703 2704 // reader 2705 synchronized (mPackages) { 2706 PackageParser.Package p = mPackages.get(packageName); 2707 if(p != null) { 2708 return UserHandle.getUid(userId, p.applicationInfo.uid); 2709 } 2710 PackageSetting ps = mSettings.mPackages.get(packageName); 2711 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2712 return -1; 2713 } 2714 p = ps.pkg; 2715 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2716 } 2717 } 2718 2719 @Override 2720 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2721 if (!sUserManager.exists(userId)) { 2722 return null; 2723 } 2724 2725 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2726 "getPackageGids"); 2727 2728 // reader 2729 synchronized (mPackages) { 2730 PackageParser.Package p = mPackages.get(packageName); 2731 if (DEBUG_PACKAGE_INFO) { 2732 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2733 } 2734 if (p != null) { 2735 PackageSetting ps = (PackageSetting) p.mExtras; 2736 return ps.getPermissionsState().computeGids(userId); 2737 } 2738 } 2739 2740 return null; 2741 } 2742 2743 static PermissionInfo generatePermissionInfo( 2744 BasePermission bp, int flags) { 2745 if (bp.perm != null) { 2746 return PackageParser.generatePermissionInfo(bp.perm, flags); 2747 } 2748 PermissionInfo pi = new PermissionInfo(); 2749 pi.name = bp.name; 2750 pi.packageName = bp.sourcePackage; 2751 pi.nonLocalizedLabel = bp.name; 2752 pi.protectionLevel = bp.protectionLevel; 2753 return pi; 2754 } 2755 2756 @Override 2757 public PermissionInfo getPermissionInfo(String name, int flags) { 2758 // reader 2759 synchronized (mPackages) { 2760 final BasePermission p = mSettings.mPermissions.get(name); 2761 if (p != null) { 2762 return generatePermissionInfo(p, flags); 2763 } 2764 return null; 2765 } 2766 } 2767 2768 @Override 2769 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2770 // reader 2771 synchronized (mPackages) { 2772 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2773 for (BasePermission p : mSettings.mPermissions.values()) { 2774 if (group == null) { 2775 if (p.perm == null || p.perm.info.group == null) { 2776 out.add(generatePermissionInfo(p, flags)); 2777 } 2778 } else { 2779 if (p.perm != null && group.equals(p.perm.info.group)) { 2780 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2781 } 2782 } 2783 } 2784 2785 if (out.size() > 0) { 2786 return out; 2787 } 2788 return mPermissionGroups.containsKey(group) ? out : null; 2789 } 2790 } 2791 2792 @Override 2793 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2794 // reader 2795 synchronized (mPackages) { 2796 return PackageParser.generatePermissionGroupInfo( 2797 mPermissionGroups.get(name), flags); 2798 } 2799 } 2800 2801 @Override 2802 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2803 // reader 2804 synchronized (mPackages) { 2805 final int N = mPermissionGroups.size(); 2806 ArrayList<PermissionGroupInfo> out 2807 = new ArrayList<PermissionGroupInfo>(N); 2808 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2809 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2810 } 2811 return out; 2812 } 2813 } 2814 2815 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2816 int userId) { 2817 if (!sUserManager.exists(userId)) return null; 2818 PackageSetting ps = mSettings.mPackages.get(packageName); 2819 if (ps != null) { 2820 if (ps.pkg == null) { 2821 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2822 flags, userId); 2823 if (pInfo != null) { 2824 return pInfo.applicationInfo; 2825 } 2826 return null; 2827 } 2828 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2829 ps.readUserState(userId), userId); 2830 } 2831 return null; 2832 } 2833 2834 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2835 int userId) { 2836 if (!sUserManager.exists(userId)) return null; 2837 PackageSetting ps = mSettings.mPackages.get(packageName); 2838 if (ps != null) { 2839 PackageParser.Package pkg = ps.pkg; 2840 if (pkg == null) { 2841 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2842 return null; 2843 } 2844 // Only data remains, so we aren't worried about code paths 2845 pkg = new PackageParser.Package(packageName); 2846 pkg.applicationInfo.packageName = packageName; 2847 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2848 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2849 pkg.applicationInfo.dataDir = Environment 2850 .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName) 2851 .getAbsolutePath(); 2852 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2853 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2854 } 2855 return generatePackageInfo(pkg, flags, userId); 2856 } 2857 return null; 2858 } 2859 2860 @Override 2861 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2862 if (!sUserManager.exists(userId)) return null; 2863 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2864 // writer 2865 synchronized (mPackages) { 2866 PackageParser.Package p = mPackages.get(packageName); 2867 if (DEBUG_PACKAGE_INFO) Log.v( 2868 TAG, "getApplicationInfo " + packageName 2869 + ": " + p); 2870 if (p != null) { 2871 PackageSetting ps = mSettings.mPackages.get(packageName); 2872 if (ps == null) return null; 2873 // Note: isEnabledLP() does not apply here - always return info 2874 return PackageParser.generateApplicationInfo( 2875 p, flags, ps.readUserState(userId), userId); 2876 } 2877 if ("android".equals(packageName)||"system".equals(packageName)) { 2878 return mAndroidApplication; 2879 } 2880 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2881 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2882 } 2883 } 2884 return null; 2885 } 2886 2887 @Override 2888 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2889 final IPackageDataObserver observer) { 2890 mContext.enforceCallingOrSelfPermission( 2891 android.Manifest.permission.CLEAR_APP_CACHE, null); 2892 // Queue up an async operation since clearing cache may take a little while. 2893 mHandler.post(new Runnable() { 2894 public void run() { 2895 mHandler.removeCallbacks(this); 2896 int retCode = -1; 2897 synchronized (mInstallLock) { 2898 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2899 if (retCode < 0) { 2900 Slog.w(TAG, "Couldn't clear application caches"); 2901 } 2902 } 2903 if (observer != null) { 2904 try { 2905 observer.onRemoveCompleted(null, (retCode >= 0)); 2906 } catch (RemoteException e) { 2907 Slog.w(TAG, "RemoveException when invoking call back"); 2908 } 2909 } 2910 } 2911 }); 2912 } 2913 2914 @Override 2915 public void freeStorage(final String volumeUuid, final long freeStorageSize, 2916 final IntentSender pi) { 2917 mContext.enforceCallingOrSelfPermission( 2918 android.Manifest.permission.CLEAR_APP_CACHE, null); 2919 // Queue up an async operation since clearing cache may take a little while. 2920 mHandler.post(new Runnable() { 2921 public void run() { 2922 mHandler.removeCallbacks(this); 2923 int retCode = -1; 2924 synchronized (mInstallLock) { 2925 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2926 if (retCode < 0) { 2927 Slog.w(TAG, "Couldn't clear application caches"); 2928 } 2929 } 2930 if(pi != null) { 2931 try { 2932 // Callback via pending intent 2933 int code = (retCode >= 0) ? 1 : 0; 2934 pi.sendIntent(null, code, null, 2935 null, null); 2936 } catch (SendIntentException e1) { 2937 Slog.i(TAG, "Failed to send pending intent"); 2938 } 2939 } 2940 } 2941 }); 2942 } 2943 2944 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 2945 synchronized (mInstallLock) { 2946 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 2947 throw new IOException("Failed to free enough space"); 2948 } 2949 } 2950 } 2951 2952 @Override 2953 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2954 if (!sUserManager.exists(userId)) return null; 2955 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2956 synchronized (mPackages) { 2957 PackageParser.Activity a = mActivities.mActivities.get(component); 2958 2959 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2960 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2961 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2962 if (ps == null) return null; 2963 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2964 userId); 2965 } 2966 if (mResolveComponentName.equals(component)) { 2967 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2968 new PackageUserState(), userId); 2969 } 2970 } 2971 return null; 2972 } 2973 2974 @Override 2975 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2976 String resolvedType) { 2977 synchronized (mPackages) { 2978 if (component.equals(mResolveComponentName)) { 2979 // The resolver supports EVERYTHING! 2980 return true; 2981 } 2982 PackageParser.Activity a = mActivities.mActivities.get(component); 2983 if (a == null) { 2984 return false; 2985 } 2986 for (int i=0; i<a.intents.size(); i++) { 2987 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2988 intent.getData(), intent.getCategories(), TAG) >= 0) { 2989 return true; 2990 } 2991 } 2992 return false; 2993 } 2994 } 2995 2996 @Override 2997 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2998 if (!sUserManager.exists(userId)) return null; 2999 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 3000 synchronized (mPackages) { 3001 PackageParser.Activity a = mReceivers.mActivities.get(component); 3002 if (DEBUG_PACKAGE_INFO) Log.v( 3003 TAG, "getReceiverInfo " + component + ": " + a); 3004 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 3005 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3006 if (ps == null) return null; 3007 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3008 userId); 3009 } 3010 } 3011 return null; 3012 } 3013 3014 @Override 3015 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3016 if (!sUserManager.exists(userId)) return null; 3017 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 3018 synchronized (mPackages) { 3019 PackageParser.Service s = mServices.mServices.get(component); 3020 if (DEBUG_PACKAGE_INFO) Log.v( 3021 TAG, "getServiceInfo " + component + ": " + s); 3022 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 3023 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3024 if (ps == null) return null; 3025 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3026 userId); 3027 } 3028 } 3029 return null; 3030 } 3031 3032 @Override 3033 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3034 if (!sUserManager.exists(userId)) return null; 3035 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 3036 synchronized (mPackages) { 3037 PackageParser.Provider p = mProviders.mProviders.get(component); 3038 if (DEBUG_PACKAGE_INFO) Log.v( 3039 TAG, "getProviderInfo " + component + ": " + p); 3040 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 3041 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3042 if (ps == null) return null; 3043 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3044 userId); 3045 } 3046 } 3047 return null; 3048 } 3049 3050 @Override 3051 public String[] getSystemSharedLibraryNames() { 3052 Set<String> libSet; 3053 synchronized (mPackages) { 3054 libSet = mSharedLibraries.keySet(); 3055 int size = libSet.size(); 3056 if (size > 0) { 3057 String[] libs = new String[size]; 3058 libSet.toArray(libs); 3059 return libs; 3060 } 3061 } 3062 return null; 3063 } 3064 3065 /** 3066 * @hide 3067 */ 3068 PackageParser.Package findSharedNonSystemLibrary(String libName) { 3069 synchronized (mPackages) { 3070 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 3071 if (lib != null && lib.apk != null) { 3072 return mPackages.get(lib.apk); 3073 } 3074 } 3075 return null; 3076 } 3077 3078 @Override 3079 public FeatureInfo[] getSystemAvailableFeatures() { 3080 Collection<FeatureInfo> featSet; 3081 synchronized (mPackages) { 3082 featSet = mAvailableFeatures.values(); 3083 int size = featSet.size(); 3084 if (size > 0) { 3085 FeatureInfo[] features = new FeatureInfo[size+1]; 3086 featSet.toArray(features); 3087 FeatureInfo fi = new FeatureInfo(); 3088 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3089 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3090 features[size] = fi; 3091 return features; 3092 } 3093 } 3094 return null; 3095 } 3096 3097 @Override 3098 public boolean hasSystemFeature(String name) { 3099 synchronized (mPackages) { 3100 return mAvailableFeatures.containsKey(name); 3101 } 3102 } 3103 3104 private void checkValidCaller(int uid, int userId) { 3105 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 3106 return; 3107 3108 throw new SecurityException("Caller uid=" + uid 3109 + " is not privileged to communicate with user=" + userId); 3110 } 3111 3112 @Override 3113 public int checkPermission(String permName, String pkgName, int userId) { 3114 if (!sUserManager.exists(userId)) { 3115 return PackageManager.PERMISSION_DENIED; 3116 } 3117 3118 synchronized (mPackages) { 3119 final PackageParser.Package p = mPackages.get(pkgName); 3120 if (p != null && p.mExtras != null) { 3121 final PackageSetting ps = (PackageSetting) p.mExtras; 3122 final PermissionsState permissionsState = ps.getPermissionsState(); 3123 if (permissionsState.hasPermission(permName, userId)) { 3124 return PackageManager.PERMISSION_GRANTED; 3125 } 3126 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3127 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3128 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3129 return PackageManager.PERMISSION_GRANTED; 3130 } 3131 } 3132 } 3133 3134 return PackageManager.PERMISSION_DENIED; 3135 } 3136 3137 @Override 3138 public int checkUidPermission(String permName, int uid) { 3139 final int userId = UserHandle.getUserId(uid); 3140 3141 if (!sUserManager.exists(userId)) { 3142 return PackageManager.PERMISSION_DENIED; 3143 } 3144 3145 synchronized (mPackages) { 3146 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3147 if (obj != null) { 3148 final SettingBase ps = (SettingBase) obj; 3149 final PermissionsState permissionsState = ps.getPermissionsState(); 3150 if (permissionsState.hasPermission(permName, userId)) { 3151 return PackageManager.PERMISSION_GRANTED; 3152 } 3153 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3154 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3155 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3156 return PackageManager.PERMISSION_GRANTED; 3157 } 3158 } else { 3159 ArraySet<String> perms = mSystemPermissions.get(uid); 3160 if (perms != null) { 3161 if (perms.contains(permName)) { 3162 return PackageManager.PERMISSION_GRANTED; 3163 } 3164 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3165 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3166 return PackageManager.PERMISSION_GRANTED; 3167 } 3168 } 3169 } 3170 } 3171 3172 return PackageManager.PERMISSION_DENIED; 3173 } 3174 3175 @Override 3176 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3177 if (UserHandle.getCallingUserId() != userId) { 3178 mContext.enforceCallingPermission( 3179 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3180 "isPermissionRevokedByPolicy for user " + userId); 3181 } 3182 3183 if (checkPermission(permission, packageName, userId) 3184 == PackageManager.PERMISSION_GRANTED) { 3185 return false; 3186 } 3187 3188 final long identity = Binder.clearCallingIdentity(); 3189 try { 3190 final int flags = getPermissionFlags(permission, packageName, userId); 3191 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3192 } finally { 3193 Binder.restoreCallingIdentity(identity); 3194 } 3195 } 3196 3197 /** 3198 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3199 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3200 * @param checkShell TODO(yamasani): 3201 * @param message the message to log on security exception 3202 */ 3203 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3204 boolean checkShell, String message) { 3205 if (userId < 0) { 3206 throw new IllegalArgumentException("Invalid userId " + userId); 3207 } 3208 if (checkShell) { 3209 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3210 } 3211 if (userId == UserHandle.getUserId(callingUid)) return; 3212 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3213 if (requireFullPermission) { 3214 mContext.enforceCallingOrSelfPermission( 3215 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3216 } else { 3217 try { 3218 mContext.enforceCallingOrSelfPermission( 3219 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3220 } catch (SecurityException se) { 3221 mContext.enforceCallingOrSelfPermission( 3222 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3223 } 3224 } 3225 } 3226 } 3227 3228 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3229 if (callingUid == Process.SHELL_UID) { 3230 if (userHandle >= 0 3231 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3232 throw new SecurityException("Shell does not have permission to access user " 3233 + userHandle); 3234 } else if (userHandle < 0) { 3235 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3236 + Debug.getCallers(3)); 3237 } 3238 } 3239 } 3240 3241 private BasePermission findPermissionTreeLP(String permName) { 3242 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3243 if (permName.startsWith(bp.name) && 3244 permName.length() > bp.name.length() && 3245 permName.charAt(bp.name.length()) == '.') { 3246 return bp; 3247 } 3248 } 3249 return null; 3250 } 3251 3252 private BasePermission checkPermissionTreeLP(String permName) { 3253 if (permName != null) { 3254 BasePermission bp = findPermissionTreeLP(permName); 3255 if (bp != null) { 3256 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3257 return bp; 3258 } 3259 throw new SecurityException("Calling uid " 3260 + Binder.getCallingUid() 3261 + " is not allowed to add to permission tree " 3262 + bp.name + " owned by uid " + bp.uid); 3263 } 3264 } 3265 throw new SecurityException("No permission tree found for " + permName); 3266 } 3267 3268 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3269 if (s1 == null) { 3270 return s2 == null; 3271 } 3272 if (s2 == null) { 3273 return false; 3274 } 3275 if (s1.getClass() != s2.getClass()) { 3276 return false; 3277 } 3278 return s1.equals(s2); 3279 } 3280 3281 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3282 if (pi1.icon != pi2.icon) return false; 3283 if (pi1.logo != pi2.logo) return false; 3284 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3285 if (!compareStrings(pi1.name, pi2.name)) return false; 3286 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3287 // We'll take care of setting this one. 3288 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3289 // These are not currently stored in settings. 3290 //if (!compareStrings(pi1.group, pi2.group)) return false; 3291 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3292 //if (pi1.labelRes != pi2.labelRes) return false; 3293 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3294 return true; 3295 } 3296 3297 int permissionInfoFootprint(PermissionInfo info) { 3298 int size = info.name.length(); 3299 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3300 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3301 return size; 3302 } 3303 3304 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3305 int size = 0; 3306 for (BasePermission perm : mSettings.mPermissions.values()) { 3307 if (perm.uid == tree.uid) { 3308 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3309 } 3310 } 3311 return size; 3312 } 3313 3314 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3315 // We calculate the max size of permissions defined by this uid and throw 3316 // if that plus the size of 'info' would exceed our stated maximum. 3317 if (tree.uid != Process.SYSTEM_UID) { 3318 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3319 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3320 throw new SecurityException("Permission tree size cap exceeded"); 3321 } 3322 } 3323 } 3324 3325 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3326 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3327 throw new SecurityException("Label must be specified in permission"); 3328 } 3329 BasePermission tree = checkPermissionTreeLP(info.name); 3330 BasePermission bp = mSettings.mPermissions.get(info.name); 3331 boolean added = bp == null; 3332 boolean changed = true; 3333 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3334 if (added) { 3335 enforcePermissionCapLocked(info, tree); 3336 bp = new BasePermission(info.name, tree.sourcePackage, 3337 BasePermission.TYPE_DYNAMIC); 3338 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3339 throw new SecurityException( 3340 "Not allowed to modify non-dynamic permission " 3341 + info.name); 3342 } else { 3343 if (bp.protectionLevel == fixedLevel 3344 && bp.perm.owner.equals(tree.perm.owner) 3345 && bp.uid == tree.uid 3346 && comparePermissionInfos(bp.perm.info, info)) { 3347 changed = false; 3348 } 3349 } 3350 bp.protectionLevel = fixedLevel; 3351 info = new PermissionInfo(info); 3352 info.protectionLevel = fixedLevel; 3353 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3354 bp.perm.info.packageName = tree.perm.info.packageName; 3355 bp.uid = tree.uid; 3356 if (added) { 3357 mSettings.mPermissions.put(info.name, bp); 3358 } 3359 if (changed) { 3360 if (!async) { 3361 mSettings.writeLPr(); 3362 } else { 3363 scheduleWriteSettingsLocked(); 3364 } 3365 } 3366 return added; 3367 } 3368 3369 @Override 3370 public boolean addPermission(PermissionInfo info) { 3371 synchronized (mPackages) { 3372 return addPermissionLocked(info, false); 3373 } 3374 } 3375 3376 @Override 3377 public boolean addPermissionAsync(PermissionInfo info) { 3378 synchronized (mPackages) { 3379 return addPermissionLocked(info, true); 3380 } 3381 } 3382 3383 @Override 3384 public void removePermission(String name) { 3385 synchronized (mPackages) { 3386 checkPermissionTreeLP(name); 3387 BasePermission bp = mSettings.mPermissions.get(name); 3388 if (bp != null) { 3389 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3390 throw new SecurityException( 3391 "Not allowed to modify non-dynamic permission " 3392 + name); 3393 } 3394 mSettings.mPermissions.remove(name); 3395 mSettings.writeLPr(); 3396 } 3397 } 3398 } 3399 3400 private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg, 3401 BasePermission bp) { 3402 int index = pkg.requestedPermissions.indexOf(bp.name); 3403 if (index == -1) { 3404 throw new SecurityException("Package " + pkg.packageName 3405 + " has not requested permission " + bp.name); 3406 } 3407 if (!bp.isRuntime()) { 3408 throw new SecurityException("Permission " + bp.name 3409 + " is not a changeable permission type"); 3410 } 3411 } 3412 3413 @Override 3414 public void grantRuntimePermission(String packageName, String name, final int userId) { 3415 if (!sUserManager.exists(userId)) { 3416 Log.e(TAG, "No such user:" + userId); 3417 return; 3418 } 3419 3420 mContext.enforceCallingOrSelfPermission( 3421 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3422 "grantRuntimePermission"); 3423 3424 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3425 "grantRuntimePermission"); 3426 3427 final int uid; 3428 final SettingBase sb; 3429 3430 synchronized (mPackages) { 3431 final PackageParser.Package pkg = mPackages.get(packageName); 3432 if (pkg == null) { 3433 throw new IllegalArgumentException("Unknown package: " + packageName); 3434 } 3435 3436 final BasePermission bp = mSettings.mPermissions.get(name); 3437 if (bp == null) { 3438 throw new IllegalArgumentException("Unknown permission: " + name); 3439 } 3440 3441 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3442 3443 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3444 sb = (SettingBase) pkg.mExtras; 3445 if (sb == null) { 3446 throw new IllegalArgumentException("Unknown package: " + packageName); 3447 } 3448 3449 final PermissionsState permissionsState = sb.getPermissionsState(); 3450 3451 final int flags = permissionsState.getPermissionFlags(name, userId); 3452 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3453 throw new SecurityException("Cannot grant system fixed permission: " 3454 + name + " for package: " + packageName); 3455 } 3456 3457 final int result = permissionsState.grantRuntimePermission(bp, userId); 3458 switch (result) { 3459 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3460 return; 3461 } 3462 3463 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3464 mHandler.post(new Runnable() { 3465 @Override 3466 public void run() { 3467 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED); 3468 } 3469 }); 3470 } break; 3471 } 3472 3473 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3474 3475 // Not critical if that is lost - app has to request again. 3476 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3477 } 3478 3479 // Only need to do this if user is initialized. Otherwise it's a new user 3480 // and there are no processes running as the user yet and there's no need 3481 // to make an expensive call to remount processes for the changed permissions. 3482 if (READ_EXTERNAL_STORAGE.equals(name) 3483 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3484 final long token = Binder.clearCallingIdentity(); 3485 try { 3486 if (sUserManager.isInitialized(userId)) { 3487 MountServiceInternal mountServiceInternal = LocalServices.getService( 3488 MountServiceInternal.class); 3489 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 3490 } 3491 } finally { 3492 Binder.restoreCallingIdentity(token); 3493 } 3494 } 3495 } 3496 3497 @Override 3498 public void revokeRuntimePermission(String packageName, String name, int userId) { 3499 if (!sUserManager.exists(userId)) { 3500 Log.e(TAG, "No such user:" + userId); 3501 return; 3502 } 3503 3504 mContext.enforceCallingOrSelfPermission( 3505 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3506 "revokeRuntimePermission"); 3507 3508 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3509 "revokeRuntimePermission"); 3510 3511 final SettingBase sb; 3512 3513 synchronized (mPackages) { 3514 final PackageParser.Package pkg = mPackages.get(packageName); 3515 if (pkg == null) { 3516 throw new IllegalArgumentException("Unknown package: " + packageName); 3517 } 3518 3519 final BasePermission bp = mSettings.mPermissions.get(name); 3520 if (bp == null) { 3521 throw new IllegalArgumentException("Unknown permission: " + name); 3522 } 3523 3524 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3525 3526 sb = (SettingBase) pkg.mExtras; 3527 if (sb == null) { 3528 throw new IllegalArgumentException("Unknown package: " + packageName); 3529 } 3530 3531 final PermissionsState permissionsState = sb.getPermissionsState(); 3532 3533 final int flags = permissionsState.getPermissionFlags(name, userId); 3534 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3535 throw new SecurityException("Cannot revoke system fixed permission: " 3536 + name + " for package: " + packageName); 3537 } 3538 3539 if (permissionsState.revokeRuntimePermission(bp, userId) == 3540 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3541 return; 3542 } 3543 3544 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3545 3546 // Critical, after this call app should never have the permission. 3547 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3548 } 3549 3550 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3551 } 3552 3553 @Override 3554 public void resetRuntimePermissions() { 3555 mContext.enforceCallingOrSelfPermission( 3556 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3557 "revokeRuntimePermission"); 3558 3559 int callingUid = Binder.getCallingUid(); 3560 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3561 mContext.enforceCallingOrSelfPermission( 3562 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3563 "resetRuntimePermissions"); 3564 } 3565 3566 synchronized (mPackages) { 3567 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 3568 for (int userId : UserManagerService.getInstance().getUserIds()) { 3569 final int packageCount = mPackages.size(); 3570 for (int i = 0; i < packageCount; i++) { 3571 PackageParser.Package pkg = mPackages.valueAt(i); 3572 if (!(pkg.mExtras instanceof PackageSetting)) { 3573 continue; 3574 } 3575 PackageSetting ps = (PackageSetting) pkg.mExtras; 3576 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 3577 } 3578 } 3579 } 3580 } 3581 3582 @Override 3583 public int getPermissionFlags(String name, String packageName, int userId) { 3584 if (!sUserManager.exists(userId)) { 3585 return 0; 3586 } 3587 3588 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 3589 3590 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3591 "getPermissionFlags"); 3592 3593 synchronized (mPackages) { 3594 final PackageParser.Package pkg = mPackages.get(packageName); 3595 if (pkg == null) { 3596 throw new IllegalArgumentException("Unknown package: " + packageName); 3597 } 3598 3599 final BasePermission bp = mSettings.mPermissions.get(name); 3600 if (bp == null) { 3601 throw new IllegalArgumentException("Unknown permission: " + name); 3602 } 3603 3604 SettingBase sb = (SettingBase) pkg.mExtras; 3605 if (sb == null) { 3606 throw new IllegalArgumentException("Unknown package: " + packageName); 3607 } 3608 3609 PermissionsState permissionsState = sb.getPermissionsState(); 3610 return permissionsState.getPermissionFlags(name, userId); 3611 } 3612 } 3613 3614 @Override 3615 public void updatePermissionFlags(String name, String packageName, int flagMask, 3616 int flagValues, int userId) { 3617 if (!sUserManager.exists(userId)) { 3618 return; 3619 } 3620 3621 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 3622 3623 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3624 "updatePermissionFlags"); 3625 3626 // Only the system can change these flags and nothing else. 3627 if (getCallingUid() != Process.SYSTEM_UID) { 3628 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3629 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3630 flagMask &= ~PackageManager.FLAG_PERMISSION_POLICY_FIXED; 3631 flagValues &= ~PackageManager.FLAG_PERMISSION_POLICY_FIXED; 3632 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3633 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3634 } 3635 3636 synchronized (mPackages) { 3637 final PackageParser.Package pkg = mPackages.get(packageName); 3638 if (pkg == null) { 3639 throw new IllegalArgumentException("Unknown package: " + packageName); 3640 } 3641 3642 final BasePermission bp = mSettings.mPermissions.get(name); 3643 if (bp == null) { 3644 throw new IllegalArgumentException("Unknown permission: " + name); 3645 } 3646 3647 SettingBase sb = (SettingBase) pkg.mExtras; 3648 if (sb == null) { 3649 throw new IllegalArgumentException("Unknown package: " + packageName); 3650 } 3651 3652 PermissionsState permissionsState = sb.getPermissionsState(); 3653 3654 // Only the package manager can change flags for system component permissions. 3655 final int flags = permissionsState.getPermissionFlags(bp.name, userId); 3656 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3657 return; 3658 } 3659 3660 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 3661 3662 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3663 // Install and runtime permissions are stored in different places, 3664 // so figure out what permission changed and persist the change. 3665 if (permissionsState.getInstallPermissionState(name) != null) { 3666 scheduleWriteSettingsLocked(); 3667 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 3668 || hadState) { 3669 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3670 } 3671 } 3672 } 3673 } 3674 3675 /** 3676 * Update the permission flags for all packages and runtime permissions of a user in order 3677 * to allow device or profile owner to remove POLICY_FIXED. 3678 */ 3679 @Override 3680 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 3681 if (!sUserManager.exists(userId)) { 3682 return; 3683 } 3684 3685 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 3686 3687 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3688 "updatePermissionFlagsForAllApps"); 3689 3690 // Only the system can change system fixed flags. 3691 if (getCallingUid() != Process.SYSTEM_UID) { 3692 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3693 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3694 } 3695 3696 synchronized (mPackages) { 3697 boolean changed = false; 3698 final int packageCount = mPackages.size(); 3699 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 3700 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 3701 SettingBase sb = (SettingBase) pkg.mExtras; 3702 if (sb == null) { 3703 continue; 3704 } 3705 PermissionsState permissionsState = sb.getPermissionsState(); 3706 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 3707 userId, flagMask, flagValues); 3708 } 3709 if (changed) { 3710 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3711 } 3712 } 3713 } 3714 3715 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 3716 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 3717 != PackageManager.PERMISSION_GRANTED 3718 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 3719 != PackageManager.PERMISSION_GRANTED) { 3720 throw new SecurityException(message + " requires " 3721 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 3722 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 3723 } 3724 } 3725 3726 @Override 3727 public boolean shouldShowRequestPermissionRationale(String permissionName, 3728 String packageName, int userId) { 3729 if (UserHandle.getCallingUserId() != userId) { 3730 mContext.enforceCallingPermission( 3731 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3732 "canShowRequestPermissionRationale for user " + userId); 3733 } 3734 3735 final int uid = getPackageUid(packageName, userId); 3736 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 3737 return false; 3738 } 3739 3740 if (checkPermission(permissionName, packageName, userId) 3741 == PackageManager.PERMISSION_GRANTED) { 3742 return false; 3743 } 3744 3745 final int flags; 3746 3747 final long identity = Binder.clearCallingIdentity(); 3748 try { 3749 flags = getPermissionFlags(permissionName, 3750 packageName, userId); 3751 } finally { 3752 Binder.restoreCallingIdentity(identity); 3753 } 3754 3755 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 3756 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 3757 | PackageManager.FLAG_PERMISSION_USER_FIXED; 3758 3759 if ((flags & fixedFlags) != 0) { 3760 return false; 3761 } 3762 3763 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 3764 } 3765 3766 void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) { 3767 BasePermission bp = mSettings.mPermissions.get(permission); 3768 if (bp == null) { 3769 throw new SecurityException("Missing " + permission + " permission"); 3770 } 3771 3772 SettingBase sb = (SettingBase) pkg.mExtras; 3773 PermissionsState permissionsState = sb.getPermissionsState(); 3774 3775 if (permissionsState.grantInstallPermission(bp) != 3776 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3777 scheduleWriteSettingsLocked(); 3778 } 3779 } 3780 3781 @Override 3782 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3783 mContext.enforceCallingOrSelfPermission( 3784 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 3785 "addOnPermissionsChangeListener"); 3786 3787 synchronized (mPackages) { 3788 mOnPermissionChangeListeners.addListenerLocked(listener); 3789 } 3790 } 3791 3792 @Override 3793 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3794 synchronized (mPackages) { 3795 mOnPermissionChangeListeners.removeListenerLocked(listener); 3796 } 3797 } 3798 3799 @Override 3800 public boolean isProtectedBroadcast(String actionName) { 3801 synchronized (mPackages) { 3802 return mProtectedBroadcasts.contains(actionName); 3803 } 3804 } 3805 3806 @Override 3807 public int checkSignatures(String pkg1, String pkg2) { 3808 synchronized (mPackages) { 3809 final PackageParser.Package p1 = mPackages.get(pkg1); 3810 final PackageParser.Package p2 = mPackages.get(pkg2); 3811 if (p1 == null || p1.mExtras == null 3812 || p2 == null || p2.mExtras == null) { 3813 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3814 } 3815 return compareSignatures(p1.mSignatures, p2.mSignatures); 3816 } 3817 } 3818 3819 @Override 3820 public int checkUidSignatures(int uid1, int uid2) { 3821 // Map to base uids. 3822 uid1 = UserHandle.getAppId(uid1); 3823 uid2 = UserHandle.getAppId(uid2); 3824 // reader 3825 synchronized (mPackages) { 3826 Signature[] s1; 3827 Signature[] s2; 3828 Object obj = mSettings.getUserIdLPr(uid1); 3829 if (obj != null) { 3830 if (obj instanceof SharedUserSetting) { 3831 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3832 } else if (obj instanceof PackageSetting) { 3833 s1 = ((PackageSetting)obj).signatures.mSignatures; 3834 } else { 3835 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3836 } 3837 } else { 3838 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3839 } 3840 obj = mSettings.getUserIdLPr(uid2); 3841 if (obj != null) { 3842 if (obj instanceof SharedUserSetting) { 3843 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3844 } else if (obj instanceof PackageSetting) { 3845 s2 = ((PackageSetting)obj).signatures.mSignatures; 3846 } else { 3847 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3848 } 3849 } else { 3850 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3851 } 3852 return compareSignatures(s1, s2); 3853 } 3854 } 3855 3856 private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) { 3857 final long identity = Binder.clearCallingIdentity(); 3858 try { 3859 if (sb instanceof SharedUserSetting) { 3860 SharedUserSetting sus = (SharedUserSetting) sb; 3861 final int packageCount = sus.packages.size(); 3862 for (int i = 0; i < packageCount; i++) { 3863 PackageSetting susPs = sus.packages.valueAt(i); 3864 if (userId == UserHandle.USER_ALL) { 3865 killApplication(susPs.pkg.packageName, susPs.appId, reason); 3866 } else { 3867 final int uid = UserHandle.getUid(userId, susPs.appId); 3868 killUid(uid, reason); 3869 } 3870 } 3871 } else if (sb instanceof PackageSetting) { 3872 PackageSetting ps = (PackageSetting) sb; 3873 if (userId == UserHandle.USER_ALL) { 3874 killApplication(ps.pkg.packageName, ps.appId, reason); 3875 } else { 3876 final int uid = UserHandle.getUid(userId, ps.appId); 3877 killUid(uid, reason); 3878 } 3879 } 3880 } finally { 3881 Binder.restoreCallingIdentity(identity); 3882 } 3883 } 3884 3885 private static void killUid(int uid, String reason) { 3886 IActivityManager am = ActivityManagerNative.getDefault(); 3887 if (am != null) { 3888 try { 3889 am.killUid(uid, reason); 3890 } catch (RemoteException e) { 3891 /* ignore - same process */ 3892 } 3893 } 3894 } 3895 3896 /** 3897 * Compares two sets of signatures. Returns: 3898 * <br /> 3899 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3900 * <br /> 3901 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3902 * <br /> 3903 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3904 * <br /> 3905 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3906 * <br /> 3907 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3908 */ 3909 static int compareSignatures(Signature[] s1, Signature[] s2) { 3910 if (s1 == null) { 3911 return s2 == null 3912 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3913 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3914 } 3915 3916 if (s2 == null) { 3917 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3918 } 3919 3920 if (s1.length != s2.length) { 3921 return PackageManager.SIGNATURE_NO_MATCH; 3922 } 3923 3924 // Since both signature sets are of size 1, we can compare without HashSets. 3925 if (s1.length == 1) { 3926 return s1[0].equals(s2[0]) ? 3927 PackageManager.SIGNATURE_MATCH : 3928 PackageManager.SIGNATURE_NO_MATCH; 3929 } 3930 3931 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3932 for (Signature sig : s1) { 3933 set1.add(sig); 3934 } 3935 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3936 for (Signature sig : s2) { 3937 set2.add(sig); 3938 } 3939 // Make sure s2 contains all signatures in s1. 3940 if (set1.equals(set2)) { 3941 return PackageManager.SIGNATURE_MATCH; 3942 } 3943 return PackageManager.SIGNATURE_NO_MATCH; 3944 } 3945 3946 /** 3947 * If the database version for this type of package (internal storage or 3948 * external storage) is less than the version where package signatures 3949 * were updated, return true. 3950 */ 3951 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3952 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 3953 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 3954 } 3955 3956 /** 3957 * Used for backward compatibility to make sure any packages with 3958 * certificate chains get upgraded to the new style. {@code existingSigs} 3959 * will be in the old format (since they were stored on disk from before the 3960 * system upgrade) and {@code scannedSigs} will be in the newer format. 3961 */ 3962 private int compareSignaturesCompat(PackageSignatures existingSigs, 3963 PackageParser.Package scannedPkg) { 3964 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 3965 return PackageManager.SIGNATURE_NO_MATCH; 3966 } 3967 3968 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 3969 for (Signature sig : existingSigs.mSignatures) { 3970 existingSet.add(sig); 3971 } 3972 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 3973 for (Signature sig : scannedPkg.mSignatures) { 3974 try { 3975 Signature[] chainSignatures = sig.getChainSignatures(); 3976 for (Signature chainSig : chainSignatures) { 3977 scannedCompatSet.add(chainSig); 3978 } 3979 } catch (CertificateEncodingException e) { 3980 scannedCompatSet.add(sig); 3981 } 3982 } 3983 /* 3984 * Make sure the expanded scanned set contains all signatures in the 3985 * existing one. 3986 */ 3987 if (scannedCompatSet.equals(existingSet)) { 3988 // Migrate the old signatures to the new scheme. 3989 existingSigs.assignSignatures(scannedPkg.mSignatures); 3990 // The new KeySets will be re-added later in the scanning process. 3991 synchronized (mPackages) { 3992 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 3993 } 3994 return PackageManager.SIGNATURE_MATCH; 3995 } 3996 return PackageManager.SIGNATURE_NO_MATCH; 3997 } 3998 3999 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4000 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4001 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4002 } 4003 4004 private int compareSignaturesRecover(PackageSignatures existingSigs, 4005 PackageParser.Package scannedPkg) { 4006 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4007 return PackageManager.SIGNATURE_NO_MATCH; 4008 } 4009 4010 String msg = null; 4011 try { 4012 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4013 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4014 + scannedPkg.packageName); 4015 return PackageManager.SIGNATURE_MATCH; 4016 } 4017 } catch (CertificateException e) { 4018 msg = e.getMessage(); 4019 } 4020 4021 logCriticalInfo(Log.INFO, 4022 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4023 return PackageManager.SIGNATURE_NO_MATCH; 4024 } 4025 4026 @Override 4027 public String[] getPackagesForUid(int uid) { 4028 uid = UserHandle.getAppId(uid); 4029 // reader 4030 synchronized (mPackages) { 4031 Object obj = mSettings.getUserIdLPr(uid); 4032 if (obj instanceof SharedUserSetting) { 4033 final SharedUserSetting sus = (SharedUserSetting) obj; 4034 final int N = sus.packages.size(); 4035 final String[] res = new String[N]; 4036 final Iterator<PackageSetting> it = sus.packages.iterator(); 4037 int i = 0; 4038 while (it.hasNext()) { 4039 res[i++] = it.next().name; 4040 } 4041 return res; 4042 } else if (obj instanceof PackageSetting) { 4043 final PackageSetting ps = (PackageSetting) obj; 4044 return new String[] { ps.name }; 4045 } 4046 } 4047 return null; 4048 } 4049 4050 @Override 4051 public String getNameForUid(int uid) { 4052 // reader 4053 synchronized (mPackages) { 4054 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4055 if (obj instanceof SharedUserSetting) { 4056 final SharedUserSetting sus = (SharedUserSetting) obj; 4057 return sus.name + ":" + sus.userId; 4058 } else if (obj instanceof PackageSetting) { 4059 final PackageSetting ps = (PackageSetting) obj; 4060 return ps.name; 4061 } 4062 } 4063 return null; 4064 } 4065 4066 @Override 4067 public int getUidForSharedUser(String sharedUserName) { 4068 if(sharedUserName == null) { 4069 return -1; 4070 } 4071 // reader 4072 synchronized (mPackages) { 4073 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4074 if (suid == null) { 4075 return -1; 4076 } 4077 return suid.userId; 4078 } 4079 } 4080 4081 @Override 4082 public int getFlagsForUid(int uid) { 4083 synchronized (mPackages) { 4084 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4085 if (obj instanceof SharedUserSetting) { 4086 final SharedUserSetting sus = (SharedUserSetting) obj; 4087 return sus.pkgFlags; 4088 } else if (obj instanceof PackageSetting) { 4089 final PackageSetting ps = (PackageSetting) obj; 4090 return ps.pkgFlags; 4091 } 4092 } 4093 return 0; 4094 } 4095 4096 @Override 4097 public int getPrivateFlagsForUid(int uid) { 4098 synchronized (mPackages) { 4099 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4100 if (obj instanceof SharedUserSetting) { 4101 final SharedUserSetting sus = (SharedUserSetting) obj; 4102 return sus.pkgPrivateFlags; 4103 } else if (obj instanceof PackageSetting) { 4104 final PackageSetting ps = (PackageSetting) obj; 4105 return ps.pkgPrivateFlags; 4106 } 4107 } 4108 return 0; 4109 } 4110 4111 @Override 4112 public boolean isUidPrivileged(int uid) { 4113 uid = UserHandle.getAppId(uid); 4114 // reader 4115 synchronized (mPackages) { 4116 Object obj = mSettings.getUserIdLPr(uid); 4117 if (obj instanceof SharedUserSetting) { 4118 final SharedUserSetting sus = (SharedUserSetting) obj; 4119 final Iterator<PackageSetting> it = sus.packages.iterator(); 4120 while (it.hasNext()) { 4121 if (it.next().isPrivileged()) { 4122 return true; 4123 } 4124 } 4125 } else if (obj instanceof PackageSetting) { 4126 final PackageSetting ps = (PackageSetting) obj; 4127 return ps.isPrivileged(); 4128 } 4129 } 4130 return false; 4131 } 4132 4133 @Override 4134 public String[] getAppOpPermissionPackages(String permissionName) { 4135 synchronized (mPackages) { 4136 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4137 if (pkgs == null) { 4138 return null; 4139 } 4140 return pkgs.toArray(new String[pkgs.size()]); 4141 } 4142 } 4143 4144 @Override 4145 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4146 int flags, int userId) { 4147 if (!sUserManager.exists(userId)) return null; 4148 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 4149 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4150 return chooseBestActivity(intent, resolvedType, flags, query, userId); 4151 } 4152 4153 @Override 4154 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4155 IntentFilter filter, int match, ComponentName activity) { 4156 final int userId = UserHandle.getCallingUserId(); 4157 if (DEBUG_PREFERRED) { 4158 Log.v(TAG, "setLastChosenActivity intent=" + intent 4159 + " resolvedType=" + resolvedType 4160 + " flags=" + flags 4161 + " filter=" + filter 4162 + " match=" + match 4163 + " activity=" + activity); 4164 filter.dump(new PrintStreamPrinter(System.out), " "); 4165 } 4166 intent.setComponent(null); 4167 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4168 // Find any earlier preferred or last chosen entries and nuke them 4169 findPreferredActivity(intent, resolvedType, 4170 flags, query, 0, false, true, false, userId); 4171 // Add the new activity as the last chosen for this filter 4172 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4173 "Setting last chosen"); 4174 } 4175 4176 @Override 4177 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4178 final int userId = UserHandle.getCallingUserId(); 4179 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4180 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4181 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4182 false, false, false, userId); 4183 } 4184 4185 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4186 int flags, List<ResolveInfo> query, int userId) { 4187 if (query != null) { 4188 final int N = query.size(); 4189 if (N == 1) { 4190 return query.get(0); 4191 } else if (N > 1) { 4192 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4193 // If there is more than one activity with the same priority, 4194 // then let the user decide between them. 4195 ResolveInfo r0 = query.get(0); 4196 ResolveInfo r1 = query.get(1); 4197 if (DEBUG_INTENT_MATCHING || debug) { 4198 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4199 + r1.activityInfo.name + "=" + r1.priority); 4200 } 4201 // If the first activity has a higher priority, or a different 4202 // default, then it is always desireable to pick it. 4203 if (r0.priority != r1.priority 4204 || r0.preferredOrder != r1.preferredOrder 4205 || r0.isDefault != r1.isDefault) { 4206 return query.get(0); 4207 } 4208 // If we have saved a preference for a preferred activity for 4209 // this Intent, use that. 4210 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4211 flags, query, r0.priority, true, false, debug, userId); 4212 if (ri != null) { 4213 return ri; 4214 } 4215 if (userId != 0) { 4216 ri = new ResolveInfo(mResolveInfo); 4217 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4218 ri.activityInfo.applicationInfo = new ApplicationInfo( 4219 ri.activityInfo.applicationInfo); 4220 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4221 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4222 return ri; 4223 } 4224 return mResolveInfo; 4225 } 4226 } 4227 return null; 4228 } 4229 4230 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4231 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4232 final int N = query.size(); 4233 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4234 .get(userId); 4235 // Get the list of persistent preferred activities that handle the intent 4236 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4237 List<PersistentPreferredActivity> pprefs = ppir != null 4238 ? ppir.queryIntent(intent, resolvedType, 4239 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4240 : null; 4241 if (pprefs != null && pprefs.size() > 0) { 4242 final int M = pprefs.size(); 4243 for (int i=0; i<M; i++) { 4244 final PersistentPreferredActivity ppa = pprefs.get(i); 4245 if (DEBUG_PREFERRED || debug) { 4246 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4247 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4248 + "\n component=" + ppa.mComponent); 4249 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4250 } 4251 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4252 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4253 if (DEBUG_PREFERRED || debug) { 4254 Slog.v(TAG, "Found persistent preferred activity:"); 4255 if (ai != null) { 4256 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4257 } else { 4258 Slog.v(TAG, " null"); 4259 } 4260 } 4261 if (ai == null) { 4262 // This previously registered persistent preferred activity 4263 // component is no longer known. Ignore it and do NOT remove it. 4264 continue; 4265 } 4266 for (int j=0; j<N; j++) { 4267 final ResolveInfo ri = query.get(j); 4268 if (!ri.activityInfo.applicationInfo.packageName 4269 .equals(ai.applicationInfo.packageName)) { 4270 continue; 4271 } 4272 if (!ri.activityInfo.name.equals(ai.name)) { 4273 continue; 4274 } 4275 // Found a persistent preference that can handle the intent. 4276 if (DEBUG_PREFERRED || debug) { 4277 Slog.v(TAG, "Returning persistent preferred activity: " + 4278 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4279 } 4280 return ri; 4281 } 4282 } 4283 } 4284 return null; 4285 } 4286 4287 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4288 List<ResolveInfo> query, int priority, boolean always, 4289 boolean removeMatches, boolean debug, int userId) { 4290 if (!sUserManager.exists(userId)) return null; 4291 // writer 4292 synchronized (mPackages) { 4293 if (intent.getSelector() != null) { 4294 intent = intent.getSelector(); 4295 } 4296 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4297 4298 // Try to find a matching persistent preferred activity. 4299 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4300 debug, userId); 4301 4302 // If a persistent preferred activity matched, use it. 4303 if (pri != null) { 4304 return pri; 4305 } 4306 4307 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4308 // Get the list of preferred activities that handle the intent 4309 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4310 List<PreferredActivity> prefs = pir != null 4311 ? pir.queryIntent(intent, resolvedType, 4312 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4313 : null; 4314 if (prefs != null && prefs.size() > 0) { 4315 boolean changed = false; 4316 try { 4317 // First figure out how good the original match set is. 4318 // We will only allow preferred activities that came 4319 // from the same match quality. 4320 int match = 0; 4321 4322 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4323 4324 final int N = query.size(); 4325 for (int j=0; j<N; j++) { 4326 final ResolveInfo ri = query.get(j); 4327 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4328 + ": 0x" + Integer.toHexString(match)); 4329 if (ri.match > match) { 4330 match = ri.match; 4331 } 4332 } 4333 4334 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4335 + Integer.toHexString(match)); 4336 4337 match &= IntentFilter.MATCH_CATEGORY_MASK; 4338 final int M = prefs.size(); 4339 for (int i=0; i<M; i++) { 4340 final PreferredActivity pa = prefs.get(i); 4341 if (DEBUG_PREFERRED || debug) { 4342 Slog.v(TAG, "Checking PreferredActivity ds=" 4343 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4344 + "\n component=" + pa.mPref.mComponent); 4345 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4346 } 4347 if (pa.mPref.mMatch != match) { 4348 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4349 + Integer.toHexString(pa.mPref.mMatch)); 4350 continue; 4351 } 4352 // If it's not an "always" type preferred activity and that's what we're 4353 // looking for, skip it. 4354 if (always && !pa.mPref.mAlways) { 4355 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4356 continue; 4357 } 4358 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4359 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4360 if (DEBUG_PREFERRED || debug) { 4361 Slog.v(TAG, "Found preferred activity:"); 4362 if (ai != null) { 4363 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4364 } else { 4365 Slog.v(TAG, " null"); 4366 } 4367 } 4368 if (ai == null) { 4369 // This previously registered preferred activity 4370 // component is no longer known. Most likely an update 4371 // to the app was installed and in the new version this 4372 // component no longer exists. Clean it up by removing 4373 // it from the preferred activities list, and skip it. 4374 Slog.w(TAG, "Removing dangling preferred activity: " 4375 + pa.mPref.mComponent); 4376 pir.removeFilter(pa); 4377 changed = true; 4378 continue; 4379 } 4380 for (int j=0; j<N; j++) { 4381 final ResolveInfo ri = query.get(j); 4382 if (!ri.activityInfo.applicationInfo.packageName 4383 .equals(ai.applicationInfo.packageName)) { 4384 continue; 4385 } 4386 if (!ri.activityInfo.name.equals(ai.name)) { 4387 continue; 4388 } 4389 4390 if (removeMatches) { 4391 pir.removeFilter(pa); 4392 changed = true; 4393 if (DEBUG_PREFERRED) { 4394 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4395 } 4396 break; 4397 } 4398 4399 // Okay we found a previously set preferred or last chosen app. 4400 // If the result set is different from when this 4401 // was created, we need to clear it and re-ask the 4402 // user their preference, if we're looking for an "always" type entry. 4403 if (always && !pa.mPref.sameSet(query)) { 4404 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4405 + intent + " type " + resolvedType); 4406 if (DEBUG_PREFERRED) { 4407 Slog.v(TAG, "Removing preferred activity since set changed " 4408 + pa.mPref.mComponent); 4409 } 4410 pir.removeFilter(pa); 4411 // Re-add the filter as a "last chosen" entry (!always) 4412 PreferredActivity lastChosen = new PreferredActivity( 4413 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4414 pir.addFilter(lastChosen); 4415 changed = true; 4416 return null; 4417 } 4418 4419 // Yay! Either the set matched or we're looking for the last chosen 4420 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4421 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4422 return ri; 4423 } 4424 } 4425 } finally { 4426 if (changed) { 4427 if (DEBUG_PREFERRED) { 4428 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4429 } 4430 scheduleWritePackageRestrictionsLocked(userId); 4431 } 4432 } 4433 } 4434 } 4435 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4436 return null; 4437 } 4438 4439 /* 4440 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4441 */ 4442 @Override 4443 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4444 int targetUserId) { 4445 mContext.enforceCallingOrSelfPermission( 4446 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4447 List<CrossProfileIntentFilter> matches = 4448 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4449 if (matches != null) { 4450 int size = matches.size(); 4451 for (int i = 0; i < size; i++) { 4452 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4453 } 4454 } 4455 if (hasWebURI(intent)) { 4456 // cross-profile app linking works only towards the parent. 4457 final UserInfo parent = getProfileParent(sourceUserId); 4458 synchronized(mPackages) { 4459 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 4460 intent, resolvedType, 0, sourceUserId, parent.id); 4461 return xpDomainInfo != null; 4462 } 4463 } 4464 return false; 4465 } 4466 4467 private UserInfo getProfileParent(int userId) { 4468 final long identity = Binder.clearCallingIdentity(); 4469 try { 4470 return sUserManager.getProfileParent(userId); 4471 } finally { 4472 Binder.restoreCallingIdentity(identity); 4473 } 4474 } 4475 4476 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4477 String resolvedType, int userId) { 4478 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4479 if (resolver != null) { 4480 return resolver.queryIntent(intent, resolvedType, false, userId); 4481 } 4482 return null; 4483 } 4484 4485 @Override 4486 public List<ResolveInfo> queryIntentActivities(Intent intent, 4487 String resolvedType, int flags, int userId) { 4488 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4489 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4490 ComponentName comp = intent.getComponent(); 4491 if (comp == null) { 4492 if (intent.getSelector() != null) { 4493 intent = intent.getSelector(); 4494 comp = intent.getComponent(); 4495 } 4496 } 4497 4498 if (comp != null) { 4499 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4500 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4501 if (ai != null) { 4502 final ResolveInfo ri = new ResolveInfo(); 4503 ri.activityInfo = ai; 4504 list.add(ri); 4505 } 4506 return list; 4507 } 4508 4509 // reader 4510 synchronized (mPackages) { 4511 final String pkgName = intent.getPackage(); 4512 if (pkgName == null) { 4513 List<CrossProfileIntentFilter> matchingFilters = 4514 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4515 // Check for results that need to skip the current profile. 4516 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4517 resolvedType, flags, userId); 4518 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4519 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4520 result.add(xpResolveInfo); 4521 return filterIfNotPrimaryUser(result, userId); 4522 } 4523 4524 // Check for results in the current profile. 4525 List<ResolveInfo> result = mActivities.queryIntent( 4526 intent, resolvedType, flags, userId); 4527 4528 // Check for cross profile results. 4529 xpResolveInfo = queryCrossProfileIntents( 4530 matchingFilters, intent, resolvedType, flags, userId); 4531 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4532 result.add(xpResolveInfo); 4533 Collections.sort(result, mResolvePrioritySorter); 4534 } 4535 result = filterIfNotPrimaryUser(result, userId); 4536 if (hasWebURI(intent)) { 4537 CrossProfileDomainInfo xpDomainInfo = null; 4538 final UserInfo parent = getProfileParent(userId); 4539 if (parent != null) { 4540 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 4541 flags, userId, parent.id); 4542 } 4543 if (xpDomainInfo != null) { 4544 if (xpResolveInfo != null) { 4545 // If we didn't remove it, the cross-profile ResolveInfo would be twice 4546 // in the result. 4547 result.remove(xpResolveInfo); 4548 } 4549 if (result.size() == 0) { 4550 result.add(xpDomainInfo.resolveInfo); 4551 return result; 4552 } 4553 } else if (result.size() <= 1) { 4554 return result; 4555 } 4556 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 4557 xpDomainInfo, userId); 4558 Collections.sort(result, mResolvePrioritySorter); 4559 } 4560 return result; 4561 } 4562 final PackageParser.Package pkg = mPackages.get(pkgName); 4563 if (pkg != null) { 4564 return filterIfNotPrimaryUser( 4565 mActivities.queryIntentForPackage( 4566 intent, resolvedType, flags, pkg.activities, userId), 4567 userId); 4568 } 4569 return new ArrayList<ResolveInfo>(); 4570 } 4571 } 4572 4573 private static class CrossProfileDomainInfo { 4574 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 4575 ResolveInfo resolveInfo; 4576 /* Best domain verification status of the activities found in the other profile */ 4577 int bestDomainVerificationStatus; 4578 } 4579 4580 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 4581 String resolvedType, int flags, int sourceUserId, int parentUserId) { 4582 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 4583 sourceUserId)) { 4584 return null; 4585 } 4586 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4587 resolvedType, flags, parentUserId); 4588 4589 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 4590 return null; 4591 } 4592 CrossProfileDomainInfo result = null; 4593 int size = resultTargetUser.size(); 4594 for (int i = 0; i < size; i++) { 4595 ResolveInfo riTargetUser = resultTargetUser.get(i); 4596 // Intent filter verification is only for filters that specify a host. So don't return 4597 // those that handle all web uris. 4598 if (riTargetUser.handleAllWebDataURI) { 4599 continue; 4600 } 4601 String packageName = riTargetUser.activityInfo.packageName; 4602 PackageSetting ps = mSettings.mPackages.get(packageName); 4603 if (ps == null) { 4604 continue; 4605 } 4606 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 4607 int status = (int)(verificationState >> 32); 4608 if (result == null) { 4609 result = new CrossProfileDomainInfo(); 4610 result.resolveInfo = 4611 createForwardingResolveInfo(null, sourceUserId, parentUserId); 4612 result.bestDomainVerificationStatus = status; 4613 } else { 4614 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 4615 result.bestDomainVerificationStatus); 4616 } 4617 } 4618 // Don't consider matches with status NEVER across profiles. 4619 if (result != null && result.bestDomainVerificationStatus 4620 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4621 return null; 4622 } 4623 return result; 4624 } 4625 4626 /** 4627 * Verification statuses are ordered from the worse to the best, except for 4628 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 4629 */ 4630 private int bestDomainVerificationStatus(int status1, int status2) { 4631 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4632 return status2; 4633 } 4634 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4635 return status1; 4636 } 4637 return (int) MathUtils.max(status1, status2); 4638 } 4639 4640 private boolean isUserEnabled(int userId) { 4641 long callingId = Binder.clearCallingIdentity(); 4642 try { 4643 UserInfo userInfo = sUserManager.getUserInfo(userId); 4644 return userInfo != null && userInfo.isEnabled(); 4645 } finally { 4646 Binder.restoreCallingIdentity(callingId); 4647 } 4648 } 4649 4650 /** 4651 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 4652 * 4653 * @return filtered list 4654 */ 4655 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 4656 if (userId == UserHandle.USER_OWNER) { 4657 return resolveInfos; 4658 } 4659 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 4660 ResolveInfo info = resolveInfos.get(i); 4661 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 4662 resolveInfos.remove(i); 4663 } 4664 } 4665 return resolveInfos; 4666 } 4667 4668 private static boolean hasWebURI(Intent intent) { 4669 if (intent.getData() == null) { 4670 return false; 4671 } 4672 final String scheme = intent.getScheme(); 4673 if (TextUtils.isEmpty(scheme)) { 4674 return false; 4675 } 4676 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4677 } 4678 4679 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 4680 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 4681 int userId) { 4682 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 4683 4684 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4685 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 4686 candidates.size()); 4687 } 4688 4689 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4690 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 4691 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4692 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4693 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4694 4695 synchronized (mPackages) { 4696 final int count = candidates.size(); 4697 // First, try to use linked apps. Partition the candidates into four lists: 4698 // one for the final results, one for the "do not use ever", one for "undefined status" 4699 // and finally one for "browser app type". 4700 for (int n=0; n<count; n++) { 4701 ResolveInfo info = candidates.get(n); 4702 String packageName = info.activityInfo.packageName; 4703 PackageSetting ps = mSettings.mPackages.get(packageName); 4704 if (ps != null) { 4705 // Add to the special match all list (Browser use case) 4706 if (info.handleAllWebDataURI) { 4707 matchAllList.add(info); 4708 continue; 4709 } 4710 // Try to get the status from User settings first 4711 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4712 int status = (int)(packedStatus >> 32); 4713 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 4714 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4715 if (DEBUG_DOMAIN_VERIFICATION) { 4716 Slog.i(TAG, " + always: " + info.activityInfo.packageName 4717 + " : linkgen=" + linkGeneration); 4718 } 4719 // Use link-enabled generation as preferredOrder, i.e. 4720 // prefer newly-enabled over earlier-enabled. 4721 info.preferredOrder = linkGeneration; 4722 alwaysList.add(info); 4723 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4724 if (DEBUG_DOMAIN_VERIFICATION) { 4725 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 4726 } 4727 neverList.add(info); 4728 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 4729 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 4730 if (DEBUG_DOMAIN_VERIFICATION) { 4731 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 4732 } 4733 undefinedList.add(info); 4734 } 4735 } 4736 } 4737 // First try to add the "always" resolution(s) for the current user, if any 4738 if (alwaysList.size() > 0) { 4739 result.addAll(alwaysList); 4740 // if there is an "always" for the parent user, add it. 4741 } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus 4742 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4743 result.add(xpDomainInfo.resolveInfo); 4744 } else { 4745 // Add all undefined Apps as we want them to appear in the Disambiguation dialog. 4746 result.addAll(undefinedList); 4747 if (xpDomainInfo != null && ( 4748 xpDomainInfo.bestDomainVerificationStatus 4749 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 4750 || xpDomainInfo.bestDomainVerificationStatus 4751 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) { 4752 result.add(xpDomainInfo.resolveInfo); 4753 } 4754 // Also add Browsers (all of them or only the default one) 4755 if ((matchFlags & MATCH_ALL) != 0) { 4756 result.addAll(matchAllList); 4757 } else { 4758 // Browser/generic handling case. If there's a default browser, go straight 4759 // to that (but only if there is no other higher-priority match). 4760 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 4761 int maxMatchPrio = 0; 4762 ResolveInfo defaultBrowserMatch = null; 4763 final int numCandidates = matchAllList.size(); 4764 for (int n = 0; n < numCandidates; n++) { 4765 ResolveInfo info = matchAllList.get(n); 4766 // track the highest overall match priority... 4767 if (info.priority > maxMatchPrio) { 4768 maxMatchPrio = info.priority; 4769 } 4770 // ...and the highest-priority default browser match 4771 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4772 if (defaultBrowserMatch == null 4773 || (defaultBrowserMatch.priority < info.priority)) { 4774 if (debug) { 4775 Slog.v(TAG, "Considering default browser match " + info); 4776 } 4777 defaultBrowserMatch = info; 4778 } 4779 } 4780 } 4781 if (defaultBrowserMatch != null 4782 && defaultBrowserMatch.priority >= maxMatchPrio 4783 && !TextUtils.isEmpty(defaultBrowserPackageName)) 4784 { 4785 if (debug) { 4786 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 4787 } 4788 result.add(defaultBrowserMatch); 4789 } else { 4790 result.addAll(matchAllList); 4791 } 4792 } 4793 4794 // If there is nothing selected, add all candidates and remove the ones that the user 4795 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 4796 if (result.size() == 0) { 4797 result.addAll(candidates); 4798 result.removeAll(neverList); 4799 } 4800 } 4801 } 4802 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4803 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 4804 result.size()); 4805 for (ResolveInfo info : result) { 4806 Slog.v(TAG, " + " + info.activityInfo); 4807 } 4808 } 4809 return result; 4810 } 4811 4812 // Returns a packed value as a long: 4813 // 4814 // high 'int'-sized word: link status: undefined/ask/never/always. 4815 // low 'int'-sized word: relative priority among 'always' results. 4816 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4817 long result = ps.getDomainVerificationStatusForUser(userId); 4818 // if none available, get the master status 4819 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4820 if (ps.getIntentFilterVerificationInfo() != null) { 4821 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 4822 } 4823 } 4824 return result; 4825 } 4826 4827 private ResolveInfo querySkipCurrentProfileIntents( 4828 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4829 int flags, int sourceUserId) { 4830 if (matchingFilters != null) { 4831 int size = matchingFilters.size(); 4832 for (int i = 0; i < size; i ++) { 4833 CrossProfileIntentFilter filter = matchingFilters.get(i); 4834 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4835 // Checking if there are activities in the target user that can handle the 4836 // intent. 4837 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4838 flags, sourceUserId); 4839 if (resolveInfo != null) { 4840 return resolveInfo; 4841 } 4842 } 4843 } 4844 } 4845 return null; 4846 } 4847 4848 // Return matching ResolveInfo if any for skip current profile intent filters. 4849 private ResolveInfo queryCrossProfileIntents( 4850 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4851 int flags, int sourceUserId) { 4852 if (matchingFilters != null) { 4853 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4854 // match the same intent. For performance reasons, it is better not to 4855 // run queryIntent twice for the same userId 4856 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4857 int size = matchingFilters.size(); 4858 for (int i = 0; i < size; i++) { 4859 CrossProfileIntentFilter filter = matchingFilters.get(i); 4860 int targetUserId = filter.getTargetUserId(); 4861 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4862 && !alreadyTriedUserIds.get(targetUserId)) { 4863 // Checking if there are activities in the target user that can handle the 4864 // intent. 4865 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4866 flags, sourceUserId); 4867 if (resolveInfo != null) return resolveInfo; 4868 alreadyTriedUserIds.put(targetUserId, true); 4869 } 4870 } 4871 } 4872 return null; 4873 } 4874 4875 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 4876 String resolvedType, int flags, int sourceUserId) { 4877 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4878 resolvedType, flags, filter.getTargetUserId()); 4879 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4880 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4881 } 4882 return null; 4883 } 4884 4885 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4886 int sourceUserId, int targetUserId) { 4887 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4888 String className; 4889 if (targetUserId == UserHandle.USER_OWNER) { 4890 className = FORWARD_INTENT_TO_USER_OWNER; 4891 } else { 4892 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4893 } 4894 ComponentName forwardingActivityComponentName = new ComponentName( 4895 mAndroidApplication.packageName, className); 4896 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4897 sourceUserId); 4898 if (targetUserId == UserHandle.USER_OWNER) { 4899 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 4900 forwardingResolveInfo.noResourceId = true; 4901 } 4902 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4903 forwardingResolveInfo.priority = 0; 4904 forwardingResolveInfo.preferredOrder = 0; 4905 forwardingResolveInfo.match = 0; 4906 forwardingResolveInfo.isDefault = true; 4907 forwardingResolveInfo.filter = filter; 4908 forwardingResolveInfo.targetUserId = targetUserId; 4909 return forwardingResolveInfo; 4910 } 4911 4912 @Override 4913 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4914 Intent[] specifics, String[] specificTypes, Intent intent, 4915 String resolvedType, int flags, int userId) { 4916 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4917 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4918 false, "query intent activity options"); 4919 final String resultsAction = intent.getAction(); 4920 4921 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4922 | PackageManager.GET_RESOLVED_FILTER, userId); 4923 4924 if (DEBUG_INTENT_MATCHING) { 4925 Log.v(TAG, "Query " + intent + ": " + results); 4926 } 4927 4928 int specificsPos = 0; 4929 int N; 4930 4931 // todo: note that the algorithm used here is O(N^2). This 4932 // isn't a problem in our current environment, but if we start running 4933 // into situations where we have more than 5 or 10 matches then this 4934 // should probably be changed to something smarter... 4935 4936 // First we go through and resolve each of the specific items 4937 // that were supplied, taking care of removing any corresponding 4938 // duplicate items in the generic resolve list. 4939 if (specifics != null) { 4940 for (int i=0; i<specifics.length; i++) { 4941 final Intent sintent = specifics[i]; 4942 if (sintent == null) { 4943 continue; 4944 } 4945 4946 if (DEBUG_INTENT_MATCHING) { 4947 Log.v(TAG, "Specific #" + i + ": " + sintent); 4948 } 4949 4950 String action = sintent.getAction(); 4951 if (resultsAction != null && resultsAction.equals(action)) { 4952 // If this action was explicitly requested, then don't 4953 // remove things that have it. 4954 action = null; 4955 } 4956 4957 ResolveInfo ri = null; 4958 ActivityInfo ai = null; 4959 4960 ComponentName comp = sintent.getComponent(); 4961 if (comp == null) { 4962 ri = resolveIntent( 4963 sintent, 4964 specificTypes != null ? specificTypes[i] : null, 4965 flags, userId); 4966 if (ri == null) { 4967 continue; 4968 } 4969 if (ri == mResolveInfo) { 4970 // ACK! Must do something better with this. 4971 } 4972 ai = ri.activityInfo; 4973 comp = new ComponentName(ai.applicationInfo.packageName, 4974 ai.name); 4975 } else { 4976 ai = getActivityInfo(comp, flags, userId); 4977 if (ai == null) { 4978 continue; 4979 } 4980 } 4981 4982 // Look for any generic query activities that are duplicates 4983 // of this specific one, and remove them from the results. 4984 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 4985 N = results.size(); 4986 int j; 4987 for (j=specificsPos; j<N; j++) { 4988 ResolveInfo sri = results.get(j); 4989 if ((sri.activityInfo.name.equals(comp.getClassName()) 4990 && sri.activityInfo.applicationInfo.packageName.equals( 4991 comp.getPackageName())) 4992 || (action != null && sri.filter.matchAction(action))) { 4993 results.remove(j); 4994 if (DEBUG_INTENT_MATCHING) Log.v( 4995 TAG, "Removing duplicate item from " + j 4996 + " due to specific " + specificsPos); 4997 if (ri == null) { 4998 ri = sri; 4999 } 5000 j--; 5001 N--; 5002 } 5003 } 5004 5005 // Add this specific item to its proper place. 5006 if (ri == null) { 5007 ri = new ResolveInfo(); 5008 ri.activityInfo = ai; 5009 } 5010 results.add(specificsPos, ri); 5011 ri.specificIndex = i; 5012 specificsPos++; 5013 } 5014 } 5015 5016 // Now we go through the remaining generic results and remove any 5017 // duplicate actions that are found here. 5018 N = results.size(); 5019 for (int i=specificsPos; i<N-1; i++) { 5020 final ResolveInfo rii = results.get(i); 5021 if (rii.filter == null) { 5022 continue; 5023 } 5024 5025 // Iterate over all of the actions of this result's intent 5026 // filter... typically this should be just one. 5027 final Iterator<String> it = rii.filter.actionsIterator(); 5028 if (it == null) { 5029 continue; 5030 } 5031 while (it.hasNext()) { 5032 final String action = it.next(); 5033 if (resultsAction != null && resultsAction.equals(action)) { 5034 // If this action was explicitly requested, then don't 5035 // remove things that have it. 5036 continue; 5037 } 5038 for (int j=i+1; j<N; j++) { 5039 final ResolveInfo rij = results.get(j); 5040 if (rij.filter != null && rij.filter.hasAction(action)) { 5041 results.remove(j); 5042 if (DEBUG_INTENT_MATCHING) Log.v( 5043 TAG, "Removing duplicate item from " + j 5044 + " due to action " + action + " at " + i); 5045 j--; 5046 N--; 5047 } 5048 } 5049 } 5050 5051 // If the caller didn't request filter information, drop it now 5052 // so we don't have to marshall/unmarshall it. 5053 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5054 rii.filter = null; 5055 } 5056 } 5057 5058 // Filter out the caller activity if so requested. 5059 if (caller != null) { 5060 N = results.size(); 5061 for (int i=0; i<N; i++) { 5062 ActivityInfo ainfo = results.get(i).activityInfo; 5063 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5064 && caller.getClassName().equals(ainfo.name)) { 5065 results.remove(i); 5066 break; 5067 } 5068 } 5069 } 5070 5071 // If the caller didn't request filter information, 5072 // drop them now so we don't have to 5073 // marshall/unmarshall it. 5074 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5075 N = results.size(); 5076 for (int i=0; i<N; i++) { 5077 results.get(i).filter = null; 5078 } 5079 } 5080 5081 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5082 return results; 5083 } 5084 5085 @Override 5086 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 5087 int userId) { 5088 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5089 ComponentName comp = intent.getComponent(); 5090 if (comp == null) { 5091 if (intent.getSelector() != null) { 5092 intent = intent.getSelector(); 5093 comp = intent.getComponent(); 5094 } 5095 } 5096 if (comp != null) { 5097 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5098 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5099 if (ai != null) { 5100 ResolveInfo ri = new ResolveInfo(); 5101 ri.activityInfo = ai; 5102 list.add(ri); 5103 } 5104 return list; 5105 } 5106 5107 // reader 5108 synchronized (mPackages) { 5109 String pkgName = intent.getPackage(); 5110 if (pkgName == null) { 5111 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5112 } 5113 final PackageParser.Package pkg = mPackages.get(pkgName); 5114 if (pkg != null) { 5115 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5116 userId); 5117 } 5118 return null; 5119 } 5120 } 5121 5122 @Override 5123 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5124 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 5125 if (!sUserManager.exists(userId)) return null; 5126 if (query != null) { 5127 if (query.size() >= 1) { 5128 // If there is more than one service with the same priority, 5129 // just arbitrarily pick the first one. 5130 return query.get(0); 5131 } 5132 } 5133 return null; 5134 } 5135 5136 @Override 5137 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 5138 int userId) { 5139 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5140 ComponentName comp = intent.getComponent(); 5141 if (comp == null) { 5142 if (intent.getSelector() != null) { 5143 intent = intent.getSelector(); 5144 comp = intent.getComponent(); 5145 } 5146 } 5147 if (comp != null) { 5148 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5149 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5150 if (si != null) { 5151 final ResolveInfo ri = new ResolveInfo(); 5152 ri.serviceInfo = si; 5153 list.add(ri); 5154 } 5155 return list; 5156 } 5157 5158 // reader 5159 synchronized (mPackages) { 5160 String pkgName = intent.getPackage(); 5161 if (pkgName == null) { 5162 return mServices.queryIntent(intent, resolvedType, flags, userId); 5163 } 5164 final PackageParser.Package pkg = mPackages.get(pkgName); 5165 if (pkg != null) { 5166 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5167 userId); 5168 } 5169 return null; 5170 } 5171 } 5172 5173 @Override 5174 public List<ResolveInfo> queryIntentContentProviders( 5175 Intent intent, String resolvedType, int flags, int userId) { 5176 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5177 ComponentName comp = intent.getComponent(); 5178 if (comp == null) { 5179 if (intent.getSelector() != null) { 5180 intent = intent.getSelector(); 5181 comp = intent.getComponent(); 5182 } 5183 } 5184 if (comp != null) { 5185 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5186 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5187 if (pi != null) { 5188 final ResolveInfo ri = new ResolveInfo(); 5189 ri.providerInfo = pi; 5190 list.add(ri); 5191 } 5192 return list; 5193 } 5194 5195 // reader 5196 synchronized (mPackages) { 5197 String pkgName = intent.getPackage(); 5198 if (pkgName == null) { 5199 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5200 } 5201 final PackageParser.Package pkg = mPackages.get(pkgName); 5202 if (pkg != null) { 5203 return mProviders.queryIntentForPackage( 5204 intent, resolvedType, flags, pkg.providers, userId); 5205 } 5206 return null; 5207 } 5208 } 5209 5210 @Override 5211 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5212 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5213 5214 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 5215 5216 // writer 5217 synchronized (mPackages) { 5218 ArrayList<PackageInfo> list; 5219 if (listUninstalled) { 5220 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5221 for (PackageSetting ps : mSettings.mPackages.values()) { 5222 PackageInfo pi; 5223 if (ps.pkg != null) { 5224 pi = generatePackageInfo(ps.pkg, flags, userId); 5225 } else { 5226 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5227 } 5228 if (pi != null) { 5229 list.add(pi); 5230 } 5231 } 5232 } else { 5233 list = new ArrayList<PackageInfo>(mPackages.size()); 5234 for (PackageParser.Package p : mPackages.values()) { 5235 PackageInfo pi = generatePackageInfo(p, flags, userId); 5236 if (pi != null) { 5237 list.add(pi); 5238 } 5239 } 5240 } 5241 5242 return new ParceledListSlice<PackageInfo>(list); 5243 } 5244 } 5245 5246 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5247 String[] permissions, boolean[] tmp, int flags, int userId) { 5248 int numMatch = 0; 5249 final PermissionsState permissionsState = ps.getPermissionsState(); 5250 for (int i=0; i<permissions.length; i++) { 5251 final String permission = permissions[i]; 5252 if (permissionsState.hasPermission(permission, userId)) { 5253 tmp[i] = true; 5254 numMatch++; 5255 } else { 5256 tmp[i] = false; 5257 } 5258 } 5259 if (numMatch == 0) { 5260 return; 5261 } 5262 PackageInfo pi; 5263 if (ps.pkg != null) { 5264 pi = generatePackageInfo(ps.pkg, flags, userId); 5265 } else { 5266 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5267 } 5268 // The above might return null in cases of uninstalled apps or install-state 5269 // skew across users/profiles. 5270 if (pi != null) { 5271 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5272 if (numMatch == permissions.length) { 5273 pi.requestedPermissions = permissions; 5274 } else { 5275 pi.requestedPermissions = new String[numMatch]; 5276 numMatch = 0; 5277 for (int i=0; i<permissions.length; i++) { 5278 if (tmp[i]) { 5279 pi.requestedPermissions[numMatch] = permissions[i]; 5280 numMatch++; 5281 } 5282 } 5283 } 5284 } 5285 list.add(pi); 5286 } 5287 } 5288 5289 @Override 5290 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5291 String[] permissions, int flags, int userId) { 5292 if (!sUserManager.exists(userId)) return null; 5293 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5294 5295 // writer 5296 synchronized (mPackages) { 5297 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5298 boolean[] tmpBools = new boolean[permissions.length]; 5299 if (listUninstalled) { 5300 for (PackageSetting ps : mSettings.mPackages.values()) { 5301 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5302 } 5303 } else { 5304 for (PackageParser.Package pkg : mPackages.values()) { 5305 PackageSetting ps = (PackageSetting)pkg.mExtras; 5306 if (ps != null) { 5307 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5308 userId); 5309 } 5310 } 5311 } 5312 5313 return new ParceledListSlice<PackageInfo>(list); 5314 } 5315 } 5316 5317 @Override 5318 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5319 if (!sUserManager.exists(userId)) return null; 5320 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5321 5322 // writer 5323 synchronized (mPackages) { 5324 ArrayList<ApplicationInfo> list; 5325 if (listUninstalled) { 5326 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5327 for (PackageSetting ps : mSettings.mPackages.values()) { 5328 ApplicationInfo ai; 5329 if (ps.pkg != null) { 5330 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5331 ps.readUserState(userId), userId); 5332 } else { 5333 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5334 } 5335 if (ai != null) { 5336 list.add(ai); 5337 } 5338 } 5339 } else { 5340 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5341 for (PackageParser.Package p : mPackages.values()) { 5342 if (p.mExtras != null) { 5343 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5344 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5345 if (ai != null) { 5346 list.add(ai); 5347 } 5348 } 5349 } 5350 } 5351 5352 return new ParceledListSlice<ApplicationInfo>(list); 5353 } 5354 } 5355 5356 public List<ApplicationInfo> getPersistentApplications(int flags) { 5357 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 5358 5359 // reader 5360 synchronized (mPackages) { 5361 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 5362 final int userId = UserHandle.getCallingUserId(); 5363 while (i.hasNext()) { 5364 final PackageParser.Package p = i.next(); 5365 if (p.applicationInfo != null 5366 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 5367 && (!mSafeMode || isSystemApp(p))) { 5368 PackageSetting ps = mSettings.mPackages.get(p.packageName); 5369 if (ps != null) { 5370 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5371 ps.readUserState(userId), userId); 5372 if (ai != null) { 5373 finalList.add(ai); 5374 } 5375 } 5376 } 5377 } 5378 } 5379 5380 return finalList; 5381 } 5382 5383 @Override 5384 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 5385 if (!sUserManager.exists(userId)) return null; 5386 // reader 5387 synchronized (mPackages) { 5388 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 5389 PackageSetting ps = provider != null 5390 ? mSettings.mPackages.get(provider.owner.packageName) 5391 : null; 5392 return ps != null 5393 && mSettings.isEnabledLPr(provider.info, flags, userId) 5394 && (!mSafeMode || (provider.info.applicationInfo.flags 5395 &ApplicationInfo.FLAG_SYSTEM) != 0) 5396 ? PackageParser.generateProviderInfo(provider, flags, 5397 ps.readUserState(userId), userId) 5398 : null; 5399 } 5400 } 5401 5402 /** 5403 * @deprecated 5404 */ 5405 @Deprecated 5406 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 5407 // reader 5408 synchronized (mPackages) { 5409 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 5410 .entrySet().iterator(); 5411 final int userId = UserHandle.getCallingUserId(); 5412 while (i.hasNext()) { 5413 Map.Entry<String, PackageParser.Provider> entry = i.next(); 5414 PackageParser.Provider p = entry.getValue(); 5415 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5416 5417 if (ps != null && p.syncable 5418 && (!mSafeMode || (p.info.applicationInfo.flags 5419 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 5420 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 5421 ps.readUserState(userId), userId); 5422 if (info != null) { 5423 outNames.add(entry.getKey()); 5424 outInfo.add(info); 5425 } 5426 } 5427 } 5428 } 5429 } 5430 5431 @Override 5432 public List<ProviderInfo> queryContentProviders(String processName, 5433 int uid, int flags) { 5434 ArrayList<ProviderInfo> finalList = null; 5435 // reader 5436 synchronized (mPackages) { 5437 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 5438 final int userId = processName != null ? 5439 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 5440 while (i.hasNext()) { 5441 final PackageParser.Provider p = i.next(); 5442 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5443 if (ps != null && p.info.authority != null 5444 && (processName == null 5445 || (p.info.processName.equals(processName) 5446 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 5447 && mSettings.isEnabledLPr(p.info, flags, userId) 5448 && (!mSafeMode 5449 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 5450 if (finalList == null) { 5451 finalList = new ArrayList<ProviderInfo>(3); 5452 } 5453 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 5454 ps.readUserState(userId), userId); 5455 if (info != null) { 5456 finalList.add(info); 5457 } 5458 } 5459 } 5460 } 5461 5462 if (finalList != null) { 5463 Collections.sort(finalList, mProviderInitOrderSorter); 5464 } 5465 5466 return finalList; 5467 } 5468 5469 @Override 5470 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 5471 int flags) { 5472 // reader 5473 synchronized (mPackages) { 5474 final PackageParser.Instrumentation i = mInstrumentation.get(name); 5475 return PackageParser.generateInstrumentationInfo(i, flags); 5476 } 5477 } 5478 5479 @Override 5480 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 5481 int flags) { 5482 ArrayList<InstrumentationInfo> finalList = 5483 new ArrayList<InstrumentationInfo>(); 5484 5485 // reader 5486 synchronized (mPackages) { 5487 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 5488 while (i.hasNext()) { 5489 final PackageParser.Instrumentation p = i.next(); 5490 if (targetPackage == null 5491 || targetPackage.equals(p.info.targetPackage)) { 5492 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 5493 flags); 5494 if (ii != null) { 5495 finalList.add(ii); 5496 } 5497 } 5498 } 5499 } 5500 5501 return finalList; 5502 } 5503 5504 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 5505 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 5506 if (overlays == null) { 5507 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 5508 return; 5509 } 5510 for (PackageParser.Package opkg : overlays.values()) { 5511 // Not much to do if idmap fails: we already logged the error 5512 // and we certainly don't want to abort installation of pkg simply 5513 // because an overlay didn't fit properly. For these reasons, 5514 // ignore the return value of createIdmapForPackagePairLI. 5515 createIdmapForPackagePairLI(pkg, opkg); 5516 } 5517 } 5518 5519 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 5520 PackageParser.Package opkg) { 5521 if (!opkg.mTrustedOverlay) { 5522 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 5523 opkg.baseCodePath + ": overlay not trusted"); 5524 return false; 5525 } 5526 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 5527 if (overlaySet == null) { 5528 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 5529 opkg.baseCodePath + " but target package has no known overlays"); 5530 return false; 5531 } 5532 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 5533 // TODO: generate idmap for split APKs 5534 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 5535 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 5536 + opkg.baseCodePath); 5537 return false; 5538 } 5539 PackageParser.Package[] overlayArray = 5540 overlaySet.values().toArray(new PackageParser.Package[0]); 5541 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 5542 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 5543 return p1.mOverlayPriority - p2.mOverlayPriority; 5544 } 5545 }; 5546 Arrays.sort(overlayArray, cmp); 5547 5548 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 5549 int i = 0; 5550 for (PackageParser.Package p : overlayArray) { 5551 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 5552 } 5553 return true; 5554 } 5555 5556 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5557 final File[] files = dir.listFiles(); 5558 if (ArrayUtils.isEmpty(files)) { 5559 Log.d(TAG, "No files in app dir " + dir); 5560 return; 5561 } 5562 5563 if (DEBUG_PACKAGE_SCANNING) { 5564 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 5565 + " flags=0x" + Integer.toHexString(parseFlags)); 5566 } 5567 5568 for (File file : files) { 5569 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 5570 && !PackageInstallerService.isStageName(file.getName()); 5571 if (!isPackage) { 5572 // Ignore entries which are not packages 5573 continue; 5574 } 5575 try { 5576 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 5577 scanFlags, currentTime, null); 5578 } catch (PackageManagerException e) { 5579 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 5580 5581 // Delete invalid userdata apps 5582 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 5583 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 5584 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 5585 if (file.isDirectory()) { 5586 mInstaller.rmPackageDir(file.getAbsolutePath()); 5587 } else { 5588 file.delete(); 5589 } 5590 } 5591 } 5592 } 5593 } 5594 5595 private static File getSettingsProblemFile() { 5596 File dataDir = Environment.getDataDirectory(); 5597 File systemDir = new File(dataDir, "system"); 5598 File fname = new File(systemDir, "uiderrors.txt"); 5599 return fname; 5600 } 5601 5602 static void reportSettingsProblem(int priority, String msg) { 5603 logCriticalInfo(priority, msg); 5604 } 5605 5606 static void logCriticalInfo(int priority, String msg) { 5607 Slog.println(priority, TAG, msg); 5608 EventLogTags.writePmCriticalInfo(msg); 5609 try { 5610 File fname = getSettingsProblemFile(); 5611 FileOutputStream out = new FileOutputStream(fname, true); 5612 PrintWriter pw = new FastPrintWriter(out); 5613 SimpleDateFormat formatter = new SimpleDateFormat(); 5614 String dateString = formatter.format(new Date(System.currentTimeMillis())); 5615 pw.println(dateString + ": " + msg); 5616 pw.close(); 5617 FileUtils.setPermissions( 5618 fname.toString(), 5619 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 5620 -1, -1); 5621 } catch (java.io.IOException e) { 5622 } 5623 } 5624 5625 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 5626 PackageParser.Package pkg, File srcFile, int parseFlags) 5627 throws PackageManagerException { 5628 if (ps != null 5629 && ps.codePath.equals(srcFile) 5630 && ps.timeStamp == srcFile.lastModified() 5631 && !isCompatSignatureUpdateNeeded(pkg) 5632 && !isRecoverSignatureUpdateNeeded(pkg)) { 5633 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 5634 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5635 ArraySet<PublicKey> signingKs; 5636 synchronized (mPackages) { 5637 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 5638 } 5639 if (ps.signatures.mSignatures != null 5640 && ps.signatures.mSignatures.length != 0 5641 && signingKs != null) { 5642 // Optimization: reuse the existing cached certificates 5643 // if the package appears to be unchanged. 5644 pkg.mSignatures = ps.signatures.mSignatures; 5645 pkg.mSigningKeys = signingKs; 5646 return; 5647 } 5648 5649 Slog.w(TAG, "PackageSetting for " + ps.name 5650 + " is missing signatures. Collecting certs again to recover them."); 5651 } else { 5652 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 5653 } 5654 5655 try { 5656 pp.collectCertificates(pkg, parseFlags); 5657 pp.collectManifestDigest(pkg); 5658 } catch (PackageParserException e) { 5659 throw PackageManagerException.from(e); 5660 } 5661 } 5662 5663 /* 5664 * Scan a package and return the newly parsed package. 5665 * Returns null in case of errors and the error code is stored in mLastScanError 5666 */ 5667 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 5668 long currentTime, UserHandle user) throws PackageManagerException { 5669 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 5670 parseFlags |= mDefParseFlags; 5671 PackageParser pp = new PackageParser(); 5672 pp.setSeparateProcesses(mSeparateProcesses); 5673 pp.setOnlyCoreApps(mOnlyCore); 5674 pp.setDisplayMetrics(mMetrics); 5675 5676 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 5677 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 5678 } 5679 5680 final PackageParser.Package pkg; 5681 try { 5682 pkg = pp.parsePackage(scanFile, parseFlags); 5683 } catch (PackageParserException e) { 5684 throw PackageManagerException.from(e); 5685 } 5686 5687 PackageSetting ps = null; 5688 PackageSetting updatedPkg; 5689 // reader 5690 synchronized (mPackages) { 5691 // Look to see if we already know about this package. 5692 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 5693 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 5694 // This package has been renamed to its original name. Let's 5695 // use that. 5696 ps = mSettings.peekPackageLPr(oldName); 5697 } 5698 // If there was no original package, see one for the real package name. 5699 if (ps == null) { 5700 ps = mSettings.peekPackageLPr(pkg.packageName); 5701 } 5702 // Check to see if this package could be hiding/updating a system 5703 // package. Must look for it either under the original or real 5704 // package name depending on our state. 5705 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 5706 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 5707 } 5708 boolean updatedPkgBetter = false; 5709 // First check if this is a system package that may involve an update 5710 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5711 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5712 // it needs to drop FLAG_PRIVILEGED. 5713 if (locationIsPrivileged(scanFile)) { 5714 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5715 } else { 5716 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5717 } 5718 5719 if (ps != null && !ps.codePath.equals(scanFile)) { 5720 // The path has changed from what was last scanned... check the 5721 // version of the new path against what we have stored to determine 5722 // what to do. 5723 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5724 if (pkg.mVersionCode <= ps.versionCode) { 5725 // The system package has been updated and the code path does not match 5726 // Ignore entry. Skip it. 5727 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5728 + " ignored: updated version " + ps.versionCode 5729 + " better than this " + pkg.mVersionCode); 5730 if (!updatedPkg.codePath.equals(scanFile)) { 5731 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5732 + ps.name + " changing from " + updatedPkg.codePathString 5733 + " to " + scanFile); 5734 updatedPkg.codePath = scanFile; 5735 updatedPkg.codePathString = scanFile.toString(); 5736 updatedPkg.resourcePath = scanFile; 5737 updatedPkg.resourcePathString = scanFile.toString(); 5738 } 5739 updatedPkg.pkg = pkg; 5740 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5741 "Package " + ps.name + " at " + scanFile 5742 + " ignored: updated version " + ps.versionCode 5743 + " better than this " + pkg.mVersionCode); 5744 } else { 5745 // The current app on the system partition is better than 5746 // what we have updated to on the data partition; switch 5747 // back to the system partition version. 5748 // At this point, its safely assumed that package installation for 5749 // apps in system partition will go through. If not there won't be a working 5750 // version of the app 5751 // writer 5752 synchronized (mPackages) { 5753 // Just remove the loaded entries from package lists. 5754 mPackages.remove(ps.name); 5755 } 5756 5757 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5758 + " reverting from " + ps.codePathString 5759 + ": new version " + pkg.mVersionCode 5760 + " better than installed " + ps.versionCode); 5761 5762 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5763 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5764 synchronized (mInstallLock) { 5765 args.cleanUpResourcesLI(); 5766 } 5767 synchronized (mPackages) { 5768 mSettings.enableSystemPackageLPw(ps.name); 5769 } 5770 updatedPkgBetter = true; 5771 } 5772 } 5773 } 5774 5775 if (updatedPkg != null) { 5776 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5777 // initially 5778 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5779 5780 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5781 // flag set initially 5782 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5783 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5784 } 5785 } 5786 5787 // Verify certificates against what was last scanned 5788 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5789 5790 /* 5791 * A new system app appeared, but we already had a non-system one of the 5792 * same name installed earlier. 5793 */ 5794 boolean shouldHideSystemApp = false; 5795 if (updatedPkg == null && ps != null 5796 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5797 /* 5798 * Check to make sure the signatures match first. If they don't, 5799 * wipe the installed application and its data. 5800 */ 5801 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5802 != PackageManager.SIGNATURE_MATCH) { 5803 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5804 + " signatures don't match existing userdata copy; removing"); 5805 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5806 ps = null; 5807 } else { 5808 /* 5809 * If the newly-added system app is an older version than the 5810 * already installed version, hide it. It will be scanned later 5811 * and re-added like an update. 5812 */ 5813 if (pkg.mVersionCode <= ps.versionCode) { 5814 shouldHideSystemApp = true; 5815 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5816 + " but new version " + pkg.mVersionCode + " better than installed " 5817 + ps.versionCode + "; hiding system"); 5818 } else { 5819 /* 5820 * The newly found system app is a newer version that the 5821 * one previously installed. Simply remove the 5822 * already-installed application and replace it with our own 5823 * while keeping the application data. 5824 */ 5825 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5826 + " reverting from " + ps.codePathString + ": new version " 5827 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5828 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5829 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5830 synchronized (mInstallLock) { 5831 args.cleanUpResourcesLI(); 5832 } 5833 } 5834 } 5835 } 5836 5837 // The apk is forward locked (not public) if its code and resources 5838 // are kept in different files. (except for app in either system or 5839 // vendor path). 5840 // TODO grab this value from PackageSettings 5841 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5842 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5843 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5844 } 5845 } 5846 5847 // TODO: extend to support forward-locked splits 5848 String resourcePath = null; 5849 String baseResourcePath = null; 5850 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5851 if (ps != null && ps.resourcePathString != null) { 5852 resourcePath = ps.resourcePathString; 5853 baseResourcePath = ps.resourcePathString; 5854 } else { 5855 // Should not happen at all. Just log an error. 5856 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5857 } 5858 } else { 5859 resourcePath = pkg.codePath; 5860 baseResourcePath = pkg.baseCodePath; 5861 } 5862 5863 // Set application objects path explicitly. 5864 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5865 pkg.applicationInfo.setCodePath(pkg.codePath); 5866 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5867 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5868 pkg.applicationInfo.setResourcePath(resourcePath); 5869 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5870 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5871 5872 // Note that we invoke the following method only if we are about to unpack an application 5873 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5874 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5875 5876 /* 5877 * If the system app should be overridden by a previously installed 5878 * data, hide the system app now and let the /data/app scan pick it up 5879 * again. 5880 */ 5881 if (shouldHideSystemApp) { 5882 synchronized (mPackages) { 5883 /* 5884 * We have to grant systems permissions before we hide, because 5885 * grantPermissions will assume the package update is trying to 5886 * expand its permissions. 5887 */ 5888 grantPermissionsLPw(pkg, true, pkg.packageName); 5889 mSettings.disableSystemPackageLPw(pkg.packageName); 5890 } 5891 } 5892 5893 return scannedPkg; 5894 } 5895 5896 private static String fixProcessName(String defProcessName, 5897 String processName, int uid) { 5898 if (processName == null) { 5899 return defProcessName; 5900 } 5901 return processName; 5902 } 5903 5904 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 5905 throws PackageManagerException { 5906 if (pkgSetting.signatures.mSignatures != null) { 5907 // Already existing package. Make sure signatures match 5908 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 5909 == PackageManager.SIGNATURE_MATCH; 5910 if (!match) { 5911 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 5912 == PackageManager.SIGNATURE_MATCH; 5913 } 5914 if (!match) { 5915 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 5916 == PackageManager.SIGNATURE_MATCH; 5917 } 5918 if (!match) { 5919 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5920 + pkg.packageName + " signatures do not match the " 5921 + "previously installed version; ignoring!"); 5922 } 5923 } 5924 5925 // Check for shared user signatures 5926 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 5927 // Already existing package. Make sure signatures match 5928 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5929 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 5930 if (!match) { 5931 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 5932 == PackageManager.SIGNATURE_MATCH; 5933 } 5934 if (!match) { 5935 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 5936 == PackageManager.SIGNATURE_MATCH; 5937 } 5938 if (!match) { 5939 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 5940 "Package " + pkg.packageName 5941 + " has no signatures that match those in shared user " 5942 + pkgSetting.sharedUser.name + "; ignoring!"); 5943 } 5944 } 5945 } 5946 5947 /** 5948 * Enforces that only the system UID or root's UID can call a method exposed 5949 * via Binder. 5950 * 5951 * @param message used as message if SecurityException is thrown 5952 * @throws SecurityException if the caller is not system or root 5953 */ 5954 private static final void enforceSystemOrRoot(String message) { 5955 final int uid = Binder.getCallingUid(); 5956 if (uid != Process.SYSTEM_UID && uid != 0) { 5957 throw new SecurityException(message); 5958 } 5959 } 5960 5961 @Override 5962 public void performBootDexOpt() { 5963 enforceSystemOrRoot("Only the system can request dexopt be performed"); 5964 5965 // Before everything else, see whether we need to fstrim. 5966 try { 5967 IMountService ms = PackageHelper.getMountService(); 5968 if (ms != null) { 5969 final boolean isUpgrade = isUpgrade(); 5970 boolean doTrim = isUpgrade; 5971 if (doTrim) { 5972 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 5973 } else { 5974 final long interval = android.provider.Settings.Global.getLong( 5975 mContext.getContentResolver(), 5976 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 5977 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 5978 if (interval > 0) { 5979 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 5980 if (timeSinceLast > interval) { 5981 doTrim = true; 5982 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 5983 + "; running immediately"); 5984 } 5985 } 5986 } 5987 if (doTrim) { 5988 if (!isFirstBoot()) { 5989 try { 5990 ActivityManagerNative.getDefault().showBootMessage( 5991 mContext.getResources().getString( 5992 R.string.android_upgrading_fstrim), true); 5993 } catch (RemoteException e) { 5994 } 5995 } 5996 ms.runMaintenance(); 5997 } 5998 } else { 5999 Slog.e(TAG, "Mount service unavailable!"); 6000 } 6001 } catch (RemoteException e) { 6002 // Can't happen; MountService is local 6003 } 6004 6005 final ArraySet<PackageParser.Package> pkgs; 6006 synchronized (mPackages) { 6007 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 6008 } 6009 6010 if (pkgs != null) { 6011 // Sort apps by importance for dexopt ordering. Important apps are given more priority 6012 // in case the device runs out of space. 6013 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 6014 // Give priority to core apps. 6015 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6016 PackageParser.Package pkg = it.next(); 6017 if (pkg.coreApp) { 6018 if (DEBUG_DEXOPT) { 6019 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 6020 } 6021 sortedPkgs.add(pkg); 6022 it.remove(); 6023 } 6024 } 6025 // Give priority to system apps that listen for pre boot complete. 6026 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 6027 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 6028 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6029 PackageParser.Package pkg = it.next(); 6030 if (pkgNames.contains(pkg.packageName)) { 6031 if (DEBUG_DEXOPT) { 6032 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 6033 } 6034 sortedPkgs.add(pkg); 6035 it.remove(); 6036 } 6037 } 6038 // Give priority to system apps. 6039 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6040 PackageParser.Package pkg = it.next(); 6041 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 6042 if (DEBUG_DEXOPT) { 6043 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 6044 } 6045 sortedPkgs.add(pkg); 6046 it.remove(); 6047 } 6048 } 6049 // Give priority to updated system apps. 6050 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6051 PackageParser.Package pkg = it.next(); 6052 if (pkg.isUpdatedSystemApp()) { 6053 if (DEBUG_DEXOPT) { 6054 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 6055 } 6056 sortedPkgs.add(pkg); 6057 it.remove(); 6058 } 6059 } 6060 // Give priority to apps that listen for boot complete. 6061 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 6062 pkgNames = getPackageNamesForIntent(intent); 6063 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6064 PackageParser.Package pkg = it.next(); 6065 if (pkgNames.contains(pkg.packageName)) { 6066 if (DEBUG_DEXOPT) { 6067 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 6068 } 6069 sortedPkgs.add(pkg); 6070 it.remove(); 6071 } 6072 } 6073 // Filter out packages that aren't recently used. 6074 filterRecentlyUsedApps(pkgs); 6075 // Add all remaining apps. 6076 for (PackageParser.Package pkg : pkgs) { 6077 if (DEBUG_DEXOPT) { 6078 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 6079 } 6080 sortedPkgs.add(pkg); 6081 } 6082 6083 // If we want to be lazy, filter everything that wasn't recently used. 6084 if (mLazyDexOpt) { 6085 filterRecentlyUsedApps(sortedPkgs); 6086 } 6087 6088 int i = 0; 6089 int total = sortedPkgs.size(); 6090 File dataDir = Environment.getDataDirectory(); 6091 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 6092 if (lowThreshold == 0) { 6093 throw new IllegalStateException("Invalid low memory threshold"); 6094 } 6095 for (PackageParser.Package pkg : sortedPkgs) { 6096 long usableSpace = dataDir.getUsableSpace(); 6097 if (usableSpace < lowThreshold) { 6098 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 6099 break; 6100 } 6101 performBootDexOpt(pkg, ++i, total); 6102 } 6103 } 6104 } 6105 6106 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 6107 // Filter out packages that aren't recently used. 6108 // 6109 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 6110 // should do a full dexopt. 6111 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 6112 int total = pkgs.size(); 6113 int skipped = 0; 6114 long now = System.currentTimeMillis(); 6115 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 6116 PackageParser.Package pkg = i.next(); 6117 long then = pkg.mLastPackageUsageTimeInMills; 6118 if (then + mDexOptLRUThresholdInMills < now) { 6119 if (DEBUG_DEXOPT) { 6120 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 6121 ((then == 0) ? "never" : new Date(then))); 6122 } 6123 i.remove(); 6124 skipped++; 6125 } 6126 } 6127 if (DEBUG_DEXOPT) { 6128 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 6129 } 6130 } 6131 } 6132 6133 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 6134 List<ResolveInfo> ris = null; 6135 try { 6136 ris = AppGlobals.getPackageManager().queryIntentReceivers( 6137 intent, null, 0, UserHandle.USER_OWNER); 6138 } catch (RemoteException e) { 6139 } 6140 ArraySet<String> pkgNames = new ArraySet<String>(); 6141 if (ris != null) { 6142 for (ResolveInfo ri : ris) { 6143 pkgNames.add(ri.activityInfo.packageName); 6144 } 6145 } 6146 return pkgNames; 6147 } 6148 6149 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 6150 if (DEBUG_DEXOPT) { 6151 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 6152 } 6153 if (!isFirstBoot()) { 6154 try { 6155 ActivityManagerNative.getDefault().showBootMessage( 6156 mContext.getResources().getString(R.string.android_upgrading_apk, 6157 curr, total), true); 6158 } catch (RemoteException e) { 6159 } 6160 } 6161 PackageParser.Package p = pkg; 6162 synchronized (mInstallLock) { 6163 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 6164 false /* force dex */, false /* defer */, true /* include dependencies */); 6165 } 6166 } 6167 6168 @Override 6169 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6170 return performDexOpt(packageName, instructionSet, false); 6171 } 6172 6173 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 6174 boolean dexopt = mLazyDexOpt || backgroundDexopt; 6175 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 6176 if (!dexopt && !updateUsage) { 6177 // We aren't going to dexopt or update usage, so bail early. 6178 return false; 6179 } 6180 PackageParser.Package p; 6181 final String targetInstructionSet; 6182 synchronized (mPackages) { 6183 p = mPackages.get(packageName); 6184 if (p == null) { 6185 return false; 6186 } 6187 if (updateUsage) { 6188 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6189 } 6190 mPackageUsage.write(false); 6191 if (!dexopt) { 6192 // We aren't going to dexopt, so bail early. 6193 return false; 6194 } 6195 6196 targetInstructionSet = instructionSet != null ? instructionSet : 6197 getPrimaryInstructionSet(p.applicationInfo); 6198 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 6199 return false; 6200 } 6201 } 6202 long callingId = Binder.clearCallingIdentity(); 6203 try { 6204 synchronized (mInstallLock) { 6205 final String[] instructionSets = new String[] { targetInstructionSet }; 6206 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 6207 false /* forceDex */, false /* defer */, true /* inclDependencies */); 6208 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6209 } 6210 } finally { 6211 Binder.restoreCallingIdentity(callingId); 6212 } 6213 } 6214 6215 public ArraySet<String> getPackagesThatNeedDexOpt() { 6216 ArraySet<String> pkgs = null; 6217 synchronized (mPackages) { 6218 for (PackageParser.Package p : mPackages.values()) { 6219 if (DEBUG_DEXOPT) { 6220 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 6221 } 6222 if (!p.mDexOptPerformed.isEmpty()) { 6223 continue; 6224 } 6225 if (pkgs == null) { 6226 pkgs = new ArraySet<String>(); 6227 } 6228 pkgs.add(p.packageName); 6229 } 6230 } 6231 return pkgs; 6232 } 6233 6234 public void shutdown() { 6235 mPackageUsage.write(true); 6236 } 6237 6238 @Override 6239 public void forceDexOpt(String packageName) { 6240 enforceSystemOrRoot("forceDexOpt"); 6241 6242 PackageParser.Package pkg; 6243 synchronized (mPackages) { 6244 pkg = mPackages.get(packageName); 6245 if (pkg == null) { 6246 throw new IllegalArgumentException("Missing package: " + packageName); 6247 } 6248 } 6249 6250 synchronized (mInstallLock) { 6251 final String[] instructionSets = new String[] { 6252 getPrimaryInstructionSet(pkg.applicationInfo) }; 6253 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 6254 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 6255 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 6256 throw new IllegalStateException("Failed to dexopt: " + res); 6257 } 6258 } 6259 } 6260 6261 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 6262 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 6263 Slog.w(TAG, "Unable to update from " + oldPkg.name 6264 + " to " + newPkg.packageName 6265 + ": old package not in system partition"); 6266 return false; 6267 } else if (mPackages.get(oldPkg.name) != null) { 6268 Slog.w(TAG, "Unable to update from " + oldPkg.name 6269 + " to " + newPkg.packageName 6270 + ": old package still exists"); 6271 return false; 6272 } 6273 return true; 6274 } 6275 6276 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 6277 int[] users = sUserManager.getUserIds(); 6278 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 6279 if (res < 0) { 6280 return res; 6281 } 6282 for (int user : users) { 6283 if (user != 0) { 6284 res = mInstaller.createUserData(volumeUuid, packageName, 6285 UserHandle.getUid(user, uid), user, seinfo); 6286 if (res < 0) { 6287 return res; 6288 } 6289 } 6290 } 6291 return res; 6292 } 6293 6294 private int removeDataDirsLI(String volumeUuid, String packageName) { 6295 int[] users = sUserManager.getUserIds(); 6296 int res = 0; 6297 for (int user : users) { 6298 int resInner = mInstaller.remove(volumeUuid, packageName, user); 6299 if (resInner < 0) { 6300 res = resInner; 6301 } 6302 } 6303 6304 return res; 6305 } 6306 6307 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 6308 int[] users = sUserManager.getUserIds(); 6309 int res = 0; 6310 for (int user : users) { 6311 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 6312 if (resInner < 0) { 6313 res = resInner; 6314 } 6315 } 6316 return res; 6317 } 6318 6319 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 6320 PackageParser.Package changingLib) { 6321 if (file.path != null) { 6322 usesLibraryFiles.add(file.path); 6323 return; 6324 } 6325 PackageParser.Package p = mPackages.get(file.apk); 6326 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 6327 // If we are doing this while in the middle of updating a library apk, 6328 // then we need to make sure to use that new apk for determining the 6329 // dependencies here. (We haven't yet finished committing the new apk 6330 // to the package manager state.) 6331 if (p == null || p.packageName.equals(changingLib.packageName)) { 6332 p = changingLib; 6333 } 6334 } 6335 if (p != null) { 6336 usesLibraryFiles.addAll(p.getAllCodePaths()); 6337 } 6338 } 6339 6340 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 6341 PackageParser.Package changingLib) throws PackageManagerException { 6342 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 6343 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 6344 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 6345 for (int i=0; i<N; i++) { 6346 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 6347 if (file == null) { 6348 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 6349 "Package " + pkg.packageName + " requires unavailable shared library " 6350 + pkg.usesLibraries.get(i) + "; failing!"); 6351 } 6352 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6353 } 6354 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 6355 for (int i=0; i<N; i++) { 6356 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 6357 if (file == null) { 6358 Slog.w(TAG, "Package " + pkg.packageName 6359 + " desires unavailable shared library " 6360 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 6361 } else { 6362 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6363 } 6364 } 6365 N = usesLibraryFiles.size(); 6366 if (N > 0) { 6367 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 6368 } else { 6369 pkg.usesLibraryFiles = null; 6370 } 6371 } 6372 } 6373 6374 private static boolean hasString(List<String> list, List<String> which) { 6375 if (list == null) { 6376 return false; 6377 } 6378 for (int i=list.size()-1; i>=0; i--) { 6379 for (int j=which.size()-1; j>=0; j--) { 6380 if (which.get(j).equals(list.get(i))) { 6381 return true; 6382 } 6383 } 6384 } 6385 return false; 6386 } 6387 6388 private void updateAllSharedLibrariesLPw() { 6389 for (PackageParser.Package pkg : mPackages.values()) { 6390 try { 6391 updateSharedLibrariesLPw(pkg, null); 6392 } catch (PackageManagerException e) { 6393 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6394 } 6395 } 6396 } 6397 6398 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 6399 PackageParser.Package changingPkg) { 6400 ArrayList<PackageParser.Package> res = null; 6401 for (PackageParser.Package pkg : mPackages.values()) { 6402 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 6403 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 6404 if (res == null) { 6405 res = new ArrayList<PackageParser.Package>(); 6406 } 6407 res.add(pkg); 6408 try { 6409 updateSharedLibrariesLPw(pkg, changingPkg); 6410 } catch (PackageManagerException e) { 6411 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6412 } 6413 } 6414 } 6415 return res; 6416 } 6417 6418 /** 6419 * Derive the value of the {@code cpuAbiOverride} based on the provided 6420 * value and an optional stored value from the package settings. 6421 */ 6422 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 6423 String cpuAbiOverride = null; 6424 6425 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 6426 cpuAbiOverride = null; 6427 } else if (abiOverride != null) { 6428 cpuAbiOverride = abiOverride; 6429 } else if (settings != null) { 6430 cpuAbiOverride = settings.cpuAbiOverrideString; 6431 } 6432 6433 return cpuAbiOverride; 6434 } 6435 6436 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 6437 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6438 boolean success = false; 6439 try { 6440 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 6441 currentTime, user); 6442 success = true; 6443 return res; 6444 } finally { 6445 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 6446 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 6447 } 6448 } 6449 } 6450 6451 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 6452 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6453 final File scanFile = new File(pkg.codePath); 6454 if (pkg.applicationInfo.getCodePath() == null || 6455 pkg.applicationInfo.getResourcePath() == null) { 6456 // Bail out. The resource and code paths haven't been set. 6457 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 6458 "Code and resource paths haven't been set correctly"); 6459 } 6460 6461 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 6462 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 6463 } else { 6464 // Only allow system apps to be flagged as core apps. 6465 pkg.coreApp = false; 6466 } 6467 6468 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 6469 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6470 } 6471 6472 if (mCustomResolverComponentName != null && 6473 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 6474 setUpCustomResolverActivity(pkg); 6475 } 6476 6477 if (pkg.packageName.equals("android")) { 6478 synchronized (mPackages) { 6479 if (mAndroidApplication != null) { 6480 Slog.w(TAG, "*************************************************"); 6481 Slog.w(TAG, "Core android package being redefined. Skipping."); 6482 Slog.w(TAG, " file=" + scanFile); 6483 Slog.w(TAG, "*************************************************"); 6484 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6485 "Core android package being redefined. Skipping."); 6486 } 6487 6488 // Set up information for our fall-back user intent resolution activity. 6489 mPlatformPackage = pkg; 6490 pkg.mVersionCode = mSdkVersion; 6491 mAndroidApplication = pkg.applicationInfo; 6492 6493 if (!mResolverReplaced) { 6494 mResolveActivity.applicationInfo = mAndroidApplication; 6495 mResolveActivity.name = ResolverActivity.class.getName(); 6496 mResolveActivity.packageName = mAndroidApplication.packageName; 6497 mResolveActivity.processName = "system:ui"; 6498 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6499 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 6500 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 6501 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 6502 mResolveActivity.exported = true; 6503 mResolveActivity.enabled = true; 6504 mResolveInfo.activityInfo = mResolveActivity; 6505 mResolveInfo.priority = 0; 6506 mResolveInfo.preferredOrder = 0; 6507 mResolveInfo.match = 0; 6508 mResolveComponentName = new ComponentName( 6509 mAndroidApplication.packageName, mResolveActivity.name); 6510 } 6511 } 6512 } 6513 6514 if (DEBUG_PACKAGE_SCANNING) { 6515 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6516 Log.d(TAG, "Scanning package " + pkg.packageName); 6517 } 6518 6519 if (mPackages.containsKey(pkg.packageName) 6520 || mSharedLibraries.containsKey(pkg.packageName)) { 6521 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6522 "Application package " + pkg.packageName 6523 + " already installed. Skipping duplicate."); 6524 } 6525 6526 // If we're only installing presumed-existing packages, require that the 6527 // scanned APK is both already known and at the path previously established 6528 // for it. Previously unknown packages we pick up normally, but if we have an 6529 // a priori expectation about this package's install presence, enforce it. 6530 // With a singular exception for new system packages. When an OTA contains 6531 // a new system package, we allow the codepath to change from a system location 6532 // to the user-installed location. If we don't allow this change, any newer, 6533 // user-installed version of the application will be ignored. 6534 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 6535 if (mExpectingBetter.containsKey(pkg.packageName)) { 6536 logCriticalInfo(Log.WARN, 6537 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 6538 } else { 6539 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 6540 if (known != null) { 6541 if (DEBUG_PACKAGE_SCANNING) { 6542 Log.d(TAG, "Examining " + pkg.codePath 6543 + " and requiring known paths " + known.codePathString 6544 + " & " + known.resourcePathString); 6545 } 6546 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6547 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6548 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6549 "Application package " + pkg.packageName 6550 + " found at " + pkg.applicationInfo.getCodePath() 6551 + " but expected at " + known.codePathString + "; ignoring."); 6552 } 6553 } 6554 } 6555 } 6556 6557 // Initialize package source and resource directories 6558 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6559 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6560 6561 SharedUserSetting suid = null; 6562 PackageSetting pkgSetting = null; 6563 6564 if (!isSystemApp(pkg)) { 6565 // Only system apps can use these features. 6566 pkg.mOriginalPackages = null; 6567 pkg.mRealPackage = null; 6568 pkg.mAdoptPermissions = null; 6569 } 6570 6571 // writer 6572 synchronized (mPackages) { 6573 if (pkg.mSharedUserId != null) { 6574 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 6575 if (suid == null) { 6576 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6577 "Creating application package " + pkg.packageName 6578 + " for shared user failed"); 6579 } 6580 if (DEBUG_PACKAGE_SCANNING) { 6581 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6582 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 6583 + "): packages=" + suid.packages); 6584 } 6585 } 6586 6587 // Check if we are renaming from an original package name. 6588 PackageSetting origPackage = null; 6589 String realName = null; 6590 if (pkg.mOriginalPackages != null) { 6591 // This package may need to be renamed to a previously 6592 // installed name. Let's check on that... 6593 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 6594 if (pkg.mOriginalPackages.contains(renamed)) { 6595 // This package had originally been installed as the 6596 // original name, and we have already taken care of 6597 // transitioning to the new one. Just update the new 6598 // one to continue using the old name. 6599 realName = pkg.mRealPackage; 6600 if (!pkg.packageName.equals(renamed)) { 6601 // Callers into this function may have already taken 6602 // care of renaming the package; only do it here if 6603 // it is not already done. 6604 pkg.setPackageName(renamed); 6605 } 6606 6607 } else { 6608 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 6609 if ((origPackage = mSettings.peekPackageLPr( 6610 pkg.mOriginalPackages.get(i))) != null) { 6611 // We do have the package already installed under its 6612 // original name... should we use it? 6613 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 6614 // New package is not compatible with original. 6615 origPackage = null; 6616 continue; 6617 } else if (origPackage.sharedUser != null) { 6618 // Make sure uid is compatible between packages. 6619 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 6620 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 6621 + " to " + pkg.packageName + ": old uid " 6622 + origPackage.sharedUser.name 6623 + " differs from " + pkg.mSharedUserId); 6624 origPackage = null; 6625 continue; 6626 } 6627 } else { 6628 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6629 + pkg.packageName + " to old name " + origPackage.name); 6630 } 6631 break; 6632 } 6633 } 6634 } 6635 } 6636 6637 if (mTransferedPackages.contains(pkg.packageName)) { 6638 Slog.w(TAG, "Package " + pkg.packageName 6639 + " was transferred to another, but its .apk remains"); 6640 } 6641 6642 // Just create the setting, don't add it yet. For already existing packages 6643 // the PkgSetting exists already and doesn't have to be created. 6644 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6645 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6646 pkg.applicationInfo.primaryCpuAbi, 6647 pkg.applicationInfo.secondaryCpuAbi, 6648 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6649 user, false); 6650 if (pkgSetting == null) { 6651 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6652 "Creating application package " + pkg.packageName + " failed"); 6653 } 6654 6655 if (pkgSetting.origPackage != null) { 6656 // If we are first transitioning from an original package, 6657 // fix up the new package's name now. We need to do this after 6658 // looking up the package under its new name, so getPackageLP 6659 // can take care of fiddling things correctly. 6660 pkg.setPackageName(origPackage.name); 6661 6662 // File a report about this. 6663 String msg = "New package " + pkgSetting.realName 6664 + " renamed to replace old package " + pkgSetting.name; 6665 reportSettingsProblem(Log.WARN, msg); 6666 6667 // Make a note of it. 6668 mTransferedPackages.add(origPackage.name); 6669 6670 // No longer need to retain this. 6671 pkgSetting.origPackage = null; 6672 } 6673 6674 if (realName != null) { 6675 // Make a note of it. 6676 mTransferedPackages.add(pkg.packageName); 6677 } 6678 6679 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6680 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6681 } 6682 6683 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6684 // Check all shared libraries and map to their actual file path. 6685 // We only do this here for apps not on a system dir, because those 6686 // are the only ones that can fail an install due to this. We 6687 // will take care of the system apps by updating all of their 6688 // library paths after the scan is done. 6689 updateSharedLibrariesLPw(pkg, null); 6690 } 6691 6692 if (mFoundPolicyFile) { 6693 SELinuxMMAC.assignSeinfoValue(pkg); 6694 } 6695 6696 pkg.applicationInfo.uid = pkgSetting.appId; 6697 pkg.mExtras = pkgSetting; 6698 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 6699 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 6700 // We just determined the app is signed correctly, so bring 6701 // over the latest parsed certs. 6702 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6703 } else { 6704 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6705 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6706 "Package " + pkg.packageName + " upgrade keys do not match the " 6707 + "previously installed version"); 6708 } else { 6709 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6710 String msg = "System package " + pkg.packageName 6711 + " signature changed; retaining data."; 6712 reportSettingsProblem(Log.WARN, msg); 6713 } 6714 } 6715 } else { 6716 try { 6717 verifySignaturesLP(pkgSetting, pkg); 6718 // We just determined the app is signed correctly, so bring 6719 // over the latest parsed certs. 6720 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6721 } catch (PackageManagerException e) { 6722 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6723 throw e; 6724 } 6725 // The signature has changed, but this package is in the system 6726 // image... let's recover! 6727 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6728 // However... if this package is part of a shared user, but it 6729 // doesn't match the signature of the shared user, let's fail. 6730 // What this means is that you can't change the signatures 6731 // associated with an overall shared user, which doesn't seem all 6732 // that unreasonable. 6733 if (pkgSetting.sharedUser != null) { 6734 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6735 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 6736 throw new PackageManagerException( 6737 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6738 "Signature mismatch for shared user : " 6739 + pkgSetting.sharedUser); 6740 } 6741 } 6742 // File a report about this. 6743 String msg = "System package " + pkg.packageName 6744 + " signature changed; retaining data."; 6745 reportSettingsProblem(Log.WARN, msg); 6746 } 6747 } 6748 // Verify that this new package doesn't have any content providers 6749 // that conflict with existing packages. Only do this if the 6750 // package isn't already installed, since we don't want to break 6751 // things that are installed. 6752 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6753 final int N = pkg.providers.size(); 6754 int i; 6755 for (i=0; i<N; i++) { 6756 PackageParser.Provider p = pkg.providers.get(i); 6757 if (p.info.authority != null) { 6758 String names[] = p.info.authority.split(";"); 6759 for (int j = 0; j < names.length; j++) { 6760 if (mProvidersByAuthority.containsKey(names[j])) { 6761 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6762 final String otherPackageName = 6763 ((other != null && other.getComponentName() != null) ? 6764 other.getComponentName().getPackageName() : "?"); 6765 throw new PackageManagerException( 6766 INSTALL_FAILED_CONFLICTING_PROVIDER, 6767 "Can't install because provider name " + names[j] 6768 + " (in package " + pkg.applicationInfo.packageName 6769 + ") is already used by " + otherPackageName); 6770 } 6771 } 6772 } 6773 } 6774 } 6775 6776 if (pkg.mAdoptPermissions != null) { 6777 // This package wants to adopt ownership of permissions from 6778 // another package. 6779 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6780 final String origName = pkg.mAdoptPermissions.get(i); 6781 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6782 if (orig != null) { 6783 if (verifyPackageUpdateLPr(orig, pkg)) { 6784 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6785 + pkg.packageName); 6786 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6787 } 6788 } 6789 } 6790 } 6791 } 6792 6793 final String pkgName = pkg.packageName; 6794 6795 final long scanFileTime = scanFile.lastModified(); 6796 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6797 pkg.applicationInfo.processName = fixProcessName( 6798 pkg.applicationInfo.packageName, 6799 pkg.applicationInfo.processName, 6800 pkg.applicationInfo.uid); 6801 6802 File dataPath; 6803 if (mPlatformPackage == pkg) { 6804 // The system package is special. 6805 dataPath = new File(Environment.getDataDirectory(), "system"); 6806 6807 pkg.applicationInfo.dataDir = dataPath.getPath(); 6808 6809 } else { 6810 // This is a normal package, need to make its data directory. 6811 dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid, 6812 UserHandle.USER_OWNER, pkg.packageName); 6813 6814 boolean uidError = false; 6815 if (dataPath.exists()) { 6816 int currentUid = 0; 6817 try { 6818 StructStat stat = Os.stat(dataPath.getPath()); 6819 currentUid = stat.st_uid; 6820 } catch (ErrnoException e) { 6821 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6822 } 6823 6824 // If we have mismatched owners for the data path, we have a problem. 6825 if (currentUid != pkg.applicationInfo.uid) { 6826 boolean recovered = false; 6827 if (currentUid == 0) { 6828 // The directory somehow became owned by root. Wow. 6829 // This is probably because the system was stopped while 6830 // installd was in the middle of messing with its libs 6831 // directory. Ask installd to fix that. 6832 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6833 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6834 if (ret >= 0) { 6835 recovered = true; 6836 String msg = "Package " + pkg.packageName 6837 + " unexpectedly changed to uid 0; recovered to " + 6838 + pkg.applicationInfo.uid; 6839 reportSettingsProblem(Log.WARN, msg); 6840 } 6841 } 6842 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6843 || (scanFlags&SCAN_BOOTING) != 0)) { 6844 // If this is a system app, we can at least delete its 6845 // current data so the application will still work. 6846 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6847 if (ret >= 0) { 6848 // TODO: Kill the processes first 6849 // Old data gone! 6850 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6851 ? "System package " : "Third party package "; 6852 String msg = prefix + pkg.packageName 6853 + " has changed from uid: " 6854 + currentUid + " to " 6855 + pkg.applicationInfo.uid + "; old data erased"; 6856 reportSettingsProblem(Log.WARN, msg); 6857 recovered = true; 6858 6859 // And now re-install the app. 6860 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6861 pkg.applicationInfo.seinfo); 6862 if (ret == -1) { 6863 // Ack should not happen! 6864 msg = prefix + pkg.packageName 6865 + " could not have data directory re-created after delete."; 6866 reportSettingsProblem(Log.WARN, msg); 6867 throw new PackageManagerException( 6868 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6869 } 6870 } 6871 if (!recovered) { 6872 mHasSystemUidErrors = true; 6873 } 6874 } else if (!recovered) { 6875 // If we allow this install to proceed, we will be broken. 6876 // Abort, abort! 6877 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6878 "scanPackageLI"); 6879 } 6880 if (!recovered) { 6881 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6882 + pkg.applicationInfo.uid + "/fs_" 6883 + currentUid; 6884 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6885 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6886 String msg = "Package " + pkg.packageName 6887 + " has mismatched uid: " 6888 + currentUid + " on disk, " 6889 + pkg.applicationInfo.uid + " in settings"; 6890 // writer 6891 synchronized (mPackages) { 6892 mSettings.mReadMessages.append(msg); 6893 mSettings.mReadMessages.append('\n'); 6894 uidError = true; 6895 if (!pkgSetting.uidError) { 6896 reportSettingsProblem(Log.ERROR, msg); 6897 } 6898 } 6899 } 6900 } 6901 pkg.applicationInfo.dataDir = dataPath.getPath(); 6902 if (mShouldRestoreconData) { 6903 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6904 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 6905 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 6906 } 6907 } else { 6908 if (DEBUG_PACKAGE_SCANNING) { 6909 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6910 Log.v(TAG, "Want this data dir: " + dataPath); 6911 } 6912 //invoke installer to do the actual installation 6913 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6914 pkg.applicationInfo.seinfo); 6915 if (ret < 0) { 6916 // Error from installer 6917 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6918 "Unable to create data dirs [errorCode=" + ret + "]"); 6919 } 6920 6921 if (dataPath.exists()) { 6922 pkg.applicationInfo.dataDir = dataPath.getPath(); 6923 } else { 6924 Slog.w(TAG, "Unable to create data directory: " + dataPath); 6925 pkg.applicationInfo.dataDir = null; 6926 } 6927 } 6928 6929 pkgSetting.uidError = uidError; 6930 } 6931 6932 final String path = scanFile.getPath(); 6933 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6934 6935 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 6936 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 6937 6938 // Some system apps still use directory structure for native libraries 6939 // in which case we might end up not detecting abi solely based on apk 6940 // structure. Try to detect abi based on directory structure. 6941 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 6942 pkg.applicationInfo.primaryCpuAbi == null) { 6943 setBundledAppAbisAndRoots(pkg, pkgSetting); 6944 setNativeLibraryPaths(pkg); 6945 } 6946 6947 } else { 6948 if ((scanFlags & SCAN_MOVE) != 0) { 6949 // We haven't run dex-opt for this move (since we've moved the compiled output too) 6950 // but we already have this packages package info in the PackageSetting. We just 6951 // use that and derive the native library path based on the new codepath. 6952 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 6953 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 6954 } 6955 6956 // Set native library paths again. For moves, the path will be updated based on the 6957 // ABIs we've determined above. For non-moves, the path will be updated based on the 6958 // ABIs we determined during compilation, but the path will depend on the final 6959 // package path (after the rename away from the stage path). 6960 setNativeLibraryPaths(pkg); 6961 } 6962 6963 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 6964 final int[] userIds = sUserManager.getUserIds(); 6965 synchronized (mInstallLock) { 6966 // Make sure all user data directories are ready to roll; we're okay 6967 // if they already exist 6968 if (!TextUtils.isEmpty(pkg.volumeUuid)) { 6969 for (int userId : userIds) { 6970 if (userId != 0) { 6971 mInstaller.createUserData(pkg.volumeUuid, pkg.packageName, 6972 UserHandle.getUid(userId, pkg.applicationInfo.uid), userId, 6973 pkg.applicationInfo.seinfo); 6974 } 6975 } 6976 } 6977 6978 // Create a native library symlink only if we have native libraries 6979 // and if the native libraries are 32 bit libraries. We do not provide 6980 // this symlink for 64 bit libraries. 6981 if (pkg.applicationInfo.primaryCpuAbi != null && 6982 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 6983 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 6984 for (int userId : userIds) { 6985 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 6986 nativeLibPath, userId) < 0) { 6987 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6988 "Failed linking native library dir (user=" + userId + ")"); 6989 } 6990 } 6991 } 6992 } 6993 6994 // This is a special case for the "system" package, where the ABI is 6995 // dictated by the zygote configuration (and init.rc). We should keep track 6996 // of this ABI so that we can deal with "normal" applications that run under 6997 // the same UID correctly. 6998 if (mPlatformPackage == pkg) { 6999 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 7000 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 7001 } 7002 7003 // If there's a mismatch between the abi-override in the package setting 7004 // and the abiOverride specified for the install. Warn about this because we 7005 // would've already compiled the app without taking the package setting into 7006 // account. 7007 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 7008 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 7009 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 7010 " for package: " + pkg.packageName); 7011 } 7012 } 7013 7014 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7015 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7016 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 7017 7018 // Copy the derived override back to the parsed package, so that we can 7019 // update the package settings accordingly. 7020 pkg.cpuAbiOverride = cpuAbiOverride; 7021 7022 if (DEBUG_ABI_SELECTION) { 7023 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 7024 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 7025 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 7026 } 7027 7028 // Push the derived path down into PackageSettings so we know what to 7029 // clean up at uninstall time. 7030 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 7031 7032 if (DEBUG_ABI_SELECTION) { 7033 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 7034 " primary=" + pkg.applicationInfo.primaryCpuAbi + 7035 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 7036 } 7037 7038 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 7039 // We don't do this here during boot because we can do it all 7040 // at once after scanning all existing packages. 7041 // 7042 // We also do this *before* we perform dexopt on this package, so that 7043 // we can avoid redundant dexopts, and also to make sure we've got the 7044 // code and package path correct. 7045 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 7046 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 7047 } 7048 7049 if ((scanFlags & SCAN_NO_DEX) == 0) { 7050 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 7051 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 7052 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7053 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 7054 } 7055 } 7056 if (mFactoryTest && pkg.requestedPermissions.contains( 7057 android.Manifest.permission.FACTORY_TEST)) { 7058 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 7059 } 7060 7061 ArrayList<PackageParser.Package> clientLibPkgs = null; 7062 7063 // writer 7064 synchronized (mPackages) { 7065 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7066 // Only system apps can add new shared libraries. 7067 if (pkg.libraryNames != null) { 7068 for (int i=0; i<pkg.libraryNames.size(); i++) { 7069 String name = pkg.libraryNames.get(i); 7070 boolean allowed = false; 7071 if (pkg.isUpdatedSystemApp()) { 7072 // New library entries can only be added through the 7073 // system image. This is important to get rid of a lot 7074 // of nasty edge cases: for example if we allowed a non- 7075 // system update of the app to add a library, then uninstalling 7076 // the update would make the library go away, and assumptions 7077 // we made such as through app install filtering would now 7078 // have allowed apps on the device which aren't compatible 7079 // with it. Better to just have the restriction here, be 7080 // conservative, and create many fewer cases that can negatively 7081 // impact the user experience. 7082 final PackageSetting sysPs = mSettings 7083 .getDisabledSystemPkgLPr(pkg.packageName); 7084 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 7085 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 7086 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 7087 allowed = true; 7088 allowed = true; 7089 break; 7090 } 7091 } 7092 } 7093 } else { 7094 allowed = true; 7095 } 7096 if (allowed) { 7097 if (!mSharedLibraries.containsKey(name)) { 7098 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 7099 } else if (!name.equals(pkg.packageName)) { 7100 Slog.w(TAG, "Package " + pkg.packageName + " library " 7101 + name + " already exists; skipping"); 7102 } 7103 } else { 7104 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 7105 + name + " that is not declared on system image; skipping"); 7106 } 7107 } 7108 if ((scanFlags&SCAN_BOOTING) == 0) { 7109 // If we are not booting, we need to update any applications 7110 // that are clients of our shared library. If we are booting, 7111 // this will all be done once the scan is complete. 7112 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 7113 } 7114 } 7115 } 7116 } 7117 7118 // We also need to dexopt any apps that are dependent on this library. Note that 7119 // if these fail, we should abort the install since installing the library will 7120 // result in some apps being broken. 7121 if (clientLibPkgs != null) { 7122 if ((scanFlags & SCAN_NO_DEX) == 0) { 7123 for (int i = 0; i < clientLibPkgs.size(); i++) { 7124 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7125 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 7126 null /* instruction sets */, forceDex, 7127 (scanFlags & SCAN_DEFER_DEX) != 0, false); 7128 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7129 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 7130 "scanPackageLI failed to dexopt clientLibPkgs"); 7131 } 7132 } 7133 } 7134 } 7135 7136 // Also need to kill any apps that are dependent on the library. 7137 if (clientLibPkgs != null) { 7138 for (int i=0; i<clientLibPkgs.size(); i++) { 7139 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7140 killApplication(clientPkg.applicationInfo.packageName, 7141 clientPkg.applicationInfo.uid, "update lib"); 7142 } 7143 } 7144 7145 // Make sure we're not adding any bogus keyset info 7146 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7147 ksms.assertScannedPackageValid(pkg); 7148 7149 // writer 7150 synchronized (mPackages) { 7151 // We don't expect installation to fail beyond this point 7152 7153 // Add the new setting to mSettings 7154 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 7155 // Add the new setting to mPackages 7156 mPackages.put(pkg.applicationInfo.packageName, pkg); 7157 // Make sure we don't accidentally delete its data. 7158 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 7159 while (iter.hasNext()) { 7160 PackageCleanItem item = iter.next(); 7161 if (pkgName.equals(item.packageName)) { 7162 iter.remove(); 7163 } 7164 } 7165 7166 // Take care of first install / last update times. 7167 if (currentTime != 0) { 7168 if (pkgSetting.firstInstallTime == 0) { 7169 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7170 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7171 pkgSetting.lastUpdateTime = currentTime; 7172 } 7173 } else if (pkgSetting.firstInstallTime == 0) { 7174 // We need *something*. Take time time stamp of the file. 7175 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7176 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7177 if (scanFileTime != pkgSetting.timeStamp) { 7178 // A package on the system image has changed; consider this 7179 // to be an update. 7180 pkgSetting.lastUpdateTime = scanFileTime; 7181 } 7182 } 7183 7184 // Add the package's KeySets to the global KeySetManagerService 7185 ksms.addScannedPackageLPw(pkg); 7186 7187 int N = pkg.providers.size(); 7188 StringBuilder r = null; 7189 int i; 7190 for (i=0; i<N; i++) { 7191 PackageParser.Provider p = pkg.providers.get(i); 7192 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7193 p.info.processName, pkg.applicationInfo.uid); 7194 mProviders.addProvider(p); 7195 p.syncable = p.info.isSyncable; 7196 if (p.info.authority != null) { 7197 String names[] = p.info.authority.split(";"); 7198 p.info.authority = null; 7199 for (int j = 0; j < names.length; j++) { 7200 if (j == 1 && p.syncable) { 7201 // We only want the first authority for a provider to possibly be 7202 // syncable, so if we already added this provider using a different 7203 // authority clear the syncable flag. We copy the provider before 7204 // changing it because the mProviders object contains a reference 7205 // to a provider that we don't want to change. 7206 // Only do this for the second authority since the resulting provider 7207 // object can be the same for all future authorities for this provider. 7208 p = new PackageParser.Provider(p); 7209 p.syncable = false; 7210 } 7211 if (!mProvidersByAuthority.containsKey(names[j])) { 7212 mProvidersByAuthority.put(names[j], p); 7213 if (p.info.authority == null) { 7214 p.info.authority = names[j]; 7215 } else { 7216 p.info.authority = p.info.authority + ";" + names[j]; 7217 } 7218 if (DEBUG_PACKAGE_SCANNING) { 7219 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7220 Log.d(TAG, "Registered content provider: " + names[j] 7221 + ", className = " + p.info.name + ", isSyncable = " 7222 + p.info.isSyncable); 7223 } 7224 } else { 7225 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7226 Slog.w(TAG, "Skipping provider name " + names[j] + 7227 " (in package " + pkg.applicationInfo.packageName + 7228 "): name already used by " 7229 + ((other != null && other.getComponentName() != null) 7230 ? other.getComponentName().getPackageName() : "?")); 7231 } 7232 } 7233 } 7234 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7235 if (r == null) { 7236 r = new StringBuilder(256); 7237 } else { 7238 r.append(' '); 7239 } 7240 r.append(p.info.name); 7241 } 7242 } 7243 if (r != null) { 7244 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7245 } 7246 7247 N = pkg.services.size(); 7248 r = null; 7249 for (i=0; i<N; i++) { 7250 PackageParser.Service s = pkg.services.get(i); 7251 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 7252 s.info.processName, pkg.applicationInfo.uid); 7253 mServices.addService(s); 7254 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7255 if (r == null) { 7256 r = new StringBuilder(256); 7257 } else { 7258 r.append(' '); 7259 } 7260 r.append(s.info.name); 7261 } 7262 } 7263 if (r != null) { 7264 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 7265 } 7266 7267 N = pkg.receivers.size(); 7268 r = null; 7269 for (i=0; i<N; i++) { 7270 PackageParser.Activity a = pkg.receivers.get(i); 7271 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7272 a.info.processName, pkg.applicationInfo.uid); 7273 mReceivers.addActivity(a, "receiver"); 7274 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7275 if (r == null) { 7276 r = new StringBuilder(256); 7277 } else { 7278 r.append(' '); 7279 } 7280 r.append(a.info.name); 7281 } 7282 } 7283 if (r != null) { 7284 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 7285 } 7286 7287 N = pkg.activities.size(); 7288 r = null; 7289 for (i=0; i<N; i++) { 7290 PackageParser.Activity a = pkg.activities.get(i); 7291 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7292 a.info.processName, pkg.applicationInfo.uid); 7293 mActivities.addActivity(a, "activity"); 7294 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7295 if (r == null) { 7296 r = new StringBuilder(256); 7297 } else { 7298 r.append(' '); 7299 } 7300 r.append(a.info.name); 7301 } 7302 } 7303 if (r != null) { 7304 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 7305 } 7306 7307 N = pkg.permissionGroups.size(); 7308 r = null; 7309 for (i=0; i<N; i++) { 7310 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 7311 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 7312 if (cur == null) { 7313 mPermissionGroups.put(pg.info.name, pg); 7314 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7315 if (r == null) { 7316 r = new StringBuilder(256); 7317 } else { 7318 r.append(' '); 7319 } 7320 r.append(pg.info.name); 7321 } 7322 } else { 7323 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 7324 + pg.info.packageName + " ignored: original from " 7325 + cur.info.packageName); 7326 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7327 if (r == null) { 7328 r = new StringBuilder(256); 7329 } else { 7330 r.append(' '); 7331 } 7332 r.append("DUP:"); 7333 r.append(pg.info.name); 7334 } 7335 } 7336 } 7337 if (r != null) { 7338 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 7339 } 7340 7341 N = pkg.permissions.size(); 7342 r = null; 7343 for (i=0; i<N; i++) { 7344 PackageParser.Permission p = pkg.permissions.get(i); 7345 7346 // Assume by default that we did not install this permission into the system. 7347 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 7348 7349 // Now that permission groups have a special meaning, we ignore permission 7350 // groups for legacy apps to prevent unexpected behavior. In particular, 7351 // permissions for one app being granted to someone just becuase they happen 7352 // to be in a group defined by another app (before this had no implications). 7353 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 7354 p.group = mPermissionGroups.get(p.info.group); 7355 // Warn for a permission in an unknown group. 7356 if (p.info.group != null && p.group == null) { 7357 Slog.w(TAG, "Permission " + p.info.name + " from package " 7358 + p.info.packageName + " in an unknown group " + p.info.group); 7359 } 7360 } 7361 7362 ArrayMap<String, BasePermission> permissionMap = 7363 p.tree ? mSettings.mPermissionTrees 7364 : mSettings.mPermissions; 7365 BasePermission bp = permissionMap.get(p.info.name); 7366 7367 // Allow system apps to redefine non-system permissions 7368 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 7369 final boolean currentOwnerIsSystem = (bp.perm != null 7370 && isSystemApp(bp.perm.owner)); 7371 if (isSystemApp(p.owner)) { 7372 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 7373 // It's a built-in permission and no owner, take ownership now 7374 bp.packageSetting = pkgSetting; 7375 bp.perm = p; 7376 bp.uid = pkg.applicationInfo.uid; 7377 bp.sourcePackage = p.info.packageName; 7378 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7379 } else if (!currentOwnerIsSystem) { 7380 String msg = "New decl " + p.owner + " of permission " 7381 + p.info.name + " is system; overriding " + bp.sourcePackage; 7382 reportSettingsProblem(Log.WARN, msg); 7383 bp = null; 7384 } 7385 } 7386 } 7387 7388 if (bp == null) { 7389 bp = new BasePermission(p.info.name, p.info.packageName, 7390 BasePermission.TYPE_NORMAL); 7391 permissionMap.put(p.info.name, bp); 7392 } 7393 7394 if (bp.perm == null) { 7395 if (bp.sourcePackage == null 7396 || bp.sourcePackage.equals(p.info.packageName)) { 7397 BasePermission tree = findPermissionTreeLP(p.info.name); 7398 if (tree == null 7399 || tree.sourcePackage.equals(p.info.packageName)) { 7400 bp.packageSetting = pkgSetting; 7401 bp.perm = p; 7402 bp.uid = pkg.applicationInfo.uid; 7403 bp.sourcePackage = p.info.packageName; 7404 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7405 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7406 if (r == null) { 7407 r = new StringBuilder(256); 7408 } else { 7409 r.append(' '); 7410 } 7411 r.append(p.info.name); 7412 } 7413 } else { 7414 Slog.w(TAG, "Permission " + p.info.name + " from package " 7415 + p.info.packageName + " ignored: base tree " 7416 + tree.name + " is from package " 7417 + tree.sourcePackage); 7418 } 7419 } else { 7420 Slog.w(TAG, "Permission " + p.info.name + " from package " 7421 + p.info.packageName + " ignored: original from " 7422 + bp.sourcePackage); 7423 } 7424 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7425 if (r == null) { 7426 r = new StringBuilder(256); 7427 } else { 7428 r.append(' '); 7429 } 7430 r.append("DUP:"); 7431 r.append(p.info.name); 7432 } 7433 if (bp.perm == p) { 7434 bp.protectionLevel = p.info.protectionLevel; 7435 } 7436 } 7437 7438 if (r != null) { 7439 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 7440 } 7441 7442 N = pkg.instrumentation.size(); 7443 r = null; 7444 for (i=0; i<N; i++) { 7445 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7446 a.info.packageName = pkg.applicationInfo.packageName; 7447 a.info.sourceDir = pkg.applicationInfo.sourceDir; 7448 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 7449 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 7450 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 7451 a.info.dataDir = pkg.applicationInfo.dataDir; 7452 7453 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 7454 // need other information about the application, like the ABI and what not ? 7455 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 7456 mInstrumentation.put(a.getComponentName(), a); 7457 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7458 if (r == null) { 7459 r = new StringBuilder(256); 7460 } else { 7461 r.append(' '); 7462 } 7463 r.append(a.info.name); 7464 } 7465 } 7466 if (r != null) { 7467 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 7468 } 7469 7470 if (pkg.protectedBroadcasts != null) { 7471 N = pkg.protectedBroadcasts.size(); 7472 for (i=0; i<N; i++) { 7473 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 7474 } 7475 } 7476 7477 pkgSetting.setTimeStamp(scanFileTime); 7478 7479 // Create idmap files for pairs of (packages, overlay packages). 7480 // Note: "android", ie framework-res.apk, is handled by native layers. 7481 if (pkg.mOverlayTarget != null) { 7482 // This is an overlay package. 7483 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 7484 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 7485 mOverlays.put(pkg.mOverlayTarget, 7486 new ArrayMap<String, PackageParser.Package>()); 7487 } 7488 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 7489 map.put(pkg.packageName, pkg); 7490 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 7491 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 7492 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7493 "scanPackageLI failed to createIdmap"); 7494 } 7495 } 7496 } else if (mOverlays.containsKey(pkg.packageName) && 7497 !pkg.packageName.equals("android")) { 7498 // This is a regular package, with one or more known overlay packages. 7499 createIdmapsForPackageLI(pkg); 7500 } 7501 } 7502 7503 return pkg; 7504 } 7505 7506 /** 7507 * Derive the ABI of a non-system package located at {@code scanFile}. This information 7508 * is derived purely on the basis of the contents of {@code scanFile} and 7509 * {@code cpuAbiOverride}. 7510 * 7511 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 7512 */ 7513 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 7514 String cpuAbiOverride, boolean extractLibs) 7515 throws PackageManagerException { 7516 // TODO: We can probably be smarter about this stuff. For installed apps, 7517 // we can calculate this information at install time once and for all. For 7518 // system apps, we can probably assume that this information doesn't change 7519 // after the first boot scan. As things stand, we do lots of unnecessary work. 7520 7521 // Give ourselves some initial paths; we'll come back for another 7522 // pass once we've determined ABI below. 7523 setNativeLibraryPaths(pkg); 7524 7525 // We would never need to extract libs for forward-locked and external packages, 7526 // since the container service will do it for us. We shouldn't attempt to 7527 // extract libs from system app when it was not updated. 7528 if (pkg.isForwardLocked() || isExternal(pkg) || 7529 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) { 7530 extractLibs = false; 7531 } 7532 7533 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7534 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7535 7536 NativeLibraryHelper.Handle handle = null; 7537 try { 7538 handle = NativeLibraryHelper.Handle.create(scanFile); 7539 // TODO(multiArch): This can be null for apps that didn't go through the 7540 // usual installation process. We can calculate it again, like we 7541 // do during install time. 7542 // 7543 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7544 // unnecessary. 7545 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7546 7547 // Null out the abis so that they can be recalculated. 7548 pkg.applicationInfo.primaryCpuAbi = null; 7549 pkg.applicationInfo.secondaryCpuAbi = null; 7550 if (isMultiArch(pkg.applicationInfo)) { 7551 // Warn if we've set an abiOverride for multi-lib packages.. 7552 // By definition, we need to copy both 32 and 64 bit libraries for 7553 // such packages. 7554 if (pkg.cpuAbiOverride != null 7555 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7556 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7557 } 7558 7559 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7560 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7561 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7562 if (extractLibs) { 7563 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7564 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7565 useIsaSpecificSubdirs); 7566 } else { 7567 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7568 } 7569 } 7570 7571 maybeThrowExceptionForMultiArchCopy( 7572 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7573 7574 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7575 if (extractLibs) { 7576 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7577 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7578 useIsaSpecificSubdirs); 7579 } else { 7580 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7581 } 7582 } 7583 7584 maybeThrowExceptionForMultiArchCopy( 7585 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7586 7587 if (abi64 >= 0) { 7588 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7589 } 7590 7591 if (abi32 >= 0) { 7592 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7593 if (abi64 >= 0) { 7594 pkg.applicationInfo.secondaryCpuAbi = abi; 7595 } else { 7596 pkg.applicationInfo.primaryCpuAbi = abi; 7597 } 7598 } 7599 } else { 7600 String[] abiList = (cpuAbiOverride != null) ? 7601 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7602 7603 // Enable gross and lame hacks for apps that are built with old 7604 // SDK tools. We must scan their APKs for renderscript bitcode and 7605 // not launch them if it's present. Don't bother checking on devices 7606 // that don't have 64 bit support. 7607 boolean needsRenderScriptOverride = false; 7608 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7609 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7610 abiList = Build.SUPPORTED_32_BIT_ABIS; 7611 needsRenderScriptOverride = true; 7612 } 7613 7614 final int copyRet; 7615 if (extractLibs) { 7616 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7617 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7618 } else { 7619 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7620 } 7621 7622 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7623 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7624 "Error unpackaging native libs for app, errorCode=" + copyRet); 7625 } 7626 7627 if (copyRet >= 0) { 7628 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7629 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7630 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7631 } else if (needsRenderScriptOverride) { 7632 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7633 } 7634 } 7635 } catch (IOException ioe) { 7636 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7637 } finally { 7638 IoUtils.closeQuietly(handle); 7639 } 7640 7641 // Now that we've calculated the ABIs and determined if it's an internal app, 7642 // we will go ahead and populate the nativeLibraryPath. 7643 setNativeLibraryPaths(pkg); 7644 } 7645 7646 /** 7647 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7648 * i.e, so that all packages can be run inside a single process if required. 7649 * 7650 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7651 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7652 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7653 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7654 * updating a package that belongs to a shared user. 7655 * 7656 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7657 * adds unnecessary complexity. 7658 */ 7659 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7660 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 7661 String requiredInstructionSet = null; 7662 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7663 requiredInstructionSet = VMRuntime.getInstructionSet( 7664 scannedPackage.applicationInfo.primaryCpuAbi); 7665 } 7666 7667 PackageSetting requirer = null; 7668 for (PackageSetting ps : packagesForUser) { 7669 // If packagesForUser contains scannedPackage, we skip it. This will happen 7670 // when scannedPackage is an update of an existing package. Without this check, 7671 // we will never be able to change the ABI of any package belonging to a shared 7672 // user, even if it's compatible with other packages. 7673 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7674 if (ps.primaryCpuAbiString == null) { 7675 continue; 7676 } 7677 7678 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7679 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7680 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7681 // this but there's not much we can do. 7682 String errorMessage = "Instruction set mismatch, " 7683 + ((requirer == null) ? "[caller]" : requirer) 7684 + " requires " + requiredInstructionSet + " whereas " + ps 7685 + " requires " + instructionSet; 7686 Slog.w(TAG, errorMessage); 7687 } 7688 7689 if (requiredInstructionSet == null) { 7690 requiredInstructionSet = instructionSet; 7691 requirer = ps; 7692 } 7693 } 7694 } 7695 7696 if (requiredInstructionSet != null) { 7697 String adjustedAbi; 7698 if (requirer != null) { 7699 // requirer != null implies that either scannedPackage was null or that scannedPackage 7700 // did not require an ABI, in which case we have to adjust scannedPackage to match 7701 // the ABI of the set (which is the same as requirer's ABI) 7702 adjustedAbi = requirer.primaryCpuAbiString; 7703 if (scannedPackage != null) { 7704 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7705 } 7706 } else { 7707 // requirer == null implies that we're updating all ABIs in the set to 7708 // match scannedPackage. 7709 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7710 } 7711 7712 for (PackageSetting ps : packagesForUser) { 7713 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7714 if (ps.primaryCpuAbiString != null) { 7715 continue; 7716 } 7717 7718 ps.primaryCpuAbiString = adjustedAbi; 7719 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7720 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7721 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7722 7723 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 7724 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 7725 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7726 ps.primaryCpuAbiString = null; 7727 ps.pkg.applicationInfo.primaryCpuAbi = null; 7728 return; 7729 } else { 7730 mInstaller.rmdex(ps.codePathString, 7731 getDexCodeInstructionSet(getPreferredInstructionSet())); 7732 } 7733 } 7734 } 7735 } 7736 } 7737 } 7738 7739 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7740 synchronized (mPackages) { 7741 mResolverReplaced = true; 7742 // Set up information for custom user intent resolution activity. 7743 mResolveActivity.applicationInfo = pkg.applicationInfo; 7744 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7745 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7746 mResolveActivity.processName = pkg.applicationInfo.packageName; 7747 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7748 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7749 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7750 mResolveActivity.theme = 0; 7751 mResolveActivity.exported = true; 7752 mResolveActivity.enabled = true; 7753 mResolveInfo.activityInfo = mResolveActivity; 7754 mResolveInfo.priority = 0; 7755 mResolveInfo.preferredOrder = 0; 7756 mResolveInfo.match = 0; 7757 mResolveComponentName = mCustomResolverComponentName; 7758 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7759 mResolveComponentName); 7760 } 7761 } 7762 7763 private static String calculateBundledApkRoot(final String codePathString) { 7764 final File codePath = new File(codePathString); 7765 final File codeRoot; 7766 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 7767 codeRoot = Environment.getRootDirectory(); 7768 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7769 codeRoot = Environment.getOemDirectory(); 7770 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7771 codeRoot = Environment.getVendorDirectory(); 7772 } else { 7773 // Unrecognized code path; take its top real segment as the apk root: 7774 // e.g. /something/app/blah.apk => /something 7775 try { 7776 File f = codePath.getCanonicalFile(); 7777 File parent = f.getParentFile(); // non-null because codePath is a file 7778 File tmp; 7779 while ((tmp = parent.getParentFile()) != null) { 7780 f = parent; 7781 parent = tmp; 7782 } 7783 codeRoot = f; 7784 Slog.w(TAG, "Unrecognized code path " 7785 + codePath + " - using " + codeRoot); 7786 } catch (IOException e) { 7787 // Can't canonicalize the code path -- shenanigans? 7788 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7789 return Environment.getRootDirectory().getPath(); 7790 } 7791 } 7792 return codeRoot.getPath(); 7793 } 7794 7795 /** 7796 * Derive and set the location of native libraries for the given package, 7797 * which varies depending on where and how the package was installed. 7798 */ 7799 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7800 final ApplicationInfo info = pkg.applicationInfo; 7801 final String codePath = pkg.codePath; 7802 final File codeFile = new File(codePath); 7803 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7804 final boolean asecApp = info.isForwardLocked() || isExternal(info); 7805 7806 info.nativeLibraryRootDir = null; 7807 info.nativeLibraryRootRequiresIsa = false; 7808 info.nativeLibraryDir = null; 7809 info.secondaryNativeLibraryDir = null; 7810 7811 if (isApkFile(codeFile)) { 7812 // Monolithic install 7813 if (bundledApp) { 7814 // If "/system/lib64/apkname" exists, assume that is the per-package 7815 // native library directory to use; otherwise use "/system/lib/apkname". 7816 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7817 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7818 getPrimaryInstructionSet(info)); 7819 7820 // This is a bundled system app so choose the path based on the ABI. 7821 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7822 // is just the default path. 7823 final String apkName = deriveCodePathName(codePath); 7824 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7825 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7826 apkName).getAbsolutePath(); 7827 7828 if (info.secondaryCpuAbi != null) { 7829 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7830 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7831 secondaryLibDir, apkName).getAbsolutePath(); 7832 } 7833 } else if (asecApp) { 7834 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 7835 .getAbsolutePath(); 7836 } else { 7837 final String apkName = deriveCodePathName(codePath); 7838 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 7839 .getAbsolutePath(); 7840 } 7841 7842 info.nativeLibraryRootRequiresIsa = false; 7843 info.nativeLibraryDir = info.nativeLibraryRootDir; 7844 } else { 7845 // Cluster install 7846 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 7847 info.nativeLibraryRootRequiresIsa = true; 7848 7849 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 7850 getPrimaryInstructionSet(info)).getAbsolutePath(); 7851 7852 if (info.secondaryCpuAbi != null) { 7853 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 7854 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 7855 } 7856 } 7857 } 7858 7859 /** 7860 * Calculate the abis and roots for a bundled app. These can uniquely 7861 * be determined from the contents of the system partition, i.e whether 7862 * it contains 64 or 32 bit shared libraries etc. We do not validate any 7863 * of this information, and instead assume that the system was built 7864 * sensibly. 7865 */ 7866 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 7867 PackageSetting pkgSetting) { 7868 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 7869 7870 // If "/system/lib64/apkname" exists, assume that is the per-package 7871 // native library directory to use; otherwise use "/system/lib/apkname". 7872 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 7873 setBundledAppAbi(pkg, apkRoot, apkName); 7874 // pkgSetting might be null during rescan following uninstall of updates 7875 // to a bundled app, so accommodate that possibility. The settings in 7876 // that case will be established later from the parsed package. 7877 // 7878 // If the settings aren't null, sync them up with what we've just derived. 7879 // note that apkRoot isn't stored in the package settings. 7880 if (pkgSetting != null) { 7881 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7882 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7883 } 7884 } 7885 7886 /** 7887 * Deduces the ABI of a bundled app and sets the relevant fields on the 7888 * parsed pkg object. 7889 * 7890 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 7891 * under which system libraries are installed. 7892 * @param apkName the name of the installed package. 7893 */ 7894 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 7895 final File codeFile = new File(pkg.codePath); 7896 7897 final boolean has64BitLibs; 7898 final boolean has32BitLibs; 7899 if (isApkFile(codeFile)) { 7900 // Monolithic install 7901 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 7902 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7903 } else { 7904 // Cluster install 7905 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7906 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7907 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7908 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7909 has64BitLibs = (new File(rootDir, isa)).exists(); 7910 } else { 7911 has64BitLibs = false; 7912 } 7913 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7914 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 7915 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 7916 has32BitLibs = (new File(rootDir, isa)).exists(); 7917 } else { 7918 has32BitLibs = false; 7919 } 7920 } 7921 7922 if (has64BitLibs && !has32BitLibs) { 7923 // The package has 64 bit libs, but not 32 bit libs. Its primary 7924 // ABI should be 64 bit. We can safely assume here that the bundled 7925 // native libraries correspond to the most preferred ABI in the list. 7926 7927 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7928 pkg.applicationInfo.secondaryCpuAbi = null; 7929 } else if (has32BitLibs && !has64BitLibs) { 7930 // The package has 32 bit libs but not 64 bit libs. Its primary 7931 // ABI should be 32 bit. 7932 7933 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7934 pkg.applicationInfo.secondaryCpuAbi = null; 7935 } else if (has32BitLibs && has64BitLibs) { 7936 // The application has both 64 and 32 bit bundled libraries. We check 7937 // here that the app declares multiArch support, and warn if it doesn't. 7938 // 7939 // We will be lenient here and record both ABIs. The primary will be the 7940 // ABI that's higher on the list, i.e, a device that's configured to prefer 7941 // 64 bit apps will see a 64 bit primary ABI, 7942 7943 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 7944 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 7945 } 7946 7947 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 7948 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7949 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7950 } else { 7951 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7952 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7953 } 7954 } else { 7955 pkg.applicationInfo.primaryCpuAbi = null; 7956 pkg.applicationInfo.secondaryCpuAbi = null; 7957 } 7958 } 7959 7960 private void killApplication(String pkgName, int appId, String reason) { 7961 // Request the ActivityManager to kill the process(only for existing packages) 7962 // so that we do not end up in a confused state while the user is still using the older 7963 // version of the application while the new one gets installed. 7964 IActivityManager am = ActivityManagerNative.getDefault(); 7965 if (am != null) { 7966 try { 7967 am.killApplicationWithAppId(pkgName, appId, reason); 7968 } catch (RemoteException e) { 7969 } 7970 } 7971 } 7972 7973 void removePackageLI(PackageSetting ps, boolean chatty) { 7974 if (DEBUG_INSTALL) { 7975 if (chatty) 7976 Log.d(TAG, "Removing package " + ps.name); 7977 } 7978 7979 // writer 7980 synchronized (mPackages) { 7981 mPackages.remove(ps.name); 7982 final PackageParser.Package pkg = ps.pkg; 7983 if (pkg != null) { 7984 cleanPackageDataStructuresLILPw(pkg, chatty); 7985 } 7986 } 7987 } 7988 7989 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 7990 if (DEBUG_INSTALL) { 7991 if (chatty) 7992 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 7993 } 7994 7995 // writer 7996 synchronized (mPackages) { 7997 mPackages.remove(pkg.applicationInfo.packageName); 7998 cleanPackageDataStructuresLILPw(pkg, chatty); 7999 } 8000 } 8001 8002 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 8003 int N = pkg.providers.size(); 8004 StringBuilder r = null; 8005 int i; 8006 for (i=0; i<N; i++) { 8007 PackageParser.Provider p = pkg.providers.get(i); 8008 mProviders.removeProvider(p); 8009 if (p.info.authority == null) { 8010 8011 /* There was another ContentProvider with this authority when 8012 * this app was installed so this authority is null, 8013 * Ignore it as we don't have to unregister the provider. 8014 */ 8015 continue; 8016 } 8017 String names[] = p.info.authority.split(";"); 8018 for (int j = 0; j < names.length; j++) { 8019 if (mProvidersByAuthority.get(names[j]) == p) { 8020 mProvidersByAuthority.remove(names[j]); 8021 if (DEBUG_REMOVE) { 8022 if (chatty) 8023 Log.d(TAG, "Unregistered content provider: " + names[j] 8024 + ", className = " + p.info.name + ", isSyncable = " 8025 + p.info.isSyncable); 8026 } 8027 } 8028 } 8029 if (DEBUG_REMOVE && chatty) { 8030 if (r == null) { 8031 r = new StringBuilder(256); 8032 } else { 8033 r.append(' '); 8034 } 8035 r.append(p.info.name); 8036 } 8037 } 8038 if (r != null) { 8039 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 8040 } 8041 8042 N = pkg.services.size(); 8043 r = null; 8044 for (i=0; i<N; i++) { 8045 PackageParser.Service s = pkg.services.get(i); 8046 mServices.removeService(s); 8047 if (chatty) { 8048 if (r == null) { 8049 r = new StringBuilder(256); 8050 } else { 8051 r.append(' '); 8052 } 8053 r.append(s.info.name); 8054 } 8055 } 8056 if (r != null) { 8057 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 8058 } 8059 8060 N = pkg.receivers.size(); 8061 r = null; 8062 for (i=0; i<N; i++) { 8063 PackageParser.Activity a = pkg.receivers.get(i); 8064 mReceivers.removeActivity(a, "receiver"); 8065 if (DEBUG_REMOVE && chatty) { 8066 if (r == null) { 8067 r = new StringBuilder(256); 8068 } else { 8069 r.append(' '); 8070 } 8071 r.append(a.info.name); 8072 } 8073 } 8074 if (r != null) { 8075 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 8076 } 8077 8078 N = pkg.activities.size(); 8079 r = null; 8080 for (i=0; i<N; i++) { 8081 PackageParser.Activity a = pkg.activities.get(i); 8082 mActivities.removeActivity(a, "activity"); 8083 if (DEBUG_REMOVE && chatty) { 8084 if (r == null) { 8085 r = new StringBuilder(256); 8086 } else { 8087 r.append(' '); 8088 } 8089 r.append(a.info.name); 8090 } 8091 } 8092 if (r != null) { 8093 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 8094 } 8095 8096 N = pkg.permissions.size(); 8097 r = null; 8098 for (i=0; i<N; i++) { 8099 PackageParser.Permission p = pkg.permissions.get(i); 8100 BasePermission bp = mSettings.mPermissions.get(p.info.name); 8101 if (bp == null) { 8102 bp = mSettings.mPermissionTrees.get(p.info.name); 8103 } 8104 if (bp != null && bp.perm == p) { 8105 bp.perm = null; 8106 if (DEBUG_REMOVE && chatty) { 8107 if (r == null) { 8108 r = new StringBuilder(256); 8109 } else { 8110 r.append(' '); 8111 } 8112 r.append(p.info.name); 8113 } 8114 } 8115 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8116 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 8117 if (appOpPerms != null) { 8118 appOpPerms.remove(pkg.packageName); 8119 } 8120 } 8121 } 8122 if (r != null) { 8123 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8124 } 8125 8126 N = pkg.requestedPermissions.size(); 8127 r = null; 8128 for (i=0; i<N; i++) { 8129 String perm = pkg.requestedPermissions.get(i); 8130 BasePermission bp = mSettings.mPermissions.get(perm); 8131 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8132 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 8133 if (appOpPerms != null) { 8134 appOpPerms.remove(pkg.packageName); 8135 if (appOpPerms.isEmpty()) { 8136 mAppOpPermissionPackages.remove(perm); 8137 } 8138 } 8139 } 8140 } 8141 if (r != null) { 8142 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8143 } 8144 8145 N = pkg.instrumentation.size(); 8146 r = null; 8147 for (i=0; i<N; i++) { 8148 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8149 mInstrumentation.remove(a.getComponentName()); 8150 if (DEBUG_REMOVE && chatty) { 8151 if (r == null) { 8152 r = new StringBuilder(256); 8153 } else { 8154 r.append(' '); 8155 } 8156 r.append(a.info.name); 8157 } 8158 } 8159 if (r != null) { 8160 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 8161 } 8162 8163 r = null; 8164 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8165 // Only system apps can hold shared libraries. 8166 if (pkg.libraryNames != null) { 8167 for (i=0; i<pkg.libraryNames.size(); i++) { 8168 String name = pkg.libraryNames.get(i); 8169 SharedLibraryEntry cur = mSharedLibraries.get(name); 8170 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 8171 mSharedLibraries.remove(name); 8172 if (DEBUG_REMOVE && chatty) { 8173 if (r == null) { 8174 r = new StringBuilder(256); 8175 } else { 8176 r.append(' '); 8177 } 8178 r.append(name); 8179 } 8180 } 8181 } 8182 } 8183 } 8184 if (r != null) { 8185 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 8186 } 8187 } 8188 8189 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 8190 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 8191 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 8192 return true; 8193 } 8194 } 8195 return false; 8196 } 8197 8198 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 8199 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 8200 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 8201 8202 private void updatePermissionsLPw(String changingPkg, 8203 PackageParser.Package pkgInfo, int flags) { 8204 // Make sure there are no dangling permission trees. 8205 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 8206 while (it.hasNext()) { 8207 final BasePermission bp = it.next(); 8208 if (bp.packageSetting == null) { 8209 // We may not yet have parsed the package, so just see if 8210 // we still know about its settings. 8211 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8212 } 8213 if (bp.packageSetting == null) { 8214 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 8215 + " from package " + bp.sourcePackage); 8216 it.remove(); 8217 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8218 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8219 Slog.i(TAG, "Removing old permission tree: " + bp.name 8220 + " from package " + bp.sourcePackage); 8221 flags |= UPDATE_PERMISSIONS_ALL; 8222 it.remove(); 8223 } 8224 } 8225 } 8226 8227 // Make sure all dynamic permissions have been assigned to a package, 8228 // and make sure there are no dangling permissions. 8229 it = mSettings.mPermissions.values().iterator(); 8230 while (it.hasNext()) { 8231 final BasePermission bp = it.next(); 8232 if (bp.type == BasePermission.TYPE_DYNAMIC) { 8233 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 8234 + bp.name + " pkg=" + bp.sourcePackage 8235 + " info=" + bp.pendingInfo); 8236 if (bp.packageSetting == null && bp.pendingInfo != null) { 8237 final BasePermission tree = findPermissionTreeLP(bp.name); 8238 if (tree != null && tree.perm != null) { 8239 bp.packageSetting = tree.packageSetting; 8240 bp.perm = new PackageParser.Permission(tree.perm.owner, 8241 new PermissionInfo(bp.pendingInfo)); 8242 bp.perm.info.packageName = tree.perm.info.packageName; 8243 bp.perm.info.name = bp.name; 8244 bp.uid = tree.uid; 8245 } 8246 } 8247 } 8248 if (bp.packageSetting == null) { 8249 // We may not yet have parsed the package, so just see if 8250 // we still know about its settings. 8251 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8252 } 8253 if (bp.packageSetting == null) { 8254 Slog.w(TAG, "Removing dangling permission: " + bp.name 8255 + " from package " + bp.sourcePackage); 8256 it.remove(); 8257 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8258 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8259 Slog.i(TAG, "Removing old permission: " + bp.name 8260 + " from package " + bp.sourcePackage); 8261 flags |= UPDATE_PERMISSIONS_ALL; 8262 it.remove(); 8263 } 8264 } 8265 } 8266 8267 // Now update the permissions for all packages, in particular 8268 // replace the granted permissions of the system packages. 8269 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 8270 for (PackageParser.Package pkg : mPackages.values()) { 8271 if (pkg != pkgInfo) { 8272 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 8273 changingPkg); 8274 } 8275 } 8276 } 8277 8278 if (pkgInfo != null) { 8279 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 8280 } 8281 } 8282 8283 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 8284 String packageOfInterest) { 8285 // IMPORTANT: There are two types of permissions: install and runtime. 8286 // Install time permissions are granted when the app is installed to 8287 // all device users and users added in the future. Runtime permissions 8288 // are granted at runtime explicitly to specific users. Normal and signature 8289 // protected permissions are install time permissions. Dangerous permissions 8290 // are install permissions if the app's target SDK is Lollipop MR1 or older, 8291 // otherwise they are runtime permissions. This function does not manage 8292 // runtime permissions except for the case an app targeting Lollipop MR1 8293 // being upgraded to target a newer SDK, in which case dangerous permissions 8294 // are transformed from install time to runtime ones. 8295 8296 final PackageSetting ps = (PackageSetting) pkg.mExtras; 8297 if (ps == null) { 8298 return; 8299 } 8300 8301 PermissionsState permissionsState = ps.getPermissionsState(); 8302 PermissionsState origPermissions = permissionsState; 8303 8304 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 8305 8306 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 8307 8308 boolean changedInstallPermission = false; 8309 8310 if (replace) { 8311 ps.installPermissionsFixed = false; 8312 if (!ps.isSharedUser()) { 8313 origPermissions = new PermissionsState(permissionsState); 8314 permissionsState.reset(); 8315 } 8316 } 8317 8318 permissionsState.setGlobalGids(mGlobalGids); 8319 8320 final int N = pkg.requestedPermissions.size(); 8321 for (int i=0; i<N; i++) { 8322 final String name = pkg.requestedPermissions.get(i); 8323 final BasePermission bp = mSettings.mPermissions.get(name); 8324 8325 if (DEBUG_INSTALL) { 8326 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 8327 } 8328 8329 if (bp == null || bp.packageSetting == null) { 8330 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8331 Slog.w(TAG, "Unknown permission " + name 8332 + " in package " + pkg.packageName); 8333 } 8334 continue; 8335 } 8336 8337 final String perm = bp.name; 8338 boolean allowedSig = false; 8339 int grant = GRANT_DENIED; 8340 8341 // Keep track of app op permissions. 8342 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8343 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 8344 if (pkgs == null) { 8345 pkgs = new ArraySet<>(); 8346 mAppOpPermissionPackages.put(bp.name, pkgs); 8347 } 8348 pkgs.add(pkg.packageName); 8349 } 8350 8351 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 8352 switch (level) { 8353 case PermissionInfo.PROTECTION_NORMAL: { 8354 // For all apps normal permissions are install time ones. 8355 grant = GRANT_INSTALL; 8356 } break; 8357 8358 case PermissionInfo.PROTECTION_DANGEROUS: { 8359 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 8360 // For legacy apps dangerous permissions are install time ones. 8361 grant = GRANT_INSTALL_LEGACY; 8362 } else if (origPermissions.hasInstallPermission(bp.name)) { 8363 // For legacy apps that became modern, install becomes runtime. 8364 grant = GRANT_UPGRADE; 8365 } else { 8366 // For modern apps keep runtime permissions unchanged. 8367 grant = GRANT_RUNTIME; 8368 } 8369 } break; 8370 8371 case PermissionInfo.PROTECTION_SIGNATURE: { 8372 // For all apps signature permissions are install time ones. 8373 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 8374 if (allowedSig) { 8375 grant = GRANT_INSTALL; 8376 } 8377 } break; 8378 } 8379 8380 if (DEBUG_INSTALL) { 8381 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 8382 } 8383 8384 if (grant != GRANT_DENIED) { 8385 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 8386 // If this is an existing, non-system package, then 8387 // we can't add any new permissions to it. 8388 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 8389 // Except... if this is a permission that was added 8390 // to the platform (note: need to only do this when 8391 // updating the platform). 8392 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 8393 grant = GRANT_DENIED; 8394 } 8395 } 8396 } 8397 8398 switch (grant) { 8399 case GRANT_INSTALL: { 8400 // Revoke this as runtime permission to handle the case of 8401 // a runtime permission being downgraded to an install one. 8402 for (int userId : UserManagerService.getInstance().getUserIds()) { 8403 if (origPermissions.getRuntimePermissionState( 8404 bp.name, userId) != null) { 8405 // Revoke the runtime permission and clear the flags. 8406 origPermissions.revokeRuntimePermission(bp, userId); 8407 origPermissions.updatePermissionFlags(bp, userId, 8408 PackageManager.MASK_PERMISSION_FLAGS, 0); 8409 // If we revoked a permission permission, we have to write. 8410 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8411 changedRuntimePermissionUserIds, userId); 8412 } 8413 } 8414 // Grant an install permission. 8415 if (permissionsState.grantInstallPermission(bp) != 8416 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8417 changedInstallPermission = true; 8418 } 8419 } break; 8420 8421 case GRANT_INSTALL_LEGACY: { 8422 // Grant an install permission. 8423 if (permissionsState.grantInstallPermission(bp) != 8424 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8425 changedInstallPermission = true; 8426 } 8427 } break; 8428 8429 case GRANT_RUNTIME: { 8430 // Grant previously granted runtime permissions. 8431 for (int userId : UserManagerService.getInstance().getUserIds()) { 8432 PermissionState permissionState = origPermissions 8433 .getRuntimePermissionState(bp.name, userId); 8434 final int flags = permissionState != null 8435 ? permissionState.getFlags() : 0; 8436 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8437 if (permissionsState.grantRuntimePermission(bp, userId) == 8438 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8439 // If we cannot put the permission as it was, we have to write. 8440 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8441 changedRuntimePermissionUserIds, userId); 8442 } 8443 } 8444 // Propagate the permission flags. 8445 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 8446 } 8447 } break; 8448 8449 case GRANT_UPGRADE: { 8450 // Grant runtime permissions for a previously held install permission. 8451 PermissionState permissionState = origPermissions 8452 .getInstallPermissionState(bp.name); 8453 final int flags = permissionState != null ? permissionState.getFlags() : 0; 8454 8455 if (origPermissions.revokeInstallPermission(bp) 8456 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 8457 // We will be transferring the permission flags, so clear them. 8458 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 8459 PackageManager.MASK_PERMISSION_FLAGS, 0); 8460 changedInstallPermission = true; 8461 } 8462 8463 // If the permission is not to be promoted to runtime we ignore it and 8464 // also its other flags as they are not applicable to install permissions. 8465 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 8466 for (int userId : currentUserIds) { 8467 if (permissionsState.grantRuntimePermission(bp, userId) != 8468 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8469 // Transfer the permission flags. 8470 permissionsState.updatePermissionFlags(bp, userId, 8471 flags, flags); 8472 // If we granted the permission, we have to write. 8473 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8474 changedRuntimePermissionUserIds, userId); 8475 } 8476 } 8477 } 8478 } break; 8479 8480 default: { 8481 if (packageOfInterest == null 8482 || packageOfInterest.equals(pkg.packageName)) { 8483 Slog.w(TAG, "Not granting permission " + perm 8484 + " to package " + pkg.packageName 8485 + " because it was previously installed without"); 8486 } 8487 } break; 8488 } 8489 } else { 8490 if (permissionsState.revokeInstallPermission(bp) != 8491 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8492 // Also drop the permission flags. 8493 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 8494 PackageManager.MASK_PERMISSION_FLAGS, 0); 8495 changedInstallPermission = true; 8496 Slog.i(TAG, "Un-granting permission " + perm 8497 + " from package " + pkg.packageName 8498 + " (protectionLevel=" + bp.protectionLevel 8499 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8500 + ")"); 8501 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 8502 // Don't print warning for app op permissions, since it is fine for them 8503 // not to be granted, there is a UI for the user to decide. 8504 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8505 Slog.w(TAG, "Not granting permission " + perm 8506 + " to package " + pkg.packageName 8507 + " (protectionLevel=" + bp.protectionLevel 8508 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8509 + ")"); 8510 } 8511 } 8512 } 8513 } 8514 8515 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 8516 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 8517 // This is the first that we have heard about this package, so the 8518 // permissions we have now selected are fixed until explicitly 8519 // changed. 8520 ps.installPermissionsFixed = true; 8521 } 8522 8523 // Persist the runtime permissions state for users with changes. 8524 for (int userId : changedRuntimePermissionUserIds) { 8525 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 8526 } 8527 } 8528 8529 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8530 boolean allowed = false; 8531 final int NP = PackageParser.NEW_PERMISSIONS.length; 8532 for (int ip=0; ip<NP; ip++) { 8533 final PackageParser.NewPermissionInfo npi 8534 = PackageParser.NEW_PERMISSIONS[ip]; 8535 if (npi.name.equals(perm) 8536 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8537 allowed = true; 8538 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8539 + pkg.packageName); 8540 break; 8541 } 8542 } 8543 return allowed; 8544 } 8545 8546 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 8547 BasePermission bp, PermissionsState origPermissions) { 8548 boolean allowed; 8549 allowed = (compareSignatures( 8550 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 8551 == PackageManager.SIGNATURE_MATCH) 8552 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 8553 == PackageManager.SIGNATURE_MATCH); 8554 if (!allowed && (bp.protectionLevel 8555 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 8556 if (isSystemApp(pkg)) { 8557 // For updated system applications, a system permission 8558 // is granted only if it had been defined by the original application. 8559 if (pkg.isUpdatedSystemApp()) { 8560 final PackageSetting sysPs = mSettings 8561 .getDisabledSystemPkgLPr(pkg.packageName); 8562 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 8563 // If the original was granted this permission, we take 8564 // that grant decision as read and propagate it to the 8565 // update. 8566 if (sysPs.isPrivileged()) { 8567 allowed = true; 8568 } 8569 } else { 8570 // The system apk may have been updated with an older 8571 // version of the one on the data partition, but which 8572 // granted a new system permission that it didn't have 8573 // before. In this case we do want to allow the app to 8574 // now get the new permission if the ancestral apk is 8575 // privileged to get it. 8576 if (sysPs.pkg != null && sysPs.isPrivileged()) { 8577 for (int j=0; 8578 j<sysPs.pkg.requestedPermissions.size(); j++) { 8579 if (perm.equals( 8580 sysPs.pkg.requestedPermissions.get(j))) { 8581 allowed = true; 8582 break; 8583 } 8584 } 8585 } 8586 } 8587 } else { 8588 allowed = isPrivilegedApp(pkg); 8589 } 8590 } 8591 } 8592 if (!allowed) { 8593 if (!allowed && (bp.protectionLevel 8594 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 8595 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.MNC) { 8596 // If this was a previously normal/dangerous permission that got moved 8597 // to a system permission as part of the runtime permission redesign, then 8598 // we still want to blindly grant it to old apps. 8599 allowed = true; 8600 } 8601 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 8602 && pkg.packageName.equals(mRequiredInstallerPackage)) { 8603 // If this permission is to be granted to the system installer and 8604 // this app is an installer, then it gets the permission. 8605 allowed = true; 8606 } 8607 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 8608 && pkg.packageName.equals(mRequiredVerifierPackage)) { 8609 // If this permission is to be granted to the system verifier and 8610 // this app is a verifier, then it gets the permission. 8611 allowed = true; 8612 } 8613 if (!allowed && (bp.protectionLevel 8614 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 8615 && isSystemApp(pkg)) { 8616 // Any pre-installed system app is allowed to get this permission. 8617 allowed = true; 8618 } 8619 if (!allowed && (bp.protectionLevel 8620 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 8621 // For development permissions, a development permission 8622 // is granted only if it was already granted. 8623 allowed = origPermissions.hasInstallPermission(perm); 8624 } 8625 } 8626 return allowed; 8627 } 8628 8629 final class ActivityIntentResolver 8630 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 8631 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8632 boolean defaultOnly, int userId) { 8633 if (!sUserManager.exists(userId)) return null; 8634 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8635 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8636 } 8637 8638 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8639 int userId) { 8640 if (!sUserManager.exists(userId)) return null; 8641 mFlags = flags; 8642 return super.queryIntent(intent, resolvedType, 8643 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8644 } 8645 8646 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8647 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 8648 if (!sUserManager.exists(userId)) return null; 8649 if (packageActivities == null) { 8650 return null; 8651 } 8652 mFlags = flags; 8653 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8654 final int N = packageActivities.size(); 8655 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 8656 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 8657 8658 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 8659 for (int i = 0; i < N; ++i) { 8660 intentFilters = packageActivities.get(i).intents; 8661 if (intentFilters != null && intentFilters.size() > 0) { 8662 PackageParser.ActivityIntentInfo[] array = 8663 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 8664 intentFilters.toArray(array); 8665 listCut.add(array); 8666 } 8667 } 8668 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8669 } 8670 8671 public final void addActivity(PackageParser.Activity a, String type) { 8672 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 8673 mActivities.put(a.getComponentName(), a); 8674 if (DEBUG_SHOW_INFO) 8675 Log.v( 8676 TAG, " " + type + " " + 8677 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 8678 if (DEBUG_SHOW_INFO) 8679 Log.v(TAG, " Class=" + a.info.name); 8680 final int NI = a.intents.size(); 8681 for (int j=0; j<NI; j++) { 8682 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8683 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 8684 intent.setPriority(0); 8685 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 8686 + a.className + " with priority > 0, forcing to 0"); 8687 } 8688 if (DEBUG_SHOW_INFO) { 8689 Log.v(TAG, " IntentFilter:"); 8690 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8691 } 8692 if (!intent.debugCheck()) { 8693 Log.w(TAG, "==> For Activity " + a.info.name); 8694 } 8695 addFilter(intent); 8696 } 8697 } 8698 8699 public final void removeActivity(PackageParser.Activity a, String type) { 8700 mActivities.remove(a.getComponentName()); 8701 if (DEBUG_SHOW_INFO) { 8702 Log.v(TAG, " " + type + " " 8703 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 8704 : a.info.name) + ":"); 8705 Log.v(TAG, " Class=" + a.info.name); 8706 } 8707 final int NI = a.intents.size(); 8708 for (int j=0; j<NI; j++) { 8709 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8710 if (DEBUG_SHOW_INFO) { 8711 Log.v(TAG, " IntentFilter:"); 8712 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8713 } 8714 removeFilter(intent); 8715 } 8716 } 8717 8718 @Override 8719 protected boolean allowFilterResult( 8720 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 8721 ActivityInfo filterAi = filter.activity.info; 8722 for (int i=dest.size()-1; i>=0; i--) { 8723 ActivityInfo destAi = dest.get(i).activityInfo; 8724 if (destAi.name == filterAi.name 8725 && destAi.packageName == filterAi.packageName) { 8726 return false; 8727 } 8728 } 8729 return true; 8730 } 8731 8732 @Override 8733 protected ActivityIntentInfo[] newArray(int size) { 8734 return new ActivityIntentInfo[size]; 8735 } 8736 8737 @Override 8738 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 8739 if (!sUserManager.exists(userId)) return true; 8740 PackageParser.Package p = filter.activity.owner; 8741 if (p != null) { 8742 PackageSetting ps = (PackageSetting)p.mExtras; 8743 if (ps != null) { 8744 // System apps are never considered stopped for purposes of 8745 // filtering, because there may be no way for the user to 8746 // actually re-launch them. 8747 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 8748 && ps.getStopped(userId); 8749 } 8750 } 8751 return false; 8752 } 8753 8754 @Override 8755 protected boolean isPackageForFilter(String packageName, 8756 PackageParser.ActivityIntentInfo info) { 8757 return packageName.equals(info.activity.owner.packageName); 8758 } 8759 8760 @Override 8761 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 8762 int match, int userId) { 8763 if (!sUserManager.exists(userId)) return null; 8764 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 8765 return null; 8766 } 8767 final PackageParser.Activity activity = info.activity; 8768 if (mSafeMode && (activity.info.applicationInfo.flags 8769 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8770 return null; 8771 } 8772 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 8773 if (ps == null) { 8774 return null; 8775 } 8776 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 8777 ps.readUserState(userId), userId); 8778 if (ai == null) { 8779 return null; 8780 } 8781 final ResolveInfo res = new ResolveInfo(); 8782 res.activityInfo = ai; 8783 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8784 res.filter = info; 8785 } 8786 if (info != null) { 8787 res.handleAllWebDataURI = info.handleAllWebDataURI(); 8788 } 8789 res.priority = info.getPriority(); 8790 res.preferredOrder = activity.owner.mPreferredOrder; 8791 //System.out.println("Result: " + res.activityInfo.className + 8792 // " = " + res.priority); 8793 res.match = match; 8794 res.isDefault = info.hasDefault; 8795 res.labelRes = info.labelRes; 8796 res.nonLocalizedLabel = info.nonLocalizedLabel; 8797 if (userNeedsBadging(userId)) { 8798 res.noResourceId = true; 8799 } else { 8800 res.icon = info.icon; 8801 } 8802 res.iconResourceId = info.icon; 8803 res.system = res.activityInfo.applicationInfo.isSystemApp(); 8804 return res; 8805 } 8806 8807 @Override 8808 protected void sortResults(List<ResolveInfo> results) { 8809 Collections.sort(results, mResolvePrioritySorter); 8810 } 8811 8812 @Override 8813 protected void dumpFilter(PrintWriter out, String prefix, 8814 PackageParser.ActivityIntentInfo filter) { 8815 out.print(prefix); out.print( 8816 Integer.toHexString(System.identityHashCode(filter.activity))); 8817 out.print(' '); 8818 filter.activity.printComponentShortName(out); 8819 out.print(" filter "); 8820 out.println(Integer.toHexString(System.identityHashCode(filter))); 8821 } 8822 8823 @Override 8824 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 8825 return filter.activity; 8826 } 8827 8828 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8829 PackageParser.Activity activity = (PackageParser.Activity)label; 8830 out.print(prefix); out.print( 8831 Integer.toHexString(System.identityHashCode(activity))); 8832 out.print(' '); 8833 activity.printComponentShortName(out); 8834 if (count > 1) { 8835 out.print(" ("); out.print(count); out.print(" filters)"); 8836 } 8837 out.println(); 8838 } 8839 8840// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8841// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8842// final List<ResolveInfo> retList = Lists.newArrayList(); 8843// while (i.hasNext()) { 8844// final ResolveInfo resolveInfo = i.next(); 8845// if (isEnabledLP(resolveInfo.activityInfo)) { 8846// retList.add(resolveInfo); 8847// } 8848// } 8849// return retList; 8850// } 8851 8852 // Keys are String (activity class name), values are Activity. 8853 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 8854 = new ArrayMap<ComponentName, PackageParser.Activity>(); 8855 private int mFlags; 8856 } 8857 8858 private final class ServiceIntentResolver 8859 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 8860 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8861 boolean defaultOnly, int userId) { 8862 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8863 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8864 } 8865 8866 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8867 int userId) { 8868 if (!sUserManager.exists(userId)) return null; 8869 mFlags = flags; 8870 return super.queryIntent(intent, resolvedType, 8871 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8872 } 8873 8874 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8875 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 8876 if (!sUserManager.exists(userId)) return null; 8877 if (packageServices == null) { 8878 return null; 8879 } 8880 mFlags = flags; 8881 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8882 final int N = packageServices.size(); 8883 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 8884 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 8885 8886 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 8887 for (int i = 0; i < N; ++i) { 8888 intentFilters = packageServices.get(i).intents; 8889 if (intentFilters != null && intentFilters.size() > 0) { 8890 PackageParser.ServiceIntentInfo[] array = 8891 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 8892 intentFilters.toArray(array); 8893 listCut.add(array); 8894 } 8895 } 8896 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8897 } 8898 8899 public final void addService(PackageParser.Service s) { 8900 mServices.put(s.getComponentName(), s); 8901 if (DEBUG_SHOW_INFO) { 8902 Log.v(TAG, " " 8903 + (s.info.nonLocalizedLabel != null 8904 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8905 Log.v(TAG, " Class=" + s.info.name); 8906 } 8907 final int NI = s.intents.size(); 8908 int j; 8909 for (j=0; j<NI; j++) { 8910 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8911 if (DEBUG_SHOW_INFO) { 8912 Log.v(TAG, " IntentFilter:"); 8913 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8914 } 8915 if (!intent.debugCheck()) { 8916 Log.w(TAG, "==> For Service " + s.info.name); 8917 } 8918 addFilter(intent); 8919 } 8920 } 8921 8922 public final void removeService(PackageParser.Service s) { 8923 mServices.remove(s.getComponentName()); 8924 if (DEBUG_SHOW_INFO) { 8925 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 8926 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8927 Log.v(TAG, " Class=" + s.info.name); 8928 } 8929 final int NI = s.intents.size(); 8930 int j; 8931 for (j=0; j<NI; j++) { 8932 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8933 if (DEBUG_SHOW_INFO) { 8934 Log.v(TAG, " IntentFilter:"); 8935 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8936 } 8937 removeFilter(intent); 8938 } 8939 } 8940 8941 @Override 8942 protected boolean allowFilterResult( 8943 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 8944 ServiceInfo filterSi = filter.service.info; 8945 for (int i=dest.size()-1; i>=0; i--) { 8946 ServiceInfo destAi = dest.get(i).serviceInfo; 8947 if (destAi.name == filterSi.name 8948 && destAi.packageName == filterSi.packageName) { 8949 return false; 8950 } 8951 } 8952 return true; 8953 } 8954 8955 @Override 8956 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 8957 return new PackageParser.ServiceIntentInfo[size]; 8958 } 8959 8960 @Override 8961 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 8962 if (!sUserManager.exists(userId)) return true; 8963 PackageParser.Package p = filter.service.owner; 8964 if (p != null) { 8965 PackageSetting ps = (PackageSetting)p.mExtras; 8966 if (ps != null) { 8967 // System apps are never considered stopped for purposes of 8968 // filtering, because there may be no way for the user to 8969 // actually re-launch them. 8970 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8971 && ps.getStopped(userId); 8972 } 8973 } 8974 return false; 8975 } 8976 8977 @Override 8978 protected boolean isPackageForFilter(String packageName, 8979 PackageParser.ServiceIntentInfo info) { 8980 return packageName.equals(info.service.owner.packageName); 8981 } 8982 8983 @Override 8984 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 8985 int match, int userId) { 8986 if (!sUserManager.exists(userId)) return null; 8987 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 8988 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 8989 return null; 8990 } 8991 final PackageParser.Service service = info.service; 8992 if (mSafeMode && (service.info.applicationInfo.flags 8993 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8994 return null; 8995 } 8996 PackageSetting ps = (PackageSetting) service.owner.mExtras; 8997 if (ps == null) { 8998 return null; 8999 } 9000 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 9001 ps.readUserState(userId), userId); 9002 if (si == null) { 9003 return null; 9004 } 9005 final ResolveInfo res = new ResolveInfo(); 9006 res.serviceInfo = si; 9007 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9008 res.filter = filter; 9009 } 9010 res.priority = info.getPriority(); 9011 res.preferredOrder = service.owner.mPreferredOrder; 9012 res.match = match; 9013 res.isDefault = info.hasDefault; 9014 res.labelRes = info.labelRes; 9015 res.nonLocalizedLabel = info.nonLocalizedLabel; 9016 res.icon = info.icon; 9017 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 9018 return res; 9019 } 9020 9021 @Override 9022 protected void sortResults(List<ResolveInfo> results) { 9023 Collections.sort(results, mResolvePrioritySorter); 9024 } 9025 9026 @Override 9027 protected void dumpFilter(PrintWriter out, String prefix, 9028 PackageParser.ServiceIntentInfo filter) { 9029 out.print(prefix); out.print( 9030 Integer.toHexString(System.identityHashCode(filter.service))); 9031 out.print(' '); 9032 filter.service.printComponentShortName(out); 9033 out.print(" filter "); 9034 out.println(Integer.toHexString(System.identityHashCode(filter))); 9035 } 9036 9037 @Override 9038 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 9039 return filter.service; 9040 } 9041 9042 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9043 PackageParser.Service service = (PackageParser.Service)label; 9044 out.print(prefix); out.print( 9045 Integer.toHexString(System.identityHashCode(service))); 9046 out.print(' '); 9047 service.printComponentShortName(out); 9048 if (count > 1) { 9049 out.print(" ("); out.print(count); out.print(" filters)"); 9050 } 9051 out.println(); 9052 } 9053 9054// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9055// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9056// final List<ResolveInfo> retList = Lists.newArrayList(); 9057// while (i.hasNext()) { 9058// final ResolveInfo resolveInfo = (ResolveInfo) i; 9059// if (isEnabledLP(resolveInfo.serviceInfo)) { 9060// retList.add(resolveInfo); 9061// } 9062// } 9063// return retList; 9064// } 9065 9066 // Keys are String (activity class name), values are Activity. 9067 private final ArrayMap<ComponentName, PackageParser.Service> mServices 9068 = new ArrayMap<ComponentName, PackageParser.Service>(); 9069 private int mFlags; 9070 }; 9071 9072 private final class ProviderIntentResolver 9073 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 9074 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9075 boolean defaultOnly, int userId) { 9076 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9077 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9078 } 9079 9080 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9081 int userId) { 9082 if (!sUserManager.exists(userId)) 9083 return null; 9084 mFlags = flags; 9085 return super.queryIntent(intent, resolvedType, 9086 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9087 } 9088 9089 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9090 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 9091 if (!sUserManager.exists(userId)) 9092 return null; 9093 if (packageProviders == null) { 9094 return null; 9095 } 9096 mFlags = flags; 9097 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 9098 final int N = packageProviders.size(); 9099 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 9100 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 9101 9102 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 9103 for (int i = 0; i < N; ++i) { 9104 intentFilters = packageProviders.get(i).intents; 9105 if (intentFilters != null && intentFilters.size() > 0) { 9106 PackageParser.ProviderIntentInfo[] array = 9107 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 9108 intentFilters.toArray(array); 9109 listCut.add(array); 9110 } 9111 } 9112 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9113 } 9114 9115 public final void addProvider(PackageParser.Provider p) { 9116 if (mProviders.containsKey(p.getComponentName())) { 9117 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 9118 return; 9119 } 9120 9121 mProviders.put(p.getComponentName(), p); 9122 if (DEBUG_SHOW_INFO) { 9123 Log.v(TAG, " " 9124 + (p.info.nonLocalizedLabel != null 9125 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9126 Log.v(TAG, " Class=" + p.info.name); 9127 } 9128 final int NI = p.intents.size(); 9129 int j; 9130 for (j = 0; j < NI; j++) { 9131 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9132 if (DEBUG_SHOW_INFO) { 9133 Log.v(TAG, " IntentFilter:"); 9134 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9135 } 9136 if (!intent.debugCheck()) { 9137 Log.w(TAG, "==> For Provider " + p.info.name); 9138 } 9139 addFilter(intent); 9140 } 9141 } 9142 9143 public final void removeProvider(PackageParser.Provider p) { 9144 mProviders.remove(p.getComponentName()); 9145 if (DEBUG_SHOW_INFO) { 9146 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 9147 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9148 Log.v(TAG, " Class=" + p.info.name); 9149 } 9150 final int NI = p.intents.size(); 9151 int j; 9152 for (j = 0; j < NI; j++) { 9153 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9154 if (DEBUG_SHOW_INFO) { 9155 Log.v(TAG, " IntentFilter:"); 9156 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9157 } 9158 removeFilter(intent); 9159 } 9160 } 9161 9162 @Override 9163 protected boolean allowFilterResult( 9164 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 9165 ProviderInfo filterPi = filter.provider.info; 9166 for (int i = dest.size() - 1; i >= 0; i--) { 9167 ProviderInfo destPi = dest.get(i).providerInfo; 9168 if (destPi.name == filterPi.name 9169 && destPi.packageName == filterPi.packageName) { 9170 return false; 9171 } 9172 } 9173 return true; 9174 } 9175 9176 @Override 9177 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 9178 return new PackageParser.ProviderIntentInfo[size]; 9179 } 9180 9181 @Override 9182 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 9183 if (!sUserManager.exists(userId)) 9184 return true; 9185 PackageParser.Package p = filter.provider.owner; 9186 if (p != null) { 9187 PackageSetting ps = (PackageSetting) p.mExtras; 9188 if (ps != null) { 9189 // System apps are never considered stopped for purposes of 9190 // filtering, because there may be no way for the user to 9191 // actually re-launch them. 9192 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9193 && ps.getStopped(userId); 9194 } 9195 } 9196 return false; 9197 } 9198 9199 @Override 9200 protected boolean isPackageForFilter(String packageName, 9201 PackageParser.ProviderIntentInfo info) { 9202 return packageName.equals(info.provider.owner.packageName); 9203 } 9204 9205 @Override 9206 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 9207 int match, int userId) { 9208 if (!sUserManager.exists(userId)) 9209 return null; 9210 final PackageParser.ProviderIntentInfo info = filter; 9211 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 9212 return null; 9213 } 9214 final PackageParser.Provider provider = info.provider; 9215 if (mSafeMode && (provider.info.applicationInfo.flags 9216 & ApplicationInfo.FLAG_SYSTEM) == 0) { 9217 return null; 9218 } 9219 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 9220 if (ps == null) { 9221 return null; 9222 } 9223 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 9224 ps.readUserState(userId), userId); 9225 if (pi == null) { 9226 return null; 9227 } 9228 final ResolveInfo res = new ResolveInfo(); 9229 res.providerInfo = pi; 9230 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 9231 res.filter = filter; 9232 } 9233 res.priority = info.getPriority(); 9234 res.preferredOrder = provider.owner.mPreferredOrder; 9235 res.match = match; 9236 res.isDefault = info.hasDefault; 9237 res.labelRes = info.labelRes; 9238 res.nonLocalizedLabel = info.nonLocalizedLabel; 9239 res.icon = info.icon; 9240 res.system = res.providerInfo.applicationInfo.isSystemApp(); 9241 return res; 9242 } 9243 9244 @Override 9245 protected void sortResults(List<ResolveInfo> results) { 9246 Collections.sort(results, mResolvePrioritySorter); 9247 } 9248 9249 @Override 9250 protected void dumpFilter(PrintWriter out, String prefix, 9251 PackageParser.ProviderIntentInfo filter) { 9252 out.print(prefix); 9253 out.print( 9254 Integer.toHexString(System.identityHashCode(filter.provider))); 9255 out.print(' '); 9256 filter.provider.printComponentShortName(out); 9257 out.print(" filter "); 9258 out.println(Integer.toHexString(System.identityHashCode(filter))); 9259 } 9260 9261 @Override 9262 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 9263 return filter.provider; 9264 } 9265 9266 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9267 PackageParser.Provider provider = (PackageParser.Provider)label; 9268 out.print(prefix); out.print( 9269 Integer.toHexString(System.identityHashCode(provider))); 9270 out.print(' '); 9271 provider.printComponentShortName(out); 9272 if (count > 1) { 9273 out.print(" ("); out.print(count); out.print(" filters)"); 9274 } 9275 out.println(); 9276 } 9277 9278 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 9279 = new ArrayMap<ComponentName, PackageParser.Provider>(); 9280 private int mFlags; 9281 }; 9282 9283 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 9284 new Comparator<ResolveInfo>() { 9285 public int compare(ResolveInfo r1, ResolveInfo r2) { 9286 int v1 = r1.priority; 9287 int v2 = r2.priority; 9288 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 9289 if (v1 != v2) { 9290 return (v1 > v2) ? -1 : 1; 9291 } 9292 v1 = r1.preferredOrder; 9293 v2 = r2.preferredOrder; 9294 if (v1 != v2) { 9295 return (v1 > v2) ? -1 : 1; 9296 } 9297 if (r1.isDefault != r2.isDefault) { 9298 return r1.isDefault ? -1 : 1; 9299 } 9300 v1 = r1.match; 9301 v2 = r2.match; 9302 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 9303 if (v1 != v2) { 9304 return (v1 > v2) ? -1 : 1; 9305 } 9306 if (r1.system != r2.system) { 9307 return r1.system ? -1 : 1; 9308 } 9309 return 0; 9310 } 9311 }; 9312 9313 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 9314 new Comparator<ProviderInfo>() { 9315 public int compare(ProviderInfo p1, ProviderInfo p2) { 9316 final int v1 = p1.initOrder; 9317 final int v2 = p2.initOrder; 9318 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 9319 } 9320 }; 9321 9322 final void sendPackageBroadcast(final String action, final String pkg, 9323 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 9324 final int[] userIds) { 9325 mHandler.post(new Runnable() { 9326 @Override 9327 public void run() { 9328 try { 9329 final IActivityManager am = ActivityManagerNative.getDefault(); 9330 if (am == null) return; 9331 final int[] resolvedUserIds; 9332 if (userIds == null) { 9333 resolvedUserIds = am.getRunningUserIds(); 9334 } else { 9335 resolvedUserIds = userIds; 9336 } 9337 for (int id : resolvedUserIds) { 9338 final Intent intent = new Intent(action, 9339 pkg != null ? Uri.fromParts("package", pkg, null) : null); 9340 if (extras != null) { 9341 intent.putExtras(extras); 9342 } 9343 if (targetPkg != null) { 9344 intent.setPackage(targetPkg); 9345 } 9346 // Modify the UID when posting to other users 9347 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 9348 if (uid > 0 && UserHandle.getUserId(uid) != id) { 9349 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 9350 intent.putExtra(Intent.EXTRA_UID, uid); 9351 } 9352 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 9353 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 9354 if (DEBUG_BROADCASTS) { 9355 RuntimeException here = new RuntimeException("here"); 9356 here.fillInStackTrace(); 9357 Slog.d(TAG, "Sending to user " + id + ": " 9358 + intent.toShortString(false, true, false, false) 9359 + " " + intent.getExtras(), here); 9360 } 9361 am.broadcastIntent(null, intent, null, finishedReceiver, 9362 0, null, null, null, android.app.AppOpsManager.OP_NONE, 9363 null, finishedReceiver != null, false, id); 9364 } 9365 } catch (RemoteException ex) { 9366 } 9367 } 9368 }); 9369 } 9370 9371 /** 9372 * Check if the external storage media is available. This is true if there 9373 * is a mounted external storage medium or if the external storage is 9374 * emulated. 9375 */ 9376 private boolean isExternalMediaAvailable() { 9377 return mMediaMounted || Environment.isExternalStorageEmulated(); 9378 } 9379 9380 @Override 9381 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 9382 // writer 9383 synchronized (mPackages) { 9384 if (!isExternalMediaAvailable()) { 9385 // If the external storage is no longer mounted at this point, 9386 // the caller may not have been able to delete all of this 9387 // packages files and can not delete any more. Bail. 9388 return null; 9389 } 9390 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 9391 if (lastPackage != null) { 9392 pkgs.remove(lastPackage); 9393 } 9394 if (pkgs.size() > 0) { 9395 return pkgs.get(0); 9396 } 9397 } 9398 return null; 9399 } 9400 9401 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 9402 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 9403 userId, andCode ? 1 : 0, packageName); 9404 if (mSystemReady) { 9405 msg.sendToTarget(); 9406 } else { 9407 if (mPostSystemReadyMessages == null) { 9408 mPostSystemReadyMessages = new ArrayList<>(); 9409 } 9410 mPostSystemReadyMessages.add(msg); 9411 } 9412 } 9413 9414 void startCleaningPackages() { 9415 // reader 9416 synchronized (mPackages) { 9417 if (!isExternalMediaAvailable()) { 9418 return; 9419 } 9420 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 9421 return; 9422 } 9423 } 9424 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 9425 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 9426 IActivityManager am = ActivityManagerNative.getDefault(); 9427 if (am != null) { 9428 try { 9429 am.startService(null, intent, null, mContext.getOpPackageName(), 9430 UserHandle.USER_OWNER); 9431 } catch (RemoteException e) { 9432 } 9433 } 9434 } 9435 9436 @Override 9437 public void installPackage(String originPath, IPackageInstallObserver2 observer, 9438 int installFlags, String installerPackageName, VerificationParams verificationParams, 9439 String packageAbiOverride) { 9440 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 9441 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 9442 } 9443 9444 @Override 9445 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 9446 int installFlags, String installerPackageName, VerificationParams verificationParams, 9447 String packageAbiOverride, int userId) { 9448 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 9449 9450 final int callingUid = Binder.getCallingUid(); 9451 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 9452 9453 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9454 try { 9455 if (observer != null) { 9456 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 9457 } 9458 } catch (RemoteException re) { 9459 } 9460 return; 9461 } 9462 9463 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 9464 installFlags |= PackageManager.INSTALL_FROM_ADB; 9465 9466 } else { 9467 // Caller holds INSTALL_PACKAGES permission, so we're less strict 9468 // about installerPackageName. 9469 9470 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 9471 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 9472 } 9473 9474 UserHandle user; 9475 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 9476 user = UserHandle.ALL; 9477 } else { 9478 user = new UserHandle(userId); 9479 } 9480 9481 // Only system components can circumvent runtime permissions when installing. 9482 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 9483 && mContext.checkCallingOrSelfPermission(Manifest.permission 9484 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 9485 throw new SecurityException("You need the " 9486 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 9487 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 9488 } 9489 9490 verificationParams.setInstallerUid(callingUid); 9491 9492 final File originFile = new File(originPath); 9493 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 9494 9495 final Message msg = mHandler.obtainMessage(INIT_COPY); 9496 msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName, 9497 null, verificationParams, user, packageAbiOverride, null); 9498 mHandler.sendMessage(msg); 9499 } 9500 9501 void installStage(String packageName, File stagedDir, String stagedCid, 9502 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 9503 String installerPackageName, int installerUid, UserHandle user) { 9504 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 9505 params.referrerUri, installerUid, null); 9506 verifParams.setInstallerUid(installerUid); 9507 9508 final OriginInfo origin; 9509 if (stagedDir != null) { 9510 origin = OriginInfo.fromStagedFile(stagedDir); 9511 } else { 9512 origin = OriginInfo.fromStagedContainer(stagedCid); 9513 } 9514 9515 final Message msg = mHandler.obtainMessage(INIT_COPY); 9516 msg.obj = new InstallParams(origin, null, observer, params.installFlags, 9517 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride, 9518 params.grantedRuntimePermissions); 9519 mHandler.sendMessage(msg); 9520 } 9521 9522 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 9523 Bundle extras = new Bundle(1); 9524 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 9525 9526 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 9527 packageName, extras, null, null, new int[] {userId}); 9528 try { 9529 IActivityManager am = ActivityManagerNative.getDefault(); 9530 final boolean isSystem = 9531 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 9532 if (isSystem && am.isUserRunning(userId, false)) { 9533 // The just-installed/enabled app is bundled on the system, so presumed 9534 // to be able to run automatically without needing an explicit launch. 9535 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 9536 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 9537 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 9538 .setPackage(packageName); 9539 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 9540 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 9541 } 9542 } catch (RemoteException e) { 9543 // shouldn't happen 9544 Slog.w(TAG, "Unable to bootstrap installed package", e); 9545 } 9546 } 9547 9548 @Override 9549 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 9550 int userId) { 9551 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9552 PackageSetting pkgSetting; 9553 final int uid = Binder.getCallingUid(); 9554 enforceCrossUserPermission(uid, userId, true, true, 9555 "setApplicationHiddenSetting for user " + userId); 9556 9557 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 9558 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 9559 return false; 9560 } 9561 9562 long callingId = Binder.clearCallingIdentity(); 9563 try { 9564 boolean sendAdded = false; 9565 boolean sendRemoved = false; 9566 // writer 9567 synchronized (mPackages) { 9568 pkgSetting = mSettings.mPackages.get(packageName); 9569 if (pkgSetting == null) { 9570 return false; 9571 } 9572 if (pkgSetting.getHidden(userId) != hidden) { 9573 pkgSetting.setHidden(hidden, userId); 9574 mSettings.writePackageRestrictionsLPr(userId); 9575 if (hidden) { 9576 sendRemoved = true; 9577 } else { 9578 sendAdded = true; 9579 } 9580 } 9581 } 9582 if (sendAdded) { 9583 sendPackageAddedForUser(packageName, pkgSetting, userId); 9584 return true; 9585 } 9586 if (sendRemoved) { 9587 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 9588 "hiding pkg"); 9589 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 9590 } 9591 } finally { 9592 Binder.restoreCallingIdentity(callingId); 9593 } 9594 return false; 9595 } 9596 9597 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 9598 int userId) { 9599 final PackageRemovedInfo info = new PackageRemovedInfo(); 9600 info.removedPackage = packageName; 9601 info.removedUsers = new int[] {userId}; 9602 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 9603 info.sendBroadcast(false, false, false); 9604 } 9605 9606 /** 9607 * Returns true if application is not found or there was an error. Otherwise it returns 9608 * the hidden state of the package for the given user. 9609 */ 9610 @Override 9611 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 9612 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9613 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 9614 false, "getApplicationHidden for user " + userId); 9615 PackageSetting pkgSetting; 9616 long callingId = Binder.clearCallingIdentity(); 9617 try { 9618 // writer 9619 synchronized (mPackages) { 9620 pkgSetting = mSettings.mPackages.get(packageName); 9621 if (pkgSetting == null) { 9622 return true; 9623 } 9624 return pkgSetting.getHidden(userId); 9625 } 9626 } finally { 9627 Binder.restoreCallingIdentity(callingId); 9628 } 9629 } 9630 9631 /** 9632 * @hide 9633 */ 9634 @Override 9635 public int installExistingPackageAsUser(String packageName, int userId) { 9636 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 9637 null); 9638 PackageSetting pkgSetting; 9639 final int uid = Binder.getCallingUid(); 9640 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 9641 + userId); 9642 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9643 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 9644 } 9645 9646 long callingId = Binder.clearCallingIdentity(); 9647 try { 9648 boolean sendAdded = false; 9649 9650 // writer 9651 synchronized (mPackages) { 9652 pkgSetting = mSettings.mPackages.get(packageName); 9653 if (pkgSetting == null) { 9654 return PackageManager.INSTALL_FAILED_INVALID_URI; 9655 } 9656 if (!pkgSetting.getInstalled(userId)) { 9657 pkgSetting.setInstalled(true, userId); 9658 pkgSetting.setHidden(false, userId); 9659 mSettings.writePackageRestrictionsLPr(userId); 9660 sendAdded = true; 9661 } 9662 } 9663 9664 if (sendAdded) { 9665 sendPackageAddedForUser(packageName, pkgSetting, userId); 9666 } 9667 } finally { 9668 Binder.restoreCallingIdentity(callingId); 9669 } 9670 9671 return PackageManager.INSTALL_SUCCEEDED; 9672 } 9673 9674 boolean isUserRestricted(int userId, String restrictionKey) { 9675 Bundle restrictions = sUserManager.getUserRestrictions(userId); 9676 if (restrictions.getBoolean(restrictionKey, false)) { 9677 Log.w(TAG, "User is restricted: " + restrictionKey); 9678 return true; 9679 } 9680 return false; 9681 } 9682 9683 @Override 9684 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 9685 mContext.enforceCallingOrSelfPermission( 9686 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9687 "Only package verification agents can verify applications"); 9688 9689 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9690 final PackageVerificationResponse response = new PackageVerificationResponse( 9691 verificationCode, Binder.getCallingUid()); 9692 msg.arg1 = id; 9693 msg.obj = response; 9694 mHandler.sendMessage(msg); 9695 } 9696 9697 @Override 9698 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 9699 long millisecondsToDelay) { 9700 mContext.enforceCallingOrSelfPermission( 9701 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9702 "Only package verification agents can extend verification timeouts"); 9703 9704 final PackageVerificationState state = mPendingVerification.get(id); 9705 final PackageVerificationResponse response = new PackageVerificationResponse( 9706 verificationCodeAtTimeout, Binder.getCallingUid()); 9707 9708 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 9709 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 9710 } 9711 if (millisecondsToDelay < 0) { 9712 millisecondsToDelay = 0; 9713 } 9714 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 9715 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 9716 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 9717 } 9718 9719 if ((state != null) && !state.timeoutExtended()) { 9720 state.extendTimeout(); 9721 9722 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9723 msg.arg1 = id; 9724 msg.obj = response; 9725 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 9726 } 9727 } 9728 9729 private void broadcastPackageVerified(int verificationId, Uri packageUri, 9730 int verificationCode, UserHandle user) { 9731 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 9732 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 9733 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9734 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9735 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 9736 9737 mContext.sendBroadcastAsUser(intent, user, 9738 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 9739 } 9740 9741 private ComponentName matchComponentForVerifier(String packageName, 9742 List<ResolveInfo> receivers) { 9743 ActivityInfo targetReceiver = null; 9744 9745 final int NR = receivers.size(); 9746 for (int i = 0; i < NR; i++) { 9747 final ResolveInfo info = receivers.get(i); 9748 if (info.activityInfo == null) { 9749 continue; 9750 } 9751 9752 if (packageName.equals(info.activityInfo.packageName)) { 9753 targetReceiver = info.activityInfo; 9754 break; 9755 } 9756 } 9757 9758 if (targetReceiver == null) { 9759 return null; 9760 } 9761 9762 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 9763 } 9764 9765 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 9766 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 9767 if (pkgInfo.verifiers.length == 0) { 9768 return null; 9769 } 9770 9771 final int N = pkgInfo.verifiers.length; 9772 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 9773 for (int i = 0; i < N; i++) { 9774 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 9775 9776 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 9777 receivers); 9778 if (comp == null) { 9779 continue; 9780 } 9781 9782 final int verifierUid = getUidForVerifier(verifierInfo); 9783 if (verifierUid == -1) { 9784 continue; 9785 } 9786 9787 if (DEBUG_VERIFY) { 9788 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 9789 + " with the correct signature"); 9790 } 9791 sufficientVerifiers.add(comp); 9792 verificationState.addSufficientVerifier(verifierUid); 9793 } 9794 9795 return sufficientVerifiers; 9796 } 9797 9798 private int getUidForVerifier(VerifierInfo verifierInfo) { 9799 synchronized (mPackages) { 9800 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 9801 if (pkg == null) { 9802 return -1; 9803 } else if (pkg.mSignatures.length != 1) { 9804 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9805 + " has more than one signature; ignoring"); 9806 return -1; 9807 } 9808 9809 /* 9810 * If the public key of the package's signature does not match 9811 * our expected public key, then this is a different package and 9812 * we should skip. 9813 */ 9814 9815 final byte[] expectedPublicKey; 9816 try { 9817 final Signature verifierSig = pkg.mSignatures[0]; 9818 final PublicKey publicKey = verifierSig.getPublicKey(); 9819 expectedPublicKey = publicKey.getEncoded(); 9820 } catch (CertificateException e) { 9821 return -1; 9822 } 9823 9824 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 9825 9826 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 9827 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9828 + " does not have the expected public key; ignoring"); 9829 return -1; 9830 } 9831 9832 return pkg.applicationInfo.uid; 9833 } 9834 } 9835 9836 @Override 9837 public void finishPackageInstall(int token) { 9838 enforceSystemOrRoot("Only the system is allowed to finish installs"); 9839 9840 if (DEBUG_INSTALL) { 9841 Slog.v(TAG, "BM finishing package install for " + token); 9842 } 9843 9844 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9845 mHandler.sendMessage(msg); 9846 } 9847 9848 /** 9849 * Get the verification agent timeout. 9850 * 9851 * @return verification timeout in milliseconds 9852 */ 9853 private long getVerificationTimeout() { 9854 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 9855 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 9856 DEFAULT_VERIFICATION_TIMEOUT); 9857 } 9858 9859 /** 9860 * Get the default verification agent response code. 9861 * 9862 * @return default verification response code 9863 */ 9864 private int getDefaultVerificationResponse() { 9865 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9866 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 9867 DEFAULT_VERIFICATION_RESPONSE); 9868 } 9869 9870 /** 9871 * Check whether or not package verification has been enabled. 9872 * 9873 * @return true if verification should be performed 9874 */ 9875 private boolean isVerificationEnabled(int userId, int installFlags) { 9876 if (!DEFAULT_VERIFY_ENABLE) { 9877 return false; 9878 } 9879 9880 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 9881 9882 // Check if installing from ADB 9883 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 9884 // Do not run verification in a test harness environment 9885 if (ActivityManager.isRunningInTestHarness()) { 9886 return false; 9887 } 9888 if (ensureVerifyAppsEnabled) { 9889 return true; 9890 } 9891 // Check if the developer does not want package verification for ADB installs 9892 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9893 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 9894 return false; 9895 } 9896 } 9897 9898 if (ensureVerifyAppsEnabled) { 9899 return true; 9900 } 9901 9902 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9903 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 9904 } 9905 9906 @Override 9907 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 9908 throws RemoteException { 9909 mContext.enforceCallingOrSelfPermission( 9910 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 9911 "Only intentfilter verification agents can verify applications"); 9912 9913 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 9914 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 9915 Binder.getCallingUid(), verificationCode, failedDomains); 9916 msg.arg1 = id; 9917 msg.obj = response; 9918 mHandler.sendMessage(msg); 9919 } 9920 9921 @Override 9922 public int getIntentVerificationStatus(String packageName, int userId) { 9923 synchronized (mPackages) { 9924 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 9925 } 9926 } 9927 9928 @Override 9929 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 9930 mContext.enforceCallingOrSelfPermission( 9931 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 9932 9933 boolean result = false; 9934 synchronized (mPackages) { 9935 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 9936 } 9937 if (result) { 9938 scheduleWritePackageRestrictionsLocked(userId); 9939 } 9940 return result; 9941 } 9942 9943 @Override 9944 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 9945 synchronized (mPackages) { 9946 return mSettings.getIntentFilterVerificationsLPr(packageName); 9947 } 9948 } 9949 9950 @Override 9951 public List<IntentFilter> getAllIntentFilters(String packageName) { 9952 if (TextUtils.isEmpty(packageName)) { 9953 return Collections.<IntentFilter>emptyList(); 9954 } 9955 synchronized (mPackages) { 9956 PackageParser.Package pkg = mPackages.get(packageName); 9957 if (pkg == null || pkg.activities == null) { 9958 return Collections.<IntentFilter>emptyList(); 9959 } 9960 final int count = pkg.activities.size(); 9961 ArrayList<IntentFilter> result = new ArrayList<>(); 9962 for (int n=0; n<count; n++) { 9963 PackageParser.Activity activity = pkg.activities.get(n); 9964 if (activity.intents != null || activity.intents.size() > 0) { 9965 result.addAll(activity.intents); 9966 } 9967 } 9968 return result; 9969 } 9970 } 9971 9972 @Override 9973 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 9974 mContext.enforceCallingOrSelfPermission( 9975 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 9976 9977 synchronized (mPackages) { 9978 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 9979 if (packageName != null) { 9980 result |= updateIntentVerificationStatus(packageName, 9981 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 9982 userId); 9983 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 9984 packageName, userId); 9985 } 9986 return result; 9987 } 9988 } 9989 9990 @Override 9991 public String getDefaultBrowserPackageName(int userId) { 9992 synchronized (mPackages) { 9993 return mSettings.getDefaultBrowserPackageNameLPw(userId); 9994 } 9995 } 9996 9997 /** 9998 * Get the "allow unknown sources" setting. 9999 * 10000 * @return the current "allow unknown sources" setting 10001 */ 10002 private int getUnknownSourcesSettings() { 10003 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10004 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 10005 -1); 10006 } 10007 10008 @Override 10009 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 10010 final int uid = Binder.getCallingUid(); 10011 // writer 10012 synchronized (mPackages) { 10013 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 10014 if (targetPackageSetting == null) { 10015 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 10016 } 10017 10018 PackageSetting installerPackageSetting; 10019 if (installerPackageName != null) { 10020 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 10021 if (installerPackageSetting == null) { 10022 throw new IllegalArgumentException("Unknown installer package: " 10023 + installerPackageName); 10024 } 10025 } else { 10026 installerPackageSetting = null; 10027 } 10028 10029 Signature[] callerSignature; 10030 Object obj = mSettings.getUserIdLPr(uid); 10031 if (obj != null) { 10032 if (obj instanceof SharedUserSetting) { 10033 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 10034 } else if (obj instanceof PackageSetting) { 10035 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 10036 } else { 10037 throw new SecurityException("Bad object " + obj + " for uid " + uid); 10038 } 10039 } else { 10040 throw new SecurityException("Unknown calling uid " + uid); 10041 } 10042 10043 // Verify: can't set installerPackageName to a package that is 10044 // not signed with the same cert as the caller. 10045 if (installerPackageSetting != null) { 10046 if (compareSignatures(callerSignature, 10047 installerPackageSetting.signatures.mSignatures) 10048 != PackageManager.SIGNATURE_MATCH) { 10049 throw new SecurityException( 10050 "Caller does not have same cert as new installer package " 10051 + installerPackageName); 10052 } 10053 } 10054 10055 // Verify: if target already has an installer package, it must 10056 // be signed with the same cert as the caller. 10057 if (targetPackageSetting.installerPackageName != null) { 10058 PackageSetting setting = mSettings.mPackages.get( 10059 targetPackageSetting.installerPackageName); 10060 // If the currently set package isn't valid, then it's always 10061 // okay to change it. 10062 if (setting != null) { 10063 if (compareSignatures(callerSignature, 10064 setting.signatures.mSignatures) 10065 != PackageManager.SIGNATURE_MATCH) { 10066 throw new SecurityException( 10067 "Caller does not have same cert as old installer package " 10068 + targetPackageSetting.installerPackageName); 10069 } 10070 } 10071 } 10072 10073 // Okay! 10074 targetPackageSetting.installerPackageName = installerPackageName; 10075 scheduleWriteSettingsLocked(); 10076 } 10077 } 10078 10079 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 10080 // Queue up an async operation since the package installation may take a little while. 10081 mHandler.post(new Runnable() { 10082 public void run() { 10083 mHandler.removeCallbacks(this); 10084 // Result object to be returned 10085 PackageInstalledInfo res = new PackageInstalledInfo(); 10086 res.returnCode = currentStatus; 10087 res.uid = -1; 10088 res.pkg = null; 10089 res.removedInfo = new PackageRemovedInfo(); 10090 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10091 args.doPreInstall(res.returnCode); 10092 synchronized (mInstallLock) { 10093 installPackageLI(args, res); 10094 } 10095 args.doPostInstall(res.returnCode, res.uid); 10096 } 10097 10098 // A restore should be performed at this point if (a) the install 10099 // succeeded, (b) the operation is not an update, and (c) the new 10100 // package has not opted out of backup participation. 10101 final boolean update = res.removedInfo.removedPackage != null; 10102 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 10103 boolean doRestore = !update 10104 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 10105 10106 // Set up the post-install work request bookkeeping. This will be used 10107 // and cleaned up by the post-install event handling regardless of whether 10108 // there's a restore pass performed. Token values are >= 1. 10109 int token; 10110 if (mNextInstallToken < 0) mNextInstallToken = 1; 10111 token = mNextInstallToken++; 10112 10113 PostInstallData data = new PostInstallData(args, res); 10114 mRunningInstalls.put(token, data); 10115 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 10116 10117 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 10118 // Pass responsibility to the Backup Manager. It will perform a 10119 // restore if appropriate, then pass responsibility back to the 10120 // Package Manager to run the post-install observer callbacks 10121 // and broadcasts. 10122 IBackupManager bm = IBackupManager.Stub.asInterface( 10123 ServiceManager.getService(Context.BACKUP_SERVICE)); 10124 if (bm != null) { 10125 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 10126 + " to BM for possible restore"); 10127 try { 10128 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 10129 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 10130 } else { 10131 doRestore = false; 10132 } 10133 } catch (RemoteException e) { 10134 // can't happen; the backup manager is local 10135 } catch (Exception e) { 10136 Slog.e(TAG, "Exception trying to enqueue restore", e); 10137 doRestore = false; 10138 } 10139 } else { 10140 Slog.e(TAG, "Backup Manager not found!"); 10141 doRestore = false; 10142 } 10143 } 10144 10145 if (!doRestore) { 10146 // No restore possible, or the Backup Manager was mysteriously not 10147 // available -- just fire the post-install work request directly. 10148 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 10149 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10150 mHandler.sendMessage(msg); 10151 } 10152 } 10153 }); 10154 } 10155 10156 private abstract class HandlerParams { 10157 private static final int MAX_RETRIES = 4; 10158 10159 /** 10160 * Number of times startCopy() has been attempted and had a non-fatal 10161 * error. 10162 */ 10163 private int mRetries = 0; 10164 10165 /** User handle for the user requesting the information or installation. */ 10166 private final UserHandle mUser; 10167 10168 HandlerParams(UserHandle user) { 10169 mUser = user; 10170 } 10171 10172 UserHandle getUser() { 10173 return mUser; 10174 } 10175 10176 final boolean startCopy() { 10177 boolean res; 10178 try { 10179 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 10180 10181 if (++mRetries > MAX_RETRIES) { 10182 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 10183 mHandler.sendEmptyMessage(MCS_GIVE_UP); 10184 handleServiceError(); 10185 return false; 10186 } else { 10187 handleStartCopy(); 10188 res = true; 10189 } 10190 } catch (RemoteException e) { 10191 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 10192 mHandler.sendEmptyMessage(MCS_RECONNECT); 10193 res = false; 10194 } 10195 handleReturnCode(); 10196 return res; 10197 } 10198 10199 final void serviceError() { 10200 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 10201 handleServiceError(); 10202 handleReturnCode(); 10203 } 10204 10205 abstract void handleStartCopy() throws RemoteException; 10206 abstract void handleServiceError(); 10207 abstract void handleReturnCode(); 10208 } 10209 10210 class MeasureParams extends HandlerParams { 10211 private final PackageStats mStats; 10212 private boolean mSuccess; 10213 10214 private final IPackageStatsObserver mObserver; 10215 10216 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 10217 super(new UserHandle(stats.userHandle)); 10218 mObserver = observer; 10219 mStats = stats; 10220 } 10221 10222 @Override 10223 public String toString() { 10224 return "MeasureParams{" 10225 + Integer.toHexString(System.identityHashCode(this)) 10226 + " " + mStats.packageName + "}"; 10227 } 10228 10229 @Override 10230 void handleStartCopy() throws RemoteException { 10231 synchronized (mInstallLock) { 10232 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 10233 } 10234 10235 if (mSuccess) { 10236 final boolean mounted; 10237 if (Environment.isExternalStorageEmulated()) { 10238 mounted = true; 10239 } else { 10240 final String status = Environment.getExternalStorageState(); 10241 mounted = (Environment.MEDIA_MOUNTED.equals(status) 10242 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 10243 } 10244 10245 if (mounted) { 10246 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 10247 10248 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 10249 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 10250 10251 mStats.externalDataSize = calculateDirectorySize(mContainerService, 10252 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 10253 10254 // Always subtract cache size, since it's a subdirectory 10255 mStats.externalDataSize -= mStats.externalCacheSize; 10256 10257 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 10258 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 10259 10260 mStats.externalObbSize = calculateDirectorySize(mContainerService, 10261 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 10262 } 10263 } 10264 } 10265 10266 @Override 10267 void handleReturnCode() { 10268 if (mObserver != null) { 10269 try { 10270 mObserver.onGetStatsCompleted(mStats, mSuccess); 10271 } catch (RemoteException e) { 10272 Slog.i(TAG, "Observer no longer exists."); 10273 } 10274 } 10275 } 10276 10277 @Override 10278 void handleServiceError() { 10279 Slog.e(TAG, "Could not measure application " + mStats.packageName 10280 + " external storage"); 10281 } 10282 } 10283 10284 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 10285 throws RemoteException { 10286 long result = 0; 10287 for (File path : paths) { 10288 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 10289 } 10290 return result; 10291 } 10292 10293 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 10294 for (File path : paths) { 10295 try { 10296 mcs.clearDirectory(path.getAbsolutePath()); 10297 } catch (RemoteException e) { 10298 } 10299 } 10300 } 10301 10302 static class OriginInfo { 10303 /** 10304 * Location where install is coming from, before it has been 10305 * copied/renamed into place. This could be a single monolithic APK 10306 * file, or a cluster directory. This location may be untrusted. 10307 */ 10308 final File file; 10309 final String cid; 10310 10311 /** 10312 * Flag indicating that {@link #file} or {@link #cid} has already been 10313 * staged, meaning downstream users don't need to defensively copy the 10314 * contents. 10315 */ 10316 final boolean staged; 10317 10318 /** 10319 * Flag indicating that {@link #file} or {@link #cid} is an already 10320 * installed app that is being moved. 10321 */ 10322 final boolean existing; 10323 10324 final String resolvedPath; 10325 final File resolvedFile; 10326 10327 static OriginInfo fromNothing() { 10328 return new OriginInfo(null, null, false, false); 10329 } 10330 10331 static OriginInfo fromUntrustedFile(File file) { 10332 return new OriginInfo(file, null, false, false); 10333 } 10334 10335 static OriginInfo fromExistingFile(File file) { 10336 return new OriginInfo(file, null, false, true); 10337 } 10338 10339 static OriginInfo fromStagedFile(File file) { 10340 return new OriginInfo(file, null, true, false); 10341 } 10342 10343 static OriginInfo fromStagedContainer(String cid) { 10344 return new OriginInfo(null, cid, true, false); 10345 } 10346 10347 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 10348 this.file = file; 10349 this.cid = cid; 10350 this.staged = staged; 10351 this.existing = existing; 10352 10353 if (cid != null) { 10354 resolvedPath = PackageHelper.getSdDir(cid); 10355 resolvedFile = new File(resolvedPath); 10356 } else if (file != null) { 10357 resolvedPath = file.getAbsolutePath(); 10358 resolvedFile = file; 10359 } else { 10360 resolvedPath = null; 10361 resolvedFile = null; 10362 } 10363 } 10364 } 10365 10366 class MoveInfo { 10367 final int moveId; 10368 final String fromUuid; 10369 final String toUuid; 10370 final String packageName; 10371 final String dataAppName; 10372 final int appId; 10373 final String seinfo; 10374 10375 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 10376 String dataAppName, int appId, String seinfo) { 10377 this.moveId = moveId; 10378 this.fromUuid = fromUuid; 10379 this.toUuid = toUuid; 10380 this.packageName = packageName; 10381 this.dataAppName = dataAppName; 10382 this.appId = appId; 10383 this.seinfo = seinfo; 10384 } 10385 } 10386 10387 class InstallParams extends HandlerParams { 10388 final OriginInfo origin; 10389 final MoveInfo move; 10390 final IPackageInstallObserver2 observer; 10391 int installFlags; 10392 final String installerPackageName; 10393 final String volumeUuid; 10394 final VerificationParams verificationParams; 10395 private InstallArgs mArgs; 10396 private int mRet; 10397 final String packageAbiOverride; 10398 final String[] grantedRuntimePermissions; 10399 10400 10401 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10402 int installFlags, String installerPackageName, String volumeUuid, 10403 VerificationParams verificationParams, UserHandle user, String packageAbiOverride, 10404 String[] grantedPermissions) { 10405 super(user); 10406 this.origin = origin; 10407 this.move = move; 10408 this.observer = observer; 10409 this.installFlags = installFlags; 10410 this.installerPackageName = installerPackageName; 10411 this.volumeUuid = volumeUuid; 10412 this.verificationParams = verificationParams; 10413 this.packageAbiOverride = packageAbiOverride; 10414 this.grantedRuntimePermissions = grantedPermissions; 10415 } 10416 10417 @Override 10418 public String toString() { 10419 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 10420 + " file=" + origin.file + " cid=" + origin.cid + "}"; 10421 } 10422 10423 public ManifestDigest getManifestDigest() { 10424 if (verificationParams == null) { 10425 return null; 10426 } 10427 return verificationParams.getManifestDigest(); 10428 } 10429 10430 private int installLocationPolicy(PackageInfoLite pkgLite) { 10431 String packageName = pkgLite.packageName; 10432 int installLocation = pkgLite.installLocation; 10433 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10434 // reader 10435 synchronized (mPackages) { 10436 PackageParser.Package pkg = mPackages.get(packageName); 10437 if (pkg != null) { 10438 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10439 // Check for downgrading. 10440 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 10441 try { 10442 checkDowngrade(pkg, pkgLite); 10443 } catch (PackageManagerException e) { 10444 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 10445 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 10446 } 10447 } 10448 // Check for updated system application. 10449 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10450 if (onSd) { 10451 Slog.w(TAG, "Cannot install update to system app on sdcard"); 10452 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 10453 } 10454 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10455 } else { 10456 if (onSd) { 10457 // Install flag overrides everything. 10458 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10459 } 10460 // If current upgrade specifies particular preference 10461 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 10462 // Application explicitly specified internal. 10463 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10464 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 10465 // App explictly prefers external. Let policy decide 10466 } else { 10467 // Prefer previous location 10468 if (isExternal(pkg)) { 10469 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10470 } 10471 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10472 } 10473 } 10474 } else { 10475 // Invalid install. Return error code 10476 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 10477 } 10478 } 10479 } 10480 // All the special cases have been taken care of. 10481 // Return result based on recommended install location. 10482 if (onSd) { 10483 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10484 } 10485 return pkgLite.recommendedInstallLocation; 10486 } 10487 10488 /* 10489 * Invoke remote method to get package information and install 10490 * location values. Override install location based on default 10491 * policy if needed and then create install arguments based 10492 * on the install location. 10493 */ 10494 public void handleStartCopy() throws RemoteException { 10495 int ret = PackageManager.INSTALL_SUCCEEDED; 10496 10497 // If we're already staged, we've firmly committed to an install location 10498 if (origin.staged) { 10499 if (origin.file != null) { 10500 installFlags |= PackageManager.INSTALL_INTERNAL; 10501 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10502 } else if (origin.cid != null) { 10503 installFlags |= PackageManager.INSTALL_EXTERNAL; 10504 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10505 } else { 10506 throw new IllegalStateException("Invalid stage location"); 10507 } 10508 } 10509 10510 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10511 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 10512 10513 PackageInfoLite pkgLite = null; 10514 10515 if (onInt && onSd) { 10516 // Check if both bits are set. 10517 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 10518 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10519 } else { 10520 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 10521 packageAbiOverride); 10522 10523 /* 10524 * If we have too little free space, try to free cache 10525 * before giving up. 10526 */ 10527 if (!origin.staged && pkgLite.recommendedInstallLocation 10528 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10529 // TODO: focus freeing disk space on the target device 10530 final StorageManager storage = StorageManager.from(mContext); 10531 final long lowThreshold = storage.getStorageLowBytes( 10532 Environment.getDataDirectory()); 10533 10534 final long sizeBytes = mContainerService.calculateInstalledSize( 10535 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 10536 10537 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 10538 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 10539 installFlags, packageAbiOverride); 10540 } 10541 10542 /* 10543 * The cache free must have deleted the file we 10544 * downloaded to install. 10545 * 10546 * TODO: fix the "freeCache" call to not delete 10547 * the file we care about. 10548 */ 10549 if (pkgLite.recommendedInstallLocation 10550 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10551 pkgLite.recommendedInstallLocation 10552 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 10553 } 10554 } 10555 } 10556 10557 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10558 int loc = pkgLite.recommendedInstallLocation; 10559 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 10560 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10561 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 10562 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 10563 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10564 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10565 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 10566 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 10567 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10568 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 10569 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 10570 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 10571 } else { 10572 // Override with defaults if needed. 10573 loc = installLocationPolicy(pkgLite); 10574 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 10575 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 10576 } else if (!onSd && !onInt) { 10577 // Override install location with flags 10578 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 10579 // Set the flag to install on external media. 10580 installFlags |= PackageManager.INSTALL_EXTERNAL; 10581 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10582 } else { 10583 // Make sure the flag for installing on external 10584 // media is unset 10585 installFlags |= PackageManager.INSTALL_INTERNAL; 10586 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10587 } 10588 } 10589 } 10590 } 10591 10592 final InstallArgs args = createInstallArgs(this); 10593 mArgs = args; 10594 10595 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10596 /* 10597 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 10598 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 10599 */ 10600 int userIdentifier = getUser().getIdentifier(); 10601 if (userIdentifier == UserHandle.USER_ALL 10602 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 10603 userIdentifier = UserHandle.USER_OWNER; 10604 } 10605 10606 /* 10607 * Determine if we have any installed package verifiers. If we 10608 * do, then we'll defer to them to verify the packages. 10609 */ 10610 final int requiredUid = mRequiredVerifierPackage == null ? -1 10611 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 10612 if (!origin.existing && requiredUid != -1 10613 && isVerificationEnabled(userIdentifier, installFlags)) { 10614 final Intent verification = new Intent( 10615 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 10616 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 10617 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 10618 PACKAGE_MIME_TYPE); 10619 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10620 10621 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 10622 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 10623 0 /* TODO: Which userId? */); 10624 10625 if (DEBUG_VERIFY) { 10626 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 10627 + verification.toString() + " with " + pkgLite.verifiers.length 10628 + " optional verifiers"); 10629 } 10630 10631 final int verificationId = mPendingVerificationToken++; 10632 10633 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10634 10635 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 10636 installerPackageName); 10637 10638 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 10639 installFlags); 10640 10641 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 10642 pkgLite.packageName); 10643 10644 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 10645 pkgLite.versionCode); 10646 10647 if (verificationParams != null) { 10648 if (verificationParams.getVerificationURI() != null) { 10649 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 10650 verificationParams.getVerificationURI()); 10651 } 10652 if (verificationParams.getOriginatingURI() != null) { 10653 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 10654 verificationParams.getOriginatingURI()); 10655 } 10656 if (verificationParams.getReferrer() != null) { 10657 verification.putExtra(Intent.EXTRA_REFERRER, 10658 verificationParams.getReferrer()); 10659 } 10660 if (verificationParams.getOriginatingUid() >= 0) { 10661 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 10662 verificationParams.getOriginatingUid()); 10663 } 10664 if (verificationParams.getInstallerUid() >= 0) { 10665 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 10666 verificationParams.getInstallerUid()); 10667 } 10668 } 10669 10670 final PackageVerificationState verificationState = new PackageVerificationState( 10671 requiredUid, args); 10672 10673 mPendingVerification.append(verificationId, verificationState); 10674 10675 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 10676 receivers, verificationState); 10677 10678 // Apps installed for "all" users use the device owner to verify the app 10679 UserHandle verifierUser = getUser(); 10680 if (verifierUser == UserHandle.ALL) { 10681 verifierUser = UserHandle.OWNER; 10682 } 10683 10684 /* 10685 * If any sufficient verifiers were listed in the package 10686 * manifest, attempt to ask them. 10687 */ 10688 if (sufficientVerifiers != null) { 10689 final int N = sufficientVerifiers.size(); 10690 if (N == 0) { 10691 Slog.i(TAG, "Additional verifiers required, but none installed."); 10692 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 10693 } else { 10694 for (int i = 0; i < N; i++) { 10695 final ComponentName verifierComponent = sufficientVerifiers.get(i); 10696 10697 final Intent sufficientIntent = new Intent(verification); 10698 sufficientIntent.setComponent(verifierComponent); 10699 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 10700 } 10701 } 10702 } 10703 10704 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 10705 mRequiredVerifierPackage, receivers); 10706 if (ret == PackageManager.INSTALL_SUCCEEDED 10707 && mRequiredVerifierPackage != null) { 10708 /* 10709 * Send the intent to the required verification agent, 10710 * but only start the verification timeout after the 10711 * target BroadcastReceivers have run. 10712 */ 10713 verification.setComponent(requiredVerifierComponent); 10714 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 10715 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10716 new BroadcastReceiver() { 10717 @Override 10718 public void onReceive(Context context, Intent intent) { 10719 final Message msg = mHandler 10720 .obtainMessage(CHECK_PENDING_VERIFICATION); 10721 msg.arg1 = verificationId; 10722 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 10723 } 10724 }, null, 0, null, null); 10725 10726 /* 10727 * We don't want the copy to proceed until verification 10728 * succeeds, so null out this field. 10729 */ 10730 mArgs = null; 10731 } 10732 } else { 10733 /* 10734 * No package verification is enabled, so immediately start 10735 * the remote call to initiate copy using temporary file. 10736 */ 10737 ret = args.copyApk(mContainerService, true); 10738 } 10739 } 10740 10741 mRet = ret; 10742 } 10743 10744 @Override 10745 void handleReturnCode() { 10746 // If mArgs is null, then MCS couldn't be reached. When it 10747 // reconnects, it will try again to install. At that point, this 10748 // will succeed. 10749 if (mArgs != null) { 10750 processPendingInstall(mArgs, mRet); 10751 } 10752 } 10753 10754 @Override 10755 void handleServiceError() { 10756 mArgs = createInstallArgs(this); 10757 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10758 } 10759 10760 public boolean isForwardLocked() { 10761 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10762 } 10763 } 10764 10765 /** 10766 * Used during creation of InstallArgs 10767 * 10768 * @param installFlags package installation flags 10769 * @return true if should be installed on external storage 10770 */ 10771 private static boolean installOnExternalAsec(int installFlags) { 10772 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 10773 return false; 10774 } 10775 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 10776 return true; 10777 } 10778 return false; 10779 } 10780 10781 /** 10782 * Used during creation of InstallArgs 10783 * 10784 * @param installFlags package installation flags 10785 * @return true if should be installed as forward locked 10786 */ 10787 private static boolean installForwardLocked(int installFlags) { 10788 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10789 } 10790 10791 private InstallArgs createInstallArgs(InstallParams params) { 10792 if (params.move != null) { 10793 return new MoveInstallArgs(params); 10794 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 10795 return new AsecInstallArgs(params); 10796 } else { 10797 return new FileInstallArgs(params); 10798 } 10799 } 10800 10801 /** 10802 * Create args that describe an existing installed package. Typically used 10803 * when cleaning up old installs, or used as a move source. 10804 */ 10805 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 10806 String resourcePath, String[] instructionSets) { 10807 final boolean isInAsec; 10808 if (installOnExternalAsec(installFlags)) { 10809 /* Apps on SD card are always in ASEC containers. */ 10810 isInAsec = true; 10811 } else if (installForwardLocked(installFlags) 10812 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 10813 /* 10814 * Forward-locked apps are only in ASEC containers if they're the 10815 * new style 10816 */ 10817 isInAsec = true; 10818 } else { 10819 isInAsec = false; 10820 } 10821 10822 if (isInAsec) { 10823 return new AsecInstallArgs(codePath, instructionSets, 10824 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 10825 } else { 10826 return new FileInstallArgs(codePath, resourcePath, instructionSets); 10827 } 10828 } 10829 10830 static abstract class InstallArgs { 10831 /** @see InstallParams#origin */ 10832 final OriginInfo origin; 10833 /** @see InstallParams#move */ 10834 final MoveInfo move; 10835 10836 final IPackageInstallObserver2 observer; 10837 // Always refers to PackageManager flags only 10838 final int installFlags; 10839 final String installerPackageName; 10840 final String volumeUuid; 10841 final ManifestDigest manifestDigest; 10842 final UserHandle user; 10843 final String abiOverride; 10844 final String[] installGrantPermissions; 10845 10846 // The list of instruction sets supported by this app. This is currently 10847 // only used during the rmdex() phase to clean up resources. We can get rid of this 10848 // if we move dex files under the common app path. 10849 /* nullable */ String[] instructionSets; 10850 10851 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10852 int installFlags, String installerPackageName, String volumeUuid, 10853 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 10854 String abiOverride, String[] installGrantPermissions) { 10855 this.origin = origin; 10856 this.move = move; 10857 this.installFlags = installFlags; 10858 this.observer = observer; 10859 this.installerPackageName = installerPackageName; 10860 this.volumeUuid = volumeUuid; 10861 this.manifestDigest = manifestDigest; 10862 this.user = user; 10863 this.instructionSets = instructionSets; 10864 this.abiOverride = abiOverride; 10865 this.installGrantPermissions = installGrantPermissions; 10866 } 10867 10868 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 10869 abstract int doPreInstall(int status); 10870 10871 /** 10872 * Rename package into final resting place. All paths on the given 10873 * scanned package should be updated to reflect the rename. 10874 */ 10875 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 10876 abstract int doPostInstall(int status, int uid); 10877 10878 /** @see PackageSettingBase#codePathString */ 10879 abstract String getCodePath(); 10880 /** @see PackageSettingBase#resourcePathString */ 10881 abstract String getResourcePath(); 10882 10883 // Need installer lock especially for dex file removal. 10884 abstract void cleanUpResourcesLI(); 10885 abstract boolean doPostDeleteLI(boolean delete); 10886 10887 /** 10888 * Called before the source arguments are copied. This is used mostly 10889 * for MoveParams when it needs to read the source file to put it in the 10890 * destination. 10891 */ 10892 int doPreCopy() { 10893 return PackageManager.INSTALL_SUCCEEDED; 10894 } 10895 10896 /** 10897 * Called after the source arguments are copied. This is used mostly for 10898 * MoveParams when it needs to read the source file to put it in the 10899 * destination. 10900 * 10901 * @return 10902 */ 10903 int doPostCopy(int uid) { 10904 return PackageManager.INSTALL_SUCCEEDED; 10905 } 10906 10907 protected boolean isFwdLocked() { 10908 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10909 } 10910 10911 protected boolean isExternalAsec() { 10912 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10913 } 10914 10915 UserHandle getUser() { 10916 return user; 10917 } 10918 } 10919 10920 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 10921 if (!allCodePaths.isEmpty()) { 10922 if (instructionSets == null) { 10923 throw new IllegalStateException("instructionSet == null"); 10924 } 10925 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 10926 for (String codePath : allCodePaths) { 10927 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 10928 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 10929 if (retCode < 0) { 10930 Slog.w(TAG, "Couldn't remove dex file for package: " 10931 + " at location " + codePath + ", retcode=" + retCode); 10932 // we don't consider this to be a failure of the core package deletion 10933 } 10934 } 10935 } 10936 } 10937 } 10938 10939 /** 10940 * Logic to handle installation of non-ASEC applications, including copying 10941 * and renaming logic. 10942 */ 10943 class FileInstallArgs extends InstallArgs { 10944 private File codeFile; 10945 private File resourceFile; 10946 10947 // Example topology: 10948 // /data/app/com.example/base.apk 10949 // /data/app/com.example/split_foo.apk 10950 // /data/app/com.example/lib/arm/libfoo.so 10951 // /data/app/com.example/lib/arm64/libfoo.so 10952 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 10953 10954 /** New install */ 10955 FileInstallArgs(InstallParams params) { 10956 super(params.origin, params.move, params.observer, params.installFlags, 10957 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10958 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 10959 params.grantedRuntimePermissions); 10960 if (isFwdLocked()) { 10961 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 10962 } 10963 } 10964 10965 /** Existing install */ 10966 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 10967 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 10968 null, null); 10969 this.codeFile = (codePath != null) ? new File(codePath) : null; 10970 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 10971 } 10972 10973 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10974 if (origin.staged) { 10975 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 10976 codeFile = origin.file; 10977 resourceFile = origin.file; 10978 return PackageManager.INSTALL_SUCCEEDED; 10979 } 10980 10981 try { 10982 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 10983 codeFile = tempDir; 10984 resourceFile = tempDir; 10985 } catch (IOException e) { 10986 Slog.w(TAG, "Failed to create copy file: " + e); 10987 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10988 } 10989 10990 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 10991 @Override 10992 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 10993 if (!FileUtils.isValidExtFilename(name)) { 10994 throw new IllegalArgumentException("Invalid filename: " + name); 10995 } 10996 try { 10997 final File file = new File(codeFile, name); 10998 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 10999 O_RDWR | O_CREAT, 0644); 11000 Os.chmod(file.getAbsolutePath(), 0644); 11001 return new ParcelFileDescriptor(fd); 11002 } catch (ErrnoException e) { 11003 throw new RemoteException("Failed to open: " + e.getMessage()); 11004 } 11005 } 11006 }; 11007 11008 int ret = PackageManager.INSTALL_SUCCEEDED; 11009 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 11010 if (ret != PackageManager.INSTALL_SUCCEEDED) { 11011 Slog.e(TAG, "Failed to copy package"); 11012 return ret; 11013 } 11014 11015 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 11016 NativeLibraryHelper.Handle handle = null; 11017 try { 11018 handle = NativeLibraryHelper.Handle.create(codeFile); 11019 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 11020 abiOverride); 11021 } catch (IOException e) { 11022 Slog.e(TAG, "Copying native libraries failed", e); 11023 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11024 } finally { 11025 IoUtils.closeQuietly(handle); 11026 } 11027 11028 return ret; 11029 } 11030 11031 int doPreInstall(int status) { 11032 if (status != PackageManager.INSTALL_SUCCEEDED) { 11033 cleanUp(); 11034 } 11035 return status; 11036 } 11037 11038 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11039 if (status != PackageManager.INSTALL_SUCCEEDED) { 11040 cleanUp(); 11041 return false; 11042 } 11043 11044 final File targetDir = codeFile.getParentFile(); 11045 final File beforeCodeFile = codeFile; 11046 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 11047 11048 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 11049 try { 11050 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 11051 } catch (ErrnoException e) { 11052 Slog.w(TAG, "Failed to rename", e); 11053 return false; 11054 } 11055 11056 if (!SELinux.restoreconRecursive(afterCodeFile)) { 11057 Slog.w(TAG, "Failed to restorecon"); 11058 return false; 11059 } 11060 11061 // Reflect the rename internally 11062 codeFile = afterCodeFile; 11063 resourceFile = afterCodeFile; 11064 11065 // Reflect the rename in scanned details 11066 pkg.codePath = afterCodeFile.getAbsolutePath(); 11067 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11068 pkg.baseCodePath); 11069 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11070 pkg.splitCodePaths); 11071 11072 // Reflect the rename in app info 11073 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11074 pkg.applicationInfo.setCodePath(pkg.codePath); 11075 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11076 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11077 pkg.applicationInfo.setResourcePath(pkg.codePath); 11078 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11079 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11080 11081 return true; 11082 } 11083 11084 int doPostInstall(int status, int uid) { 11085 if (status != PackageManager.INSTALL_SUCCEEDED) { 11086 cleanUp(); 11087 } 11088 return status; 11089 } 11090 11091 @Override 11092 String getCodePath() { 11093 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11094 } 11095 11096 @Override 11097 String getResourcePath() { 11098 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11099 } 11100 11101 private boolean cleanUp() { 11102 if (codeFile == null || !codeFile.exists()) { 11103 return false; 11104 } 11105 11106 if (codeFile.isDirectory()) { 11107 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11108 } else { 11109 codeFile.delete(); 11110 } 11111 11112 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 11113 resourceFile.delete(); 11114 } 11115 11116 return true; 11117 } 11118 11119 void cleanUpResourcesLI() { 11120 // Try enumerating all code paths before deleting 11121 List<String> allCodePaths = Collections.EMPTY_LIST; 11122 if (codeFile != null && codeFile.exists()) { 11123 try { 11124 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11125 allCodePaths = pkg.getAllCodePaths(); 11126 } catch (PackageParserException e) { 11127 // Ignored; we tried our best 11128 } 11129 } 11130 11131 cleanUp(); 11132 removeDexFiles(allCodePaths, instructionSets); 11133 } 11134 11135 boolean doPostDeleteLI(boolean delete) { 11136 // XXX err, shouldn't we respect the delete flag? 11137 cleanUpResourcesLI(); 11138 return true; 11139 } 11140 } 11141 11142 private boolean isAsecExternal(String cid) { 11143 final String asecPath = PackageHelper.getSdFilesystem(cid); 11144 return !asecPath.startsWith(mAsecInternalPath); 11145 } 11146 11147 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 11148 PackageManagerException { 11149 if (copyRet < 0) { 11150 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 11151 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 11152 throw new PackageManagerException(copyRet, message); 11153 } 11154 } 11155 } 11156 11157 /** 11158 * Extract the MountService "container ID" from the full code path of an 11159 * .apk. 11160 */ 11161 static String cidFromCodePath(String fullCodePath) { 11162 int eidx = fullCodePath.lastIndexOf("/"); 11163 String subStr1 = fullCodePath.substring(0, eidx); 11164 int sidx = subStr1.lastIndexOf("/"); 11165 return subStr1.substring(sidx+1, eidx); 11166 } 11167 11168 /** 11169 * Logic to handle installation of ASEC applications, including copying and 11170 * renaming logic. 11171 */ 11172 class AsecInstallArgs extends InstallArgs { 11173 static final String RES_FILE_NAME = "pkg.apk"; 11174 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 11175 11176 String cid; 11177 String packagePath; 11178 String resourcePath; 11179 11180 /** New install */ 11181 AsecInstallArgs(InstallParams params) { 11182 super(params.origin, params.move, params.observer, params.installFlags, 11183 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11184 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11185 params.grantedRuntimePermissions); 11186 } 11187 11188 /** Existing install */ 11189 AsecInstallArgs(String fullCodePath, String[] instructionSets, 11190 boolean isExternal, boolean isForwardLocked) { 11191 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 11192 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11193 instructionSets, null, null); 11194 // Hackily pretend we're still looking at a full code path 11195 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 11196 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 11197 } 11198 11199 // Extract cid from fullCodePath 11200 int eidx = fullCodePath.lastIndexOf("/"); 11201 String subStr1 = fullCodePath.substring(0, eidx); 11202 int sidx = subStr1.lastIndexOf("/"); 11203 cid = subStr1.substring(sidx+1, eidx); 11204 setMountPath(subStr1); 11205 } 11206 11207 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 11208 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 11209 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11210 instructionSets, null, null); 11211 this.cid = cid; 11212 setMountPath(PackageHelper.getSdDir(cid)); 11213 } 11214 11215 void createCopyFile() { 11216 cid = mInstallerService.allocateExternalStageCidLegacy(); 11217 } 11218 11219 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11220 if (origin.staged) { 11221 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 11222 cid = origin.cid; 11223 setMountPath(PackageHelper.getSdDir(cid)); 11224 return PackageManager.INSTALL_SUCCEEDED; 11225 } 11226 11227 if (temp) { 11228 createCopyFile(); 11229 } else { 11230 /* 11231 * Pre-emptively destroy the container since it's destroyed if 11232 * copying fails due to it existing anyway. 11233 */ 11234 PackageHelper.destroySdDir(cid); 11235 } 11236 11237 final String newMountPath = imcs.copyPackageToContainer( 11238 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 11239 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 11240 11241 if (newMountPath != null) { 11242 setMountPath(newMountPath); 11243 return PackageManager.INSTALL_SUCCEEDED; 11244 } else { 11245 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11246 } 11247 } 11248 11249 @Override 11250 String getCodePath() { 11251 return packagePath; 11252 } 11253 11254 @Override 11255 String getResourcePath() { 11256 return resourcePath; 11257 } 11258 11259 int doPreInstall(int status) { 11260 if (status != PackageManager.INSTALL_SUCCEEDED) { 11261 // Destroy container 11262 PackageHelper.destroySdDir(cid); 11263 } else { 11264 boolean mounted = PackageHelper.isContainerMounted(cid); 11265 if (!mounted) { 11266 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 11267 Process.SYSTEM_UID); 11268 if (newMountPath != null) { 11269 setMountPath(newMountPath); 11270 } else { 11271 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11272 } 11273 } 11274 } 11275 return status; 11276 } 11277 11278 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11279 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 11280 String newMountPath = null; 11281 if (PackageHelper.isContainerMounted(cid)) { 11282 // Unmount the container 11283 if (!PackageHelper.unMountSdDir(cid)) { 11284 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 11285 return false; 11286 } 11287 } 11288 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11289 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 11290 " which might be stale. Will try to clean up."); 11291 // Clean up the stale container and proceed to recreate. 11292 if (!PackageHelper.destroySdDir(newCacheId)) { 11293 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 11294 return false; 11295 } 11296 // Successfully cleaned up stale container. Try to rename again. 11297 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11298 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 11299 + " inspite of cleaning it up."); 11300 return false; 11301 } 11302 } 11303 if (!PackageHelper.isContainerMounted(newCacheId)) { 11304 Slog.w(TAG, "Mounting container " + newCacheId); 11305 newMountPath = PackageHelper.mountSdDir(newCacheId, 11306 getEncryptKey(), Process.SYSTEM_UID); 11307 } else { 11308 newMountPath = PackageHelper.getSdDir(newCacheId); 11309 } 11310 if (newMountPath == null) { 11311 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 11312 return false; 11313 } 11314 Log.i(TAG, "Succesfully renamed " + cid + 11315 " to " + newCacheId + 11316 " at new path: " + newMountPath); 11317 cid = newCacheId; 11318 11319 final File beforeCodeFile = new File(packagePath); 11320 setMountPath(newMountPath); 11321 final File afterCodeFile = new File(packagePath); 11322 11323 // Reflect the rename in scanned details 11324 pkg.codePath = afterCodeFile.getAbsolutePath(); 11325 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11326 pkg.baseCodePath); 11327 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11328 pkg.splitCodePaths); 11329 11330 // Reflect the rename in app info 11331 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11332 pkg.applicationInfo.setCodePath(pkg.codePath); 11333 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11334 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11335 pkg.applicationInfo.setResourcePath(pkg.codePath); 11336 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11337 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11338 11339 return true; 11340 } 11341 11342 private void setMountPath(String mountPath) { 11343 final File mountFile = new File(mountPath); 11344 11345 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 11346 if (monolithicFile.exists()) { 11347 packagePath = monolithicFile.getAbsolutePath(); 11348 if (isFwdLocked()) { 11349 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 11350 } else { 11351 resourcePath = packagePath; 11352 } 11353 } else { 11354 packagePath = mountFile.getAbsolutePath(); 11355 resourcePath = packagePath; 11356 } 11357 } 11358 11359 int doPostInstall(int status, int uid) { 11360 if (status != PackageManager.INSTALL_SUCCEEDED) { 11361 cleanUp(); 11362 } else { 11363 final int groupOwner; 11364 final String protectedFile; 11365 if (isFwdLocked()) { 11366 groupOwner = UserHandle.getSharedAppGid(uid); 11367 protectedFile = RES_FILE_NAME; 11368 } else { 11369 groupOwner = -1; 11370 protectedFile = null; 11371 } 11372 11373 if (uid < Process.FIRST_APPLICATION_UID 11374 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 11375 Slog.e(TAG, "Failed to finalize " + cid); 11376 PackageHelper.destroySdDir(cid); 11377 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11378 } 11379 11380 boolean mounted = PackageHelper.isContainerMounted(cid); 11381 if (!mounted) { 11382 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 11383 } 11384 } 11385 return status; 11386 } 11387 11388 private void cleanUp() { 11389 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 11390 11391 // Destroy secure container 11392 PackageHelper.destroySdDir(cid); 11393 } 11394 11395 private List<String> getAllCodePaths() { 11396 final File codeFile = new File(getCodePath()); 11397 if (codeFile != null && codeFile.exists()) { 11398 try { 11399 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11400 return pkg.getAllCodePaths(); 11401 } catch (PackageParserException e) { 11402 // Ignored; we tried our best 11403 } 11404 } 11405 return Collections.EMPTY_LIST; 11406 } 11407 11408 void cleanUpResourcesLI() { 11409 // Enumerate all code paths before deleting 11410 cleanUpResourcesLI(getAllCodePaths()); 11411 } 11412 11413 private void cleanUpResourcesLI(List<String> allCodePaths) { 11414 cleanUp(); 11415 removeDexFiles(allCodePaths, instructionSets); 11416 } 11417 11418 String getPackageName() { 11419 return getAsecPackageName(cid); 11420 } 11421 11422 boolean doPostDeleteLI(boolean delete) { 11423 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 11424 final List<String> allCodePaths = getAllCodePaths(); 11425 boolean mounted = PackageHelper.isContainerMounted(cid); 11426 if (mounted) { 11427 // Unmount first 11428 if (PackageHelper.unMountSdDir(cid)) { 11429 mounted = false; 11430 } 11431 } 11432 if (!mounted && delete) { 11433 cleanUpResourcesLI(allCodePaths); 11434 } 11435 return !mounted; 11436 } 11437 11438 @Override 11439 int doPreCopy() { 11440 if (isFwdLocked()) { 11441 if (!PackageHelper.fixSdPermissions(cid, 11442 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 11443 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11444 } 11445 } 11446 11447 return PackageManager.INSTALL_SUCCEEDED; 11448 } 11449 11450 @Override 11451 int doPostCopy(int uid) { 11452 if (isFwdLocked()) { 11453 if (uid < Process.FIRST_APPLICATION_UID 11454 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 11455 RES_FILE_NAME)) { 11456 Slog.e(TAG, "Failed to finalize " + cid); 11457 PackageHelper.destroySdDir(cid); 11458 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11459 } 11460 } 11461 11462 return PackageManager.INSTALL_SUCCEEDED; 11463 } 11464 } 11465 11466 /** 11467 * Logic to handle movement of existing installed applications. 11468 */ 11469 class MoveInstallArgs extends InstallArgs { 11470 private File codeFile; 11471 private File resourceFile; 11472 11473 /** New install */ 11474 MoveInstallArgs(InstallParams params) { 11475 super(params.origin, params.move, params.observer, params.installFlags, 11476 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11477 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11478 params.grantedRuntimePermissions); 11479 } 11480 11481 int copyApk(IMediaContainerService imcs, boolean temp) { 11482 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 11483 + move.fromUuid + " to " + move.toUuid); 11484 synchronized (mInstaller) { 11485 if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName, 11486 move.dataAppName, move.appId, move.seinfo) != 0) { 11487 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11488 } 11489 } 11490 11491 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 11492 resourceFile = codeFile; 11493 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 11494 11495 return PackageManager.INSTALL_SUCCEEDED; 11496 } 11497 11498 int doPreInstall(int status) { 11499 if (status != PackageManager.INSTALL_SUCCEEDED) { 11500 cleanUp(move.toUuid); 11501 } 11502 return status; 11503 } 11504 11505 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11506 if (status != PackageManager.INSTALL_SUCCEEDED) { 11507 cleanUp(move.toUuid); 11508 return false; 11509 } 11510 11511 // Reflect the move in app info 11512 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11513 pkg.applicationInfo.setCodePath(pkg.codePath); 11514 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11515 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11516 pkg.applicationInfo.setResourcePath(pkg.codePath); 11517 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11518 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11519 11520 return true; 11521 } 11522 11523 int doPostInstall(int status, int uid) { 11524 if (status == PackageManager.INSTALL_SUCCEEDED) { 11525 cleanUp(move.fromUuid); 11526 } else { 11527 cleanUp(move.toUuid); 11528 } 11529 return status; 11530 } 11531 11532 @Override 11533 String getCodePath() { 11534 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11535 } 11536 11537 @Override 11538 String getResourcePath() { 11539 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11540 } 11541 11542 private boolean cleanUp(String volumeUuid) { 11543 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 11544 move.dataAppName); 11545 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 11546 synchronized (mInstallLock) { 11547 // Clean up both app data and code 11548 removeDataDirsLI(volumeUuid, move.packageName); 11549 if (codeFile.isDirectory()) { 11550 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11551 } else { 11552 codeFile.delete(); 11553 } 11554 } 11555 return true; 11556 } 11557 11558 void cleanUpResourcesLI() { 11559 throw new UnsupportedOperationException(); 11560 } 11561 11562 boolean doPostDeleteLI(boolean delete) { 11563 throw new UnsupportedOperationException(); 11564 } 11565 } 11566 11567 static String getAsecPackageName(String packageCid) { 11568 int idx = packageCid.lastIndexOf("-"); 11569 if (idx == -1) { 11570 return packageCid; 11571 } 11572 return packageCid.substring(0, idx); 11573 } 11574 11575 // Utility method used to create code paths based on package name and available index. 11576 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 11577 String idxStr = ""; 11578 int idx = 1; 11579 // Fall back to default value of idx=1 if prefix is not 11580 // part of oldCodePath 11581 if (oldCodePath != null) { 11582 String subStr = oldCodePath; 11583 // Drop the suffix right away 11584 if (suffix != null && subStr.endsWith(suffix)) { 11585 subStr = subStr.substring(0, subStr.length() - suffix.length()); 11586 } 11587 // If oldCodePath already contains prefix find out the 11588 // ending index to either increment or decrement. 11589 int sidx = subStr.lastIndexOf(prefix); 11590 if (sidx != -1) { 11591 subStr = subStr.substring(sidx + prefix.length()); 11592 if (subStr != null) { 11593 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 11594 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 11595 } 11596 try { 11597 idx = Integer.parseInt(subStr); 11598 if (idx <= 1) { 11599 idx++; 11600 } else { 11601 idx--; 11602 } 11603 } catch(NumberFormatException e) { 11604 } 11605 } 11606 } 11607 } 11608 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 11609 return prefix + idxStr; 11610 } 11611 11612 private File getNextCodePath(File targetDir, String packageName) { 11613 int suffix = 1; 11614 File result; 11615 do { 11616 result = new File(targetDir, packageName + "-" + suffix); 11617 suffix++; 11618 } while (result.exists()); 11619 return result; 11620 } 11621 11622 // Utility method that returns the relative package path with respect 11623 // to the installation directory. Like say for /data/data/com.test-1.apk 11624 // string com.test-1 is returned. 11625 static String deriveCodePathName(String codePath) { 11626 if (codePath == null) { 11627 return null; 11628 } 11629 final File codeFile = new File(codePath); 11630 final String name = codeFile.getName(); 11631 if (codeFile.isDirectory()) { 11632 return name; 11633 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 11634 final int lastDot = name.lastIndexOf('.'); 11635 return name.substring(0, lastDot); 11636 } else { 11637 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 11638 return null; 11639 } 11640 } 11641 11642 class PackageInstalledInfo { 11643 String name; 11644 int uid; 11645 // The set of users that originally had this package installed. 11646 int[] origUsers; 11647 // The set of users that now have this package installed. 11648 int[] newUsers; 11649 PackageParser.Package pkg; 11650 int returnCode; 11651 String returnMsg; 11652 PackageRemovedInfo removedInfo; 11653 11654 public void setError(int code, String msg) { 11655 returnCode = code; 11656 returnMsg = msg; 11657 Slog.w(TAG, msg); 11658 } 11659 11660 public void setError(String msg, PackageParserException e) { 11661 returnCode = e.error; 11662 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11663 Slog.w(TAG, msg, e); 11664 } 11665 11666 public void setError(String msg, PackageManagerException e) { 11667 returnCode = e.error; 11668 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11669 Slog.w(TAG, msg, e); 11670 } 11671 11672 // In some error cases we want to convey more info back to the observer 11673 String origPackage; 11674 String origPermission; 11675 } 11676 11677 /* 11678 * Install a non-existing package. 11679 */ 11680 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11681 UserHandle user, String installerPackageName, String volumeUuid, 11682 PackageInstalledInfo res) { 11683 // Remember this for later, in case we need to rollback this install 11684 String pkgName = pkg.packageName; 11685 11686 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 11687 final boolean dataDirExists = Environment 11688 .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists(); 11689 synchronized(mPackages) { 11690 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 11691 // A package with the same name is already installed, though 11692 // it has been renamed to an older name. The package we 11693 // are trying to install should be installed as an update to 11694 // the existing one, but that has not been requested, so bail. 11695 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11696 + " without first uninstalling package running as " 11697 + mSettings.mRenamedPackages.get(pkgName)); 11698 return; 11699 } 11700 if (mPackages.containsKey(pkgName)) { 11701 // Don't allow installation over an existing package with the same name. 11702 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11703 + " without first uninstalling."); 11704 return; 11705 } 11706 } 11707 11708 try { 11709 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 11710 System.currentTimeMillis(), user); 11711 11712 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 11713 // delete the partially installed application. the data directory will have to be 11714 // restored if it was already existing 11715 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11716 // remove package from internal structures. Note that we want deletePackageX to 11717 // delete the package data and cache directories that it created in 11718 // scanPackageLocked, unless those directories existed before we even tried to 11719 // install. 11720 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 11721 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 11722 res.removedInfo, true); 11723 } 11724 11725 } catch (PackageManagerException e) { 11726 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11727 } 11728 } 11729 11730 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 11731 // Can't rotate keys during boot or if sharedUser. 11732 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 11733 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 11734 return false; 11735 } 11736 // app is using upgradeKeySets; make sure all are valid 11737 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11738 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 11739 for (int i = 0; i < upgradeKeySets.length; i++) { 11740 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 11741 Slog.wtf(TAG, "Package " 11742 + (oldPs.name != null ? oldPs.name : "<null>") 11743 + " contains upgrade-key-set reference to unknown key-set: " 11744 + upgradeKeySets[i] 11745 + " reverting to signatures check."); 11746 return false; 11747 } 11748 } 11749 return true; 11750 } 11751 11752 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 11753 // Upgrade keysets are being used. Determine if new package has a superset of the 11754 // required keys. 11755 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 11756 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11757 for (int i = 0; i < upgradeKeySets.length; i++) { 11758 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 11759 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 11760 return true; 11761 } 11762 } 11763 return false; 11764 } 11765 11766 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11767 UserHandle user, String installerPackageName, String volumeUuid, 11768 PackageInstalledInfo res) { 11769 final PackageParser.Package oldPackage; 11770 final String pkgName = pkg.packageName; 11771 final int[] allUsers; 11772 final boolean[] perUserInstalled; 11773 final boolean weFroze; 11774 11775 // First find the old package info and check signatures 11776 synchronized(mPackages) { 11777 oldPackage = mPackages.get(pkgName); 11778 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 11779 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11780 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 11781 if(!checkUpgradeKeySetLP(ps, pkg)) { 11782 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11783 "New package not signed by keys specified by upgrade-keysets: " 11784 + pkgName); 11785 return; 11786 } 11787 } else { 11788 // default to original signature matching 11789 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 11790 != PackageManager.SIGNATURE_MATCH) { 11791 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11792 "New package has a different signature: " + pkgName); 11793 return; 11794 } 11795 } 11796 11797 // In case of rollback, remember per-user/profile install state 11798 allUsers = sUserManager.getUserIds(); 11799 perUserInstalled = new boolean[allUsers.length]; 11800 for (int i = 0; i < allUsers.length; i++) { 11801 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11802 } 11803 11804 // Mark the app as frozen to prevent launching during the upgrade 11805 // process, and then kill all running instances 11806 if (!ps.frozen) { 11807 ps.frozen = true; 11808 weFroze = true; 11809 } else { 11810 weFroze = false; 11811 } 11812 } 11813 11814 // Now that we're guarded by frozen state, kill app during upgrade 11815 killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg"); 11816 11817 try { 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 } finally { 11827 // Regardless of success or failure of upgrade steps above, always 11828 // unfreeze the package if we froze it 11829 if (weFroze) { 11830 unfreezePackage(pkgName); 11831 } 11832 } 11833 } 11834 11835 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 11836 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11837 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11838 String volumeUuid, PackageInstalledInfo res) { 11839 String pkgName = deletedPackage.packageName; 11840 boolean deletedPkg = true; 11841 boolean updatedSettings = false; 11842 11843 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 11844 + deletedPackage); 11845 long origUpdateTime; 11846 if (pkg.mExtras != null) { 11847 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 11848 } else { 11849 origUpdateTime = 0; 11850 } 11851 11852 // First delete the existing package while retaining the data directory 11853 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 11854 res.removedInfo, true)) { 11855 // If the existing package wasn't successfully deleted 11856 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 11857 deletedPkg = false; 11858 } else { 11859 // Successfully deleted the old package; proceed with replace. 11860 11861 // If deleted package lived in a container, give users a chance to 11862 // relinquish resources before killing. 11863 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 11864 if (DEBUG_INSTALL) { 11865 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 11866 } 11867 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 11868 final ArrayList<String> pkgList = new ArrayList<String>(1); 11869 pkgList.add(deletedPackage.applicationInfo.packageName); 11870 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 11871 } 11872 11873 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 11874 try { 11875 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 11876 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 11877 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11878 perUserInstalled, res, user); 11879 updatedSettings = true; 11880 } catch (PackageManagerException e) { 11881 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11882 } 11883 } 11884 11885 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11886 // remove package from internal structures. Note that we want deletePackageX to 11887 // delete the package data and cache directories that it created in 11888 // scanPackageLocked, unless those directories existed before we even tried to 11889 // install. 11890 if(updatedSettings) { 11891 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 11892 deletePackageLI( 11893 pkgName, null, true, allUsers, perUserInstalled, 11894 PackageManager.DELETE_KEEP_DATA, 11895 res.removedInfo, true); 11896 } 11897 // Since we failed to install the new package we need to restore the old 11898 // package that we deleted. 11899 if (deletedPkg) { 11900 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 11901 File restoreFile = new File(deletedPackage.codePath); 11902 // Parse old package 11903 boolean oldExternal = isExternal(deletedPackage); 11904 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 11905 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 11906 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11907 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 11908 try { 11909 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 11910 } catch (PackageManagerException e) { 11911 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 11912 + e.getMessage()); 11913 return; 11914 } 11915 // Restore of old package succeeded. Update permissions. 11916 // writer 11917 synchronized (mPackages) { 11918 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 11919 UPDATE_PERMISSIONS_ALL); 11920 // can downgrade to reader 11921 mSettings.writeLPr(); 11922 } 11923 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 11924 } 11925 } 11926 } 11927 11928 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 11929 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11930 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11931 String volumeUuid, PackageInstalledInfo res) { 11932 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 11933 + ", old=" + deletedPackage); 11934 boolean disabledSystem = false; 11935 boolean updatedSettings = false; 11936 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 11937 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 11938 != 0) { 11939 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11940 } 11941 String packageName = deletedPackage.packageName; 11942 if (packageName == null) { 11943 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11944 "Attempt to delete null packageName."); 11945 return; 11946 } 11947 PackageParser.Package oldPkg; 11948 PackageSetting oldPkgSetting; 11949 // reader 11950 synchronized (mPackages) { 11951 oldPkg = mPackages.get(packageName); 11952 oldPkgSetting = mSettings.mPackages.get(packageName); 11953 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 11954 (oldPkgSetting == null)) { 11955 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11956 "Couldn't find package:" + packageName + " information"); 11957 return; 11958 } 11959 } 11960 11961 res.removedInfo.uid = oldPkg.applicationInfo.uid; 11962 res.removedInfo.removedPackage = packageName; 11963 // Remove existing system package 11964 removePackageLI(oldPkgSetting, true); 11965 // writer 11966 synchronized (mPackages) { 11967 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 11968 if (!disabledSystem && deletedPackage != null) { 11969 // We didn't need to disable the .apk as a current system package, 11970 // which means we are replacing another update that is already 11971 // installed. We need to make sure to delete the older one's .apk. 11972 res.removedInfo.args = createInstallArgsForExisting(0, 11973 deletedPackage.applicationInfo.getCodePath(), 11974 deletedPackage.applicationInfo.getResourcePath(), 11975 getAppDexInstructionSets(deletedPackage.applicationInfo)); 11976 } else { 11977 res.removedInfo.args = null; 11978 } 11979 } 11980 11981 // Successfully disabled the old package. Now proceed with re-installation 11982 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 11983 11984 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11985 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 11986 11987 PackageParser.Package newPackage = null; 11988 try { 11989 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 11990 if (newPackage.mExtras != null) { 11991 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 11992 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 11993 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 11994 11995 // is the update attempting to change shared user? that isn't going to work... 11996 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 11997 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 11998 "Forbidding shared user change from " + oldPkgSetting.sharedUser 11999 + " to " + newPkgSetting.sharedUser); 12000 updatedSettings = true; 12001 } 12002 } 12003 12004 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12005 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12006 perUserInstalled, res, user); 12007 updatedSettings = true; 12008 } 12009 12010 } catch (PackageManagerException e) { 12011 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12012 } 12013 12014 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12015 // Re installation failed. Restore old information 12016 // Remove new pkg information 12017 if (newPackage != null) { 12018 removeInstalledPackageLI(newPackage, true); 12019 } 12020 // Add back the old system package 12021 try { 12022 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 12023 } catch (PackageManagerException e) { 12024 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 12025 } 12026 // Restore the old system information in Settings 12027 synchronized (mPackages) { 12028 if (disabledSystem) { 12029 mSettings.enableSystemPackageLPw(packageName); 12030 } 12031 if (updatedSettings) { 12032 mSettings.setInstallerPackageName(packageName, 12033 oldPkgSetting.installerPackageName); 12034 } 12035 mSettings.writeLPr(); 12036 } 12037 } 12038 } 12039 12040 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 12041 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 12042 UserHandle user) { 12043 String pkgName = newPackage.packageName; 12044 synchronized (mPackages) { 12045 //write settings. the installStatus will be incomplete at this stage. 12046 //note that the new package setting would have already been 12047 //added to mPackages. It hasn't been persisted yet. 12048 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 12049 mSettings.writeLPr(); 12050 } 12051 12052 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 12053 12054 synchronized (mPackages) { 12055 updatePermissionsLPw(newPackage.packageName, newPackage, 12056 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 12057 ? UPDATE_PERMISSIONS_ALL : 0)); 12058 // For system-bundled packages, we assume that installing an upgraded version 12059 // of the package implies that the user actually wants to run that new code, 12060 // so we enable the package. 12061 PackageSetting ps = mSettings.mPackages.get(pkgName); 12062 if (ps != null) { 12063 if (isSystemApp(newPackage)) { 12064 // NB: implicit assumption that system package upgrades apply to all users 12065 if (DEBUG_INSTALL) { 12066 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 12067 } 12068 if (res.origUsers != null) { 12069 for (int userHandle : res.origUsers) { 12070 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 12071 userHandle, installerPackageName); 12072 } 12073 } 12074 // Also convey the prior install/uninstall state 12075 if (allUsers != null && perUserInstalled != null) { 12076 for (int i = 0; i < allUsers.length; i++) { 12077 if (DEBUG_INSTALL) { 12078 Slog.d(TAG, " user " + allUsers[i] 12079 + " => " + perUserInstalled[i]); 12080 } 12081 ps.setInstalled(perUserInstalled[i], allUsers[i]); 12082 } 12083 // these install state changes will be persisted in the 12084 // upcoming call to mSettings.writeLPr(). 12085 } 12086 } 12087 // It's implied that when a user requests installation, they want the app to be 12088 // installed and enabled. 12089 int userId = user.getIdentifier(); 12090 if (userId != UserHandle.USER_ALL) { 12091 ps.setInstalled(true, userId); 12092 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 12093 } 12094 } 12095 res.name = pkgName; 12096 res.uid = newPackage.applicationInfo.uid; 12097 res.pkg = newPackage; 12098 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 12099 mSettings.setInstallerPackageName(pkgName, installerPackageName); 12100 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12101 //to update install status 12102 mSettings.writeLPr(); 12103 } 12104 } 12105 12106 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 12107 final int installFlags = args.installFlags; 12108 final String installerPackageName = args.installerPackageName; 12109 final String volumeUuid = args.volumeUuid; 12110 final File tmpPackageFile = new File(args.getCodePath()); 12111 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 12112 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 12113 || (args.volumeUuid != null)); 12114 boolean replace = false; 12115 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 12116 if (args.move != null) { 12117 // moving a complete application; perfom an initial scan on the new install location 12118 scanFlags |= SCAN_INITIAL; 12119 } 12120 // Result object to be returned 12121 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12122 12123 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 12124 // Retrieve PackageSettings and parse package 12125 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 12126 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 12127 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 12128 PackageParser pp = new PackageParser(); 12129 pp.setSeparateProcesses(mSeparateProcesses); 12130 pp.setDisplayMetrics(mMetrics); 12131 12132 final PackageParser.Package pkg; 12133 try { 12134 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 12135 } catch (PackageParserException e) { 12136 res.setError("Failed parse during installPackageLI", e); 12137 return; 12138 } 12139 12140 // Mark that we have an install time CPU ABI override. 12141 pkg.cpuAbiOverride = args.abiOverride; 12142 12143 String pkgName = res.name = pkg.packageName; 12144 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 12145 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 12146 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 12147 return; 12148 } 12149 } 12150 12151 try { 12152 pp.collectCertificates(pkg, parseFlags); 12153 pp.collectManifestDigest(pkg); 12154 } catch (PackageParserException e) { 12155 res.setError("Failed collect during installPackageLI", e); 12156 return; 12157 } 12158 12159 /* If the installer passed in a manifest digest, compare it now. */ 12160 if (args.manifestDigest != null) { 12161 if (DEBUG_INSTALL) { 12162 final String parsedManifest = pkg.manifestDigest == null ? "null" 12163 : pkg.manifestDigest.toString(); 12164 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 12165 + parsedManifest); 12166 } 12167 12168 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 12169 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 12170 return; 12171 } 12172 } else if (DEBUG_INSTALL) { 12173 final String parsedManifest = pkg.manifestDigest == null 12174 ? "null" : pkg.manifestDigest.toString(); 12175 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 12176 } 12177 12178 // Get rid of all references to package scan path via parser. 12179 pp = null; 12180 String oldCodePath = null; 12181 boolean systemApp = false; 12182 synchronized (mPackages) { 12183 // Check if installing already existing package 12184 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12185 String oldName = mSettings.mRenamedPackages.get(pkgName); 12186 if (pkg.mOriginalPackages != null 12187 && pkg.mOriginalPackages.contains(oldName) 12188 && mPackages.containsKey(oldName)) { 12189 // This package is derived from an original package, 12190 // and this device has been updating from that original 12191 // name. We must continue using the original name, so 12192 // rename the new package here. 12193 pkg.setPackageName(oldName); 12194 pkgName = pkg.packageName; 12195 replace = true; 12196 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 12197 + oldName + " pkgName=" + pkgName); 12198 } else if (mPackages.containsKey(pkgName)) { 12199 // This package, under its official name, already exists 12200 // on the device; we should replace it. 12201 replace = true; 12202 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 12203 } 12204 12205 // Prevent apps opting out from runtime permissions 12206 if (replace) { 12207 PackageParser.Package oldPackage = mPackages.get(pkgName); 12208 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 12209 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 12210 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 12211 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 12212 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 12213 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 12214 + " doesn't support runtime permissions but the old" 12215 + " target SDK " + oldTargetSdk + " does."); 12216 return; 12217 } 12218 } 12219 } 12220 12221 PackageSetting ps = mSettings.mPackages.get(pkgName); 12222 if (ps != null) { 12223 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 12224 12225 // Quick sanity check that we're signed correctly if updating; 12226 // we'll check this again later when scanning, but we want to 12227 // bail early here before tripping over redefined permissions. 12228 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12229 if (!checkUpgradeKeySetLP(ps, pkg)) { 12230 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 12231 + pkg.packageName + " upgrade keys do not match the " 12232 + "previously installed version"); 12233 return; 12234 } 12235 } else { 12236 try { 12237 verifySignaturesLP(ps, pkg); 12238 } catch (PackageManagerException e) { 12239 res.setError(e.error, e.getMessage()); 12240 return; 12241 } 12242 } 12243 12244 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 12245 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 12246 systemApp = (ps.pkg.applicationInfo.flags & 12247 ApplicationInfo.FLAG_SYSTEM) != 0; 12248 } 12249 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12250 } 12251 12252 // Check whether the newly-scanned package wants to define an already-defined perm 12253 int N = pkg.permissions.size(); 12254 for (int i = N-1; i >= 0; i--) { 12255 PackageParser.Permission perm = pkg.permissions.get(i); 12256 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 12257 if (bp != null) { 12258 // If the defining package is signed with our cert, it's okay. This 12259 // also includes the "updating the same package" case, of course. 12260 // "updating same package" could also involve key-rotation. 12261 final boolean sigsOk; 12262 if (bp.sourcePackage.equals(pkg.packageName) 12263 && (bp.packageSetting instanceof PackageSetting) 12264 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 12265 scanFlags))) { 12266 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 12267 } else { 12268 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 12269 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 12270 } 12271 if (!sigsOk) { 12272 // If the owning package is the system itself, we log but allow 12273 // install to proceed; we fail the install on all other permission 12274 // redefinitions. 12275 if (!bp.sourcePackage.equals("android")) { 12276 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 12277 + pkg.packageName + " attempting to redeclare permission " 12278 + perm.info.name + " already owned by " + bp.sourcePackage); 12279 res.origPermission = perm.info.name; 12280 res.origPackage = bp.sourcePackage; 12281 return; 12282 } else { 12283 Slog.w(TAG, "Package " + pkg.packageName 12284 + " attempting to redeclare system permission " 12285 + perm.info.name + "; ignoring new declaration"); 12286 pkg.permissions.remove(i); 12287 } 12288 } 12289 } 12290 } 12291 12292 } 12293 12294 if (systemApp && onExternal) { 12295 // Disable updates to system apps on sdcard 12296 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 12297 "Cannot install updates to system apps on sdcard"); 12298 return; 12299 } 12300 12301 if (args.move != null) { 12302 // We did an in-place move, so dex is ready to roll 12303 scanFlags |= SCAN_NO_DEX; 12304 scanFlags |= SCAN_MOVE; 12305 12306 synchronized (mPackages) { 12307 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12308 if (ps == null) { 12309 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 12310 "Missing settings for moved package " + pkgName); 12311 } 12312 12313 // We moved the entire application as-is, so bring over the 12314 // previously derived ABI information. 12315 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 12316 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 12317 } 12318 12319 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 12320 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 12321 scanFlags |= SCAN_NO_DEX; 12322 12323 try { 12324 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 12325 true /* extract libs */); 12326 } catch (PackageManagerException pme) { 12327 Slog.e(TAG, "Error deriving application ABI", pme); 12328 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 12329 return; 12330 } 12331 12332 // Run dexopt before old package gets removed, to minimize time when app is unavailable 12333 int result = mPackageDexOptimizer 12334 .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */, 12335 false /* defer */, false /* inclDependencies */); 12336 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 12337 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 12338 return; 12339 } 12340 } 12341 12342 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 12343 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 12344 return; 12345 } 12346 12347 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 12348 12349 if (replace) { 12350 replacePackageLI(pkg, parseFlags, scanFlags, args.user, 12351 installerPackageName, volumeUuid, res); 12352 } else { 12353 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 12354 args.user, installerPackageName, volumeUuid, res); 12355 } 12356 synchronized (mPackages) { 12357 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12358 if (ps != null) { 12359 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12360 } 12361 } 12362 } 12363 12364 private void startIntentFilterVerifications(int userId, boolean replacing, 12365 PackageParser.Package pkg) { 12366 if (mIntentFilterVerifierComponent == null) { 12367 Slog.w(TAG, "No IntentFilter verification will not be done as " 12368 + "there is no IntentFilterVerifier available!"); 12369 return; 12370 } 12371 12372 final int verifierUid = getPackageUid( 12373 mIntentFilterVerifierComponent.getPackageName(), 12374 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 12375 12376 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 12377 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 12378 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 12379 mHandler.sendMessage(msg); 12380 } 12381 12382 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 12383 PackageParser.Package pkg) { 12384 int size = pkg.activities.size(); 12385 if (size == 0) { 12386 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12387 "No activity, so no need to verify any IntentFilter!"); 12388 return; 12389 } 12390 12391 final boolean hasDomainURLs = hasDomainURLs(pkg); 12392 if (!hasDomainURLs) { 12393 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12394 "No domain URLs, so no need to verify any IntentFilter!"); 12395 return; 12396 } 12397 12398 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 12399 + " if any IntentFilter from the " + size 12400 + " Activities needs verification ..."); 12401 12402 int count = 0; 12403 final String packageName = pkg.packageName; 12404 12405 synchronized (mPackages) { 12406 // If this is a new install and we see that we've already run verification for this 12407 // package, we have nothing to do: it means the state was restored from backup. 12408 if (!replacing) { 12409 IntentFilterVerificationInfo ivi = 12410 mSettings.getIntentFilterVerificationLPr(packageName); 12411 if (ivi != null) { 12412 if (DEBUG_DOMAIN_VERIFICATION) { 12413 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 12414 + ivi.getStatusString()); 12415 } 12416 return; 12417 } 12418 } 12419 12420 // If any filters need to be verified, then all need to be. 12421 boolean needToVerify = false; 12422 for (PackageParser.Activity a : pkg.activities) { 12423 for (ActivityIntentInfo filter : a.intents) { 12424 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 12425 if (DEBUG_DOMAIN_VERIFICATION) { 12426 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 12427 } 12428 needToVerify = true; 12429 break; 12430 } 12431 } 12432 } 12433 12434 if (needToVerify) { 12435 final int verificationId = mIntentFilterVerificationToken++; 12436 for (PackageParser.Activity a : pkg.activities) { 12437 for (ActivityIntentInfo filter : a.intents) { 12438 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 12439 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12440 "Verification needed for IntentFilter:" + filter.toString()); 12441 mIntentFilterVerifier.addOneIntentFilterVerification( 12442 verifierUid, userId, verificationId, filter, packageName); 12443 count++; 12444 } 12445 } 12446 } 12447 } 12448 } 12449 12450 if (count > 0) { 12451 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 12452 + " IntentFilter verification" + (count > 1 ? "s" : "") 12453 + " for userId:" + userId); 12454 mIntentFilterVerifier.startVerifications(userId); 12455 } else { 12456 if (DEBUG_DOMAIN_VERIFICATION) { 12457 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 12458 } 12459 } 12460 } 12461 12462 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 12463 final ComponentName cn = filter.activity.getComponentName(); 12464 final String packageName = cn.getPackageName(); 12465 12466 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 12467 packageName); 12468 if (ivi == null) { 12469 return true; 12470 } 12471 int status = ivi.getStatus(); 12472 switch (status) { 12473 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 12474 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 12475 return true; 12476 12477 default: 12478 // Nothing to do 12479 return false; 12480 } 12481 } 12482 12483 private static boolean isMultiArch(PackageSetting ps) { 12484 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12485 } 12486 12487 private static boolean isMultiArch(ApplicationInfo info) { 12488 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12489 } 12490 12491 private static boolean isExternal(PackageParser.Package pkg) { 12492 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12493 } 12494 12495 private static boolean isExternal(PackageSetting ps) { 12496 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12497 } 12498 12499 private static boolean isExternal(ApplicationInfo info) { 12500 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12501 } 12502 12503 private static boolean isSystemApp(PackageParser.Package pkg) { 12504 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 12505 } 12506 12507 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 12508 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 12509 } 12510 12511 private static boolean hasDomainURLs(PackageParser.Package pkg) { 12512 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 12513 } 12514 12515 private static boolean isSystemApp(PackageSetting ps) { 12516 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 12517 } 12518 12519 private static boolean isUpdatedSystemApp(PackageSetting ps) { 12520 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 12521 } 12522 12523 private int packageFlagsToInstallFlags(PackageSetting ps) { 12524 int installFlags = 0; 12525 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 12526 // This existing package was an external ASEC install when we have 12527 // the external flag without a UUID 12528 installFlags |= PackageManager.INSTALL_EXTERNAL; 12529 } 12530 if (ps.isForwardLocked()) { 12531 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12532 } 12533 return installFlags; 12534 } 12535 12536 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 12537 if (isExternal(pkg)) { 12538 if (TextUtils.isEmpty(pkg.volumeUuid)) { 12539 return mSettings.getExternalVersion(); 12540 } else { 12541 return mSettings.findOrCreateVersion(pkg.volumeUuid); 12542 } 12543 } else { 12544 return mSettings.getInternalVersion(); 12545 } 12546 } 12547 12548 private void deleteTempPackageFiles() { 12549 final FilenameFilter filter = new FilenameFilter() { 12550 public boolean accept(File dir, String name) { 12551 return name.startsWith("vmdl") && name.endsWith(".tmp"); 12552 } 12553 }; 12554 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 12555 file.delete(); 12556 } 12557 } 12558 12559 @Override 12560 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 12561 int flags) { 12562 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 12563 flags); 12564 } 12565 12566 @Override 12567 public void deletePackage(final String packageName, 12568 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 12569 mContext.enforceCallingOrSelfPermission( 12570 android.Manifest.permission.DELETE_PACKAGES, null); 12571 Preconditions.checkNotNull(packageName); 12572 Preconditions.checkNotNull(observer); 12573 final int uid = Binder.getCallingUid(); 12574 if (UserHandle.getUserId(uid) != userId) { 12575 mContext.enforceCallingPermission( 12576 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 12577 "deletePackage for user " + userId); 12578 } 12579 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 12580 try { 12581 observer.onPackageDeleted(packageName, 12582 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 12583 } catch (RemoteException re) { 12584 } 12585 return; 12586 } 12587 12588 boolean uninstallBlocked = false; 12589 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 12590 int[] users = sUserManager.getUserIds(); 12591 for (int i = 0; i < users.length; ++i) { 12592 if (getBlockUninstallForUser(packageName, users[i])) { 12593 uninstallBlocked = true; 12594 break; 12595 } 12596 } 12597 } else { 12598 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 12599 } 12600 if (uninstallBlocked) { 12601 try { 12602 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 12603 null); 12604 } catch (RemoteException re) { 12605 } 12606 return; 12607 } 12608 12609 if (DEBUG_REMOVE) { 12610 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 12611 } 12612 // Queue up an async operation since the package deletion may take a little while. 12613 mHandler.post(new Runnable() { 12614 public void run() { 12615 mHandler.removeCallbacks(this); 12616 final int returnCode = deletePackageX(packageName, userId, flags); 12617 if (observer != null) { 12618 try { 12619 observer.onPackageDeleted(packageName, returnCode, null); 12620 } catch (RemoteException e) { 12621 Log.i(TAG, "Observer no longer exists."); 12622 } //end catch 12623 } //end if 12624 } //end run 12625 }); 12626 } 12627 12628 private boolean isPackageDeviceAdmin(String packageName, int userId) { 12629 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 12630 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 12631 try { 12632 if (dpm != null) { 12633 if (dpm.isDeviceOwner(packageName)) { 12634 return true; 12635 } 12636 int[] users; 12637 if (userId == UserHandle.USER_ALL) { 12638 users = sUserManager.getUserIds(); 12639 } else { 12640 users = new int[]{userId}; 12641 } 12642 for (int i = 0; i < users.length; ++i) { 12643 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 12644 return true; 12645 } 12646 } 12647 } 12648 } catch (RemoteException e) { 12649 } 12650 return false; 12651 } 12652 12653 /** 12654 * This method is an internal method that could be get invoked either 12655 * to delete an installed package or to clean up a failed installation. 12656 * After deleting an installed package, a broadcast is sent to notify any 12657 * listeners that the package has been installed. For cleaning up a failed 12658 * installation, the broadcast is not necessary since the package's 12659 * installation wouldn't have sent the initial broadcast either 12660 * The key steps in deleting a package are 12661 * deleting the package information in internal structures like mPackages, 12662 * deleting the packages base directories through installd 12663 * updating mSettings to reflect current status 12664 * persisting settings for later use 12665 * sending a broadcast if necessary 12666 */ 12667 private int deletePackageX(String packageName, int userId, int flags) { 12668 final PackageRemovedInfo info = new PackageRemovedInfo(); 12669 final boolean res; 12670 12671 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 12672 ? UserHandle.ALL : new UserHandle(userId); 12673 12674 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 12675 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 12676 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 12677 } 12678 12679 boolean removedForAllUsers = false; 12680 boolean systemUpdate = false; 12681 12682 // for the uninstall-updates case and restricted profiles, remember the per- 12683 // userhandle installed state 12684 int[] allUsers; 12685 boolean[] perUserInstalled; 12686 synchronized (mPackages) { 12687 PackageSetting ps = mSettings.mPackages.get(packageName); 12688 allUsers = sUserManager.getUserIds(); 12689 perUserInstalled = new boolean[allUsers.length]; 12690 for (int i = 0; i < allUsers.length; i++) { 12691 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12692 } 12693 } 12694 12695 synchronized (mInstallLock) { 12696 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 12697 res = deletePackageLI(packageName, removeForUser, 12698 true, allUsers, perUserInstalled, 12699 flags | REMOVE_CHATTY, info, true); 12700 systemUpdate = info.isRemovedPackageSystemUpdate; 12701 if (res && !systemUpdate && mPackages.get(packageName) == null) { 12702 removedForAllUsers = true; 12703 } 12704 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 12705 + " removedForAllUsers=" + removedForAllUsers); 12706 } 12707 12708 if (res) { 12709 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 12710 12711 // If the removed package was a system update, the old system package 12712 // was re-enabled; we need to broadcast this information 12713 if (systemUpdate) { 12714 Bundle extras = new Bundle(1); 12715 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 12716 ? info.removedAppId : info.uid); 12717 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12718 12719 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 12720 extras, null, null, null); 12721 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 12722 extras, null, null, null); 12723 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 12724 null, packageName, null, null); 12725 } 12726 } 12727 // Force a gc here. 12728 Runtime.getRuntime().gc(); 12729 // Delete the resources here after sending the broadcast to let 12730 // other processes clean up before deleting resources. 12731 if (info.args != null) { 12732 synchronized (mInstallLock) { 12733 info.args.doPostDeleteLI(true); 12734 } 12735 } 12736 12737 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 12738 } 12739 12740 class PackageRemovedInfo { 12741 String removedPackage; 12742 int uid = -1; 12743 int removedAppId = -1; 12744 int[] removedUsers = null; 12745 boolean isRemovedPackageSystemUpdate = false; 12746 // Clean up resources deleted packages. 12747 InstallArgs args = null; 12748 12749 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 12750 Bundle extras = new Bundle(1); 12751 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 12752 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 12753 if (replacing) { 12754 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12755 } 12756 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 12757 if (removedPackage != null) { 12758 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 12759 extras, null, null, removedUsers); 12760 if (fullRemove && !replacing) { 12761 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 12762 extras, null, null, removedUsers); 12763 } 12764 } 12765 if (removedAppId >= 0) { 12766 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 12767 removedUsers); 12768 } 12769 } 12770 } 12771 12772 /* 12773 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 12774 * flag is not set, the data directory is removed as well. 12775 * make sure this flag is set for partially installed apps. If not its meaningless to 12776 * delete a partially installed application. 12777 */ 12778 private void removePackageDataLI(PackageSetting ps, 12779 int[] allUserHandles, boolean[] perUserInstalled, 12780 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 12781 String packageName = ps.name; 12782 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 12783 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 12784 // Retrieve object to delete permissions for shared user later on 12785 final PackageSetting deletedPs; 12786 // reader 12787 synchronized (mPackages) { 12788 deletedPs = mSettings.mPackages.get(packageName); 12789 if (outInfo != null) { 12790 outInfo.removedPackage = packageName; 12791 outInfo.removedUsers = deletedPs != null 12792 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 12793 : null; 12794 } 12795 } 12796 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12797 removeDataDirsLI(ps.volumeUuid, packageName); 12798 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 12799 } 12800 // writer 12801 synchronized (mPackages) { 12802 if (deletedPs != null) { 12803 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12804 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 12805 clearDefaultBrowserIfNeeded(packageName); 12806 if (outInfo != null) { 12807 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 12808 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 12809 } 12810 updatePermissionsLPw(deletedPs.name, null, 0); 12811 if (deletedPs.sharedUser != null) { 12812 // Remove permissions associated with package. Since runtime 12813 // permissions are per user we have to kill the removed package 12814 // or packages running under the shared user of the removed 12815 // package if revoking the permissions requested only by the removed 12816 // package is successful and this causes a change in gids. 12817 for (int userId : UserManagerService.getInstance().getUserIds()) { 12818 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 12819 userId); 12820 if (userIdToKill == UserHandle.USER_ALL 12821 || userIdToKill >= UserHandle.USER_OWNER) { 12822 // If gids changed for this user, kill all affected packages. 12823 mHandler.post(new Runnable() { 12824 @Override 12825 public void run() { 12826 // This has to happen with no lock held. 12827 killSettingPackagesForUser(deletedPs, userIdToKill, 12828 KILL_APP_REASON_GIDS_CHANGED); 12829 } 12830 }); 12831 break; 12832 } 12833 } 12834 } 12835 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 12836 } 12837 // make sure to preserve per-user disabled state if this removal was just 12838 // a downgrade of a system app to the factory package 12839 if (allUserHandles != null && perUserInstalled != null) { 12840 if (DEBUG_REMOVE) { 12841 Slog.d(TAG, "Propagating install state across downgrade"); 12842 } 12843 for (int i = 0; i < allUserHandles.length; i++) { 12844 if (DEBUG_REMOVE) { 12845 Slog.d(TAG, " user " + allUserHandles[i] 12846 + " => " + perUserInstalled[i]); 12847 } 12848 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12849 } 12850 } 12851 } 12852 // can downgrade to reader 12853 if (writeSettings) { 12854 // Save settings now 12855 mSettings.writeLPr(); 12856 } 12857 } 12858 if (outInfo != null) { 12859 // A user ID was deleted here. Go through all users and remove it 12860 // from KeyStore. 12861 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 12862 } 12863 } 12864 12865 static boolean locationIsPrivileged(File path) { 12866 try { 12867 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 12868 .getCanonicalPath(); 12869 return path.getCanonicalPath().startsWith(privilegedAppDir); 12870 } catch (IOException e) { 12871 Slog.e(TAG, "Unable to access code path " + path); 12872 } 12873 return false; 12874 } 12875 12876 /* 12877 * Tries to delete system package. 12878 */ 12879 private boolean deleteSystemPackageLI(PackageSetting newPs, 12880 int[] allUserHandles, boolean[] perUserInstalled, 12881 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 12882 final boolean applyUserRestrictions 12883 = (allUserHandles != null) && (perUserInstalled != null); 12884 PackageSetting disabledPs = null; 12885 // Confirm if the system package has been updated 12886 // An updated system app can be deleted. This will also have to restore 12887 // the system pkg from system partition 12888 // reader 12889 synchronized (mPackages) { 12890 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 12891 } 12892 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 12893 + " disabledPs=" + disabledPs); 12894 if (disabledPs == null) { 12895 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 12896 return false; 12897 } else if (DEBUG_REMOVE) { 12898 Slog.d(TAG, "Deleting system pkg from data partition"); 12899 } 12900 if (DEBUG_REMOVE) { 12901 if (applyUserRestrictions) { 12902 Slog.d(TAG, "Remembering install states:"); 12903 for (int i = 0; i < allUserHandles.length; i++) { 12904 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 12905 } 12906 } 12907 } 12908 // Delete the updated package 12909 outInfo.isRemovedPackageSystemUpdate = true; 12910 if (disabledPs.versionCode < newPs.versionCode) { 12911 // Delete data for downgrades 12912 flags &= ~PackageManager.DELETE_KEEP_DATA; 12913 } else { 12914 // Preserve data by setting flag 12915 flags |= PackageManager.DELETE_KEEP_DATA; 12916 } 12917 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 12918 allUserHandles, perUserInstalled, outInfo, writeSettings); 12919 if (!ret) { 12920 return false; 12921 } 12922 // writer 12923 synchronized (mPackages) { 12924 // Reinstate the old system package 12925 mSettings.enableSystemPackageLPw(newPs.name); 12926 // Remove any native libraries from the upgraded package. 12927 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 12928 } 12929 // Install the system package 12930 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 12931 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 12932 if (locationIsPrivileged(disabledPs.codePath)) { 12933 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12934 } 12935 12936 final PackageParser.Package newPkg; 12937 try { 12938 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 12939 } catch (PackageManagerException e) { 12940 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 12941 return false; 12942 } 12943 12944 // writer 12945 synchronized (mPackages) { 12946 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 12947 12948 updatePermissionsLPw(newPkg.packageName, newPkg, 12949 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 12950 12951 if (applyUserRestrictions) { 12952 if (DEBUG_REMOVE) { 12953 Slog.d(TAG, "Propagating install state across reinstall"); 12954 } 12955 for (int i = 0; i < allUserHandles.length; i++) { 12956 if (DEBUG_REMOVE) { 12957 Slog.d(TAG, " user " + allUserHandles[i] 12958 + " => " + perUserInstalled[i]); 12959 } 12960 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12961 12962 mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false); 12963 } 12964 // Regardless of writeSettings we need to ensure that this restriction 12965 // state propagation is persisted 12966 mSettings.writeAllUsersPackageRestrictionsLPr(); 12967 } 12968 // can downgrade to reader here 12969 if (writeSettings) { 12970 mSettings.writeLPr(); 12971 } 12972 } 12973 return true; 12974 } 12975 12976 private boolean deleteInstalledPackageLI(PackageSetting ps, 12977 boolean deleteCodeAndResources, int flags, 12978 int[] allUserHandles, boolean[] perUserInstalled, 12979 PackageRemovedInfo outInfo, boolean writeSettings) { 12980 if (outInfo != null) { 12981 outInfo.uid = ps.appId; 12982 } 12983 12984 // Delete package data from internal structures and also remove data if flag is set 12985 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 12986 12987 // Delete application code and resources 12988 if (deleteCodeAndResources && (outInfo != null)) { 12989 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 12990 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 12991 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 12992 } 12993 return true; 12994 } 12995 12996 @Override 12997 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 12998 int userId) { 12999 mContext.enforceCallingOrSelfPermission( 13000 android.Manifest.permission.DELETE_PACKAGES, null); 13001 synchronized (mPackages) { 13002 PackageSetting ps = mSettings.mPackages.get(packageName); 13003 if (ps == null) { 13004 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 13005 return false; 13006 } 13007 if (!ps.getInstalled(userId)) { 13008 // Can't block uninstall for an app that is not installed or enabled. 13009 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 13010 return false; 13011 } 13012 ps.setBlockUninstall(blockUninstall, userId); 13013 mSettings.writePackageRestrictionsLPr(userId); 13014 } 13015 return true; 13016 } 13017 13018 @Override 13019 public boolean getBlockUninstallForUser(String packageName, int userId) { 13020 synchronized (mPackages) { 13021 PackageSetting ps = mSettings.mPackages.get(packageName); 13022 if (ps == null) { 13023 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 13024 return false; 13025 } 13026 return ps.getBlockUninstall(userId); 13027 } 13028 } 13029 13030 /* 13031 * This method handles package deletion in general 13032 */ 13033 private boolean deletePackageLI(String packageName, UserHandle user, 13034 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 13035 int flags, PackageRemovedInfo outInfo, 13036 boolean writeSettings) { 13037 if (packageName == null) { 13038 Slog.w(TAG, "Attempt to delete null packageName."); 13039 return false; 13040 } 13041 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 13042 PackageSetting ps; 13043 boolean dataOnly = false; 13044 int removeUser = -1; 13045 int appId = -1; 13046 synchronized (mPackages) { 13047 ps = mSettings.mPackages.get(packageName); 13048 if (ps == null) { 13049 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13050 return false; 13051 } 13052 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 13053 && user.getIdentifier() != UserHandle.USER_ALL) { 13054 // The caller is asking that the package only be deleted for a single 13055 // user. To do this, we just mark its uninstalled state and delete 13056 // its data. If this is a system app, we only allow this to happen if 13057 // they have set the special DELETE_SYSTEM_APP which requests different 13058 // semantics than normal for uninstalling system apps. 13059 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 13060 ps.setUserState(user.getIdentifier(), 13061 COMPONENT_ENABLED_STATE_DEFAULT, 13062 false, //installed 13063 true, //stopped 13064 true, //notLaunched 13065 false, //hidden 13066 null, null, null, 13067 false, // blockUninstall 13068 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED, 0); 13069 if (!isSystemApp(ps)) { 13070 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 13071 // Other user still have this package installed, so all 13072 // we need to do is clear this user's data and save that 13073 // it is uninstalled. 13074 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 13075 removeUser = user.getIdentifier(); 13076 appId = ps.appId; 13077 scheduleWritePackageRestrictionsLocked(removeUser); 13078 } else { 13079 // We need to set it back to 'installed' so the uninstall 13080 // broadcasts will be sent correctly. 13081 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 13082 ps.setInstalled(true, user.getIdentifier()); 13083 } 13084 } else { 13085 // This is a system app, so we assume that the 13086 // other users still have this package installed, so all 13087 // we need to do is clear this user's data and save that 13088 // it is uninstalled. 13089 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 13090 removeUser = user.getIdentifier(); 13091 appId = ps.appId; 13092 scheduleWritePackageRestrictionsLocked(removeUser); 13093 } 13094 } 13095 } 13096 13097 if (removeUser >= 0) { 13098 // From above, we determined that we are deleting this only 13099 // for a single user. Continue the work here. 13100 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 13101 if (outInfo != null) { 13102 outInfo.removedPackage = packageName; 13103 outInfo.removedAppId = appId; 13104 outInfo.removedUsers = new int[] {removeUser}; 13105 } 13106 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 13107 removeKeystoreDataIfNeeded(removeUser, appId); 13108 schedulePackageCleaning(packageName, removeUser, false); 13109 synchronized (mPackages) { 13110 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 13111 scheduleWritePackageRestrictionsLocked(removeUser); 13112 } 13113 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser); 13114 } 13115 return true; 13116 } 13117 13118 if (dataOnly) { 13119 // Delete application data first 13120 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 13121 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 13122 return true; 13123 } 13124 13125 boolean ret = false; 13126 if (isSystemApp(ps)) { 13127 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 13128 // When an updated system application is deleted we delete the existing resources as well and 13129 // fall back to existing code in system partition 13130 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 13131 flags, outInfo, writeSettings); 13132 } else { 13133 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 13134 // Kill application pre-emptively especially for apps on sd. 13135 killApplication(packageName, ps.appId, "uninstall pkg"); 13136 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 13137 allUserHandles, perUserInstalled, 13138 outInfo, writeSettings); 13139 } 13140 13141 return ret; 13142 } 13143 13144 private final class ClearStorageConnection implements ServiceConnection { 13145 IMediaContainerService mContainerService; 13146 13147 @Override 13148 public void onServiceConnected(ComponentName name, IBinder service) { 13149 synchronized (this) { 13150 mContainerService = IMediaContainerService.Stub.asInterface(service); 13151 notifyAll(); 13152 } 13153 } 13154 13155 @Override 13156 public void onServiceDisconnected(ComponentName name) { 13157 } 13158 } 13159 13160 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 13161 final boolean mounted; 13162 if (Environment.isExternalStorageEmulated()) { 13163 mounted = true; 13164 } else { 13165 final String status = Environment.getExternalStorageState(); 13166 13167 mounted = status.equals(Environment.MEDIA_MOUNTED) 13168 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 13169 } 13170 13171 if (!mounted) { 13172 return; 13173 } 13174 13175 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 13176 int[] users; 13177 if (userId == UserHandle.USER_ALL) { 13178 users = sUserManager.getUserIds(); 13179 } else { 13180 users = new int[] { userId }; 13181 } 13182 final ClearStorageConnection conn = new ClearStorageConnection(); 13183 if (mContext.bindServiceAsUser( 13184 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 13185 try { 13186 for (int curUser : users) { 13187 long timeout = SystemClock.uptimeMillis() + 5000; 13188 synchronized (conn) { 13189 long now = SystemClock.uptimeMillis(); 13190 while (conn.mContainerService == null && now < timeout) { 13191 try { 13192 conn.wait(timeout - now); 13193 } catch (InterruptedException e) { 13194 } 13195 } 13196 } 13197 if (conn.mContainerService == null) { 13198 return; 13199 } 13200 13201 final UserEnvironment userEnv = new UserEnvironment(curUser); 13202 clearDirectory(conn.mContainerService, 13203 userEnv.buildExternalStorageAppCacheDirs(packageName)); 13204 if (allData) { 13205 clearDirectory(conn.mContainerService, 13206 userEnv.buildExternalStorageAppDataDirs(packageName)); 13207 clearDirectory(conn.mContainerService, 13208 userEnv.buildExternalStorageAppMediaDirs(packageName)); 13209 } 13210 } 13211 } finally { 13212 mContext.unbindService(conn); 13213 } 13214 } 13215 } 13216 13217 @Override 13218 public void clearApplicationUserData(final String packageName, 13219 final IPackageDataObserver observer, final int userId) { 13220 mContext.enforceCallingOrSelfPermission( 13221 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 13222 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 13223 // Queue up an async operation since the package deletion may take a little while. 13224 mHandler.post(new Runnable() { 13225 public void run() { 13226 mHandler.removeCallbacks(this); 13227 final boolean succeeded; 13228 synchronized (mInstallLock) { 13229 succeeded = clearApplicationUserDataLI(packageName, userId); 13230 } 13231 clearExternalStorageDataSync(packageName, userId, true); 13232 if (succeeded) { 13233 // invoke DeviceStorageMonitor's update method to clear any notifications 13234 DeviceStorageMonitorInternal 13235 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13236 if (dsm != null) { 13237 dsm.checkMemory(); 13238 } 13239 } 13240 if(observer != null) { 13241 try { 13242 observer.onRemoveCompleted(packageName, succeeded); 13243 } catch (RemoteException e) { 13244 Log.i(TAG, "Observer no longer exists."); 13245 } 13246 } //end if observer 13247 } //end run 13248 }); 13249 } 13250 13251 private boolean clearApplicationUserDataLI(String packageName, int userId) { 13252 if (packageName == null) { 13253 Slog.w(TAG, "Attempt to delete null packageName."); 13254 return false; 13255 } 13256 13257 // Try finding details about the requested package 13258 PackageParser.Package pkg; 13259 synchronized (mPackages) { 13260 pkg = mPackages.get(packageName); 13261 if (pkg == null) { 13262 final PackageSetting ps = mSettings.mPackages.get(packageName); 13263 if (ps != null) { 13264 pkg = ps.pkg; 13265 } 13266 } 13267 13268 if (pkg == null) { 13269 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13270 return false; 13271 } 13272 13273 PackageSetting ps = (PackageSetting) pkg.mExtras; 13274 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 13275 } 13276 13277 // Always delete data directories for package, even if we found no other 13278 // record of app. This helps users recover from UID mismatches without 13279 // resorting to a full data wipe. 13280 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 13281 if (retCode < 0) { 13282 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 13283 return false; 13284 } 13285 13286 final int appId = pkg.applicationInfo.uid; 13287 removeKeystoreDataIfNeeded(userId, appId); 13288 13289 // Create a native library symlink only if we have native libraries 13290 // and if the native libraries are 32 bit libraries. We do not provide 13291 // this symlink for 64 bit libraries. 13292 if (pkg.applicationInfo.primaryCpuAbi != null && 13293 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 13294 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 13295 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 13296 nativeLibPath, userId) < 0) { 13297 Slog.w(TAG, "Failed linking native library dir"); 13298 return false; 13299 } 13300 } 13301 13302 return true; 13303 } 13304 13305 /** 13306 * Reverts user permission state changes (permissions and flags) in 13307 * all packages for a given user. 13308 * 13309 * @param userId The device user for which to do a reset. 13310 */ 13311 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 13312 final int packageCount = mPackages.size(); 13313 for (int i = 0; i < packageCount; i++) { 13314 PackageParser.Package pkg = mPackages.valueAt(i); 13315 PackageSetting ps = (PackageSetting) pkg.mExtras; 13316 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 13317 } 13318 } 13319 13320 /** 13321 * Reverts user permission state changes (permissions and flags). 13322 * 13323 * @param ps The package for which to reset. 13324 * @param userId The device user for which to do a reset. 13325 */ 13326 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 13327 final PackageSetting ps, final int userId) { 13328 if (ps.pkg == null) { 13329 return; 13330 } 13331 13332 final int userSettableFlags = FLAG_PERMISSION_USER_SET 13333 | FLAG_PERMISSION_USER_FIXED 13334 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 13335 13336 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 13337 | FLAG_PERMISSION_POLICY_FIXED; 13338 13339 boolean writeInstallPermissions = false; 13340 boolean writeRuntimePermissions = false; 13341 13342 final int permissionCount = ps.pkg.requestedPermissions.size(); 13343 for (int i = 0; i < permissionCount; i++) { 13344 String permission = ps.pkg.requestedPermissions.get(i); 13345 13346 BasePermission bp = mSettings.mPermissions.get(permission); 13347 if (bp == null) { 13348 continue; 13349 } 13350 13351 // If shared user we just reset the state to which only this app contributed. 13352 if (ps.sharedUser != null) { 13353 boolean used = false; 13354 final int packageCount = ps.sharedUser.packages.size(); 13355 for (int j = 0; j < packageCount; j++) { 13356 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 13357 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 13358 && pkg.pkg.requestedPermissions.contains(permission)) { 13359 used = true; 13360 break; 13361 } 13362 } 13363 if (used) { 13364 continue; 13365 } 13366 } 13367 13368 PermissionsState permissionsState = ps.getPermissionsState(); 13369 13370 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 13371 13372 // Always clear the user settable flags. 13373 final boolean hasInstallState = permissionsState.getInstallPermissionState( 13374 bp.name) != null; 13375 if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) { 13376 if (hasInstallState) { 13377 writeInstallPermissions = true; 13378 } else { 13379 writeRuntimePermissions = true; 13380 } 13381 } 13382 13383 // Below is only runtime permission handling. 13384 if (!bp.isRuntime()) { 13385 continue; 13386 } 13387 13388 // Never clobber system or policy. 13389 if ((oldFlags & policyOrSystemFlags) != 0) { 13390 continue; 13391 } 13392 13393 // If this permission was granted by default, make sure it is. 13394 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 13395 if (permissionsState.grantRuntimePermission(bp, userId) 13396 != PERMISSION_OPERATION_FAILURE) { 13397 writeRuntimePermissions = true; 13398 } 13399 } else { 13400 // Otherwise, reset the permission. 13401 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 13402 switch (revokeResult) { 13403 case PERMISSION_OPERATION_SUCCESS: { 13404 writeRuntimePermissions = true; 13405 } break; 13406 13407 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 13408 writeRuntimePermissions = true; 13409 // If gids changed for this user, kill all affected packages. 13410 mHandler.post(new Runnable() { 13411 @Override 13412 public void run() { 13413 // This has to happen with no lock held. 13414 killSettingPackagesForUser(ps, userId, 13415 KILL_APP_REASON_GIDS_CHANGED); 13416 } 13417 }); 13418 } break; 13419 } 13420 } 13421 } 13422 13423 // Synchronously write as we are taking permissions away. 13424 if (writeRuntimePermissions) { 13425 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 13426 } 13427 13428 // Synchronously write as we are taking permissions away. 13429 if (writeInstallPermissions) { 13430 mSettings.writeLPr(); 13431 } 13432 } 13433 13434 /** 13435 * Remove entries from the keystore daemon. Will only remove it if the 13436 * {@code appId} is valid. 13437 */ 13438 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 13439 if (appId < 0) { 13440 return; 13441 } 13442 13443 final KeyStore keyStore = KeyStore.getInstance(); 13444 if (keyStore != null) { 13445 if (userId == UserHandle.USER_ALL) { 13446 for (final int individual : sUserManager.getUserIds()) { 13447 keyStore.clearUid(UserHandle.getUid(individual, appId)); 13448 } 13449 } else { 13450 keyStore.clearUid(UserHandle.getUid(userId, appId)); 13451 } 13452 } else { 13453 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 13454 } 13455 } 13456 13457 @Override 13458 public void deleteApplicationCacheFiles(final String packageName, 13459 final IPackageDataObserver observer) { 13460 mContext.enforceCallingOrSelfPermission( 13461 android.Manifest.permission.DELETE_CACHE_FILES, null); 13462 // Queue up an async operation since the package deletion may take a little while. 13463 final int userId = UserHandle.getCallingUserId(); 13464 mHandler.post(new Runnable() { 13465 public void run() { 13466 mHandler.removeCallbacks(this); 13467 final boolean succeded; 13468 synchronized (mInstallLock) { 13469 succeded = deleteApplicationCacheFilesLI(packageName, userId); 13470 } 13471 clearExternalStorageDataSync(packageName, userId, false); 13472 if (observer != null) { 13473 try { 13474 observer.onRemoveCompleted(packageName, succeded); 13475 } catch (RemoteException e) { 13476 Log.i(TAG, "Observer no longer exists."); 13477 } 13478 } //end if observer 13479 } //end run 13480 }); 13481 } 13482 13483 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 13484 if (packageName == null) { 13485 Slog.w(TAG, "Attempt to delete null packageName."); 13486 return false; 13487 } 13488 PackageParser.Package p; 13489 synchronized (mPackages) { 13490 p = mPackages.get(packageName); 13491 } 13492 if (p == null) { 13493 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13494 return false; 13495 } 13496 final ApplicationInfo applicationInfo = p.applicationInfo; 13497 if (applicationInfo == null) { 13498 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13499 return false; 13500 } 13501 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 13502 if (retCode < 0) { 13503 Slog.w(TAG, "Couldn't remove cache files for package: " 13504 + packageName + " u" + userId); 13505 return false; 13506 } 13507 return true; 13508 } 13509 13510 @Override 13511 public void getPackageSizeInfo(final String packageName, int userHandle, 13512 final IPackageStatsObserver observer) { 13513 mContext.enforceCallingOrSelfPermission( 13514 android.Manifest.permission.GET_PACKAGE_SIZE, null); 13515 if (packageName == null) { 13516 throw new IllegalArgumentException("Attempt to get size of null packageName"); 13517 } 13518 13519 PackageStats stats = new PackageStats(packageName, userHandle); 13520 13521 /* 13522 * Queue up an async operation since the package measurement may take a 13523 * little while. 13524 */ 13525 Message msg = mHandler.obtainMessage(INIT_COPY); 13526 msg.obj = new MeasureParams(stats, observer); 13527 mHandler.sendMessage(msg); 13528 } 13529 13530 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 13531 PackageStats pStats) { 13532 if (packageName == null) { 13533 Slog.w(TAG, "Attempt to get size of null packageName."); 13534 return false; 13535 } 13536 PackageParser.Package p; 13537 boolean dataOnly = false; 13538 String libDirRoot = null; 13539 String asecPath = null; 13540 PackageSetting ps = null; 13541 synchronized (mPackages) { 13542 p = mPackages.get(packageName); 13543 ps = mSettings.mPackages.get(packageName); 13544 if(p == null) { 13545 dataOnly = true; 13546 if((ps == null) || (ps.pkg == null)) { 13547 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13548 return false; 13549 } 13550 p = ps.pkg; 13551 } 13552 if (ps != null) { 13553 libDirRoot = ps.legacyNativeLibraryPathString; 13554 } 13555 if (p != null && (isExternal(p) || p.isForwardLocked())) { 13556 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 13557 if (secureContainerId != null) { 13558 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 13559 } 13560 } 13561 } 13562 String publicSrcDir = null; 13563 if(!dataOnly) { 13564 final ApplicationInfo applicationInfo = p.applicationInfo; 13565 if (applicationInfo == null) { 13566 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13567 return false; 13568 } 13569 if (p.isForwardLocked()) { 13570 publicSrcDir = applicationInfo.getBaseResourcePath(); 13571 } 13572 } 13573 // TODO: extend to measure size of split APKs 13574 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 13575 // not just the first level. 13576 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 13577 // just the primary. 13578 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 13579 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath, 13580 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 13581 if (res < 0) { 13582 return false; 13583 } 13584 13585 // Fix-up for forward-locked applications in ASEC containers. 13586 if (!isExternal(p)) { 13587 pStats.codeSize += pStats.externalCodeSize; 13588 pStats.externalCodeSize = 0L; 13589 } 13590 13591 return true; 13592 } 13593 13594 13595 @Override 13596 public void addPackageToPreferred(String packageName) { 13597 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 13598 } 13599 13600 @Override 13601 public void removePackageFromPreferred(String packageName) { 13602 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 13603 } 13604 13605 @Override 13606 public List<PackageInfo> getPreferredPackages(int flags) { 13607 return new ArrayList<PackageInfo>(); 13608 } 13609 13610 private int getUidTargetSdkVersionLockedLPr(int uid) { 13611 Object obj = mSettings.getUserIdLPr(uid); 13612 if (obj instanceof SharedUserSetting) { 13613 final SharedUserSetting sus = (SharedUserSetting) obj; 13614 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 13615 final Iterator<PackageSetting> it = sus.packages.iterator(); 13616 while (it.hasNext()) { 13617 final PackageSetting ps = it.next(); 13618 if (ps.pkg != null) { 13619 int v = ps.pkg.applicationInfo.targetSdkVersion; 13620 if (v < vers) vers = v; 13621 } 13622 } 13623 return vers; 13624 } else if (obj instanceof PackageSetting) { 13625 final PackageSetting ps = (PackageSetting) obj; 13626 if (ps.pkg != null) { 13627 return ps.pkg.applicationInfo.targetSdkVersion; 13628 } 13629 } 13630 return Build.VERSION_CODES.CUR_DEVELOPMENT; 13631 } 13632 13633 @Override 13634 public void addPreferredActivity(IntentFilter filter, int match, 13635 ComponentName[] set, ComponentName activity, int userId) { 13636 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13637 "Adding preferred"); 13638 } 13639 13640 private void addPreferredActivityInternal(IntentFilter filter, int match, 13641 ComponentName[] set, ComponentName activity, boolean always, int userId, 13642 String opname) { 13643 // writer 13644 int callingUid = Binder.getCallingUid(); 13645 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 13646 if (filter.countActions() == 0) { 13647 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13648 return; 13649 } 13650 synchronized (mPackages) { 13651 if (mContext.checkCallingOrSelfPermission( 13652 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13653 != PackageManager.PERMISSION_GRANTED) { 13654 if (getUidTargetSdkVersionLockedLPr(callingUid) 13655 < Build.VERSION_CODES.FROYO) { 13656 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 13657 + callingUid); 13658 return; 13659 } 13660 mContext.enforceCallingOrSelfPermission( 13661 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13662 } 13663 13664 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 13665 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 13666 + userId + ":"); 13667 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13668 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 13669 scheduleWritePackageRestrictionsLocked(userId); 13670 } 13671 } 13672 13673 @Override 13674 public void replacePreferredActivity(IntentFilter filter, int match, 13675 ComponentName[] set, ComponentName activity, int userId) { 13676 if (filter.countActions() != 1) { 13677 throw new IllegalArgumentException( 13678 "replacePreferredActivity expects filter to have only 1 action."); 13679 } 13680 if (filter.countDataAuthorities() != 0 13681 || filter.countDataPaths() != 0 13682 || filter.countDataSchemes() > 1 13683 || filter.countDataTypes() != 0) { 13684 throw new IllegalArgumentException( 13685 "replacePreferredActivity expects filter to have no data authorities, " + 13686 "paths, or types; and at most one scheme."); 13687 } 13688 13689 final int callingUid = Binder.getCallingUid(); 13690 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 13691 synchronized (mPackages) { 13692 if (mContext.checkCallingOrSelfPermission( 13693 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13694 != PackageManager.PERMISSION_GRANTED) { 13695 if (getUidTargetSdkVersionLockedLPr(callingUid) 13696 < Build.VERSION_CODES.FROYO) { 13697 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 13698 + Binder.getCallingUid()); 13699 return; 13700 } 13701 mContext.enforceCallingOrSelfPermission( 13702 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13703 } 13704 13705 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13706 if (pir != null) { 13707 // Get all of the existing entries that exactly match this filter. 13708 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 13709 if (existing != null && existing.size() == 1) { 13710 PreferredActivity cur = existing.get(0); 13711 if (DEBUG_PREFERRED) { 13712 Slog.i(TAG, "Checking replace of preferred:"); 13713 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13714 if (!cur.mPref.mAlways) { 13715 Slog.i(TAG, " -- CUR; not mAlways!"); 13716 } else { 13717 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 13718 Slog.i(TAG, " -- CUR: mSet=" 13719 + Arrays.toString(cur.mPref.mSetComponents)); 13720 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 13721 Slog.i(TAG, " -- NEW: mMatch=" 13722 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 13723 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 13724 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 13725 } 13726 } 13727 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 13728 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 13729 && cur.mPref.sameSet(set)) { 13730 // Setting the preferred activity to what it happens to be already 13731 if (DEBUG_PREFERRED) { 13732 Slog.i(TAG, "Replacing with same preferred activity " 13733 + cur.mPref.mShortComponent + " for user " 13734 + userId + ":"); 13735 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13736 } 13737 return; 13738 } 13739 } 13740 13741 if (existing != null) { 13742 if (DEBUG_PREFERRED) { 13743 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 13744 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13745 } 13746 for (int i = 0; i < existing.size(); i++) { 13747 PreferredActivity pa = existing.get(i); 13748 if (DEBUG_PREFERRED) { 13749 Slog.i(TAG, "Removing existing preferred activity " 13750 + pa.mPref.mComponent + ":"); 13751 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 13752 } 13753 pir.removeFilter(pa); 13754 } 13755 } 13756 } 13757 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13758 "Replacing preferred"); 13759 } 13760 } 13761 13762 @Override 13763 public void clearPackagePreferredActivities(String packageName) { 13764 final int uid = Binder.getCallingUid(); 13765 // writer 13766 synchronized (mPackages) { 13767 PackageParser.Package pkg = mPackages.get(packageName); 13768 if (pkg == null || pkg.applicationInfo.uid != uid) { 13769 if (mContext.checkCallingOrSelfPermission( 13770 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13771 != PackageManager.PERMISSION_GRANTED) { 13772 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 13773 < Build.VERSION_CODES.FROYO) { 13774 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 13775 + Binder.getCallingUid()); 13776 return; 13777 } 13778 mContext.enforceCallingOrSelfPermission( 13779 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13780 } 13781 } 13782 13783 int user = UserHandle.getCallingUserId(); 13784 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 13785 scheduleWritePackageRestrictionsLocked(user); 13786 } 13787 } 13788 } 13789 13790 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13791 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 13792 ArrayList<PreferredActivity> removed = null; 13793 boolean changed = false; 13794 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13795 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 13796 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13797 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 13798 continue; 13799 } 13800 Iterator<PreferredActivity> it = pir.filterIterator(); 13801 while (it.hasNext()) { 13802 PreferredActivity pa = it.next(); 13803 // Mark entry for removal only if it matches the package name 13804 // and the entry is of type "always". 13805 if (packageName == null || 13806 (pa.mPref.mComponent.getPackageName().equals(packageName) 13807 && pa.mPref.mAlways)) { 13808 if (removed == null) { 13809 removed = new ArrayList<PreferredActivity>(); 13810 } 13811 removed.add(pa); 13812 } 13813 } 13814 if (removed != null) { 13815 for (int j=0; j<removed.size(); j++) { 13816 PreferredActivity pa = removed.get(j); 13817 pir.removeFilter(pa); 13818 } 13819 changed = true; 13820 } 13821 } 13822 return changed; 13823 } 13824 13825 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13826 private void clearIntentFilterVerificationsLPw(int userId) { 13827 final int packageCount = mPackages.size(); 13828 for (int i = 0; i < packageCount; i++) { 13829 PackageParser.Package pkg = mPackages.valueAt(i); 13830 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 13831 } 13832 } 13833 13834 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13835 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 13836 if (userId == UserHandle.USER_ALL) { 13837 if (mSettings.removeIntentFilterVerificationLPw(packageName, 13838 sUserManager.getUserIds())) { 13839 for (int oneUserId : sUserManager.getUserIds()) { 13840 scheduleWritePackageRestrictionsLocked(oneUserId); 13841 } 13842 } 13843 } else { 13844 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 13845 scheduleWritePackageRestrictionsLocked(userId); 13846 } 13847 } 13848 } 13849 13850 void clearDefaultBrowserIfNeeded(String packageName) { 13851 for (int oneUserId : sUserManager.getUserIds()) { 13852 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 13853 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 13854 if (packageName.equals(defaultBrowserPackageName)) { 13855 setDefaultBrowserPackageName(null, oneUserId); 13856 } 13857 } 13858 } 13859 13860 @Override 13861 public void resetApplicationPreferences(int userId) { 13862 mContext.enforceCallingOrSelfPermission( 13863 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13864 // writer 13865 synchronized (mPackages) { 13866 final long identity = Binder.clearCallingIdentity(); 13867 try { 13868 clearPackagePreferredActivitiesLPw(null, userId); 13869 mSettings.applyDefaultPreferredAppsLPw(this, userId); 13870 // TODO: We have to reset the default SMS and Phone. This requires 13871 // significant refactoring to keep all default apps in the package 13872 // manager (cleaner but more work) or have the services provide 13873 // callbacks to the package manager to request a default app reset. 13874 applyFactoryDefaultBrowserLPw(userId); 13875 clearIntentFilterVerificationsLPw(userId); 13876 primeDomainVerificationsLPw(userId); 13877 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 13878 scheduleWritePackageRestrictionsLocked(userId); 13879 } finally { 13880 Binder.restoreCallingIdentity(identity); 13881 } 13882 } 13883 } 13884 13885 @Override 13886 public int getPreferredActivities(List<IntentFilter> outFilters, 13887 List<ComponentName> outActivities, String packageName) { 13888 13889 int num = 0; 13890 final int userId = UserHandle.getCallingUserId(); 13891 // reader 13892 synchronized (mPackages) { 13893 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13894 if (pir != null) { 13895 final Iterator<PreferredActivity> it = pir.filterIterator(); 13896 while (it.hasNext()) { 13897 final PreferredActivity pa = it.next(); 13898 if (packageName == null 13899 || (pa.mPref.mComponent.getPackageName().equals(packageName) 13900 && pa.mPref.mAlways)) { 13901 if (outFilters != null) { 13902 outFilters.add(new IntentFilter(pa)); 13903 } 13904 if (outActivities != null) { 13905 outActivities.add(pa.mPref.mComponent); 13906 } 13907 } 13908 } 13909 } 13910 } 13911 13912 return num; 13913 } 13914 13915 @Override 13916 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 13917 int userId) { 13918 int callingUid = Binder.getCallingUid(); 13919 if (callingUid != Process.SYSTEM_UID) { 13920 throw new SecurityException( 13921 "addPersistentPreferredActivity can only be run by the system"); 13922 } 13923 if (filter.countActions() == 0) { 13924 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13925 return; 13926 } 13927 synchronized (mPackages) { 13928 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 13929 " :"); 13930 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13931 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 13932 new PersistentPreferredActivity(filter, activity)); 13933 scheduleWritePackageRestrictionsLocked(userId); 13934 } 13935 } 13936 13937 @Override 13938 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 13939 int callingUid = Binder.getCallingUid(); 13940 if (callingUid != Process.SYSTEM_UID) { 13941 throw new SecurityException( 13942 "clearPackagePersistentPreferredActivities can only be run by the system"); 13943 } 13944 ArrayList<PersistentPreferredActivity> removed = null; 13945 boolean changed = false; 13946 synchronized (mPackages) { 13947 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 13948 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 13949 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 13950 .valueAt(i); 13951 if (userId != thisUserId) { 13952 continue; 13953 } 13954 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 13955 while (it.hasNext()) { 13956 PersistentPreferredActivity ppa = it.next(); 13957 // Mark entry for removal only if it matches the package name. 13958 if (ppa.mComponent.getPackageName().equals(packageName)) { 13959 if (removed == null) { 13960 removed = new ArrayList<PersistentPreferredActivity>(); 13961 } 13962 removed.add(ppa); 13963 } 13964 } 13965 if (removed != null) { 13966 for (int j=0; j<removed.size(); j++) { 13967 PersistentPreferredActivity ppa = removed.get(j); 13968 ppir.removeFilter(ppa); 13969 } 13970 changed = true; 13971 } 13972 } 13973 13974 if (changed) { 13975 scheduleWritePackageRestrictionsLocked(userId); 13976 } 13977 } 13978 } 13979 13980 /** 13981 * Common machinery for picking apart a restored XML blob and passing 13982 * it to a caller-supplied functor to be applied to the running system. 13983 */ 13984 private void restoreFromXml(XmlPullParser parser, int userId, 13985 String expectedStartTag, BlobXmlRestorer functor) 13986 throws IOException, XmlPullParserException { 13987 int type; 13988 while ((type = parser.next()) != XmlPullParser.START_TAG 13989 && type != XmlPullParser.END_DOCUMENT) { 13990 } 13991 if (type != XmlPullParser.START_TAG) { 13992 // oops didn't find a start tag?! 13993 if (DEBUG_BACKUP) { 13994 Slog.e(TAG, "Didn't find start tag during restore"); 13995 } 13996 return; 13997 } 13998 13999 // this is supposed to be TAG_PREFERRED_BACKUP 14000 if (!expectedStartTag.equals(parser.getName())) { 14001 if (DEBUG_BACKUP) { 14002 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 14003 } 14004 return; 14005 } 14006 14007 // skip interfering stuff, then we're aligned with the backing implementation 14008 while ((type = parser.next()) == XmlPullParser.TEXT) { } 14009 functor.apply(parser, userId); 14010 } 14011 14012 private interface BlobXmlRestorer { 14013 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 14014 } 14015 14016 /** 14017 * Non-Binder method, support for the backup/restore mechanism: write the 14018 * full set of preferred activities in its canonical XML format. Returns the 14019 * XML output as a byte array, or null if there is none. 14020 */ 14021 @Override 14022 public byte[] getPreferredActivityBackup(int userId) { 14023 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14024 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 14025 } 14026 14027 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14028 try { 14029 final XmlSerializer serializer = new FastXmlSerializer(); 14030 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14031 serializer.startDocument(null, true); 14032 serializer.startTag(null, TAG_PREFERRED_BACKUP); 14033 14034 synchronized (mPackages) { 14035 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 14036 } 14037 14038 serializer.endTag(null, TAG_PREFERRED_BACKUP); 14039 serializer.endDocument(); 14040 serializer.flush(); 14041 } catch (Exception e) { 14042 if (DEBUG_BACKUP) { 14043 Slog.e(TAG, "Unable to write preferred activities for backup", e); 14044 } 14045 return null; 14046 } 14047 14048 return dataStream.toByteArray(); 14049 } 14050 14051 @Override 14052 public void restorePreferredActivities(byte[] backup, int userId) { 14053 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14054 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14055 } 14056 14057 try { 14058 final XmlPullParser parser = Xml.newPullParser(); 14059 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14060 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 14061 new BlobXmlRestorer() { 14062 @Override 14063 public void apply(XmlPullParser parser, int userId) 14064 throws XmlPullParserException, IOException { 14065 synchronized (mPackages) { 14066 mSettings.readPreferredActivitiesLPw(parser, userId); 14067 } 14068 } 14069 } ); 14070 } catch (Exception e) { 14071 if (DEBUG_BACKUP) { 14072 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14073 } 14074 } 14075 } 14076 14077 /** 14078 * Non-Binder method, support for the backup/restore mechanism: write the 14079 * default browser (etc) settings in its canonical XML format. Returns the default 14080 * browser XML representation as a byte array, or null if there is none. 14081 */ 14082 @Override 14083 public byte[] getDefaultAppsBackup(int userId) { 14084 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14085 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 14086 } 14087 14088 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14089 try { 14090 final XmlSerializer serializer = new FastXmlSerializer(); 14091 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14092 serializer.startDocument(null, true); 14093 serializer.startTag(null, TAG_DEFAULT_APPS); 14094 14095 synchronized (mPackages) { 14096 mSettings.writeDefaultAppsLPr(serializer, userId); 14097 } 14098 14099 serializer.endTag(null, TAG_DEFAULT_APPS); 14100 serializer.endDocument(); 14101 serializer.flush(); 14102 } catch (Exception e) { 14103 if (DEBUG_BACKUP) { 14104 Slog.e(TAG, "Unable to write default apps for backup", e); 14105 } 14106 return null; 14107 } 14108 14109 return dataStream.toByteArray(); 14110 } 14111 14112 @Override 14113 public void restoreDefaultApps(byte[] backup, int userId) { 14114 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14115 throw new SecurityException("Only the system may call restoreDefaultApps()"); 14116 } 14117 14118 try { 14119 final XmlPullParser parser = Xml.newPullParser(); 14120 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14121 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 14122 new BlobXmlRestorer() { 14123 @Override 14124 public void apply(XmlPullParser parser, int userId) 14125 throws XmlPullParserException, IOException { 14126 synchronized (mPackages) { 14127 mSettings.readDefaultAppsLPw(parser, userId); 14128 } 14129 } 14130 } ); 14131 } catch (Exception e) { 14132 if (DEBUG_BACKUP) { 14133 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 14134 } 14135 } 14136 } 14137 14138 @Override 14139 public byte[] getIntentFilterVerificationBackup(int userId) { 14140 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14141 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 14142 } 14143 14144 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14145 try { 14146 final XmlSerializer serializer = new FastXmlSerializer(); 14147 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14148 serializer.startDocument(null, true); 14149 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 14150 14151 synchronized (mPackages) { 14152 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 14153 } 14154 14155 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 14156 serializer.endDocument(); 14157 serializer.flush(); 14158 } catch (Exception e) { 14159 if (DEBUG_BACKUP) { 14160 Slog.e(TAG, "Unable to write default apps for backup", e); 14161 } 14162 return null; 14163 } 14164 14165 return dataStream.toByteArray(); 14166 } 14167 14168 @Override 14169 public void restoreIntentFilterVerification(byte[] backup, int userId) { 14170 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14171 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14172 } 14173 14174 try { 14175 final XmlPullParser parser = Xml.newPullParser(); 14176 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14177 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 14178 new BlobXmlRestorer() { 14179 @Override 14180 public void apply(XmlPullParser parser, int userId) 14181 throws XmlPullParserException, IOException { 14182 synchronized (mPackages) { 14183 mSettings.readAllDomainVerificationsLPr(parser, userId); 14184 mSettings.writeLPr(); 14185 } 14186 } 14187 } ); 14188 } catch (Exception e) { 14189 if (DEBUG_BACKUP) { 14190 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14191 } 14192 } 14193 } 14194 14195 @Override 14196 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 14197 int sourceUserId, int targetUserId, int flags) { 14198 mContext.enforceCallingOrSelfPermission( 14199 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14200 int callingUid = Binder.getCallingUid(); 14201 enforceOwnerRights(ownerPackage, callingUid); 14202 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14203 if (intentFilter.countActions() == 0) { 14204 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 14205 return; 14206 } 14207 synchronized (mPackages) { 14208 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 14209 ownerPackage, targetUserId, flags); 14210 CrossProfileIntentResolver resolver = 14211 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14212 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 14213 // We have all those whose filter is equal. Now checking if the rest is equal as well. 14214 if (existing != null) { 14215 int size = existing.size(); 14216 for (int i = 0; i < size; i++) { 14217 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 14218 return; 14219 } 14220 } 14221 } 14222 resolver.addFilter(newFilter); 14223 scheduleWritePackageRestrictionsLocked(sourceUserId); 14224 } 14225 } 14226 14227 @Override 14228 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 14229 mContext.enforceCallingOrSelfPermission( 14230 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14231 int callingUid = Binder.getCallingUid(); 14232 enforceOwnerRights(ownerPackage, callingUid); 14233 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14234 synchronized (mPackages) { 14235 CrossProfileIntentResolver resolver = 14236 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14237 ArraySet<CrossProfileIntentFilter> set = 14238 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 14239 for (CrossProfileIntentFilter filter : set) { 14240 if (filter.getOwnerPackage().equals(ownerPackage)) { 14241 resolver.removeFilter(filter); 14242 } 14243 } 14244 scheduleWritePackageRestrictionsLocked(sourceUserId); 14245 } 14246 } 14247 14248 // Enforcing that callingUid is owning pkg on userId 14249 private void enforceOwnerRights(String pkg, int callingUid) { 14250 // The system owns everything. 14251 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 14252 return; 14253 } 14254 int callingUserId = UserHandle.getUserId(callingUid); 14255 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 14256 if (pi == null) { 14257 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 14258 + callingUserId); 14259 } 14260 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 14261 throw new SecurityException("Calling uid " + callingUid 14262 + " does not own package " + pkg); 14263 } 14264 } 14265 14266 @Override 14267 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 14268 Intent intent = new Intent(Intent.ACTION_MAIN); 14269 intent.addCategory(Intent.CATEGORY_HOME); 14270 14271 final int callingUserId = UserHandle.getCallingUserId(); 14272 List<ResolveInfo> list = queryIntentActivities(intent, null, 14273 PackageManager.GET_META_DATA, callingUserId); 14274 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 14275 true, false, false, callingUserId); 14276 14277 allHomeCandidates.clear(); 14278 if (list != null) { 14279 for (ResolveInfo ri : list) { 14280 allHomeCandidates.add(ri); 14281 } 14282 } 14283 return (preferred == null || preferred.activityInfo == null) 14284 ? null 14285 : new ComponentName(preferred.activityInfo.packageName, 14286 preferred.activityInfo.name); 14287 } 14288 14289 @Override 14290 public void setApplicationEnabledSetting(String appPackageName, 14291 int newState, int flags, int userId, String callingPackage) { 14292 if (!sUserManager.exists(userId)) return; 14293 if (callingPackage == null) { 14294 callingPackage = Integer.toString(Binder.getCallingUid()); 14295 } 14296 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 14297 } 14298 14299 @Override 14300 public void setComponentEnabledSetting(ComponentName componentName, 14301 int newState, int flags, int userId) { 14302 if (!sUserManager.exists(userId)) return; 14303 setEnabledSetting(componentName.getPackageName(), 14304 componentName.getClassName(), newState, flags, userId, null); 14305 } 14306 14307 private void setEnabledSetting(final String packageName, String className, int newState, 14308 final int flags, int userId, String callingPackage) { 14309 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 14310 || newState == COMPONENT_ENABLED_STATE_ENABLED 14311 || newState == COMPONENT_ENABLED_STATE_DISABLED 14312 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 14313 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 14314 throw new IllegalArgumentException("Invalid new component state: " 14315 + newState); 14316 } 14317 PackageSetting pkgSetting; 14318 final int uid = Binder.getCallingUid(); 14319 final int permission = mContext.checkCallingOrSelfPermission( 14320 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14321 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 14322 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14323 boolean sendNow = false; 14324 boolean isApp = (className == null); 14325 String componentName = isApp ? packageName : className; 14326 int packageUid = -1; 14327 ArrayList<String> components; 14328 14329 // writer 14330 synchronized (mPackages) { 14331 pkgSetting = mSettings.mPackages.get(packageName); 14332 if (pkgSetting == null) { 14333 if (className == null) { 14334 throw new IllegalArgumentException( 14335 "Unknown package: " + packageName); 14336 } 14337 throw new IllegalArgumentException( 14338 "Unknown component: " + packageName 14339 + "/" + className); 14340 } 14341 // Allow root and verify that userId is not being specified by a different user 14342 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 14343 throw new SecurityException( 14344 "Permission Denial: attempt to change component state from pid=" 14345 + Binder.getCallingPid() 14346 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 14347 } 14348 if (className == null) { 14349 // We're dealing with an application/package level state change 14350 if (pkgSetting.getEnabled(userId) == newState) { 14351 // Nothing to do 14352 return; 14353 } 14354 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 14355 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 14356 // Don't care about who enables an app. 14357 callingPackage = null; 14358 } 14359 pkgSetting.setEnabled(newState, userId, callingPackage); 14360 // pkgSetting.pkg.mSetEnabled = newState; 14361 } else { 14362 // We're dealing with a component level state change 14363 // First, verify that this is a valid class name. 14364 PackageParser.Package pkg = pkgSetting.pkg; 14365 if (pkg == null || !pkg.hasComponentClassName(className)) { 14366 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 14367 throw new IllegalArgumentException("Component class " + className 14368 + " does not exist in " + packageName); 14369 } else { 14370 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 14371 + className + " does not exist in " + packageName); 14372 } 14373 } 14374 switch (newState) { 14375 case COMPONENT_ENABLED_STATE_ENABLED: 14376 if (!pkgSetting.enableComponentLPw(className, userId)) { 14377 return; 14378 } 14379 break; 14380 case COMPONENT_ENABLED_STATE_DISABLED: 14381 if (!pkgSetting.disableComponentLPw(className, userId)) { 14382 return; 14383 } 14384 break; 14385 case COMPONENT_ENABLED_STATE_DEFAULT: 14386 if (!pkgSetting.restoreComponentLPw(className, userId)) { 14387 return; 14388 } 14389 break; 14390 default: 14391 Slog.e(TAG, "Invalid new component state: " + newState); 14392 return; 14393 } 14394 } 14395 scheduleWritePackageRestrictionsLocked(userId); 14396 components = mPendingBroadcasts.get(userId, packageName); 14397 final boolean newPackage = components == null; 14398 if (newPackage) { 14399 components = new ArrayList<String>(); 14400 } 14401 if (!components.contains(componentName)) { 14402 components.add(componentName); 14403 } 14404 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 14405 sendNow = true; 14406 // Purge entry from pending broadcast list if another one exists already 14407 // since we are sending one right away. 14408 mPendingBroadcasts.remove(userId, packageName); 14409 } else { 14410 if (newPackage) { 14411 mPendingBroadcasts.put(userId, packageName, components); 14412 } 14413 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 14414 // Schedule a message 14415 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 14416 } 14417 } 14418 } 14419 14420 long callingId = Binder.clearCallingIdentity(); 14421 try { 14422 if (sendNow) { 14423 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 14424 sendPackageChangedBroadcast(packageName, 14425 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 14426 } 14427 } finally { 14428 Binder.restoreCallingIdentity(callingId); 14429 } 14430 } 14431 14432 private void sendPackageChangedBroadcast(String packageName, 14433 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 14434 if (DEBUG_INSTALL) 14435 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 14436 + componentNames); 14437 Bundle extras = new Bundle(4); 14438 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 14439 String nameList[] = new String[componentNames.size()]; 14440 componentNames.toArray(nameList); 14441 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 14442 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 14443 extras.putInt(Intent.EXTRA_UID, packageUid); 14444 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 14445 new int[] {UserHandle.getUserId(packageUid)}); 14446 } 14447 14448 @Override 14449 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 14450 if (!sUserManager.exists(userId)) return; 14451 final int uid = Binder.getCallingUid(); 14452 final int permission = mContext.checkCallingOrSelfPermission( 14453 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14454 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14455 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 14456 // writer 14457 synchronized (mPackages) { 14458 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 14459 allowedByPermission, uid, userId)) { 14460 scheduleWritePackageRestrictionsLocked(userId); 14461 } 14462 } 14463 } 14464 14465 @Override 14466 public String getInstallerPackageName(String packageName) { 14467 // reader 14468 synchronized (mPackages) { 14469 return mSettings.getInstallerPackageNameLPr(packageName); 14470 } 14471 } 14472 14473 @Override 14474 public int getApplicationEnabledSetting(String packageName, int userId) { 14475 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14476 int uid = Binder.getCallingUid(); 14477 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 14478 // reader 14479 synchronized (mPackages) { 14480 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 14481 } 14482 } 14483 14484 @Override 14485 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 14486 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14487 int uid = Binder.getCallingUid(); 14488 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 14489 // reader 14490 synchronized (mPackages) { 14491 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 14492 } 14493 } 14494 14495 @Override 14496 public void enterSafeMode() { 14497 enforceSystemOrRoot("Only the system can request entering safe mode"); 14498 14499 if (!mSystemReady) { 14500 mSafeMode = true; 14501 } 14502 } 14503 14504 @Override 14505 public void systemReady() { 14506 mSystemReady = true; 14507 14508 // Read the compatibilty setting when the system is ready. 14509 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 14510 mContext.getContentResolver(), 14511 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 14512 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 14513 if (DEBUG_SETTINGS) { 14514 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 14515 } 14516 14517 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 14518 14519 synchronized (mPackages) { 14520 // Verify that all of the preferred activity components actually 14521 // exist. It is possible for applications to be updated and at 14522 // that point remove a previously declared activity component that 14523 // had been set as a preferred activity. We try to clean this up 14524 // the next time we encounter that preferred activity, but it is 14525 // possible for the user flow to never be able to return to that 14526 // situation so here we do a sanity check to make sure we haven't 14527 // left any junk around. 14528 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 14529 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14530 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14531 removed.clear(); 14532 for (PreferredActivity pa : pir.filterSet()) { 14533 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 14534 removed.add(pa); 14535 } 14536 } 14537 if (removed.size() > 0) { 14538 for (int r=0; r<removed.size(); r++) { 14539 PreferredActivity pa = removed.get(r); 14540 Slog.w(TAG, "Removing dangling preferred activity: " 14541 + pa.mPref.mComponent); 14542 pir.removeFilter(pa); 14543 } 14544 mSettings.writePackageRestrictionsLPr( 14545 mSettings.mPreferredActivities.keyAt(i)); 14546 } 14547 } 14548 14549 for (int userId : UserManagerService.getInstance().getUserIds()) { 14550 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 14551 grantPermissionsUserIds = ArrayUtils.appendInt( 14552 grantPermissionsUserIds, userId); 14553 } 14554 } 14555 } 14556 sUserManager.systemReady(); 14557 14558 // If we upgraded grant all default permissions before kicking off. 14559 for (int userId : grantPermissionsUserIds) { 14560 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 14561 } 14562 14563 // Kick off any messages waiting for system ready 14564 if (mPostSystemReadyMessages != null) { 14565 for (Message msg : mPostSystemReadyMessages) { 14566 msg.sendToTarget(); 14567 } 14568 mPostSystemReadyMessages = null; 14569 } 14570 14571 // Watch for external volumes that come and go over time 14572 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14573 storage.registerListener(mStorageListener); 14574 14575 mInstallerService.systemReady(); 14576 mPackageDexOptimizer.systemReady(); 14577 14578 MountServiceInternal mountServiceInternal = LocalServices.getService( 14579 MountServiceInternal.class); 14580 mountServiceInternal.addExternalStoragePolicy( 14581 new MountServiceInternal.ExternalStorageMountPolicy() { 14582 @Override 14583 public int getMountMode(int uid, String packageName) { 14584 if (Process.isIsolated(uid)) { 14585 return Zygote.MOUNT_EXTERNAL_NONE; 14586 } 14587 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 14588 return Zygote.MOUNT_EXTERNAL_DEFAULT; 14589 } 14590 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 14591 return Zygote.MOUNT_EXTERNAL_DEFAULT; 14592 } 14593 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 14594 return Zygote.MOUNT_EXTERNAL_READ; 14595 } 14596 return Zygote.MOUNT_EXTERNAL_WRITE; 14597 } 14598 14599 @Override 14600 public boolean hasExternalStorage(int uid, String packageName) { 14601 return true; 14602 } 14603 }); 14604 } 14605 14606 @Override 14607 public boolean isSafeMode() { 14608 return mSafeMode; 14609 } 14610 14611 @Override 14612 public boolean hasSystemUidErrors() { 14613 return mHasSystemUidErrors; 14614 } 14615 14616 static String arrayToString(int[] array) { 14617 StringBuffer buf = new StringBuffer(128); 14618 buf.append('['); 14619 if (array != null) { 14620 for (int i=0; i<array.length; i++) { 14621 if (i > 0) buf.append(", "); 14622 buf.append(array[i]); 14623 } 14624 } 14625 buf.append(']'); 14626 return buf.toString(); 14627 } 14628 14629 static class DumpState { 14630 public static final int DUMP_LIBS = 1 << 0; 14631 public static final int DUMP_FEATURES = 1 << 1; 14632 public static final int DUMP_RESOLVERS = 1 << 2; 14633 public static final int DUMP_PERMISSIONS = 1 << 3; 14634 public static final int DUMP_PACKAGES = 1 << 4; 14635 public static final int DUMP_SHARED_USERS = 1 << 5; 14636 public static final int DUMP_MESSAGES = 1 << 6; 14637 public static final int DUMP_PROVIDERS = 1 << 7; 14638 public static final int DUMP_VERIFIERS = 1 << 8; 14639 public static final int DUMP_PREFERRED = 1 << 9; 14640 public static final int DUMP_PREFERRED_XML = 1 << 10; 14641 public static final int DUMP_KEYSETS = 1 << 11; 14642 public static final int DUMP_VERSION = 1 << 12; 14643 public static final int DUMP_INSTALLS = 1 << 13; 14644 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 14645 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 14646 14647 public static final int OPTION_SHOW_FILTERS = 1 << 0; 14648 14649 private int mTypes; 14650 14651 private int mOptions; 14652 14653 private boolean mTitlePrinted; 14654 14655 private SharedUserSetting mSharedUser; 14656 14657 public boolean isDumping(int type) { 14658 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 14659 return true; 14660 } 14661 14662 return (mTypes & type) != 0; 14663 } 14664 14665 public void setDump(int type) { 14666 mTypes |= type; 14667 } 14668 14669 public boolean isOptionEnabled(int option) { 14670 return (mOptions & option) != 0; 14671 } 14672 14673 public void setOptionEnabled(int option) { 14674 mOptions |= option; 14675 } 14676 14677 public boolean onTitlePrinted() { 14678 final boolean printed = mTitlePrinted; 14679 mTitlePrinted = true; 14680 return printed; 14681 } 14682 14683 public boolean getTitlePrinted() { 14684 return mTitlePrinted; 14685 } 14686 14687 public void setTitlePrinted(boolean enabled) { 14688 mTitlePrinted = enabled; 14689 } 14690 14691 public SharedUserSetting getSharedUser() { 14692 return mSharedUser; 14693 } 14694 14695 public void setSharedUser(SharedUserSetting user) { 14696 mSharedUser = user; 14697 } 14698 } 14699 14700 @Override 14701 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 14702 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 14703 != PackageManager.PERMISSION_GRANTED) { 14704 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 14705 + Binder.getCallingPid() 14706 + ", uid=" + Binder.getCallingUid() 14707 + " without permission " 14708 + android.Manifest.permission.DUMP); 14709 return; 14710 } 14711 14712 DumpState dumpState = new DumpState(); 14713 boolean fullPreferred = false; 14714 boolean checkin = false; 14715 14716 String packageName = null; 14717 ArraySet<String> permissionNames = null; 14718 14719 int opti = 0; 14720 while (opti < args.length) { 14721 String opt = args[opti]; 14722 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 14723 break; 14724 } 14725 opti++; 14726 14727 if ("-a".equals(opt)) { 14728 // Right now we only know how to print all. 14729 } else if ("-h".equals(opt)) { 14730 pw.println("Package manager dump options:"); 14731 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 14732 pw.println(" --checkin: dump for a checkin"); 14733 pw.println(" -f: print details of intent filters"); 14734 pw.println(" -h: print this help"); 14735 pw.println(" cmd may be one of:"); 14736 pw.println(" l[ibraries]: list known shared libraries"); 14737 pw.println(" f[ibraries]: list device features"); 14738 pw.println(" k[eysets]: print known keysets"); 14739 pw.println(" r[esolvers]: dump intent resolvers"); 14740 pw.println(" perm[issions]: dump permissions"); 14741 pw.println(" permission [name ...]: dump declaration and use of given permission"); 14742 pw.println(" pref[erred]: print preferred package settings"); 14743 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 14744 pw.println(" prov[iders]: dump content providers"); 14745 pw.println(" p[ackages]: dump installed packages"); 14746 pw.println(" s[hared-users]: dump shared user IDs"); 14747 pw.println(" m[essages]: print collected runtime messages"); 14748 pw.println(" v[erifiers]: print package verifier info"); 14749 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 14750 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 14751 pw.println(" version: print database version info"); 14752 pw.println(" write: write current settings now"); 14753 pw.println(" installs: details about install sessions"); 14754 pw.println(" <package.name>: info about given package"); 14755 return; 14756 } else if ("--checkin".equals(opt)) { 14757 checkin = true; 14758 } else if ("-f".equals(opt)) { 14759 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14760 } else { 14761 pw.println("Unknown argument: " + opt + "; use -h for help"); 14762 } 14763 } 14764 14765 // Is the caller requesting to dump a particular piece of data? 14766 if (opti < args.length) { 14767 String cmd = args[opti]; 14768 opti++; 14769 // Is this a package name? 14770 if ("android".equals(cmd) || cmd.contains(".")) { 14771 packageName = cmd; 14772 // When dumping a single package, we always dump all of its 14773 // filter information since the amount of data will be reasonable. 14774 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14775 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 14776 dumpState.setDump(DumpState.DUMP_LIBS); 14777 } else if ("f".equals(cmd) || "features".equals(cmd)) { 14778 dumpState.setDump(DumpState.DUMP_FEATURES); 14779 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 14780 dumpState.setDump(DumpState.DUMP_RESOLVERS); 14781 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 14782 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 14783 } else if ("permission".equals(cmd)) { 14784 if (opti >= args.length) { 14785 pw.println("Error: permission requires permission name"); 14786 return; 14787 } 14788 permissionNames = new ArraySet<>(); 14789 while (opti < args.length) { 14790 permissionNames.add(args[opti]); 14791 opti++; 14792 } 14793 dumpState.setDump(DumpState.DUMP_PERMISSIONS 14794 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 14795 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 14796 dumpState.setDump(DumpState.DUMP_PREFERRED); 14797 } else if ("preferred-xml".equals(cmd)) { 14798 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 14799 if (opti < args.length && "--full".equals(args[opti])) { 14800 fullPreferred = true; 14801 opti++; 14802 } 14803 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 14804 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 14805 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 14806 dumpState.setDump(DumpState.DUMP_PACKAGES); 14807 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 14808 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 14809 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 14810 dumpState.setDump(DumpState.DUMP_PROVIDERS); 14811 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 14812 dumpState.setDump(DumpState.DUMP_MESSAGES); 14813 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 14814 dumpState.setDump(DumpState.DUMP_VERIFIERS); 14815 } else if ("i".equals(cmd) || "ifv".equals(cmd) 14816 || "intent-filter-verifiers".equals(cmd)) { 14817 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 14818 } else if ("version".equals(cmd)) { 14819 dumpState.setDump(DumpState.DUMP_VERSION); 14820 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 14821 dumpState.setDump(DumpState.DUMP_KEYSETS); 14822 } else if ("installs".equals(cmd)) { 14823 dumpState.setDump(DumpState.DUMP_INSTALLS); 14824 } else if ("write".equals(cmd)) { 14825 synchronized (mPackages) { 14826 mSettings.writeLPr(); 14827 pw.println("Settings written."); 14828 return; 14829 } 14830 } 14831 } 14832 14833 if (checkin) { 14834 pw.println("vers,1"); 14835 } 14836 14837 // reader 14838 synchronized (mPackages) { 14839 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 14840 if (!checkin) { 14841 if (dumpState.onTitlePrinted()) 14842 pw.println(); 14843 pw.println("Database versions:"); 14844 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 14845 } 14846 } 14847 14848 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 14849 if (!checkin) { 14850 if (dumpState.onTitlePrinted()) 14851 pw.println(); 14852 pw.println("Verifiers:"); 14853 pw.print(" Required: "); 14854 pw.print(mRequiredVerifierPackage); 14855 pw.print(" (uid="); 14856 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 14857 pw.println(")"); 14858 } else if (mRequiredVerifierPackage != null) { 14859 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 14860 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 14861 } 14862 } 14863 14864 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 14865 packageName == null) { 14866 if (mIntentFilterVerifierComponent != null) { 14867 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 14868 if (!checkin) { 14869 if (dumpState.onTitlePrinted()) 14870 pw.println(); 14871 pw.println("Intent Filter Verifier:"); 14872 pw.print(" Using: "); 14873 pw.print(verifierPackageName); 14874 pw.print(" (uid="); 14875 pw.print(getPackageUid(verifierPackageName, 0)); 14876 pw.println(")"); 14877 } else if (verifierPackageName != null) { 14878 pw.print("ifv,"); pw.print(verifierPackageName); 14879 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 14880 } 14881 } else { 14882 pw.println(); 14883 pw.println("No Intent Filter Verifier available!"); 14884 } 14885 } 14886 14887 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 14888 boolean printedHeader = false; 14889 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 14890 while (it.hasNext()) { 14891 String name = it.next(); 14892 SharedLibraryEntry ent = mSharedLibraries.get(name); 14893 if (!checkin) { 14894 if (!printedHeader) { 14895 if (dumpState.onTitlePrinted()) 14896 pw.println(); 14897 pw.println("Libraries:"); 14898 printedHeader = true; 14899 } 14900 pw.print(" "); 14901 } else { 14902 pw.print("lib,"); 14903 } 14904 pw.print(name); 14905 if (!checkin) { 14906 pw.print(" -> "); 14907 } 14908 if (ent.path != null) { 14909 if (!checkin) { 14910 pw.print("(jar) "); 14911 pw.print(ent.path); 14912 } else { 14913 pw.print(",jar,"); 14914 pw.print(ent.path); 14915 } 14916 } else { 14917 if (!checkin) { 14918 pw.print("(apk) "); 14919 pw.print(ent.apk); 14920 } else { 14921 pw.print(",apk,"); 14922 pw.print(ent.apk); 14923 } 14924 } 14925 pw.println(); 14926 } 14927 } 14928 14929 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 14930 if (dumpState.onTitlePrinted()) 14931 pw.println(); 14932 if (!checkin) { 14933 pw.println("Features:"); 14934 } 14935 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 14936 while (it.hasNext()) { 14937 String name = it.next(); 14938 if (!checkin) { 14939 pw.print(" "); 14940 } else { 14941 pw.print("feat,"); 14942 } 14943 pw.println(name); 14944 } 14945 } 14946 14947 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 14948 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 14949 : "Activity Resolver Table:", " ", packageName, 14950 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14951 dumpState.setTitlePrinted(true); 14952 } 14953 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 14954 : "Receiver Resolver Table:", " ", packageName, 14955 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14956 dumpState.setTitlePrinted(true); 14957 } 14958 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 14959 : "Service Resolver Table:", " ", packageName, 14960 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14961 dumpState.setTitlePrinted(true); 14962 } 14963 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 14964 : "Provider Resolver Table:", " ", packageName, 14965 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14966 dumpState.setTitlePrinted(true); 14967 } 14968 } 14969 14970 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 14971 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14972 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14973 int user = mSettings.mPreferredActivities.keyAt(i); 14974 if (pir.dump(pw, 14975 dumpState.getTitlePrinted() 14976 ? "\nPreferred Activities User " + user + ":" 14977 : "Preferred Activities User " + user + ":", " ", 14978 packageName, true, false)) { 14979 dumpState.setTitlePrinted(true); 14980 } 14981 } 14982 } 14983 14984 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 14985 pw.flush(); 14986 FileOutputStream fout = new FileOutputStream(fd); 14987 BufferedOutputStream str = new BufferedOutputStream(fout); 14988 XmlSerializer serializer = new FastXmlSerializer(); 14989 try { 14990 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 14991 serializer.startDocument(null, true); 14992 serializer.setFeature( 14993 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 14994 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 14995 serializer.endDocument(); 14996 serializer.flush(); 14997 } catch (IllegalArgumentException e) { 14998 pw.println("Failed writing: " + e); 14999 } catch (IllegalStateException e) { 15000 pw.println("Failed writing: " + e); 15001 } catch (IOException e) { 15002 pw.println("Failed writing: " + e); 15003 } 15004 } 15005 15006 if (!checkin 15007 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 15008 && packageName == null) { 15009 pw.println(); 15010 int count = mSettings.mPackages.size(); 15011 if (count == 0) { 15012 pw.println("No applications!"); 15013 pw.println(); 15014 } else { 15015 final String prefix = " "; 15016 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 15017 if (allPackageSettings.size() == 0) { 15018 pw.println("No domain preferred apps!"); 15019 pw.println(); 15020 } else { 15021 pw.println("App verification status:"); 15022 pw.println(); 15023 count = 0; 15024 for (PackageSetting ps : allPackageSettings) { 15025 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 15026 if (ivi == null || ivi.getPackageName() == null) continue; 15027 pw.println(prefix + "Package: " + ivi.getPackageName()); 15028 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 15029 pw.println(prefix + "Status: " + ivi.getStatusString()); 15030 pw.println(); 15031 count++; 15032 } 15033 if (count == 0) { 15034 pw.println(prefix + "No app verification established."); 15035 pw.println(); 15036 } 15037 for (int userId : sUserManager.getUserIds()) { 15038 pw.println("App linkages for user " + userId + ":"); 15039 pw.println(); 15040 count = 0; 15041 for (PackageSetting ps : allPackageSettings) { 15042 final long status = ps.getDomainVerificationStatusForUser(userId); 15043 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 15044 continue; 15045 } 15046 pw.println(prefix + "Package: " + ps.name); 15047 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 15048 String statusStr = IntentFilterVerificationInfo. 15049 getStatusStringFromValue(status); 15050 pw.println(prefix + "Status: " + statusStr); 15051 pw.println(); 15052 count++; 15053 } 15054 if (count == 0) { 15055 pw.println(prefix + "No configured app linkages."); 15056 pw.println(); 15057 } 15058 } 15059 } 15060 } 15061 } 15062 15063 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 15064 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 15065 if (packageName == null && permissionNames == null) { 15066 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 15067 if (iperm == 0) { 15068 if (dumpState.onTitlePrinted()) 15069 pw.println(); 15070 pw.println("AppOp Permissions:"); 15071 } 15072 pw.print(" AppOp Permission "); 15073 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 15074 pw.println(":"); 15075 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 15076 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 15077 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 15078 } 15079 } 15080 } 15081 } 15082 15083 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 15084 boolean printedSomething = false; 15085 for (PackageParser.Provider p : mProviders.mProviders.values()) { 15086 if (packageName != null && !packageName.equals(p.info.packageName)) { 15087 continue; 15088 } 15089 if (!printedSomething) { 15090 if (dumpState.onTitlePrinted()) 15091 pw.println(); 15092 pw.println("Registered ContentProviders:"); 15093 printedSomething = true; 15094 } 15095 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 15096 pw.print(" "); pw.println(p.toString()); 15097 } 15098 printedSomething = false; 15099 for (Map.Entry<String, PackageParser.Provider> entry : 15100 mProvidersByAuthority.entrySet()) { 15101 PackageParser.Provider p = entry.getValue(); 15102 if (packageName != null && !packageName.equals(p.info.packageName)) { 15103 continue; 15104 } 15105 if (!printedSomething) { 15106 if (dumpState.onTitlePrinted()) 15107 pw.println(); 15108 pw.println("ContentProvider Authorities:"); 15109 printedSomething = true; 15110 } 15111 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 15112 pw.print(" "); pw.println(p.toString()); 15113 if (p.info != null && p.info.applicationInfo != null) { 15114 final String appInfo = p.info.applicationInfo.toString(); 15115 pw.print(" applicationInfo="); pw.println(appInfo); 15116 } 15117 } 15118 } 15119 15120 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 15121 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 15122 } 15123 15124 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 15125 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 15126 } 15127 15128 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 15129 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 15130 } 15131 15132 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 15133 // XXX should handle packageName != null by dumping only install data that 15134 // the given package is involved with. 15135 if (dumpState.onTitlePrinted()) pw.println(); 15136 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 15137 } 15138 15139 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 15140 if (dumpState.onTitlePrinted()) pw.println(); 15141 mSettings.dumpReadMessagesLPr(pw, dumpState); 15142 15143 pw.println(); 15144 pw.println("Package warning messages:"); 15145 BufferedReader in = null; 15146 String line = null; 15147 try { 15148 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15149 while ((line = in.readLine()) != null) { 15150 if (line.contains("ignored: updated version")) continue; 15151 pw.println(line); 15152 } 15153 } catch (IOException ignored) { 15154 } finally { 15155 IoUtils.closeQuietly(in); 15156 } 15157 } 15158 15159 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 15160 BufferedReader in = null; 15161 String line = null; 15162 try { 15163 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15164 while ((line = in.readLine()) != null) { 15165 if (line.contains("ignored: updated version")) continue; 15166 pw.print("msg,"); 15167 pw.println(line); 15168 } 15169 } catch (IOException ignored) { 15170 } finally { 15171 IoUtils.closeQuietly(in); 15172 } 15173 } 15174 } 15175 } 15176 15177 private String dumpDomainString(String packageName) { 15178 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName); 15179 List<IntentFilter> filters = getAllIntentFilters(packageName); 15180 15181 ArraySet<String> result = new ArraySet<>(); 15182 if (iviList.size() > 0) { 15183 for (IntentFilterVerificationInfo ivi : iviList) { 15184 for (String host : ivi.getDomains()) { 15185 result.add(host); 15186 } 15187 } 15188 } 15189 if (filters != null && filters.size() > 0) { 15190 for (IntentFilter filter : filters) { 15191 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 15192 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 15193 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 15194 result.addAll(filter.getHostsList()); 15195 } 15196 } 15197 } 15198 15199 StringBuilder sb = new StringBuilder(result.size() * 16); 15200 for (String domain : result) { 15201 if (sb.length() > 0) sb.append(" "); 15202 sb.append(domain); 15203 } 15204 return sb.toString(); 15205 } 15206 15207 // ------- apps on sdcard specific code ------- 15208 static final boolean DEBUG_SD_INSTALL = false; 15209 15210 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 15211 15212 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 15213 15214 private boolean mMediaMounted = false; 15215 15216 static String getEncryptKey() { 15217 try { 15218 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 15219 SD_ENCRYPTION_KEYSTORE_NAME); 15220 if (sdEncKey == null) { 15221 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 15222 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 15223 if (sdEncKey == null) { 15224 Slog.e(TAG, "Failed to create encryption keys"); 15225 return null; 15226 } 15227 } 15228 return sdEncKey; 15229 } catch (NoSuchAlgorithmException nsae) { 15230 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 15231 return null; 15232 } catch (IOException ioe) { 15233 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 15234 return null; 15235 } 15236 } 15237 15238 /* 15239 * Update media status on PackageManager. 15240 */ 15241 @Override 15242 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 15243 int callingUid = Binder.getCallingUid(); 15244 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 15245 throw new SecurityException("Media status can only be updated by the system"); 15246 } 15247 // reader; this apparently protects mMediaMounted, but should probably 15248 // be a different lock in that case. 15249 synchronized (mPackages) { 15250 Log.i(TAG, "Updating external media status from " 15251 + (mMediaMounted ? "mounted" : "unmounted") + " to " 15252 + (mediaStatus ? "mounted" : "unmounted")); 15253 if (DEBUG_SD_INSTALL) 15254 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 15255 + ", mMediaMounted=" + mMediaMounted); 15256 if (mediaStatus == mMediaMounted) { 15257 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 15258 : 0, -1); 15259 mHandler.sendMessage(msg); 15260 return; 15261 } 15262 mMediaMounted = mediaStatus; 15263 } 15264 // Queue up an async operation since the package installation may take a 15265 // little while. 15266 mHandler.post(new Runnable() { 15267 public void run() { 15268 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 15269 } 15270 }); 15271 } 15272 15273 /** 15274 * Called by MountService when the initial ASECs to scan are available. 15275 * Should block until all the ASEC containers are finished being scanned. 15276 */ 15277 public void scanAvailableAsecs() { 15278 updateExternalMediaStatusInner(true, false, false); 15279 if (mShouldRestoreconData) { 15280 SELinuxMMAC.setRestoreconDone(); 15281 mShouldRestoreconData = false; 15282 } 15283 } 15284 15285 /* 15286 * Collect information of applications on external media, map them against 15287 * existing containers and update information based on current mount status. 15288 * Please note that we always have to report status if reportStatus has been 15289 * set to true especially when unloading packages. 15290 */ 15291 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 15292 boolean externalStorage) { 15293 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 15294 int[] uidArr = EmptyArray.INT; 15295 15296 final String[] list = PackageHelper.getSecureContainerList(); 15297 if (ArrayUtils.isEmpty(list)) { 15298 Log.i(TAG, "No secure containers found"); 15299 } else { 15300 // Process list of secure containers and categorize them 15301 // as active or stale based on their package internal state. 15302 15303 // reader 15304 synchronized (mPackages) { 15305 for (String cid : list) { 15306 // Leave stages untouched for now; installer service owns them 15307 if (PackageInstallerService.isStageName(cid)) continue; 15308 15309 if (DEBUG_SD_INSTALL) 15310 Log.i(TAG, "Processing container " + cid); 15311 String pkgName = getAsecPackageName(cid); 15312 if (pkgName == null) { 15313 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 15314 continue; 15315 } 15316 if (DEBUG_SD_INSTALL) 15317 Log.i(TAG, "Looking for pkg : " + pkgName); 15318 15319 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15320 if (ps == null) { 15321 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 15322 continue; 15323 } 15324 15325 /* 15326 * Skip packages that are not external if we're unmounting 15327 * external storage. 15328 */ 15329 if (externalStorage && !isMounted && !isExternal(ps)) { 15330 continue; 15331 } 15332 15333 final AsecInstallArgs args = new AsecInstallArgs(cid, 15334 getAppDexInstructionSets(ps), ps.isForwardLocked()); 15335 // The package status is changed only if the code path 15336 // matches between settings and the container id. 15337 if (ps.codePathString != null 15338 && ps.codePathString.startsWith(args.getCodePath())) { 15339 if (DEBUG_SD_INSTALL) { 15340 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 15341 + " at code path: " + ps.codePathString); 15342 } 15343 15344 // We do have a valid package installed on sdcard 15345 processCids.put(args, ps.codePathString); 15346 final int uid = ps.appId; 15347 if (uid != -1) { 15348 uidArr = ArrayUtils.appendInt(uidArr, uid); 15349 } 15350 } else { 15351 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 15352 + ps.codePathString); 15353 } 15354 } 15355 } 15356 15357 Arrays.sort(uidArr); 15358 } 15359 15360 // Process packages with valid entries. 15361 if (isMounted) { 15362 if (DEBUG_SD_INSTALL) 15363 Log.i(TAG, "Loading packages"); 15364 loadMediaPackages(processCids, uidArr); 15365 startCleaningPackages(); 15366 mInstallerService.onSecureContainersAvailable(); 15367 } else { 15368 if (DEBUG_SD_INSTALL) 15369 Log.i(TAG, "Unloading packages"); 15370 unloadMediaPackages(processCids, uidArr, reportStatus); 15371 } 15372 } 15373 15374 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15375 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 15376 final int size = infos.size(); 15377 final String[] packageNames = new String[size]; 15378 final int[] packageUids = new int[size]; 15379 for (int i = 0; i < size; i++) { 15380 final ApplicationInfo info = infos.get(i); 15381 packageNames[i] = info.packageName; 15382 packageUids[i] = info.uid; 15383 } 15384 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 15385 finishedReceiver); 15386 } 15387 15388 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15389 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15390 sendResourcesChangedBroadcast(mediaStatus, replacing, 15391 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 15392 } 15393 15394 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15395 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15396 int size = pkgList.length; 15397 if (size > 0) { 15398 // Send broadcasts here 15399 Bundle extras = new Bundle(); 15400 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 15401 if (uidArr != null) { 15402 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 15403 } 15404 if (replacing) { 15405 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 15406 } 15407 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 15408 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 15409 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 15410 } 15411 } 15412 15413 /* 15414 * Look at potentially valid container ids from processCids If package 15415 * information doesn't match the one on record or package scanning fails, 15416 * the cid is added to list of removeCids. We currently don't delete stale 15417 * containers. 15418 */ 15419 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 15420 ArrayList<String> pkgList = new ArrayList<String>(); 15421 Set<AsecInstallArgs> keys = processCids.keySet(); 15422 15423 for (AsecInstallArgs args : keys) { 15424 String codePath = processCids.get(args); 15425 if (DEBUG_SD_INSTALL) 15426 Log.i(TAG, "Loading container : " + args.cid); 15427 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15428 try { 15429 // Make sure there are no container errors first. 15430 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 15431 Slog.e(TAG, "Failed to mount cid : " + args.cid 15432 + " when installing from sdcard"); 15433 continue; 15434 } 15435 // Check code path here. 15436 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 15437 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 15438 + " does not match one in settings " + codePath); 15439 continue; 15440 } 15441 // Parse package 15442 int parseFlags = mDefParseFlags; 15443 if (args.isExternalAsec()) { 15444 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 15445 } 15446 if (args.isFwdLocked()) { 15447 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 15448 } 15449 15450 synchronized (mInstallLock) { 15451 PackageParser.Package pkg = null; 15452 try { 15453 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 15454 } catch (PackageManagerException e) { 15455 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 15456 } 15457 // Scan the package 15458 if (pkg != null) { 15459 /* 15460 * TODO why is the lock being held? doPostInstall is 15461 * called in other places without the lock. This needs 15462 * to be straightened out. 15463 */ 15464 // writer 15465 synchronized (mPackages) { 15466 retCode = PackageManager.INSTALL_SUCCEEDED; 15467 pkgList.add(pkg.packageName); 15468 // Post process args 15469 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 15470 pkg.applicationInfo.uid); 15471 } 15472 } else { 15473 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 15474 } 15475 } 15476 15477 } finally { 15478 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 15479 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 15480 } 15481 } 15482 } 15483 // writer 15484 synchronized (mPackages) { 15485 // If the platform SDK has changed since the last time we booted, 15486 // we need to re-grant app permission to catch any new ones that 15487 // appear. This is really a hack, and means that apps can in some 15488 // cases get permissions that the user didn't initially explicitly 15489 // allow... it would be nice to have some better way to handle 15490 // this situation. 15491 final VersionInfo ver = mSettings.getExternalVersion(); 15492 15493 int updateFlags = UPDATE_PERMISSIONS_ALL; 15494 if (ver.sdkVersion != mSdkVersion) { 15495 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 15496 + mSdkVersion + "; regranting permissions for external"); 15497 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 15498 } 15499 updatePermissionsLPw(null, null, updateFlags); 15500 15501 // Yay, everything is now upgraded 15502 ver.forceCurrent(); 15503 15504 // can downgrade to reader 15505 // Persist settings 15506 mSettings.writeLPr(); 15507 } 15508 // Send a broadcast to let everyone know we are done processing 15509 if (pkgList.size() > 0) { 15510 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 15511 } 15512 } 15513 15514 /* 15515 * Utility method to unload a list of specified containers 15516 */ 15517 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 15518 // Just unmount all valid containers. 15519 for (AsecInstallArgs arg : cidArgs) { 15520 synchronized (mInstallLock) { 15521 arg.doPostDeleteLI(false); 15522 } 15523 } 15524 } 15525 15526 /* 15527 * Unload packages mounted on external media. This involves deleting package 15528 * data from internal structures, sending broadcasts about diabled packages, 15529 * gc'ing to free up references, unmounting all secure containers 15530 * corresponding to packages on external media, and posting a 15531 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 15532 * that we always have to post this message if status has been requested no 15533 * matter what. 15534 */ 15535 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 15536 final boolean reportStatus) { 15537 if (DEBUG_SD_INSTALL) 15538 Log.i(TAG, "unloading media packages"); 15539 ArrayList<String> pkgList = new ArrayList<String>(); 15540 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 15541 final Set<AsecInstallArgs> keys = processCids.keySet(); 15542 for (AsecInstallArgs args : keys) { 15543 String pkgName = args.getPackageName(); 15544 if (DEBUG_SD_INSTALL) 15545 Log.i(TAG, "Trying to unload pkg : " + pkgName); 15546 // Delete package internally 15547 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15548 synchronized (mInstallLock) { 15549 boolean res = deletePackageLI(pkgName, null, false, null, null, 15550 PackageManager.DELETE_KEEP_DATA, outInfo, false); 15551 if (res) { 15552 pkgList.add(pkgName); 15553 } else { 15554 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 15555 failedList.add(args); 15556 } 15557 } 15558 } 15559 15560 // reader 15561 synchronized (mPackages) { 15562 // We didn't update the settings after removing each package; 15563 // write them now for all packages. 15564 mSettings.writeLPr(); 15565 } 15566 15567 // We have to absolutely send UPDATED_MEDIA_STATUS only 15568 // after confirming that all the receivers processed the ordered 15569 // broadcast when packages get disabled, force a gc to clean things up. 15570 // and unload all the containers. 15571 if (pkgList.size() > 0) { 15572 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 15573 new IIntentReceiver.Stub() { 15574 public void performReceive(Intent intent, int resultCode, String data, 15575 Bundle extras, boolean ordered, boolean sticky, 15576 int sendingUser) throws RemoteException { 15577 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 15578 reportStatus ? 1 : 0, 1, keys); 15579 mHandler.sendMessage(msg); 15580 } 15581 }); 15582 } else { 15583 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 15584 keys); 15585 mHandler.sendMessage(msg); 15586 } 15587 } 15588 15589 private void loadPrivatePackages(VolumeInfo vol) { 15590 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 15591 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 15592 synchronized (mInstallLock) { 15593 synchronized (mPackages) { 15594 final VersionInfo ver = mSettings.findOrCreateVersion(vol.fsUuid); 15595 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15596 for (PackageSetting ps : packages) { 15597 final PackageParser.Package pkg; 15598 try { 15599 pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null); 15600 loaded.add(pkg.applicationInfo); 15601 } catch (PackageManagerException e) { 15602 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 15603 } 15604 15605 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 15606 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 15607 } 15608 } 15609 15610 int updateFlags = UPDATE_PERMISSIONS_ALL; 15611 if (ver.sdkVersion != mSdkVersion) { 15612 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 15613 + mSdkVersion + "; regranting permissions for " + vol.fsUuid); 15614 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 15615 } 15616 updatePermissionsLPw(null, null, updateFlags); 15617 15618 // Yay, everything is now upgraded 15619 ver.forceCurrent(); 15620 15621 mSettings.writeLPr(); 15622 } 15623 } 15624 15625 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 15626 sendResourcesChangedBroadcast(true, false, loaded, null); 15627 } 15628 15629 private void unloadPrivatePackages(VolumeInfo vol) { 15630 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 15631 synchronized (mInstallLock) { 15632 synchronized (mPackages) { 15633 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15634 for (PackageSetting ps : packages) { 15635 if (ps.pkg == null) continue; 15636 15637 final ApplicationInfo info = ps.pkg.applicationInfo; 15638 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15639 if (deletePackageLI(ps.name, null, false, null, null, 15640 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 15641 unloaded.add(info); 15642 } else { 15643 Slog.w(TAG, "Failed to unload " + ps.codePath); 15644 } 15645 } 15646 15647 mSettings.writeLPr(); 15648 } 15649 } 15650 15651 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 15652 sendResourcesChangedBroadcast(false, false, unloaded, null); 15653 } 15654 15655 /** 15656 * Examine all users present on given mounted volume, and destroy data 15657 * belonging to users that are no longer valid, or whose user ID has been 15658 * recycled. 15659 */ 15660 private void reconcileUsers(String volumeUuid) { 15661 final File[] files = FileUtils 15662 .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid)); 15663 for (File file : files) { 15664 if (!file.isDirectory()) continue; 15665 15666 final int userId; 15667 final UserInfo info; 15668 try { 15669 userId = Integer.parseInt(file.getName()); 15670 info = sUserManager.getUserInfo(userId); 15671 } catch (NumberFormatException e) { 15672 Slog.w(TAG, "Invalid user directory " + file); 15673 continue; 15674 } 15675 15676 boolean destroyUser = false; 15677 if (info == null) { 15678 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15679 + " because no matching user was found"); 15680 destroyUser = true; 15681 } else { 15682 try { 15683 UserManagerService.enforceSerialNumber(file, info.serialNumber); 15684 } catch (IOException e) { 15685 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15686 + " because we failed to enforce serial number: " + e); 15687 destroyUser = true; 15688 } 15689 } 15690 15691 if (destroyUser) { 15692 synchronized (mInstallLock) { 15693 mInstaller.removeUserDataDirs(volumeUuid, userId); 15694 } 15695 } 15696 } 15697 15698 final UserManager um = mContext.getSystemService(UserManager.class); 15699 for (UserInfo user : um.getUsers()) { 15700 final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id); 15701 if (userDir.exists()) continue; 15702 15703 try { 15704 UserManagerService.prepareUserDirectory(mContext, volumeUuid, user.id); 15705 UserManagerService.enforceSerialNumber(userDir, user.serialNumber); 15706 } catch (IOException e) { 15707 Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e); 15708 } 15709 } 15710 } 15711 15712 /** 15713 * Examine all apps present on given mounted volume, and destroy apps that 15714 * aren't expected, either due to uninstallation or reinstallation on 15715 * another volume. 15716 */ 15717 private void reconcileApps(String volumeUuid) { 15718 final File[] files = FileUtils 15719 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 15720 for (File file : files) { 15721 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 15722 && !PackageInstallerService.isStageName(file.getName()); 15723 if (!isPackage) { 15724 // Ignore entries which are not packages 15725 continue; 15726 } 15727 15728 boolean destroyApp = false; 15729 String packageName = null; 15730 try { 15731 final PackageLite pkg = PackageParser.parsePackageLite(file, 15732 PackageParser.PARSE_MUST_BE_APK); 15733 packageName = pkg.packageName; 15734 15735 synchronized (mPackages) { 15736 final PackageSetting ps = mSettings.mPackages.get(packageName); 15737 if (ps == null) { 15738 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + " 15739 + volumeUuid + " because we found no install record"); 15740 destroyApp = true; 15741 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 15742 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on " 15743 + volumeUuid + " because we expected it on " + ps.volumeUuid); 15744 destroyApp = true; 15745 } 15746 } 15747 15748 } catch (PackageParserException e) { 15749 logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e); 15750 destroyApp = true; 15751 } 15752 15753 if (destroyApp) { 15754 synchronized (mInstallLock) { 15755 if (packageName != null) { 15756 removeDataDirsLI(volumeUuid, packageName); 15757 } 15758 if (file.isDirectory()) { 15759 mInstaller.rmPackageDir(file.getAbsolutePath()); 15760 } else { 15761 file.delete(); 15762 } 15763 } 15764 } 15765 } 15766 } 15767 15768 private void unfreezePackage(String packageName) { 15769 synchronized (mPackages) { 15770 final PackageSetting ps = mSettings.mPackages.get(packageName); 15771 if (ps != null) { 15772 ps.frozen = false; 15773 } 15774 } 15775 } 15776 15777 @Override 15778 public int movePackage(final String packageName, final String volumeUuid) { 15779 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15780 15781 final int moveId = mNextMoveId.getAndIncrement(); 15782 try { 15783 movePackageInternal(packageName, volumeUuid, moveId); 15784 } catch (PackageManagerException e) { 15785 Slog.w(TAG, "Failed to move " + packageName, e); 15786 mMoveCallbacks.notifyStatusChanged(moveId, 15787 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15788 } 15789 return moveId; 15790 } 15791 15792 private void movePackageInternal(final String packageName, final String volumeUuid, 15793 final int moveId) throws PackageManagerException { 15794 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 15795 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15796 final PackageManager pm = mContext.getPackageManager(); 15797 15798 final boolean currentAsec; 15799 final String currentVolumeUuid; 15800 final File codeFile; 15801 final String installerPackageName; 15802 final String packageAbiOverride; 15803 final int appId; 15804 final String seinfo; 15805 final String label; 15806 15807 // reader 15808 synchronized (mPackages) { 15809 final PackageParser.Package pkg = mPackages.get(packageName); 15810 final PackageSetting ps = mSettings.mPackages.get(packageName); 15811 if (pkg == null || ps == null) { 15812 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 15813 } 15814 15815 if (pkg.applicationInfo.isSystemApp()) { 15816 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 15817 "Cannot move system application"); 15818 } 15819 15820 if (Objects.equals(ps.volumeUuid, volumeUuid)) { 15821 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15822 "Package already moved to " + volumeUuid); 15823 } 15824 15825 final File probe = new File(pkg.codePath); 15826 final File probeOat = new File(probe, "oat"); 15827 if (!probe.isDirectory() || !probeOat.isDirectory()) { 15828 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15829 "Move only supported for modern cluster style installs"); 15830 } 15831 15832 if (ps.frozen) { 15833 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 15834 "Failed to move already frozen package"); 15835 } 15836 ps.frozen = true; 15837 15838 currentAsec = pkg.applicationInfo.isForwardLocked() 15839 || pkg.applicationInfo.isExternalAsec(); 15840 currentVolumeUuid = ps.volumeUuid; 15841 codeFile = new File(pkg.codePath); 15842 installerPackageName = ps.installerPackageName; 15843 packageAbiOverride = ps.cpuAbiOverrideString; 15844 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 15845 seinfo = pkg.applicationInfo.seinfo; 15846 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 15847 } 15848 15849 // Now that we're guarded by frozen state, kill app during move 15850 final long token = Binder.clearCallingIdentity(); 15851 try { 15852 killApplication(packageName, appId, "move pkg"); 15853 } finally { 15854 Binder.restoreCallingIdentity(token); 15855 } 15856 15857 final Bundle extras = new Bundle(); 15858 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 15859 extras.putString(Intent.EXTRA_TITLE, label); 15860 mMoveCallbacks.notifyCreated(moveId, extras); 15861 15862 int installFlags; 15863 final boolean moveCompleteApp; 15864 final File measurePath; 15865 15866 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 15867 installFlags = INSTALL_INTERNAL; 15868 moveCompleteApp = !currentAsec; 15869 measurePath = Environment.getDataAppDirectory(volumeUuid); 15870 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 15871 installFlags = INSTALL_EXTERNAL; 15872 moveCompleteApp = false; 15873 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 15874 } else { 15875 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 15876 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 15877 || !volume.isMountedWritable()) { 15878 unfreezePackage(packageName); 15879 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15880 "Move location not mounted private volume"); 15881 } 15882 15883 Preconditions.checkState(!currentAsec); 15884 15885 installFlags = INSTALL_INTERNAL; 15886 moveCompleteApp = true; 15887 measurePath = Environment.getDataAppDirectory(volumeUuid); 15888 } 15889 15890 final PackageStats stats = new PackageStats(null, -1); 15891 synchronized (mInstaller) { 15892 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 15893 unfreezePackage(packageName); 15894 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15895 "Failed to measure package size"); 15896 } 15897 } 15898 15899 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 15900 + stats.dataSize); 15901 15902 final long startFreeBytes = measurePath.getFreeSpace(); 15903 final long sizeBytes; 15904 if (moveCompleteApp) { 15905 sizeBytes = stats.codeSize + stats.dataSize; 15906 } else { 15907 sizeBytes = stats.codeSize; 15908 } 15909 15910 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 15911 unfreezePackage(packageName); 15912 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15913 "Not enough free space to move"); 15914 } 15915 15916 mMoveCallbacks.notifyStatusChanged(moveId, 10); 15917 15918 final CountDownLatch installedLatch = new CountDownLatch(1); 15919 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 15920 @Override 15921 public void onUserActionRequired(Intent intent) throws RemoteException { 15922 throw new IllegalStateException(); 15923 } 15924 15925 @Override 15926 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 15927 Bundle extras) throws RemoteException { 15928 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 15929 + PackageManager.installStatusToString(returnCode, msg)); 15930 15931 installedLatch.countDown(); 15932 15933 // Regardless of success or failure of the move operation, 15934 // always unfreeze the package 15935 unfreezePackage(packageName); 15936 15937 final int status = PackageManager.installStatusToPublicStatus(returnCode); 15938 switch (status) { 15939 case PackageInstaller.STATUS_SUCCESS: 15940 mMoveCallbacks.notifyStatusChanged(moveId, 15941 PackageManager.MOVE_SUCCEEDED); 15942 break; 15943 case PackageInstaller.STATUS_FAILURE_STORAGE: 15944 mMoveCallbacks.notifyStatusChanged(moveId, 15945 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 15946 break; 15947 default: 15948 mMoveCallbacks.notifyStatusChanged(moveId, 15949 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15950 break; 15951 } 15952 } 15953 }; 15954 15955 final MoveInfo move; 15956 if (moveCompleteApp) { 15957 // Kick off a thread to report progress estimates 15958 new Thread() { 15959 @Override 15960 public void run() { 15961 while (true) { 15962 try { 15963 if (installedLatch.await(1, TimeUnit.SECONDS)) { 15964 break; 15965 } 15966 } catch (InterruptedException ignored) { 15967 } 15968 15969 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 15970 final int progress = 10 + (int) MathUtils.constrain( 15971 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 15972 mMoveCallbacks.notifyStatusChanged(moveId, progress); 15973 } 15974 } 15975 }.start(); 15976 15977 final String dataAppName = codeFile.getName(); 15978 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 15979 dataAppName, appId, seinfo); 15980 } else { 15981 move = null; 15982 } 15983 15984 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 15985 15986 final Message msg = mHandler.obtainMessage(INIT_COPY); 15987 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 15988 msg.obj = new InstallParams(origin, move, installObserver, installFlags, 15989 installerPackageName, volumeUuid, null, user, packageAbiOverride, null); 15990 mHandler.sendMessage(msg); 15991 } 15992 15993 @Override 15994 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 15995 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15996 15997 final int realMoveId = mNextMoveId.getAndIncrement(); 15998 final Bundle extras = new Bundle(); 15999 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 16000 mMoveCallbacks.notifyCreated(realMoveId, extras); 16001 16002 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 16003 @Override 16004 public void onCreated(int moveId, Bundle extras) { 16005 // Ignored 16006 } 16007 16008 @Override 16009 public void onStatusChanged(int moveId, int status, long estMillis) { 16010 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 16011 } 16012 }; 16013 16014 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16015 storage.setPrimaryStorageUuid(volumeUuid, callback); 16016 return realMoveId; 16017 } 16018 16019 @Override 16020 public int getMoveStatus(int moveId) { 16021 mContext.enforceCallingOrSelfPermission( 16022 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16023 return mMoveCallbacks.mLastStatus.get(moveId); 16024 } 16025 16026 @Override 16027 public void registerMoveCallback(IPackageMoveObserver callback) { 16028 mContext.enforceCallingOrSelfPermission( 16029 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16030 mMoveCallbacks.register(callback); 16031 } 16032 16033 @Override 16034 public void unregisterMoveCallback(IPackageMoveObserver callback) { 16035 mContext.enforceCallingOrSelfPermission( 16036 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16037 mMoveCallbacks.unregister(callback); 16038 } 16039 16040 @Override 16041 public boolean setInstallLocation(int loc) { 16042 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 16043 null); 16044 if (getInstallLocation() == loc) { 16045 return true; 16046 } 16047 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 16048 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 16049 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 16050 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 16051 return true; 16052 } 16053 return false; 16054 } 16055 16056 @Override 16057 public int getInstallLocation() { 16058 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 16059 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 16060 PackageHelper.APP_INSTALL_AUTO); 16061 } 16062 16063 /** Called by UserManagerService */ 16064 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 16065 mDirtyUsers.remove(userHandle); 16066 mSettings.removeUserLPw(userHandle); 16067 mPendingBroadcasts.remove(userHandle); 16068 if (mInstaller != null) { 16069 // Technically, we shouldn't be doing this with the package lock 16070 // held. However, this is very rare, and there is already so much 16071 // other disk I/O going on, that we'll let it slide for now. 16072 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16073 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 16074 final String volumeUuid = vol.getFsUuid(); 16075 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 16076 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 16077 } 16078 } 16079 mUserNeedsBadging.delete(userHandle); 16080 removeUnusedPackagesLILPw(userManager, userHandle); 16081 } 16082 16083 /** 16084 * We're removing userHandle and would like to remove any downloaded packages 16085 * that are no longer in use by any other user. 16086 * @param userHandle the user being removed 16087 */ 16088 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 16089 final boolean DEBUG_CLEAN_APKS = false; 16090 int [] users = userManager.getUserIdsLPr(); 16091 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 16092 while (psit.hasNext()) { 16093 PackageSetting ps = psit.next(); 16094 if (ps.pkg == null) { 16095 continue; 16096 } 16097 final String packageName = ps.pkg.packageName; 16098 // Skip over if system app 16099 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 16100 continue; 16101 } 16102 if (DEBUG_CLEAN_APKS) { 16103 Slog.i(TAG, "Checking package " + packageName); 16104 } 16105 boolean keep = false; 16106 for (int i = 0; i < users.length; i++) { 16107 if (users[i] != userHandle && ps.getInstalled(users[i])) { 16108 keep = true; 16109 if (DEBUG_CLEAN_APKS) { 16110 Slog.i(TAG, " Keeping package " + packageName + " for user " 16111 + users[i]); 16112 } 16113 break; 16114 } 16115 } 16116 if (!keep) { 16117 if (DEBUG_CLEAN_APKS) { 16118 Slog.i(TAG, " Removing package " + packageName); 16119 } 16120 mHandler.post(new Runnable() { 16121 public void run() { 16122 deletePackageX(packageName, userHandle, 0); 16123 } //end run 16124 }); 16125 } 16126 } 16127 } 16128 16129 /** Called by UserManagerService */ 16130 void createNewUserLILPw(int userHandle) { 16131 if (mInstaller != null) { 16132 mInstaller.createUserConfig(userHandle); 16133 mSettings.createNewUserLILPw(this, mInstaller, userHandle); 16134 applyFactoryDefaultBrowserLPw(userHandle); 16135 primeDomainVerificationsLPw(userHandle); 16136 } 16137 } 16138 16139 void newUserCreated(final int userHandle) { 16140 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 16141 } 16142 16143 @Override 16144 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 16145 mContext.enforceCallingOrSelfPermission( 16146 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 16147 "Only package verification agents can read the verifier device identity"); 16148 16149 synchronized (mPackages) { 16150 return mSettings.getVerifierDeviceIdentityLPw(); 16151 } 16152 } 16153 16154 @Override 16155 public void setPermissionEnforced(String permission, boolean enforced) { 16156 // TODO: Now that we no longer change GID for storage, this should to away. 16157 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 16158 "setPermissionEnforced"); 16159 if (READ_EXTERNAL_STORAGE.equals(permission)) { 16160 synchronized (mPackages) { 16161 if (mSettings.mReadExternalStorageEnforced == null 16162 || mSettings.mReadExternalStorageEnforced != enforced) { 16163 mSettings.mReadExternalStorageEnforced = enforced; 16164 mSettings.writeLPr(); 16165 } 16166 } 16167 // kill any non-foreground processes so we restart them and 16168 // grant/revoke the GID. 16169 final IActivityManager am = ActivityManagerNative.getDefault(); 16170 if (am != null) { 16171 final long token = Binder.clearCallingIdentity(); 16172 try { 16173 am.killProcessesBelowForeground("setPermissionEnforcement"); 16174 } catch (RemoteException e) { 16175 } finally { 16176 Binder.restoreCallingIdentity(token); 16177 } 16178 } 16179 } else { 16180 throw new IllegalArgumentException("No selective enforcement for " + permission); 16181 } 16182 } 16183 16184 @Override 16185 @Deprecated 16186 public boolean isPermissionEnforced(String permission) { 16187 return true; 16188 } 16189 16190 @Override 16191 public boolean isStorageLow() { 16192 final long token = Binder.clearCallingIdentity(); 16193 try { 16194 final DeviceStorageMonitorInternal 16195 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 16196 if (dsm != null) { 16197 return dsm.isMemoryLow(); 16198 } else { 16199 return false; 16200 } 16201 } finally { 16202 Binder.restoreCallingIdentity(token); 16203 } 16204 } 16205 16206 @Override 16207 public IPackageInstaller getPackageInstaller() { 16208 return mInstallerService; 16209 } 16210 16211 private boolean userNeedsBadging(int userId) { 16212 int index = mUserNeedsBadging.indexOfKey(userId); 16213 if (index < 0) { 16214 final UserInfo userInfo; 16215 final long token = Binder.clearCallingIdentity(); 16216 try { 16217 userInfo = sUserManager.getUserInfo(userId); 16218 } finally { 16219 Binder.restoreCallingIdentity(token); 16220 } 16221 final boolean b; 16222 if (userInfo != null && userInfo.isManagedProfile()) { 16223 b = true; 16224 } else { 16225 b = false; 16226 } 16227 mUserNeedsBadging.put(userId, b); 16228 return b; 16229 } 16230 return mUserNeedsBadging.valueAt(index); 16231 } 16232 16233 @Override 16234 public KeySet getKeySetByAlias(String packageName, String alias) { 16235 if (packageName == null || alias == null) { 16236 return null; 16237 } 16238 synchronized(mPackages) { 16239 final PackageParser.Package pkg = mPackages.get(packageName); 16240 if (pkg == null) { 16241 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16242 throw new IllegalArgumentException("Unknown package: " + packageName); 16243 } 16244 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16245 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 16246 } 16247 } 16248 16249 @Override 16250 public KeySet getSigningKeySet(String packageName) { 16251 if (packageName == null) { 16252 return null; 16253 } 16254 synchronized(mPackages) { 16255 final PackageParser.Package pkg = mPackages.get(packageName); 16256 if (pkg == null) { 16257 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16258 throw new IllegalArgumentException("Unknown package: " + packageName); 16259 } 16260 if (pkg.applicationInfo.uid != Binder.getCallingUid() 16261 && Process.SYSTEM_UID != Binder.getCallingUid()) { 16262 throw new SecurityException("May not access signing KeySet of other apps."); 16263 } 16264 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16265 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 16266 } 16267 } 16268 16269 @Override 16270 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 16271 if (packageName == null || ks == null) { 16272 return false; 16273 } 16274 synchronized(mPackages) { 16275 final PackageParser.Package pkg = mPackages.get(packageName); 16276 if (pkg == null) { 16277 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16278 throw new IllegalArgumentException("Unknown package: " + packageName); 16279 } 16280 IBinder ksh = ks.getToken(); 16281 if (ksh instanceof KeySetHandle) { 16282 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16283 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 16284 } 16285 return false; 16286 } 16287 } 16288 16289 @Override 16290 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 16291 if (packageName == null || ks == null) { 16292 return false; 16293 } 16294 synchronized(mPackages) { 16295 final PackageParser.Package pkg = mPackages.get(packageName); 16296 if (pkg == null) { 16297 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16298 throw new IllegalArgumentException("Unknown package: " + packageName); 16299 } 16300 IBinder ksh = ks.getToken(); 16301 if (ksh instanceof KeySetHandle) { 16302 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16303 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 16304 } 16305 return false; 16306 } 16307 } 16308 16309 public void getUsageStatsIfNoPackageUsageInfo() { 16310 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 16311 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 16312 if (usm == null) { 16313 throw new IllegalStateException("UsageStatsManager must be initialized"); 16314 } 16315 long now = System.currentTimeMillis(); 16316 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 16317 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 16318 String packageName = entry.getKey(); 16319 PackageParser.Package pkg = mPackages.get(packageName); 16320 if (pkg == null) { 16321 continue; 16322 } 16323 UsageStats usage = entry.getValue(); 16324 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 16325 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 16326 } 16327 } 16328 } 16329 16330 /** 16331 * Check and throw if the given before/after packages would be considered a 16332 * downgrade. 16333 */ 16334 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 16335 throws PackageManagerException { 16336 if (after.versionCode < before.mVersionCode) { 16337 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16338 "Update version code " + after.versionCode + " is older than current " 16339 + before.mVersionCode); 16340 } else if (after.versionCode == before.mVersionCode) { 16341 if (after.baseRevisionCode < before.baseRevisionCode) { 16342 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16343 "Update base revision code " + after.baseRevisionCode 16344 + " is older than current " + before.baseRevisionCode); 16345 } 16346 16347 if (!ArrayUtils.isEmpty(after.splitNames)) { 16348 for (int i = 0; i < after.splitNames.length; i++) { 16349 final String splitName = after.splitNames[i]; 16350 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 16351 if (j != -1) { 16352 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 16353 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16354 "Update split " + splitName + " revision code " 16355 + after.splitRevisionCodes[i] + " is older than current " 16356 + before.splitRevisionCodes[j]); 16357 } 16358 } 16359 } 16360 } 16361 } 16362 } 16363 16364 private static class MoveCallbacks extends Handler { 16365 private static final int MSG_CREATED = 1; 16366 private static final int MSG_STATUS_CHANGED = 2; 16367 16368 private final RemoteCallbackList<IPackageMoveObserver> 16369 mCallbacks = new RemoteCallbackList<>(); 16370 16371 private final SparseIntArray mLastStatus = new SparseIntArray(); 16372 16373 public MoveCallbacks(Looper looper) { 16374 super(looper); 16375 } 16376 16377 public void register(IPackageMoveObserver callback) { 16378 mCallbacks.register(callback); 16379 } 16380 16381 public void unregister(IPackageMoveObserver callback) { 16382 mCallbacks.unregister(callback); 16383 } 16384 16385 @Override 16386 public void handleMessage(Message msg) { 16387 final SomeArgs args = (SomeArgs) msg.obj; 16388 final int n = mCallbacks.beginBroadcast(); 16389 for (int i = 0; i < n; i++) { 16390 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 16391 try { 16392 invokeCallback(callback, msg.what, args); 16393 } catch (RemoteException ignored) { 16394 } 16395 } 16396 mCallbacks.finishBroadcast(); 16397 args.recycle(); 16398 } 16399 16400 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 16401 throws RemoteException { 16402 switch (what) { 16403 case MSG_CREATED: { 16404 callback.onCreated(args.argi1, (Bundle) args.arg2); 16405 break; 16406 } 16407 case MSG_STATUS_CHANGED: { 16408 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 16409 break; 16410 } 16411 } 16412 } 16413 16414 private void notifyCreated(int moveId, Bundle extras) { 16415 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 16416 16417 final SomeArgs args = SomeArgs.obtain(); 16418 args.argi1 = moveId; 16419 args.arg2 = extras; 16420 obtainMessage(MSG_CREATED, args).sendToTarget(); 16421 } 16422 16423 private void notifyStatusChanged(int moveId, int status) { 16424 notifyStatusChanged(moveId, status, -1); 16425 } 16426 16427 private void notifyStatusChanged(int moveId, int status, long estMillis) { 16428 Slog.v(TAG, "Move " + moveId + " status " + status); 16429 16430 final SomeArgs args = SomeArgs.obtain(); 16431 args.argi1 = moveId; 16432 args.argi2 = status; 16433 args.arg3 = estMillis; 16434 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 16435 16436 synchronized (mLastStatus) { 16437 mLastStatus.put(moveId, status); 16438 } 16439 } 16440 } 16441 16442 private final class OnPermissionChangeListeners extends Handler { 16443 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 16444 16445 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 16446 new RemoteCallbackList<>(); 16447 16448 public OnPermissionChangeListeners(Looper looper) { 16449 super(looper); 16450 } 16451 16452 @Override 16453 public void handleMessage(Message msg) { 16454 switch (msg.what) { 16455 case MSG_ON_PERMISSIONS_CHANGED: { 16456 final int uid = msg.arg1; 16457 handleOnPermissionsChanged(uid); 16458 } break; 16459 } 16460 } 16461 16462 public void addListenerLocked(IOnPermissionsChangeListener listener) { 16463 mPermissionListeners.register(listener); 16464 16465 } 16466 16467 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 16468 mPermissionListeners.unregister(listener); 16469 } 16470 16471 public void onPermissionsChanged(int uid) { 16472 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 16473 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 16474 } 16475 } 16476 16477 private void handleOnPermissionsChanged(int uid) { 16478 final int count = mPermissionListeners.beginBroadcast(); 16479 try { 16480 for (int i = 0; i < count; i++) { 16481 IOnPermissionsChangeListener callback = mPermissionListeners 16482 .getBroadcastItem(i); 16483 try { 16484 callback.onPermissionsChanged(uid); 16485 } catch (RemoteException e) { 16486 Log.e(TAG, "Permission listener is dead", e); 16487 } 16488 } 16489 } finally { 16490 mPermissionListeners.finishBroadcast(); 16491 } 16492 } 16493 } 16494 16495 private class PackageManagerInternalImpl extends PackageManagerInternal { 16496 @Override 16497 public void setLocationPackagesProvider(PackagesProvider provider) { 16498 synchronized (mPackages) { 16499 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 16500 } 16501 } 16502 16503 @Override 16504 public void setImePackagesProvider(PackagesProvider provider) { 16505 synchronized (mPackages) { 16506 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 16507 } 16508 } 16509 16510 @Override 16511 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 16512 synchronized (mPackages) { 16513 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 16514 } 16515 } 16516 16517 @Override 16518 public void setSmsAppPackagesProvider(PackagesProvider provider) { 16519 synchronized (mPackages) { 16520 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 16521 } 16522 } 16523 16524 @Override 16525 public void setDialerAppPackagesProvider(PackagesProvider provider) { 16526 synchronized (mPackages) { 16527 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 16528 } 16529 } 16530 16531 @Override 16532 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 16533 synchronized (mPackages) { 16534 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 16535 } 16536 } 16537 16538 @Override 16539 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 16540 synchronized (mPackages) { 16541 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 16542 packageName, userId); 16543 } 16544 } 16545 16546 @Override 16547 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 16548 synchronized (mPackages) { 16549 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 16550 packageName, userId); 16551 } 16552 } 16553 } 16554 16555 @Override 16556 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 16557 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 16558 synchronized (mPackages) { 16559 final long identity = Binder.clearCallingIdentity(); 16560 try { 16561 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 16562 packageNames, userId); 16563 } finally { 16564 Binder.restoreCallingIdentity(identity); 16565 } 16566 } 16567 } 16568 16569 private static void enforceSystemOrPhoneCaller(String tag) { 16570 int callingUid = Binder.getCallingUid(); 16571 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 16572 throw new SecurityException( 16573 "Cannot call " + tag + " from UID " + callingUid); 16574 } 16575 } 16576} 16577