PackageManagerService.java revision 525bc7a5a68cf2bf5159780ebb66ca4a3bf600ee
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_REPLACING = 1<<11; 327 static final int SCAN_REQUIRE_KNOWN = 1<<12; 328 static final int SCAN_MOVE = 1<<13; 329 static final int SCAN_INITIAL = 1<<14; 330 331 static final int REMOVE_CHATTY = 1<<16; 332 333 private static final int[] EMPTY_INT_ARRAY = new int[0]; 334 335 /** 336 * Timeout (in milliseconds) after which the watchdog should declare that 337 * our handler thread is wedged. The usual default for such things is one 338 * minute but we sometimes do very lengthy I/O operations on this thread, 339 * such as installing multi-gigabyte applications, so ours needs to be longer. 340 */ 341 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 342 343 /** 344 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 345 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 346 * settings entry if available, otherwise we use the hardcoded default. If it's been 347 * more than this long since the last fstrim, we force one during the boot sequence. 348 * 349 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 350 * one gets run at the next available charging+idle time. This final mandatory 351 * no-fstrim check kicks in only of the other scheduling criteria is never met. 352 */ 353 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 354 355 /** 356 * Whether verification is enabled by default. 357 */ 358 private static final boolean DEFAULT_VERIFY_ENABLE = true; 359 360 /** 361 * The default maximum time to wait for the verification agent to return in 362 * milliseconds. 363 */ 364 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 365 366 /** 367 * The default response for package verification timeout. 368 * 369 * This can be either PackageManager.VERIFICATION_ALLOW or 370 * PackageManager.VERIFICATION_REJECT. 371 */ 372 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 373 374 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 375 376 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 377 DEFAULT_CONTAINER_PACKAGE, 378 "com.android.defcontainer.DefaultContainerService"); 379 380 private static final String KILL_APP_REASON_GIDS_CHANGED = 381 "permission grant or revoke changed gids"; 382 383 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 384 "permissions revoked"; 385 386 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 387 388 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 389 390 /** Permission grant: not grant the permission. */ 391 private static final int GRANT_DENIED = 1; 392 393 /** Permission grant: grant the permission as an install permission. */ 394 private static final int GRANT_INSTALL = 2; 395 396 /** Permission grant: grant the permission as an install permission for a legacy app. */ 397 private static final int GRANT_INSTALL_LEGACY = 3; 398 399 /** Permission grant: grant the permission as a runtime one. */ 400 private static final int GRANT_RUNTIME = 4; 401 402 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 403 private static final int GRANT_UPGRADE = 5; 404 405 /** Canonical intent used to identify what counts as a "web browser" app */ 406 private static final Intent sBrowserIntent; 407 static { 408 sBrowserIntent = new Intent(); 409 sBrowserIntent.setAction(Intent.ACTION_VIEW); 410 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 411 sBrowserIntent.setData(Uri.parse("http:")); 412 } 413 414 final ServiceThread mHandlerThread; 415 416 final PackageHandler mHandler; 417 418 /** 419 * Messages for {@link #mHandler} that need to wait for system ready before 420 * being dispatched. 421 */ 422 private ArrayList<Message> mPostSystemReadyMessages; 423 424 final int mSdkVersion = Build.VERSION.SDK_INT; 425 426 final Context mContext; 427 final boolean mFactoryTest; 428 final boolean mOnlyCore; 429 final boolean mLazyDexOpt; 430 final long mDexOptLRUThresholdInMills; 431 final DisplayMetrics mMetrics; 432 final int mDefParseFlags; 433 final String[] mSeparateProcesses; 434 final boolean mIsUpgrade; 435 436 // This is where all application persistent data goes. 437 final File mAppDataDir; 438 439 // This is where all application persistent data goes for secondary users. 440 final File mUserAppDataDir; 441 442 /** The location for ASEC container files on internal storage. */ 443 final String mAsecInternalPath; 444 445 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 446 // LOCK HELD. Can be called with mInstallLock held. 447 @GuardedBy("mInstallLock") 448 final Installer mInstaller; 449 450 /** Directory where installed third-party apps stored */ 451 final File mAppInstallDir; 452 453 /** 454 * Directory to which applications installed internally have their 455 * 32 bit native libraries copied. 456 */ 457 private File mAppLib32InstallDir; 458 459 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 460 // apps. 461 final File mDrmAppPrivateInstallDir; 462 463 // ---------------------------------------------------------------- 464 465 // Lock for state used when installing and doing other long running 466 // operations. Methods that must be called with this lock held have 467 // the suffix "LI". 468 final Object mInstallLock = new Object(); 469 470 // ---------------------------------------------------------------- 471 472 // Keys are String (package name), values are Package. This also serves 473 // as the lock for the global state. Methods that must be called with 474 // this lock held have the prefix "LP". 475 @GuardedBy("mPackages") 476 final ArrayMap<String, PackageParser.Package> mPackages = 477 new ArrayMap<String, PackageParser.Package>(); 478 479 // Tracks available target package names -> overlay package paths. 480 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 481 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 482 483 /** 484 * Tracks new system packages [receiving in an OTA] that we expect to 485 * find updated user-installed versions. Keys are package name, values 486 * are package location. 487 */ 488 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 489 490 final Settings mSettings; 491 boolean mRestoredSettings; 492 493 // System configuration read by SystemConfig. 494 final int[] mGlobalGids; 495 final SparseArray<ArraySet<String>> mSystemPermissions; 496 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 497 498 // If mac_permissions.xml was found for seinfo labeling. 499 boolean mFoundPolicyFile; 500 501 // If a recursive restorecon of /data/data/<pkg> is needed. 502 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 503 504 public static final class SharedLibraryEntry { 505 public final String path; 506 public final String apk; 507 508 SharedLibraryEntry(String _path, String _apk) { 509 path = _path; 510 apk = _apk; 511 } 512 } 513 514 // Currently known shared libraries. 515 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 516 new ArrayMap<String, SharedLibraryEntry>(); 517 518 // All available activities, for your resolving pleasure. 519 final ActivityIntentResolver mActivities = 520 new ActivityIntentResolver(); 521 522 // All available receivers, for your resolving pleasure. 523 final ActivityIntentResolver mReceivers = 524 new ActivityIntentResolver(); 525 526 // All available services, for your resolving pleasure. 527 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 528 529 // All available providers, for your resolving pleasure. 530 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 531 532 // Mapping from provider base names (first directory in content URI codePath) 533 // to the provider information. 534 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 535 new ArrayMap<String, PackageParser.Provider>(); 536 537 // Mapping from instrumentation class names to info about them. 538 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 539 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 540 541 // Mapping from permission names to info about them. 542 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 543 new ArrayMap<String, PackageParser.PermissionGroup>(); 544 545 // Packages whose data we have transfered into another package, thus 546 // should no longer exist. 547 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 548 549 // Broadcast actions that are only available to the system. 550 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 551 552 /** List of packages waiting for verification. */ 553 final SparseArray<PackageVerificationState> mPendingVerification 554 = new SparseArray<PackageVerificationState>(); 555 556 /** Set of packages associated with each app op permission. */ 557 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 558 559 final PackageInstallerService mInstallerService; 560 561 private final PackageDexOptimizer mPackageDexOptimizer; 562 563 private AtomicInteger mNextMoveId = new AtomicInteger(); 564 private final MoveCallbacks mMoveCallbacks; 565 566 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 567 568 // Cache of users who need badging. 569 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 570 571 /** Token for keys in mPendingVerification. */ 572 private int mPendingVerificationToken = 0; 573 574 volatile boolean mSystemReady; 575 volatile boolean mSafeMode; 576 volatile boolean mHasSystemUidErrors; 577 578 ApplicationInfo mAndroidApplication; 579 final ActivityInfo mResolveActivity = new ActivityInfo(); 580 final ResolveInfo mResolveInfo = new ResolveInfo(); 581 ComponentName mResolveComponentName; 582 PackageParser.Package mPlatformPackage; 583 ComponentName mCustomResolverComponentName; 584 585 boolean mResolverReplaced = false; 586 587 private final ComponentName mIntentFilterVerifierComponent; 588 private int mIntentFilterVerificationToken = 0; 589 590 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 591 = new SparseArray<IntentFilterVerificationState>(); 592 593 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 594 new DefaultPermissionGrantPolicy(this); 595 596 private static class IFVerificationParams { 597 PackageParser.Package pkg; 598 boolean replacing; 599 int userId; 600 int verifierUid; 601 602 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 603 int _userId, int _verifierUid) { 604 pkg = _pkg; 605 replacing = _replacing; 606 userId = _userId; 607 replacing = _replacing; 608 verifierUid = _verifierUid; 609 } 610 } 611 612 private interface IntentFilterVerifier<T extends IntentFilter> { 613 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 614 T filter, String packageName); 615 void startVerifications(int userId); 616 void receiveVerificationResponse(int verificationId); 617 } 618 619 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 620 private Context mContext; 621 private ComponentName mIntentFilterVerifierComponent; 622 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 623 624 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 625 mContext = context; 626 mIntentFilterVerifierComponent = verifierComponent; 627 } 628 629 private String getDefaultScheme() { 630 return IntentFilter.SCHEME_HTTPS; 631 } 632 633 @Override 634 public void startVerifications(int userId) { 635 // Launch verifications requests 636 int count = mCurrentIntentFilterVerifications.size(); 637 for (int n=0; n<count; n++) { 638 int verificationId = mCurrentIntentFilterVerifications.get(n); 639 final IntentFilterVerificationState ivs = 640 mIntentFilterVerificationStates.get(verificationId); 641 642 String packageName = ivs.getPackageName(); 643 644 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 645 final int filterCount = filters.size(); 646 ArraySet<String> domainsSet = new ArraySet<>(); 647 for (int m=0; m<filterCount; m++) { 648 PackageParser.ActivityIntentInfo filter = filters.get(m); 649 domainsSet.addAll(filter.getHostsList()); 650 } 651 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 652 synchronized (mPackages) { 653 if (mSettings.createIntentFilterVerificationIfNeededLPw( 654 packageName, domainsList) != null) { 655 scheduleWriteSettingsLocked(); 656 } 657 } 658 sendVerificationRequest(userId, verificationId, ivs); 659 } 660 mCurrentIntentFilterVerifications.clear(); 661 } 662 663 private void sendVerificationRequest(int userId, int verificationId, 664 IntentFilterVerificationState ivs) { 665 666 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 667 verificationIntent.putExtra( 668 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 669 verificationId); 670 verificationIntent.putExtra( 671 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 672 getDefaultScheme()); 673 verificationIntent.putExtra( 674 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 675 ivs.getHostsString()); 676 verificationIntent.putExtra( 677 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 678 ivs.getPackageName()); 679 verificationIntent.setComponent(mIntentFilterVerifierComponent); 680 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 681 682 UserHandle user = new UserHandle(userId); 683 mContext.sendBroadcastAsUser(verificationIntent, user); 684 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 685 "Sending IntentFilter verification broadcast"); 686 } 687 688 public void receiveVerificationResponse(int verificationId) { 689 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 690 691 final boolean verified = ivs.isVerified(); 692 693 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 694 final int count = filters.size(); 695 if (DEBUG_DOMAIN_VERIFICATION) { 696 Slog.i(TAG, "Received verification response " + verificationId 697 + " for " + count + " filters, verified=" + verified); 698 } 699 for (int n=0; n<count; n++) { 700 PackageParser.ActivityIntentInfo filter = filters.get(n); 701 filter.setVerified(verified); 702 703 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 704 + " verified with result:" + verified + " and hosts:" 705 + ivs.getHostsString()); 706 } 707 708 mIntentFilterVerificationStates.remove(verificationId); 709 710 final String packageName = ivs.getPackageName(); 711 IntentFilterVerificationInfo ivi = null; 712 713 synchronized (mPackages) { 714 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 715 } 716 if (ivi == null) { 717 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 718 + verificationId + " packageName:" + packageName); 719 return; 720 } 721 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 722 "Updating IntentFilterVerificationInfo for package " + packageName 723 +" verificationId:" + verificationId); 724 725 synchronized (mPackages) { 726 if (verified) { 727 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 728 } else { 729 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 730 } 731 scheduleWriteSettingsLocked(); 732 733 final int userId = ivs.getUserId(); 734 if (userId != UserHandle.USER_ALL) { 735 final int userStatus = 736 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 737 738 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 739 boolean needUpdate = false; 740 741 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 742 // already been set by the User thru the Disambiguation dialog 743 switch (userStatus) { 744 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 745 if (verified) { 746 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 747 } else { 748 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 749 } 750 needUpdate = true; 751 break; 752 753 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 754 if (verified) { 755 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 756 needUpdate = true; 757 } 758 break; 759 760 default: 761 // Nothing to do 762 } 763 764 if (needUpdate) { 765 mSettings.updateIntentFilterVerificationStatusLPw( 766 packageName, updatedStatus, userId); 767 scheduleWritePackageRestrictionsLocked(userId); 768 } 769 } 770 } 771 } 772 773 @Override 774 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 775 ActivityIntentInfo filter, String packageName) { 776 if (!hasValidDomains(filter)) { 777 return false; 778 } 779 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 780 if (ivs == null) { 781 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 782 packageName); 783 } 784 if (DEBUG_DOMAIN_VERIFICATION) { 785 Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter); 786 } 787 ivs.addFilter(filter); 788 return true; 789 } 790 791 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 792 int userId, int verificationId, String packageName) { 793 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 794 verifierUid, userId, packageName); 795 ivs.setPendingState(); 796 synchronized (mPackages) { 797 mIntentFilterVerificationStates.append(verificationId, ivs); 798 mCurrentIntentFilterVerifications.add(verificationId); 799 } 800 return ivs; 801 } 802 } 803 804 private static boolean hasValidDomains(ActivityIntentInfo filter) { 805 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 806 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 807 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 808 } 809 810 private IntentFilterVerifier mIntentFilterVerifier; 811 812 // Set of pending broadcasts for aggregating enable/disable of components. 813 static class PendingPackageBroadcasts { 814 // for each user id, a map of <package name -> components within that package> 815 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 816 817 public PendingPackageBroadcasts() { 818 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 819 } 820 821 public ArrayList<String> get(int userId, String packageName) { 822 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 823 return packages.get(packageName); 824 } 825 826 public void put(int userId, String packageName, ArrayList<String> components) { 827 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 828 packages.put(packageName, components); 829 } 830 831 public void remove(int userId, String packageName) { 832 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 833 if (packages != null) { 834 packages.remove(packageName); 835 } 836 } 837 838 public void remove(int userId) { 839 mUidMap.remove(userId); 840 } 841 842 public int userIdCount() { 843 return mUidMap.size(); 844 } 845 846 public int userIdAt(int n) { 847 return mUidMap.keyAt(n); 848 } 849 850 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 851 return mUidMap.get(userId); 852 } 853 854 public int size() { 855 // total number of pending broadcast entries across all userIds 856 int num = 0; 857 for (int i = 0; i< mUidMap.size(); i++) { 858 num += mUidMap.valueAt(i).size(); 859 } 860 return num; 861 } 862 863 public void clear() { 864 mUidMap.clear(); 865 } 866 867 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 868 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 869 if (map == null) { 870 map = new ArrayMap<String, ArrayList<String>>(); 871 mUidMap.put(userId, map); 872 } 873 return map; 874 } 875 } 876 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 877 878 // Service Connection to remote media container service to copy 879 // package uri's from external media onto secure containers 880 // or internal storage. 881 private IMediaContainerService mContainerService = null; 882 883 static final int SEND_PENDING_BROADCAST = 1; 884 static final int MCS_BOUND = 3; 885 static final int END_COPY = 4; 886 static final int INIT_COPY = 5; 887 static final int MCS_UNBIND = 6; 888 static final int START_CLEANING_PACKAGE = 7; 889 static final int FIND_INSTALL_LOC = 8; 890 static final int POST_INSTALL = 9; 891 static final int MCS_RECONNECT = 10; 892 static final int MCS_GIVE_UP = 11; 893 static final int UPDATED_MEDIA_STATUS = 12; 894 static final int WRITE_SETTINGS = 13; 895 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 896 static final int PACKAGE_VERIFIED = 15; 897 static final int CHECK_PENDING_VERIFICATION = 16; 898 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 899 static final int INTENT_FILTER_VERIFIED = 18; 900 901 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 902 903 // Delay time in millisecs 904 static final int BROADCAST_DELAY = 10 * 1000; 905 906 static UserManagerService sUserManager; 907 908 // Stores a list of users whose package restrictions file needs to be updated 909 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 910 911 final private DefaultContainerConnection mDefContainerConn = 912 new DefaultContainerConnection(); 913 class DefaultContainerConnection implements ServiceConnection { 914 public void onServiceConnected(ComponentName name, IBinder service) { 915 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 916 IMediaContainerService imcs = 917 IMediaContainerService.Stub.asInterface(service); 918 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 919 } 920 921 public void onServiceDisconnected(ComponentName name) { 922 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 923 } 924 } 925 926 // Recordkeeping of restore-after-install operations that are currently in flight 927 // between the Package Manager and the Backup Manager 928 class PostInstallData { 929 public InstallArgs args; 930 public PackageInstalledInfo res; 931 932 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 933 args = _a; 934 res = _r; 935 } 936 } 937 938 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 939 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 940 941 // XML tags for backup/restore of various bits of state 942 private static final String TAG_PREFERRED_BACKUP = "pa"; 943 private static final String TAG_DEFAULT_APPS = "da"; 944 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 945 946 final String mRequiredVerifierPackage; 947 final String mRequiredInstallerPackage; 948 949 private final PackageUsage mPackageUsage = new PackageUsage(); 950 951 private class PackageUsage { 952 private static final int WRITE_INTERVAL 953 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 954 955 private final Object mFileLock = new Object(); 956 private final AtomicLong mLastWritten = new AtomicLong(0); 957 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 958 959 private boolean mIsHistoricalPackageUsageAvailable = true; 960 961 boolean isHistoricalPackageUsageAvailable() { 962 return mIsHistoricalPackageUsageAvailable; 963 } 964 965 void write(boolean force) { 966 if (force) { 967 writeInternal(); 968 return; 969 } 970 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 971 && !DEBUG_DEXOPT) { 972 return; 973 } 974 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 975 new Thread("PackageUsage_DiskWriter") { 976 @Override 977 public void run() { 978 try { 979 writeInternal(); 980 } finally { 981 mBackgroundWriteRunning.set(false); 982 } 983 } 984 }.start(); 985 } 986 } 987 988 private void writeInternal() { 989 synchronized (mPackages) { 990 synchronized (mFileLock) { 991 AtomicFile file = getFile(); 992 FileOutputStream f = null; 993 try { 994 f = file.startWrite(); 995 BufferedOutputStream out = new BufferedOutputStream(f); 996 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 997 StringBuilder sb = new StringBuilder(); 998 for (PackageParser.Package pkg : mPackages.values()) { 999 if (pkg.mLastPackageUsageTimeInMills == 0) { 1000 continue; 1001 } 1002 sb.setLength(0); 1003 sb.append(pkg.packageName); 1004 sb.append(' '); 1005 sb.append((long)pkg.mLastPackageUsageTimeInMills); 1006 sb.append('\n'); 1007 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1008 } 1009 out.flush(); 1010 file.finishWrite(f); 1011 } catch (IOException e) { 1012 if (f != null) { 1013 file.failWrite(f); 1014 } 1015 Log.e(TAG, "Failed to write package usage times", e); 1016 } 1017 } 1018 } 1019 mLastWritten.set(SystemClock.elapsedRealtime()); 1020 } 1021 1022 void readLP() { 1023 synchronized (mFileLock) { 1024 AtomicFile file = getFile(); 1025 BufferedInputStream in = null; 1026 try { 1027 in = new BufferedInputStream(file.openRead()); 1028 StringBuffer sb = new StringBuffer(); 1029 while (true) { 1030 String packageName = readToken(in, sb, ' '); 1031 if (packageName == null) { 1032 break; 1033 } 1034 String timeInMillisString = readToken(in, sb, '\n'); 1035 if (timeInMillisString == null) { 1036 throw new IOException("Failed to find last usage time for package " 1037 + packageName); 1038 } 1039 PackageParser.Package pkg = mPackages.get(packageName); 1040 if (pkg == null) { 1041 continue; 1042 } 1043 long timeInMillis; 1044 try { 1045 timeInMillis = Long.parseLong(timeInMillisString.toString()); 1046 } catch (NumberFormatException e) { 1047 throw new IOException("Failed to parse " + timeInMillisString 1048 + " as a long.", e); 1049 } 1050 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1051 } 1052 } catch (FileNotFoundException expected) { 1053 mIsHistoricalPackageUsageAvailable = false; 1054 } catch (IOException e) { 1055 Log.w(TAG, "Failed to read package usage times", e); 1056 } finally { 1057 IoUtils.closeQuietly(in); 1058 } 1059 } 1060 mLastWritten.set(SystemClock.elapsedRealtime()); 1061 } 1062 1063 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1064 throws IOException { 1065 sb.setLength(0); 1066 while (true) { 1067 int ch = in.read(); 1068 if (ch == -1) { 1069 if (sb.length() == 0) { 1070 return null; 1071 } 1072 throw new IOException("Unexpected EOF"); 1073 } 1074 if (ch == endOfToken) { 1075 return sb.toString(); 1076 } 1077 sb.append((char)ch); 1078 } 1079 } 1080 1081 private AtomicFile getFile() { 1082 File dataDir = Environment.getDataDirectory(); 1083 File systemDir = new File(dataDir, "system"); 1084 File fname = new File(systemDir, "package-usage.list"); 1085 return new AtomicFile(fname); 1086 } 1087 } 1088 1089 class PackageHandler extends Handler { 1090 private boolean mBound = false; 1091 final ArrayList<HandlerParams> mPendingInstalls = 1092 new ArrayList<HandlerParams>(); 1093 1094 private boolean connectToService() { 1095 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1096 " DefaultContainerService"); 1097 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1098 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1099 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1100 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 1101 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1102 mBound = true; 1103 return true; 1104 } 1105 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1106 return false; 1107 } 1108 1109 private void disconnectService() { 1110 mContainerService = null; 1111 mBound = false; 1112 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1113 mContext.unbindService(mDefContainerConn); 1114 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1115 } 1116 1117 PackageHandler(Looper looper) { 1118 super(looper); 1119 } 1120 1121 public void handleMessage(Message msg) { 1122 try { 1123 doHandleMessage(msg); 1124 } finally { 1125 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1126 } 1127 } 1128 1129 void doHandleMessage(Message msg) { 1130 switch (msg.what) { 1131 case INIT_COPY: { 1132 HandlerParams params = (HandlerParams) msg.obj; 1133 int idx = mPendingInstalls.size(); 1134 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1135 // If a bind was already initiated we dont really 1136 // need to do anything. The pending install 1137 // will be processed later on. 1138 if (!mBound) { 1139 // If this is the only one pending we might 1140 // have to bind to the service again. 1141 if (!connectToService()) { 1142 Slog.e(TAG, "Failed to bind to media container service"); 1143 params.serviceError(); 1144 return; 1145 } else { 1146 // Once we bind to the service, the first 1147 // pending request will be processed. 1148 mPendingInstalls.add(idx, params); 1149 } 1150 } else { 1151 mPendingInstalls.add(idx, params); 1152 // Already bound to the service. Just make 1153 // sure we trigger off processing the first request. 1154 if (idx == 0) { 1155 mHandler.sendEmptyMessage(MCS_BOUND); 1156 } 1157 } 1158 break; 1159 } 1160 case MCS_BOUND: { 1161 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1162 if (msg.obj != null) { 1163 mContainerService = (IMediaContainerService) msg.obj; 1164 } 1165 if (mContainerService == null) { 1166 if (!mBound) { 1167 // Something seriously wrong since we are not bound and we are not 1168 // waiting for connection. Bail out. 1169 Slog.e(TAG, "Cannot bind to media container service"); 1170 for (HandlerParams params : mPendingInstalls) { 1171 // Indicate service bind error 1172 params.serviceError(); 1173 } 1174 mPendingInstalls.clear(); 1175 } else { 1176 Slog.w(TAG, "Waiting to connect to media container service"); 1177 } 1178 } else if (mPendingInstalls.size() > 0) { 1179 HandlerParams params = mPendingInstalls.get(0); 1180 if (params != null) { 1181 if (params.startCopy()) { 1182 // We are done... look for more work or to 1183 // go idle. 1184 if (DEBUG_SD_INSTALL) Log.i(TAG, 1185 "Checking for more work or unbind..."); 1186 // Delete pending install 1187 if (mPendingInstalls.size() > 0) { 1188 mPendingInstalls.remove(0); 1189 } 1190 if (mPendingInstalls.size() == 0) { 1191 if (mBound) { 1192 if (DEBUG_SD_INSTALL) Log.i(TAG, 1193 "Posting delayed MCS_UNBIND"); 1194 removeMessages(MCS_UNBIND); 1195 Message ubmsg = obtainMessage(MCS_UNBIND); 1196 // Unbind after a little delay, to avoid 1197 // continual thrashing. 1198 sendMessageDelayed(ubmsg, 10000); 1199 } 1200 } else { 1201 // There are more pending requests in queue. 1202 // Just post MCS_BOUND message to trigger processing 1203 // of next pending install. 1204 if (DEBUG_SD_INSTALL) Log.i(TAG, 1205 "Posting MCS_BOUND for next work"); 1206 mHandler.sendEmptyMessage(MCS_BOUND); 1207 } 1208 } 1209 } 1210 } else { 1211 // Should never happen ideally. 1212 Slog.w(TAG, "Empty queue"); 1213 } 1214 break; 1215 } 1216 case MCS_RECONNECT: { 1217 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1218 if (mPendingInstalls.size() > 0) { 1219 if (mBound) { 1220 disconnectService(); 1221 } 1222 if (!connectToService()) { 1223 Slog.e(TAG, "Failed to bind to media container service"); 1224 for (HandlerParams params : mPendingInstalls) { 1225 // Indicate service bind error 1226 params.serviceError(); 1227 } 1228 mPendingInstalls.clear(); 1229 } 1230 } 1231 break; 1232 } 1233 case MCS_UNBIND: { 1234 // If there is no actual work left, then time to unbind. 1235 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1236 1237 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1238 if (mBound) { 1239 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1240 1241 disconnectService(); 1242 } 1243 } else if (mPendingInstalls.size() > 0) { 1244 // There are more pending requests in queue. 1245 // Just post MCS_BOUND message to trigger processing 1246 // of next pending install. 1247 mHandler.sendEmptyMessage(MCS_BOUND); 1248 } 1249 1250 break; 1251 } 1252 case MCS_GIVE_UP: { 1253 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1254 mPendingInstalls.remove(0); 1255 break; 1256 } 1257 case SEND_PENDING_BROADCAST: { 1258 String packages[]; 1259 ArrayList<String> components[]; 1260 int size = 0; 1261 int uids[]; 1262 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1263 synchronized (mPackages) { 1264 if (mPendingBroadcasts == null) { 1265 return; 1266 } 1267 size = mPendingBroadcasts.size(); 1268 if (size <= 0) { 1269 // Nothing to be done. Just return 1270 return; 1271 } 1272 packages = new String[size]; 1273 components = new ArrayList[size]; 1274 uids = new int[size]; 1275 int i = 0; // filling out the above arrays 1276 1277 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1278 int packageUserId = mPendingBroadcasts.userIdAt(n); 1279 Iterator<Map.Entry<String, ArrayList<String>>> it 1280 = mPendingBroadcasts.packagesForUserId(packageUserId) 1281 .entrySet().iterator(); 1282 while (it.hasNext() && i < size) { 1283 Map.Entry<String, ArrayList<String>> ent = it.next(); 1284 packages[i] = ent.getKey(); 1285 components[i] = ent.getValue(); 1286 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1287 uids[i] = (ps != null) 1288 ? UserHandle.getUid(packageUserId, ps.appId) 1289 : -1; 1290 i++; 1291 } 1292 } 1293 size = i; 1294 mPendingBroadcasts.clear(); 1295 } 1296 // Send broadcasts 1297 for (int i = 0; i < size; i++) { 1298 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1299 } 1300 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1301 break; 1302 } 1303 case START_CLEANING_PACKAGE: { 1304 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1305 final String packageName = (String)msg.obj; 1306 final int userId = msg.arg1; 1307 final boolean andCode = msg.arg2 != 0; 1308 synchronized (mPackages) { 1309 if (userId == UserHandle.USER_ALL) { 1310 int[] users = sUserManager.getUserIds(); 1311 for (int user : users) { 1312 mSettings.addPackageToCleanLPw( 1313 new PackageCleanItem(user, packageName, andCode)); 1314 } 1315 } else { 1316 mSettings.addPackageToCleanLPw( 1317 new PackageCleanItem(userId, packageName, andCode)); 1318 } 1319 } 1320 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1321 startCleaningPackages(); 1322 } break; 1323 case POST_INSTALL: { 1324 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1325 PostInstallData data = mRunningInstalls.get(msg.arg1); 1326 mRunningInstalls.delete(msg.arg1); 1327 boolean deleteOld = false; 1328 1329 if (data != null) { 1330 InstallArgs args = data.args; 1331 PackageInstalledInfo res = data.res; 1332 1333 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1334 final String packageName = res.pkg.applicationInfo.packageName; 1335 res.removedInfo.sendBroadcast(false, true, false); 1336 Bundle extras = new Bundle(1); 1337 extras.putInt(Intent.EXTRA_UID, res.uid); 1338 1339 // Now that we successfully installed the package, grant runtime 1340 // permissions if requested before broadcasting the install. 1341 if ((args.installFlags 1342 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1343 grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(), 1344 args.installGrantPermissions); 1345 } 1346 1347 // Determine the set of users who are adding this 1348 // package for the first time vs. those who are seeing 1349 // an update. 1350 int[] firstUsers; 1351 int[] updateUsers = new int[0]; 1352 if (res.origUsers == null || res.origUsers.length == 0) { 1353 firstUsers = res.newUsers; 1354 } else { 1355 firstUsers = new int[0]; 1356 for (int i=0; i<res.newUsers.length; i++) { 1357 int user = res.newUsers[i]; 1358 boolean isNew = true; 1359 for (int j=0; j<res.origUsers.length; j++) { 1360 if (res.origUsers[j] == user) { 1361 isNew = false; 1362 break; 1363 } 1364 } 1365 if (isNew) { 1366 int[] newFirst = new int[firstUsers.length+1]; 1367 System.arraycopy(firstUsers, 0, newFirst, 0, 1368 firstUsers.length); 1369 newFirst[firstUsers.length] = user; 1370 firstUsers = newFirst; 1371 } else { 1372 int[] newUpdate = new int[updateUsers.length+1]; 1373 System.arraycopy(updateUsers, 0, newUpdate, 0, 1374 updateUsers.length); 1375 newUpdate[updateUsers.length] = user; 1376 updateUsers = newUpdate; 1377 } 1378 } 1379 } 1380 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1381 packageName, extras, null, null, firstUsers); 1382 final boolean update = res.removedInfo.removedPackage != null; 1383 if (update) { 1384 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1385 } 1386 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1387 packageName, extras, null, null, updateUsers); 1388 if (update) { 1389 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1390 packageName, extras, null, null, updateUsers); 1391 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1392 null, null, packageName, null, updateUsers); 1393 1394 // treat asec-hosted packages like removable media on upgrade 1395 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1396 if (DEBUG_INSTALL) { 1397 Slog.i(TAG, "upgrading pkg " + res.pkg 1398 + " is ASEC-hosted -> AVAILABLE"); 1399 } 1400 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1401 ArrayList<String> pkgList = new ArrayList<String>(1); 1402 pkgList.add(packageName); 1403 sendResourcesChangedBroadcast(true, true, 1404 pkgList,uidArray, null); 1405 } 1406 } 1407 if (res.removedInfo.args != null) { 1408 // Remove the replaced package's older resources safely now 1409 deleteOld = true; 1410 } 1411 1412 // If this app is a browser and it's newly-installed for some 1413 // users, clear any default-browser state in those users 1414 if (firstUsers.length > 0) { 1415 // the app's nature doesn't depend on the user, so we can just 1416 // check its browser nature in any user and generalize. 1417 if (packageIsBrowser(packageName, firstUsers[0])) { 1418 synchronized (mPackages) { 1419 for (int userId : firstUsers) { 1420 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1421 } 1422 } 1423 } 1424 } 1425 // Log current value of "unknown sources" setting 1426 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1427 getUnknownSourcesSettings()); 1428 } 1429 // Force a gc to clear up things 1430 Runtime.getRuntime().gc(); 1431 // We delete after a gc for applications on sdcard. 1432 if (deleteOld) { 1433 synchronized (mInstallLock) { 1434 res.removedInfo.args.doPostDeleteLI(true); 1435 } 1436 } 1437 if (args.observer != null) { 1438 try { 1439 Bundle extras = extrasForInstallResult(res); 1440 args.observer.onPackageInstalled(res.name, res.returnCode, 1441 res.returnMsg, extras); 1442 } catch (RemoteException e) { 1443 Slog.i(TAG, "Observer no longer exists."); 1444 } 1445 } 1446 } else { 1447 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1448 } 1449 } break; 1450 case UPDATED_MEDIA_STATUS: { 1451 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1452 boolean reportStatus = msg.arg1 == 1; 1453 boolean doGc = msg.arg2 == 1; 1454 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1455 if (doGc) { 1456 // Force a gc to clear up stale containers. 1457 Runtime.getRuntime().gc(); 1458 } 1459 if (msg.obj != null) { 1460 @SuppressWarnings("unchecked") 1461 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1462 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1463 // Unload containers 1464 unloadAllContainers(args); 1465 } 1466 if (reportStatus) { 1467 try { 1468 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1469 PackageHelper.getMountService().finishMediaUpdate(); 1470 } catch (RemoteException e) { 1471 Log.e(TAG, "MountService not running?"); 1472 } 1473 } 1474 } break; 1475 case WRITE_SETTINGS: { 1476 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1477 synchronized (mPackages) { 1478 removeMessages(WRITE_SETTINGS); 1479 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1480 mSettings.writeLPr(); 1481 mDirtyUsers.clear(); 1482 } 1483 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1484 } break; 1485 case WRITE_PACKAGE_RESTRICTIONS: { 1486 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1487 synchronized (mPackages) { 1488 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1489 for (int userId : mDirtyUsers) { 1490 mSettings.writePackageRestrictionsLPr(userId); 1491 } 1492 mDirtyUsers.clear(); 1493 } 1494 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1495 } break; 1496 case CHECK_PENDING_VERIFICATION: { 1497 final int verificationId = msg.arg1; 1498 final PackageVerificationState state = mPendingVerification.get(verificationId); 1499 1500 if ((state != null) && !state.timeoutExtended()) { 1501 final InstallArgs args = state.getInstallArgs(); 1502 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1503 1504 Slog.i(TAG, "Verification timed out for " + originUri); 1505 mPendingVerification.remove(verificationId); 1506 1507 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1508 1509 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1510 Slog.i(TAG, "Continuing with installation of " + originUri); 1511 state.setVerifierResponse(Binder.getCallingUid(), 1512 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1513 broadcastPackageVerified(verificationId, originUri, 1514 PackageManager.VERIFICATION_ALLOW, 1515 state.getInstallArgs().getUser()); 1516 try { 1517 ret = args.copyApk(mContainerService, true); 1518 } catch (RemoteException e) { 1519 Slog.e(TAG, "Could not contact the ContainerService"); 1520 } 1521 } else { 1522 broadcastPackageVerified(verificationId, originUri, 1523 PackageManager.VERIFICATION_REJECT, 1524 state.getInstallArgs().getUser()); 1525 } 1526 1527 processPendingInstall(args, ret); 1528 mHandler.sendEmptyMessage(MCS_UNBIND); 1529 } 1530 break; 1531 } 1532 case PACKAGE_VERIFIED: { 1533 final int verificationId = msg.arg1; 1534 1535 final PackageVerificationState state = mPendingVerification.get(verificationId); 1536 if (state == null) { 1537 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1538 break; 1539 } 1540 1541 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1542 1543 state.setVerifierResponse(response.callerUid, response.code); 1544 1545 if (state.isVerificationComplete()) { 1546 mPendingVerification.remove(verificationId); 1547 1548 final InstallArgs args = state.getInstallArgs(); 1549 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1550 1551 int ret; 1552 if (state.isInstallAllowed()) { 1553 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1554 broadcastPackageVerified(verificationId, originUri, 1555 response.code, state.getInstallArgs().getUser()); 1556 try { 1557 ret = args.copyApk(mContainerService, true); 1558 } catch (RemoteException e) { 1559 Slog.e(TAG, "Could not contact the ContainerService"); 1560 } 1561 } else { 1562 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1563 } 1564 1565 processPendingInstall(args, ret); 1566 1567 mHandler.sendEmptyMessage(MCS_UNBIND); 1568 } 1569 1570 break; 1571 } 1572 case START_INTENT_FILTER_VERIFICATIONS: { 1573 IFVerificationParams params = (IFVerificationParams) msg.obj; 1574 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1575 params.replacing, params.pkg); 1576 break; 1577 } 1578 case INTENT_FILTER_VERIFIED: { 1579 final int verificationId = msg.arg1; 1580 1581 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1582 verificationId); 1583 if (state == null) { 1584 Slog.w(TAG, "Invalid IntentFilter verification token " 1585 + verificationId + " received"); 1586 break; 1587 } 1588 1589 final int userId = state.getUserId(); 1590 1591 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1592 "Processing IntentFilter verification with token:" 1593 + verificationId + " and userId:" + userId); 1594 1595 final IntentFilterVerificationResponse response = 1596 (IntentFilterVerificationResponse) msg.obj; 1597 1598 state.setVerifierResponse(response.callerUid, response.code); 1599 1600 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1601 "IntentFilter verification with token:" + verificationId 1602 + " and userId:" + userId 1603 + " is settings verifier response with response code:" 1604 + response.code); 1605 1606 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1607 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1608 + response.getFailedDomainsString()); 1609 } 1610 1611 if (state.isVerificationComplete()) { 1612 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1613 } else { 1614 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1615 "IntentFilter verification with token:" + verificationId 1616 + " was not said to be complete"); 1617 } 1618 1619 break; 1620 } 1621 } 1622 } 1623 } 1624 1625 private StorageEventListener mStorageListener = new StorageEventListener() { 1626 @Override 1627 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1628 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1629 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1630 final String volumeUuid = vol.getFsUuid(); 1631 1632 // Clean up any users or apps that were removed or recreated 1633 // while this volume was missing 1634 reconcileUsers(volumeUuid); 1635 reconcileApps(volumeUuid); 1636 1637 // Clean up any install sessions that expired or were 1638 // cancelled while this volume was missing 1639 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1640 1641 loadPrivatePackages(vol); 1642 1643 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1644 unloadPrivatePackages(vol); 1645 } 1646 } 1647 1648 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1649 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1650 updateExternalMediaStatus(true, false); 1651 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1652 updateExternalMediaStatus(false, false); 1653 } 1654 } 1655 } 1656 1657 @Override 1658 public void onVolumeForgotten(String fsUuid) { 1659 if (TextUtils.isEmpty(fsUuid)) { 1660 Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1661 return; 1662 } 1663 1664 // Remove any apps installed on the forgotten volume 1665 synchronized (mPackages) { 1666 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1667 for (PackageSetting ps : packages) { 1668 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1669 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1670 UserHandle.USER_OWNER, PackageManager.DELETE_ALL_USERS); 1671 } 1672 1673 mSettings.onVolumeForgotten(fsUuid); 1674 mSettings.writeLPr(); 1675 } 1676 } 1677 }; 1678 1679 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId, 1680 String[] grantedPermissions) { 1681 if (userId >= UserHandle.USER_OWNER) { 1682 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1683 } else if (userId == UserHandle.USER_ALL) { 1684 final int[] userIds; 1685 synchronized (mPackages) { 1686 userIds = UserManagerService.getInstance().getUserIds(); 1687 } 1688 for (int someUserId : userIds) { 1689 grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions); 1690 } 1691 } 1692 1693 // We could have touched GID membership, so flush out packages.list 1694 synchronized (mPackages) { 1695 mSettings.writePackageListLPr(); 1696 } 1697 } 1698 1699 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1700 String[] grantedPermissions) { 1701 SettingBase sb = (SettingBase) pkg.mExtras; 1702 if (sb == null) { 1703 return; 1704 } 1705 1706 PermissionsState permissionsState = sb.getPermissionsState(); 1707 1708 for (String permission : pkg.requestedPermissions) { 1709 BasePermission bp = mSettings.mPermissions.get(permission); 1710 if (bp != null && bp.isRuntime() && (grantedPermissions == null 1711 || ArrayUtils.contains(grantedPermissions, permission))) { 1712 permissionsState.grantRuntimePermission(bp, userId); 1713 } 1714 } 1715 } 1716 1717 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1718 Bundle extras = null; 1719 switch (res.returnCode) { 1720 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1721 extras = new Bundle(); 1722 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1723 res.origPermission); 1724 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1725 res.origPackage); 1726 break; 1727 } 1728 case PackageManager.INSTALL_SUCCEEDED: { 1729 extras = new Bundle(); 1730 extras.putBoolean(Intent.EXTRA_REPLACING, 1731 res.removedInfo != null && res.removedInfo.removedPackage != null); 1732 break; 1733 } 1734 } 1735 return extras; 1736 } 1737 1738 void scheduleWriteSettingsLocked() { 1739 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1740 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1741 } 1742 } 1743 1744 void scheduleWritePackageRestrictionsLocked(int userId) { 1745 if (!sUserManager.exists(userId)) return; 1746 mDirtyUsers.add(userId); 1747 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1748 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1749 } 1750 } 1751 1752 public static PackageManagerService main(Context context, Installer installer, 1753 boolean factoryTest, boolean onlyCore) { 1754 PackageManagerService m = new PackageManagerService(context, installer, 1755 factoryTest, onlyCore); 1756 ServiceManager.addService("package", m); 1757 return m; 1758 } 1759 1760 static String[] splitString(String str, char sep) { 1761 int count = 1; 1762 int i = 0; 1763 while ((i=str.indexOf(sep, i)) >= 0) { 1764 count++; 1765 i++; 1766 } 1767 1768 String[] res = new String[count]; 1769 i=0; 1770 count = 0; 1771 int lastI=0; 1772 while ((i=str.indexOf(sep, i)) >= 0) { 1773 res[count] = str.substring(lastI, i); 1774 count++; 1775 i++; 1776 lastI = i; 1777 } 1778 res[count] = str.substring(lastI, str.length()); 1779 return res; 1780 } 1781 1782 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1783 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1784 Context.DISPLAY_SERVICE); 1785 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1786 } 1787 1788 public PackageManagerService(Context context, Installer installer, 1789 boolean factoryTest, boolean onlyCore) { 1790 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1791 SystemClock.uptimeMillis()); 1792 1793 if (mSdkVersion <= 0) { 1794 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1795 } 1796 1797 mContext = context; 1798 mFactoryTest = factoryTest; 1799 mOnlyCore = onlyCore; 1800 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1801 mMetrics = new DisplayMetrics(); 1802 mSettings = new Settings(mPackages); 1803 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1804 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1805 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1806 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1807 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1808 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1809 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1810 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1811 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1812 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1813 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1814 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1815 1816 // TODO: add a property to control this? 1817 long dexOptLRUThresholdInMinutes; 1818 if (mLazyDexOpt) { 1819 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1820 } else { 1821 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1822 } 1823 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1824 1825 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1826 if (separateProcesses != null && separateProcesses.length() > 0) { 1827 if ("*".equals(separateProcesses)) { 1828 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1829 mSeparateProcesses = null; 1830 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1831 } else { 1832 mDefParseFlags = 0; 1833 mSeparateProcesses = separateProcesses.split(","); 1834 Slog.w(TAG, "Running with debug.separate_processes: " 1835 + separateProcesses); 1836 } 1837 } else { 1838 mDefParseFlags = 0; 1839 mSeparateProcesses = null; 1840 } 1841 1842 mInstaller = installer; 1843 mPackageDexOptimizer = new PackageDexOptimizer(this); 1844 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1845 1846 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 1847 FgThread.get().getLooper()); 1848 1849 getDefaultDisplayMetrics(context, mMetrics); 1850 1851 SystemConfig systemConfig = SystemConfig.getInstance(); 1852 mGlobalGids = systemConfig.getGlobalGids(); 1853 mSystemPermissions = systemConfig.getSystemPermissions(); 1854 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1855 1856 synchronized (mInstallLock) { 1857 // writer 1858 synchronized (mPackages) { 1859 mHandlerThread = new ServiceThread(TAG, 1860 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1861 mHandlerThread.start(); 1862 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1863 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1864 1865 File dataDir = Environment.getDataDirectory(); 1866 mAppDataDir = new File(dataDir, "data"); 1867 mAppInstallDir = new File(dataDir, "app"); 1868 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1869 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1870 mUserAppDataDir = new File(dataDir, "user"); 1871 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1872 1873 sUserManager = new UserManagerService(context, this, 1874 mInstallLock, mPackages); 1875 1876 // Propagate permission configuration in to package manager. 1877 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1878 = systemConfig.getPermissions(); 1879 for (int i=0; i<permConfig.size(); i++) { 1880 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1881 BasePermission bp = mSettings.mPermissions.get(perm.name); 1882 if (bp == null) { 1883 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1884 mSettings.mPermissions.put(perm.name, bp); 1885 } 1886 if (perm.gids != null) { 1887 bp.setGids(perm.gids, perm.perUser); 1888 } 1889 } 1890 1891 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1892 for (int i=0; i<libConfig.size(); i++) { 1893 mSharedLibraries.put(libConfig.keyAt(i), 1894 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1895 } 1896 1897 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1898 1899 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1900 mSdkVersion, mOnlyCore); 1901 1902 String customResolverActivity = Resources.getSystem().getString( 1903 R.string.config_customResolverActivity); 1904 if (TextUtils.isEmpty(customResolverActivity)) { 1905 customResolverActivity = null; 1906 } else { 1907 mCustomResolverComponentName = ComponentName.unflattenFromString( 1908 customResolverActivity); 1909 } 1910 1911 long startTime = SystemClock.uptimeMillis(); 1912 1913 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1914 startTime); 1915 1916 // Set flag to monitor and not change apk file paths when 1917 // scanning install directories. 1918 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 1919 1920 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1921 1922 /** 1923 * Add everything in the in the boot class path to the 1924 * list of process files because dexopt will have been run 1925 * if necessary during zygote startup. 1926 */ 1927 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1928 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1929 1930 if (bootClassPath != null) { 1931 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1932 for (String element : bootClassPathElements) { 1933 alreadyDexOpted.add(element); 1934 } 1935 } else { 1936 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1937 } 1938 1939 if (systemServerClassPath != null) { 1940 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1941 for (String element : systemServerClassPathElements) { 1942 alreadyDexOpted.add(element); 1943 } 1944 } else { 1945 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1946 } 1947 1948 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1949 final String[] dexCodeInstructionSets = 1950 getDexCodeInstructionSets( 1951 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1952 1953 /** 1954 * Ensure all external libraries have had dexopt run on them. 1955 */ 1956 if (mSharedLibraries.size() > 0) { 1957 // NOTE: For now, we're compiling these system "shared libraries" 1958 // (and framework jars) into all available architectures. It's possible 1959 // to compile them only when we come across an app that uses them (there's 1960 // already logic for that in scanPackageLI) but that adds some complexity. 1961 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1962 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1963 final String lib = libEntry.path; 1964 if (lib == null) { 1965 continue; 1966 } 1967 1968 try { 1969 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 1970 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1971 alreadyDexOpted.add(lib); 1972 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1973 } 1974 } catch (FileNotFoundException e) { 1975 Slog.w(TAG, "Library not found: " + lib); 1976 } catch (IOException e) { 1977 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1978 + e.getMessage()); 1979 } 1980 } 1981 } 1982 } 1983 1984 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1985 1986 // Gross hack for now: we know this file doesn't contain any 1987 // code, so don't dexopt it to avoid the resulting log spew. 1988 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1989 1990 // Gross hack for now: we know this file is only part of 1991 // the boot class path for art, so don't dexopt it to 1992 // avoid the resulting log spew. 1993 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1994 1995 /** 1996 * There are a number of commands implemented in Java, which 1997 * we currently need to do the dexopt on so that they can be 1998 * run from a non-root shell. 1999 */ 2000 String[] frameworkFiles = frameworkDir.list(); 2001 if (frameworkFiles != null) { 2002 // TODO: We could compile these only for the most preferred ABI. We should 2003 // first double check that the dex files for these commands are not referenced 2004 // by other system apps. 2005 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2006 for (int i=0; i<frameworkFiles.length; i++) { 2007 File libPath = new File(frameworkDir, frameworkFiles[i]); 2008 String path = libPath.getPath(); 2009 // Skip the file if we already did it. 2010 if (alreadyDexOpted.contains(path)) { 2011 continue; 2012 } 2013 // Skip the file if it is not a type we want to dexopt. 2014 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 2015 continue; 2016 } 2017 try { 2018 int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false); 2019 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2020 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 2021 } 2022 } catch (FileNotFoundException e) { 2023 Slog.w(TAG, "Jar not found: " + path); 2024 } catch (IOException e) { 2025 Slog.w(TAG, "Exception reading jar: " + path, e); 2026 } 2027 } 2028 } 2029 } 2030 2031 // Collect vendor overlay packages. 2032 // (Do this before scanning any apps.) 2033 // For security and version matching reason, only consider 2034 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2035 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2036 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2037 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2038 2039 // Find base frameworks (resource packages without code). 2040 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2041 | PackageParser.PARSE_IS_SYSTEM_DIR 2042 | PackageParser.PARSE_IS_PRIVILEGED, 2043 scanFlags | SCAN_NO_DEX, 0); 2044 2045 // Collected privileged system packages. 2046 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2047 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2048 | PackageParser.PARSE_IS_SYSTEM_DIR 2049 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2050 2051 // Collect ordinary system packages. 2052 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2053 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2054 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2055 2056 // Collect all vendor packages. 2057 File vendorAppDir = new File("/vendor/app"); 2058 try { 2059 vendorAppDir = vendorAppDir.getCanonicalFile(); 2060 } catch (IOException e) { 2061 // failed to look up canonical path, continue with original one 2062 } 2063 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2064 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2065 2066 // Collect all OEM packages. 2067 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2068 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2069 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2070 2071 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 2072 mInstaller.moveFiles(); 2073 2074 // Prune any system packages that no longer exist. 2075 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2076 if (!mOnlyCore) { 2077 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2078 while (psit.hasNext()) { 2079 PackageSetting ps = psit.next(); 2080 2081 /* 2082 * If this is not a system app, it can't be a 2083 * disable system app. 2084 */ 2085 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2086 continue; 2087 } 2088 2089 /* 2090 * If the package is scanned, it's not erased. 2091 */ 2092 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2093 if (scannedPkg != null) { 2094 /* 2095 * If the system app is both scanned and in the 2096 * disabled packages list, then it must have been 2097 * added via OTA. Remove it from the currently 2098 * scanned package so the previously user-installed 2099 * application can be scanned. 2100 */ 2101 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2102 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2103 + ps.name + "; removing system app. Last known codePath=" 2104 + ps.codePathString + ", installStatus=" + ps.installStatus 2105 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2106 + scannedPkg.mVersionCode); 2107 removePackageLI(ps, true); 2108 mExpectingBetter.put(ps.name, ps.codePath); 2109 } 2110 2111 continue; 2112 } 2113 2114 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2115 psit.remove(); 2116 logCriticalInfo(Log.WARN, "System package " + ps.name 2117 + " no longer exists; wiping its data"); 2118 removeDataDirsLI(null, ps.name); 2119 } else { 2120 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2121 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2122 possiblyDeletedUpdatedSystemApps.add(ps.name); 2123 } 2124 } 2125 } 2126 } 2127 2128 //look for any incomplete package installations 2129 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2130 //clean up list 2131 for(int i = 0; i < deletePkgsList.size(); i++) { 2132 //clean up here 2133 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2134 } 2135 //delete tmp files 2136 deleteTempPackageFiles(); 2137 2138 // Remove any shared userIDs that have no associated packages 2139 mSettings.pruneSharedUsersLPw(); 2140 2141 if (!mOnlyCore) { 2142 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2143 SystemClock.uptimeMillis()); 2144 scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2145 2146 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2147 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2148 2149 /** 2150 * Remove disable package settings for any updated system 2151 * apps that were removed via an OTA. If they're not a 2152 * previously-updated app, remove them completely. 2153 * Otherwise, just revoke their system-level permissions. 2154 */ 2155 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2156 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2157 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2158 2159 String msg; 2160 if (deletedPkg == null) { 2161 msg = "Updated system package " + deletedAppName 2162 + " no longer exists; wiping its data"; 2163 removeDataDirsLI(null, deletedAppName); 2164 } else { 2165 msg = "Updated system app + " + deletedAppName 2166 + " no longer present; removing system privileges for " 2167 + deletedAppName; 2168 2169 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2170 2171 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2172 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2173 } 2174 logCriticalInfo(Log.WARN, msg); 2175 } 2176 2177 /** 2178 * Make sure all system apps that we expected to appear on 2179 * the userdata partition actually showed up. If they never 2180 * appeared, crawl back and revive the system version. 2181 */ 2182 for (int i = 0; i < mExpectingBetter.size(); i++) { 2183 final String packageName = mExpectingBetter.keyAt(i); 2184 if (!mPackages.containsKey(packageName)) { 2185 final File scanFile = mExpectingBetter.valueAt(i); 2186 2187 logCriticalInfo(Log.WARN, "Expected better " + packageName 2188 + " but never showed up; reverting to system"); 2189 2190 final int reparseFlags; 2191 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2192 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2193 | PackageParser.PARSE_IS_SYSTEM_DIR 2194 | PackageParser.PARSE_IS_PRIVILEGED; 2195 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2196 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2197 | PackageParser.PARSE_IS_SYSTEM_DIR; 2198 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2199 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2200 | PackageParser.PARSE_IS_SYSTEM_DIR; 2201 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2202 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2203 | PackageParser.PARSE_IS_SYSTEM_DIR; 2204 } else { 2205 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2206 continue; 2207 } 2208 2209 mSettings.enableSystemPackageLPw(packageName); 2210 2211 try { 2212 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 2213 } catch (PackageManagerException e) { 2214 Slog.e(TAG, "Failed to parse original system package: " 2215 + e.getMessage()); 2216 } 2217 } 2218 } 2219 } 2220 mExpectingBetter.clear(); 2221 2222 // Now that we know all of the shared libraries, update all clients to have 2223 // the correct library paths. 2224 updateAllSharedLibrariesLPw(); 2225 2226 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2227 // NOTE: We ignore potential failures here during a system scan (like 2228 // the rest of the commands above) because there's precious little we 2229 // can do about it. A settings error is reported, though. 2230 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2231 false /* force dexopt */, false /* defer dexopt */); 2232 } 2233 2234 // Now that we know all the packages we are keeping, 2235 // read and update their last usage times. 2236 mPackageUsage.readLP(); 2237 2238 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2239 SystemClock.uptimeMillis()); 2240 Slog.i(TAG, "Time to scan packages: " 2241 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2242 + " seconds"); 2243 2244 // If the platform SDK has changed since the last time we booted, 2245 // we need to re-grant app permission to catch any new ones that 2246 // appear. This is really a hack, and means that apps can in some 2247 // cases get permissions that the user didn't initially explicitly 2248 // allow... it would be nice to have some better way to handle 2249 // this situation. 2250 final VersionInfo ver = mSettings.getInternalVersion(); 2251 2252 int updateFlags = UPDATE_PERMISSIONS_ALL; 2253 if (ver.sdkVersion != mSdkVersion) { 2254 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2255 + mSdkVersion + "; regranting permissions for internal storage"); 2256 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2257 } 2258 updatePermissionsLPw(null, null, updateFlags); 2259 ver.sdkVersion = mSdkVersion; 2260 2261 // If this is the first boot, and it is a normal boot, then 2262 // we need to initialize the default preferred apps. 2263 if (!mRestoredSettings && !onlyCore) { 2264 mSettings.applyDefaultPreferredAppsLPw(this, UserHandle.USER_OWNER); 2265 applyFactoryDefaultBrowserLPw(UserHandle.USER_OWNER); 2266 primeDomainVerificationsLPw(UserHandle.USER_OWNER); 2267 } 2268 2269 // If this is first boot after an OTA, and a normal boot, then 2270 // we need to clear code cache directories. 2271 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2272 if (mIsUpgrade && !onlyCore) { 2273 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2274 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2275 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2276 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2277 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2278 } 2279 } 2280 ver.fingerprint = Build.FINGERPRINT; 2281 } 2282 2283 checkDefaultBrowser(); 2284 2285 // All the changes are done during package scanning. 2286 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2287 2288 // can downgrade to reader 2289 mSettings.writeLPr(); 2290 2291 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2292 SystemClock.uptimeMillis()); 2293 2294 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2295 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2296 2297 mInstallerService = new PackageInstallerService(context, this); 2298 2299 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2300 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2301 mIntentFilterVerifierComponent); 2302 2303 } // synchronized (mPackages) 2304 } // synchronized (mInstallLock) 2305 2306 // Now after opening every single application zip, make sure they 2307 // are all flushed. Not really needed, but keeps things nice and 2308 // tidy. 2309 Runtime.getRuntime().gc(); 2310 2311 // Expose private service for system components to use. 2312 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2313 } 2314 2315 @Override 2316 public boolean isFirstBoot() { 2317 return !mRestoredSettings; 2318 } 2319 2320 @Override 2321 public boolean isOnlyCoreApps() { 2322 return mOnlyCore; 2323 } 2324 2325 @Override 2326 public boolean isUpgrade() { 2327 return mIsUpgrade; 2328 } 2329 2330 private String getRequiredVerifierLPr() { 2331 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2332 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2333 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 2334 2335 String requiredVerifier = null; 2336 2337 final int N = receivers.size(); 2338 for (int i = 0; i < N; i++) { 2339 final ResolveInfo info = receivers.get(i); 2340 2341 if (info.activityInfo == null) { 2342 continue; 2343 } 2344 2345 final String packageName = info.activityInfo.packageName; 2346 2347 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2348 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2349 continue; 2350 } 2351 2352 if (requiredVerifier != null) { 2353 throw new RuntimeException("There can be only one required verifier"); 2354 } 2355 2356 requiredVerifier = packageName; 2357 } 2358 2359 return requiredVerifier; 2360 } 2361 2362 private String getRequiredInstallerLPr() { 2363 Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2364 installerIntent.addCategory(Intent.CATEGORY_DEFAULT); 2365 installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2366 2367 final List<ResolveInfo> installers = queryIntentActivities(installerIntent, 2368 PACKAGE_MIME_TYPE, 0, 0); 2369 2370 String requiredInstaller = null; 2371 2372 final int N = installers.size(); 2373 for (int i = 0; i < N; i++) { 2374 final ResolveInfo info = installers.get(i); 2375 final String packageName = info.activityInfo.packageName; 2376 2377 if (!info.activityInfo.applicationInfo.isSystemApp()) { 2378 continue; 2379 } 2380 2381 if (requiredInstaller != null) { 2382 throw new RuntimeException("There must be one required installer"); 2383 } 2384 2385 requiredInstaller = packageName; 2386 } 2387 2388 if (requiredInstaller == null) { 2389 throw new RuntimeException("There must be one required installer"); 2390 } 2391 2392 return requiredInstaller; 2393 } 2394 2395 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2396 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2397 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2398 PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */); 2399 2400 ComponentName verifierComponentName = null; 2401 2402 int priority = -1000; 2403 final int N = receivers.size(); 2404 for (int i = 0; i < N; i++) { 2405 final ResolveInfo info = receivers.get(i); 2406 2407 if (info.activityInfo == null) { 2408 continue; 2409 } 2410 2411 final String packageName = info.activityInfo.packageName; 2412 2413 final PackageSetting ps = mSettings.mPackages.get(packageName); 2414 if (ps == null) { 2415 continue; 2416 } 2417 2418 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2419 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2420 continue; 2421 } 2422 2423 // Select the IntentFilterVerifier with the highest priority 2424 if (priority < info.priority) { 2425 priority = info.priority; 2426 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2427 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: " 2428 + verifierComponentName + " with priority: " + info.priority); 2429 } 2430 } 2431 2432 return verifierComponentName; 2433 } 2434 2435 private void primeDomainVerificationsLPw(int userId) { 2436 if (DEBUG_DOMAIN_VERIFICATION) { 2437 Slog.d(TAG, "Priming domain verifications in user " + userId); 2438 } 2439 2440 SystemConfig systemConfig = SystemConfig.getInstance(); 2441 ArraySet<String> packages = systemConfig.getLinkedApps(); 2442 ArraySet<String> domains = new ArraySet<String>(); 2443 2444 for (String packageName : packages) { 2445 PackageParser.Package pkg = mPackages.get(packageName); 2446 if (pkg != null) { 2447 if (!pkg.isSystemApp()) { 2448 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2449 continue; 2450 } 2451 2452 domains.clear(); 2453 for (PackageParser.Activity a : pkg.activities) { 2454 for (ActivityIntentInfo filter : a.intents) { 2455 if (hasValidDomains(filter)) { 2456 domains.addAll(filter.getHostsList()); 2457 } 2458 } 2459 } 2460 2461 if (domains.size() > 0) { 2462 if (DEBUG_DOMAIN_VERIFICATION) { 2463 Slog.v(TAG, " + " + packageName); 2464 } 2465 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2466 // state w.r.t. the formal app-linkage "no verification attempted" state; 2467 // and then 'always' in the per-user state actually used for intent resolution. 2468 final IntentFilterVerificationInfo ivi; 2469 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2470 new ArrayList<String>(domains)); 2471 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2472 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2473 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2474 } else { 2475 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2476 + "' does not handle web links"); 2477 } 2478 } else { 2479 Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>"); 2480 } 2481 } 2482 2483 scheduleWritePackageRestrictionsLocked(userId); 2484 scheduleWriteSettingsLocked(); 2485 } 2486 2487 private void applyFactoryDefaultBrowserLPw(int userId) { 2488 // The default browser app's package name is stored in a string resource, 2489 // with a product-specific overlay used for vendor customization. 2490 String browserPkg = mContext.getResources().getString( 2491 com.android.internal.R.string.default_browser); 2492 if (!TextUtils.isEmpty(browserPkg)) { 2493 // non-empty string => required to be a known package 2494 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2495 if (ps == null) { 2496 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2497 browserPkg = null; 2498 } else { 2499 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2500 } 2501 } 2502 2503 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2504 // default. If there's more than one, just leave everything alone. 2505 if (browserPkg == null) { 2506 calculateDefaultBrowserLPw(userId); 2507 } 2508 } 2509 2510 private void calculateDefaultBrowserLPw(int userId) { 2511 List<String> allBrowsers = resolveAllBrowserApps(userId); 2512 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2513 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2514 } 2515 2516 private List<String> resolveAllBrowserApps(int userId) { 2517 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2518 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2519 PackageManager.MATCH_ALL, userId); 2520 2521 final int count = list.size(); 2522 List<String> result = new ArrayList<String>(count); 2523 for (int i=0; i<count; i++) { 2524 ResolveInfo info = list.get(i); 2525 if (info.activityInfo == null 2526 || !info.handleAllWebDataURI 2527 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2528 || result.contains(info.activityInfo.packageName)) { 2529 continue; 2530 } 2531 result.add(info.activityInfo.packageName); 2532 } 2533 2534 return result; 2535 } 2536 2537 private boolean packageIsBrowser(String packageName, int userId) { 2538 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2539 PackageManager.MATCH_ALL, userId); 2540 final int N = list.size(); 2541 for (int i = 0; i < N; i++) { 2542 ResolveInfo info = list.get(i); 2543 if (packageName.equals(info.activityInfo.packageName)) { 2544 return true; 2545 } 2546 } 2547 return false; 2548 } 2549 2550 private void checkDefaultBrowser() { 2551 final int myUserId = UserHandle.myUserId(); 2552 final String packageName = getDefaultBrowserPackageName(myUserId); 2553 if (packageName != null) { 2554 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2555 if (info == null) { 2556 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2557 synchronized (mPackages) { 2558 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2559 } 2560 } 2561 } 2562 } 2563 2564 @Override 2565 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2566 throws RemoteException { 2567 try { 2568 return super.onTransact(code, data, reply, flags); 2569 } catch (RuntimeException e) { 2570 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2571 Slog.wtf(TAG, "Package Manager Crash", e); 2572 } 2573 throw e; 2574 } 2575 } 2576 2577 void cleanupInstallFailedPackage(PackageSetting ps) { 2578 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2579 2580 removeDataDirsLI(ps.volumeUuid, ps.name); 2581 if (ps.codePath != null) { 2582 if (ps.codePath.isDirectory()) { 2583 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2584 } else { 2585 ps.codePath.delete(); 2586 } 2587 } 2588 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2589 if (ps.resourcePath.isDirectory()) { 2590 FileUtils.deleteContents(ps.resourcePath); 2591 } 2592 ps.resourcePath.delete(); 2593 } 2594 mSettings.removePackageLPw(ps.name); 2595 } 2596 2597 static int[] appendInts(int[] cur, int[] add) { 2598 if (add == null) return cur; 2599 if (cur == null) return add; 2600 final int N = add.length; 2601 for (int i=0; i<N; i++) { 2602 cur = appendInt(cur, add[i]); 2603 } 2604 return cur; 2605 } 2606 2607 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2608 if (!sUserManager.exists(userId)) return null; 2609 final PackageSetting ps = (PackageSetting) p.mExtras; 2610 if (ps == null) { 2611 return null; 2612 } 2613 2614 final PermissionsState permissionsState = ps.getPermissionsState(); 2615 2616 final int[] gids = permissionsState.computeGids(userId); 2617 final Set<String> permissions = permissionsState.getPermissions(userId); 2618 final PackageUserState state = ps.readUserState(userId); 2619 2620 return PackageParser.generatePackageInfo(p, gids, flags, 2621 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2622 } 2623 2624 @Override 2625 public boolean isPackageFrozen(String packageName) { 2626 synchronized (mPackages) { 2627 final PackageSetting ps = mSettings.mPackages.get(packageName); 2628 if (ps != null) { 2629 return ps.frozen; 2630 } 2631 } 2632 Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen"); 2633 return true; 2634 } 2635 2636 @Override 2637 public boolean isPackageAvailable(String packageName, int userId) { 2638 if (!sUserManager.exists(userId)) return false; 2639 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2640 synchronized (mPackages) { 2641 PackageParser.Package p = mPackages.get(packageName); 2642 if (p != null) { 2643 final PackageSetting ps = (PackageSetting) p.mExtras; 2644 if (ps != null) { 2645 final PackageUserState state = ps.readUserState(userId); 2646 if (state != null) { 2647 return PackageParser.isAvailable(state); 2648 } 2649 } 2650 } 2651 } 2652 return false; 2653 } 2654 2655 @Override 2656 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2657 if (!sUserManager.exists(userId)) return null; 2658 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2659 // reader 2660 synchronized (mPackages) { 2661 PackageParser.Package p = mPackages.get(packageName); 2662 if (DEBUG_PACKAGE_INFO) 2663 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2664 if (p != null) { 2665 return generatePackageInfo(p, flags, userId); 2666 } 2667 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2668 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2669 } 2670 } 2671 return null; 2672 } 2673 2674 @Override 2675 public String[] currentToCanonicalPackageNames(String[] names) { 2676 String[] out = new String[names.length]; 2677 // reader 2678 synchronized (mPackages) { 2679 for (int i=names.length-1; i>=0; i--) { 2680 PackageSetting ps = mSettings.mPackages.get(names[i]); 2681 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2682 } 2683 } 2684 return out; 2685 } 2686 2687 @Override 2688 public String[] canonicalToCurrentPackageNames(String[] names) { 2689 String[] out = new String[names.length]; 2690 // reader 2691 synchronized (mPackages) { 2692 for (int i=names.length-1; i>=0; i--) { 2693 String cur = mSettings.mRenamedPackages.get(names[i]); 2694 out[i] = cur != null ? cur : names[i]; 2695 } 2696 } 2697 return out; 2698 } 2699 2700 @Override 2701 public int getPackageUid(String packageName, int userId) { 2702 if (!sUserManager.exists(userId)) return -1; 2703 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2704 2705 // reader 2706 synchronized (mPackages) { 2707 PackageParser.Package p = mPackages.get(packageName); 2708 if(p != null) { 2709 return UserHandle.getUid(userId, p.applicationInfo.uid); 2710 } 2711 PackageSetting ps = mSettings.mPackages.get(packageName); 2712 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2713 return -1; 2714 } 2715 p = ps.pkg; 2716 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2717 } 2718 } 2719 2720 @Override 2721 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2722 if (!sUserManager.exists(userId)) { 2723 return null; 2724 } 2725 2726 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2727 "getPackageGids"); 2728 2729 // reader 2730 synchronized (mPackages) { 2731 PackageParser.Package p = mPackages.get(packageName); 2732 if (DEBUG_PACKAGE_INFO) { 2733 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2734 } 2735 if (p != null) { 2736 PackageSetting ps = (PackageSetting) p.mExtras; 2737 return ps.getPermissionsState().computeGids(userId); 2738 } 2739 } 2740 2741 return null; 2742 } 2743 2744 static PermissionInfo generatePermissionInfo( 2745 BasePermission bp, int flags) { 2746 if (bp.perm != null) { 2747 return PackageParser.generatePermissionInfo(bp.perm, flags); 2748 } 2749 PermissionInfo pi = new PermissionInfo(); 2750 pi.name = bp.name; 2751 pi.packageName = bp.sourcePackage; 2752 pi.nonLocalizedLabel = bp.name; 2753 pi.protectionLevel = bp.protectionLevel; 2754 return pi; 2755 } 2756 2757 @Override 2758 public PermissionInfo getPermissionInfo(String name, int flags) { 2759 // reader 2760 synchronized (mPackages) { 2761 final BasePermission p = mSettings.mPermissions.get(name); 2762 if (p != null) { 2763 return generatePermissionInfo(p, flags); 2764 } 2765 return null; 2766 } 2767 } 2768 2769 @Override 2770 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2771 // reader 2772 synchronized (mPackages) { 2773 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2774 for (BasePermission p : mSettings.mPermissions.values()) { 2775 if (group == null) { 2776 if (p.perm == null || p.perm.info.group == null) { 2777 out.add(generatePermissionInfo(p, flags)); 2778 } 2779 } else { 2780 if (p.perm != null && group.equals(p.perm.info.group)) { 2781 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2782 } 2783 } 2784 } 2785 2786 if (out.size() > 0) { 2787 return out; 2788 } 2789 return mPermissionGroups.containsKey(group) ? out : null; 2790 } 2791 } 2792 2793 @Override 2794 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2795 // reader 2796 synchronized (mPackages) { 2797 return PackageParser.generatePermissionGroupInfo( 2798 mPermissionGroups.get(name), flags); 2799 } 2800 } 2801 2802 @Override 2803 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2804 // reader 2805 synchronized (mPackages) { 2806 final int N = mPermissionGroups.size(); 2807 ArrayList<PermissionGroupInfo> out 2808 = new ArrayList<PermissionGroupInfo>(N); 2809 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2810 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2811 } 2812 return out; 2813 } 2814 } 2815 2816 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2817 int userId) { 2818 if (!sUserManager.exists(userId)) return null; 2819 PackageSetting ps = mSettings.mPackages.get(packageName); 2820 if (ps != null) { 2821 if (ps.pkg == null) { 2822 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2823 flags, userId); 2824 if (pInfo != null) { 2825 return pInfo.applicationInfo; 2826 } 2827 return null; 2828 } 2829 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2830 ps.readUserState(userId), userId); 2831 } 2832 return null; 2833 } 2834 2835 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2836 int userId) { 2837 if (!sUserManager.exists(userId)) return null; 2838 PackageSetting ps = mSettings.mPackages.get(packageName); 2839 if (ps != null) { 2840 PackageParser.Package pkg = ps.pkg; 2841 if (pkg == null) { 2842 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2843 return null; 2844 } 2845 // Only data remains, so we aren't worried about code paths 2846 pkg = new PackageParser.Package(packageName); 2847 pkg.applicationInfo.packageName = packageName; 2848 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2849 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2850 pkg.applicationInfo.dataDir = Environment 2851 .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName) 2852 .getAbsolutePath(); 2853 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2854 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2855 } 2856 return generatePackageInfo(pkg, flags, userId); 2857 } 2858 return null; 2859 } 2860 2861 @Override 2862 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2863 if (!sUserManager.exists(userId)) return null; 2864 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2865 // writer 2866 synchronized (mPackages) { 2867 PackageParser.Package p = mPackages.get(packageName); 2868 if (DEBUG_PACKAGE_INFO) Log.v( 2869 TAG, "getApplicationInfo " + packageName 2870 + ": " + p); 2871 if (p != null) { 2872 PackageSetting ps = mSettings.mPackages.get(packageName); 2873 if (ps == null) return null; 2874 // Note: isEnabledLP() does not apply here - always return info 2875 return PackageParser.generateApplicationInfo( 2876 p, flags, ps.readUserState(userId), userId); 2877 } 2878 if ("android".equals(packageName)||"system".equals(packageName)) { 2879 return mAndroidApplication; 2880 } 2881 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2882 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2883 } 2884 } 2885 return null; 2886 } 2887 2888 @Override 2889 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2890 final IPackageDataObserver observer) { 2891 mContext.enforceCallingOrSelfPermission( 2892 android.Manifest.permission.CLEAR_APP_CACHE, null); 2893 // Queue up an async operation since clearing cache may take a little while. 2894 mHandler.post(new Runnable() { 2895 public void run() { 2896 mHandler.removeCallbacks(this); 2897 int retCode = -1; 2898 synchronized (mInstallLock) { 2899 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2900 if (retCode < 0) { 2901 Slog.w(TAG, "Couldn't clear application caches"); 2902 } 2903 } 2904 if (observer != null) { 2905 try { 2906 observer.onRemoveCompleted(null, (retCode >= 0)); 2907 } catch (RemoteException e) { 2908 Slog.w(TAG, "RemoveException when invoking call back"); 2909 } 2910 } 2911 } 2912 }); 2913 } 2914 2915 @Override 2916 public void freeStorage(final String volumeUuid, final long freeStorageSize, 2917 final IntentSender pi) { 2918 mContext.enforceCallingOrSelfPermission( 2919 android.Manifest.permission.CLEAR_APP_CACHE, null); 2920 // Queue up an async operation since clearing cache may take a little while. 2921 mHandler.post(new Runnable() { 2922 public void run() { 2923 mHandler.removeCallbacks(this); 2924 int retCode = -1; 2925 synchronized (mInstallLock) { 2926 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2927 if (retCode < 0) { 2928 Slog.w(TAG, "Couldn't clear application caches"); 2929 } 2930 } 2931 if(pi != null) { 2932 try { 2933 // Callback via pending intent 2934 int code = (retCode >= 0) ? 1 : 0; 2935 pi.sendIntent(null, code, null, 2936 null, null); 2937 } catch (SendIntentException e1) { 2938 Slog.i(TAG, "Failed to send pending intent"); 2939 } 2940 } 2941 } 2942 }); 2943 } 2944 2945 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 2946 synchronized (mInstallLock) { 2947 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 2948 throw new IOException("Failed to free enough space"); 2949 } 2950 } 2951 } 2952 2953 @Override 2954 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2955 if (!sUserManager.exists(userId)) return null; 2956 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2957 synchronized (mPackages) { 2958 PackageParser.Activity a = mActivities.mActivities.get(component); 2959 2960 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2961 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2962 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2963 if (ps == null) return null; 2964 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2965 userId); 2966 } 2967 if (mResolveComponentName.equals(component)) { 2968 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2969 new PackageUserState(), userId); 2970 } 2971 } 2972 return null; 2973 } 2974 2975 @Override 2976 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2977 String resolvedType) { 2978 synchronized (mPackages) { 2979 if (component.equals(mResolveComponentName)) { 2980 // The resolver supports EVERYTHING! 2981 return true; 2982 } 2983 PackageParser.Activity a = mActivities.mActivities.get(component); 2984 if (a == null) { 2985 return false; 2986 } 2987 for (int i=0; i<a.intents.size(); i++) { 2988 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2989 intent.getData(), intent.getCategories(), TAG) >= 0) { 2990 return true; 2991 } 2992 } 2993 return false; 2994 } 2995 } 2996 2997 @Override 2998 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2999 if (!sUserManager.exists(userId)) return null; 3000 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 3001 synchronized (mPackages) { 3002 PackageParser.Activity a = mReceivers.mActivities.get(component); 3003 if (DEBUG_PACKAGE_INFO) Log.v( 3004 TAG, "getReceiverInfo " + component + ": " + a); 3005 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 3006 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3007 if (ps == null) return null; 3008 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3009 userId); 3010 } 3011 } 3012 return null; 3013 } 3014 3015 @Override 3016 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3017 if (!sUserManager.exists(userId)) return null; 3018 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 3019 synchronized (mPackages) { 3020 PackageParser.Service s = mServices.mServices.get(component); 3021 if (DEBUG_PACKAGE_INFO) Log.v( 3022 TAG, "getServiceInfo " + component + ": " + s); 3023 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 3024 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3025 if (ps == null) return null; 3026 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3027 userId); 3028 } 3029 } 3030 return null; 3031 } 3032 3033 @Override 3034 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3035 if (!sUserManager.exists(userId)) return null; 3036 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 3037 synchronized (mPackages) { 3038 PackageParser.Provider p = mProviders.mProviders.get(component); 3039 if (DEBUG_PACKAGE_INFO) Log.v( 3040 TAG, "getProviderInfo " + component + ": " + p); 3041 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 3042 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3043 if (ps == null) return null; 3044 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3045 userId); 3046 } 3047 } 3048 return null; 3049 } 3050 3051 @Override 3052 public String[] getSystemSharedLibraryNames() { 3053 Set<String> libSet; 3054 synchronized (mPackages) { 3055 libSet = mSharedLibraries.keySet(); 3056 int size = libSet.size(); 3057 if (size > 0) { 3058 String[] libs = new String[size]; 3059 libSet.toArray(libs); 3060 return libs; 3061 } 3062 } 3063 return null; 3064 } 3065 3066 /** 3067 * @hide 3068 */ 3069 PackageParser.Package findSharedNonSystemLibrary(String libName) { 3070 synchronized (mPackages) { 3071 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 3072 if (lib != null && lib.apk != null) { 3073 return mPackages.get(lib.apk); 3074 } 3075 } 3076 return null; 3077 } 3078 3079 @Override 3080 public FeatureInfo[] getSystemAvailableFeatures() { 3081 Collection<FeatureInfo> featSet; 3082 synchronized (mPackages) { 3083 featSet = mAvailableFeatures.values(); 3084 int size = featSet.size(); 3085 if (size > 0) { 3086 FeatureInfo[] features = new FeatureInfo[size+1]; 3087 featSet.toArray(features); 3088 FeatureInfo fi = new FeatureInfo(); 3089 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3090 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3091 features[size] = fi; 3092 return features; 3093 } 3094 } 3095 return null; 3096 } 3097 3098 @Override 3099 public boolean hasSystemFeature(String name) { 3100 synchronized (mPackages) { 3101 return mAvailableFeatures.containsKey(name); 3102 } 3103 } 3104 3105 private void checkValidCaller(int uid, int userId) { 3106 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 3107 return; 3108 3109 throw new SecurityException("Caller uid=" + uid 3110 + " is not privileged to communicate with user=" + userId); 3111 } 3112 3113 @Override 3114 public int checkPermission(String permName, String pkgName, int userId) { 3115 if (!sUserManager.exists(userId)) { 3116 return PackageManager.PERMISSION_DENIED; 3117 } 3118 3119 synchronized (mPackages) { 3120 final PackageParser.Package p = mPackages.get(pkgName); 3121 if (p != null && p.mExtras != null) { 3122 final PackageSetting ps = (PackageSetting) p.mExtras; 3123 final PermissionsState permissionsState = ps.getPermissionsState(); 3124 if (permissionsState.hasPermission(permName, userId)) { 3125 return PackageManager.PERMISSION_GRANTED; 3126 } 3127 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3128 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3129 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3130 return PackageManager.PERMISSION_GRANTED; 3131 } 3132 } 3133 } 3134 3135 return PackageManager.PERMISSION_DENIED; 3136 } 3137 3138 @Override 3139 public int checkUidPermission(String permName, int uid) { 3140 final int userId = UserHandle.getUserId(uid); 3141 3142 if (!sUserManager.exists(userId)) { 3143 return PackageManager.PERMISSION_DENIED; 3144 } 3145 3146 synchronized (mPackages) { 3147 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3148 if (obj != null) { 3149 final SettingBase ps = (SettingBase) obj; 3150 final PermissionsState permissionsState = ps.getPermissionsState(); 3151 if (permissionsState.hasPermission(permName, userId)) { 3152 return PackageManager.PERMISSION_GRANTED; 3153 } 3154 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3155 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3156 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3157 return PackageManager.PERMISSION_GRANTED; 3158 } 3159 } else { 3160 ArraySet<String> perms = mSystemPermissions.get(uid); 3161 if (perms != null) { 3162 if (perms.contains(permName)) { 3163 return PackageManager.PERMISSION_GRANTED; 3164 } 3165 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3166 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3167 return PackageManager.PERMISSION_GRANTED; 3168 } 3169 } 3170 } 3171 } 3172 3173 return PackageManager.PERMISSION_DENIED; 3174 } 3175 3176 @Override 3177 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3178 if (UserHandle.getCallingUserId() != userId) { 3179 mContext.enforceCallingPermission( 3180 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3181 "isPermissionRevokedByPolicy for user " + userId); 3182 } 3183 3184 if (checkPermission(permission, packageName, userId) 3185 == PackageManager.PERMISSION_GRANTED) { 3186 return false; 3187 } 3188 3189 final long identity = Binder.clearCallingIdentity(); 3190 try { 3191 final int flags = getPermissionFlags(permission, packageName, userId); 3192 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3193 } finally { 3194 Binder.restoreCallingIdentity(identity); 3195 } 3196 } 3197 3198 /** 3199 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3200 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3201 * @param checkShell TODO(yamasani): 3202 * @param message the message to log on security exception 3203 */ 3204 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3205 boolean checkShell, String message) { 3206 if (userId < 0) { 3207 throw new IllegalArgumentException("Invalid userId " + userId); 3208 } 3209 if (checkShell) { 3210 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3211 } 3212 if (userId == UserHandle.getUserId(callingUid)) return; 3213 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3214 if (requireFullPermission) { 3215 mContext.enforceCallingOrSelfPermission( 3216 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3217 } else { 3218 try { 3219 mContext.enforceCallingOrSelfPermission( 3220 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3221 } catch (SecurityException se) { 3222 mContext.enforceCallingOrSelfPermission( 3223 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3224 } 3225 } 3226 } 3227 } 3228 3229 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3230 if (callingUid == Process.SHELL_UID) { 3231 if (userHandle >= 0 3232 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3233 throw new SecurityException("Shell does not have permission to access user " 3234 + userHandle); 3235 } else if (userHandle < 0) { 3236 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3237 + Debug.getCallers(3)); 3238 } 3239 } 3240 } 3241 3242 private BasePermission findPermissionTreeLP(String permName) { 3243 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3244 if (permName.startsWith(bp.name) && 3245 permName.length() > bp.name.length() && 3246 permName.charAt(bp.name.length()) == '.') { 3247 return bp; 3248 } 3249 } 3250 return null; 3251 } 3252 3253 private BasePermission checkPermissionTreeLP(String permName) { 3254 if (permName != null) { 3255 BasePermission bp = findPermissionTreeLP(permName); 3256 if (bp != null) { 3257 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3258 return bp; 3259 } 3260 throw new SecurityException("Calling uid " 3261 + Binder.getCallingUid() 3262 + " is not allowed to add to permission tree " 3263 + bp.name + " owned by uid " + bp.uid); 3264 } 3265 } 3266 throw new SecurityException("No permission tree found for " + permName); 3267 } 3268 3269 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3270 if (s1 == null) { 3271 return s2 == null; 3272 } 3273 if (s2 == null) { 3274 return false; 3275 } 3276 if (s1.getClass() != s2.getClass()) { 3277 return false; 3278 } 3279 return s1.equals(s2); 3280 } 3281 3282 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3283 if (pi1.icon != pi2.icon) return false; 3284 if (pi1.logo != pi2.logo) return false; 3285 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3286 if (!compareStrings(pi1.name, pi2.name)) return false; 3287 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3288 // We'll take care of setting this one. 3289 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3290 // These are not currently stored in settings. 3291 //if (!compareStrings(pi1.group, pi2.group)) return false; 3292 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3293 //if (pi1.labelRes != pi2.labelRes) return false; 3294 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3295 return true; 3296 } 3297 3298 int permissionInfoFootprint(PermissionInfo info) { 3299 int size = info.name.length(); 3300 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3301 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3302 return size; 3303 } 3304 3305 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3306 int size = 0; 3307 for (BasePermission perm : mSettings.mPermissions.values()) { 3308 if (perm.uid == tree.uid) { 3309 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3310 } 3311 } 3312 return size; 3313 } 3314 3315 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3316 // We calculate the max size of permissions defined by this uid and throw 3317 // if that plus the size of 'info' would exceed our stated maximum. 3318 if (tree.uid != Process.SYSTEM_UID) { 3319 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3320 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3321 throw new SecurityException("Permission tree size cap exceeded"); 3322 } 3323 } 3324 } 3325 3326 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3327 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3328 throw new SecurityException("Label must be specified in permission"); 3329 } 3330 BasePermission tree = checkPermissionTreeLP(info.name); 3331 BasePermission bp = mSettings.mPermissions.get(info.name); 3332 boolean added = bp == null; 3333 boolean changed = true; 3334 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3335 if (added) { 3336 enforcePermissionCapLocked(info, tree); 3337 bp = new BasePermission(info.name, tree.sourcePackage, 3338 BasePermission.TYPE_DYNAMIC); 3339 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3340 throw new SecurityException( 3341 "Not allowed to modify non-dynamic permission " 3342 + info.name); 3343 } else { 3344 if (bp.protectionLevel == fixedLevel 3345 && bp.perm.owner.equals(tree.perm.owner) 3346 && bp.uid == tree.uid 3347 && comparePermissionInfos(bp.perm.info, info)) { 3348 changed = false; 3349 } 3350 } 3351 bp.protectionLevel = fixedLevel; 3352 info = new PermissionInfo(info); 3353 info.protectionLevel = fixedLevel; 3354 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3355 bp.perm.info.packageName = tree.perm.info.packageName; 3356 bp.uid = tree.uid; 3357 if (added) { 3358 mSettings.mPermissions.put(info.name, bp); 3359 } 3360 if (changed) { 3361 if (!async) { 3362 mSettings.writeLPr(); 3363 } else { 3364 scheduleWriteSettingsLocked(); 3365 } 3366 } 3367 return added; 3368 } 3369 3370 @Override 3371 public boolean addPermission(PermissionInfo info) { 3372 synchronized (mPackages) { 3373 return addPermissionLocked(info, false); 3374 } 3375 } 3376 3377 @Override 3378 public boolean addPermissionAsync(PermissionInfo info) { 3379 synchronized (mPackages) { 3380 return addPermissionLocked(info, true); 3381 } 3382 } 3383 3384 @Override 3385 public void removePermission(String name) { 3386 synchronized (mPackages) { 3387 checkPermissionTreeLP(name); 3388 BasePermission bp = mSettings.mPermissions.get(name); 3389 if (bp != null) { 3390 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3391 throw new SecurityException( 3392 "Not allowed to modify non-dynamic permission " 3393 + name); 3394 } 3395 mSettings.mPermissions.remove(name); 3396 mSettings.writeLPr(); 3397 } 3398 } 3399 } 3400 3401 private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg, 3402 BasePermission bp) { 3403 int index = pkg.requestedPermissions.indexOf(bp.name); 3404 if (index == -1) { 3405 throw new SecurityException("Package " + pkg.packageName 3406 + " has not requested permission " + bp.name); 3407 } 3408 if (!bp.isRuntime()) { 3409 throw new SecurityException("Permission " + bp.name 3410 + " is not a changeable permission type"); 3411 } 3412 } 3413 3414 @Override 3415 public void grantRuntimePermission(String packageName, String name, final int userId) { 3416 if (!sUserManager.exists(userId)) { 3417 Log.e(TAG, "No such user:" + userId); 3418 return; 3419 } 3420 3421 mContext.enforceCallingOrSelfPermission( 3422 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3423 "grantRuntimePermission"); 3424 3425 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3426 "grantRuntimePermission"); 3427 3428 final int uid; 3429 final SettingBase sb; 3430 3431 synchronized (mPackages) { 3432 final PackageParser.Package pkg = mPackages.get(packageName); 3433 if (pkg == null) { 3434 throw new IllegalArgumentException("Unknown package: " + packageName); 3435 } 3436 3437 final BasePermission bp = mSettings.mPermissions.get(name); 3438 if (bp == null) { 3439 throw new IllegalArgumentException("Unknown permission: " + name); 3440 } 3441 3442 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3443 3444 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3445 sb = (SettingBase) pkg.mExtras; 3446 if (sb == null) { 3447 throw new IllegalArgumentException("Unknown package: " + packageName); 3448 } 3449 3450 final PermissionsState permissionsState = sb.getPermissionsState(); 3451 3452 final int flags = permissionsState.getPermissionFlags(name, userId); 3453 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3454 throw new SecurityException("Cannot grant system fixed permission: " 3455 + name + " for package: " + packageName); 3456 } 3457 3458 final int result = permissionsState.grantRuntimePermission(bp, userId); 3459 switch (result) { 3460 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3461 return; 3462 } 3463 3464 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3465 mHandler.post(new Runnable() { 3466 @Override 3467 public void run() { 3468 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED); 3469 } 3470 }); 3471 } break; 3472 } 3473 3474 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3475 3476 // Not critical if that is lost - app has to request again. 3477 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3478 } 3479 3480 // Only need to do this if user is initialized. Otherwise it's a new user 3481 // and there are no processes running as the user yet and there's no need 3482 // to make an expensive call to remount processes for the changed permissions. 3483 if (READ_EXTERNAL_STORAGE.equals(name) 3484 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3485 final long token = Binder.clearCallingIdentity(); 3486 try { 3487 if (sUserManager.isInitialized(userId)) { 3488 MountServiceInternal mountServiceInternal = LocalServices.getService( 3489 MountServiceInternal.class); 3490 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 3491 } 3492 } finally { 3493 Binder.restoreCallingIdentity(token); 3494 } 3495 } 3496 } 3497 3498 @Override 3499 public void revokeRuntimePermission(String packageName, String name, int userId) { 3500 if (!sUserManager.exists(userId)) { 3501 Log.e(TAG, "No such user:" + userId); 3502 return; 3503 } 3504 3505 mContext.enforceCallingOrSelfPermission( 3506 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3507 "revokeRuntimePermission"); 3508 3509 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3510 "revokeRuntimePermission"); 3511 3512 final SettingBase sb; 3513 3514 synchronized (mPackages) { 3515 final PackageParser.Package pkg = mPackages.get(packageName); 3516 if (pkg == null) { 3517 throw new IllegalArgumentException("Unknown package: " + packageName); 3518 } 3519 3520 final BasePermission bp = mSettings.mPermissions.get(name); 3521 if (bp == null) { 3522 throw new IllegalArgumentException("Unknown permission: " + name); 3523 } 3524 3525 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3526 3527 sb = (SettingBase) pkg.mExtras; 3528 if (sb == null) { 3529 throw new IllegalArgumentException("Unknown package: " + packageName); 3530 } 3531 3532 final PermissionsState permissionsState = sb.getPermissionsState(); 3533 3534 final int flags = permissionsState.getPermissionFlags(name, userId); 3535 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3536 throw new SecurityException("Cannot revoke system fixed permission: " 3537 + name + " for package: " + packageName); 3538 } 3539 3540 if (permissionsState.revokeRuntimePermission(bp, userId) == 3541 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3542 return; 3543 } 3544 3545 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3546 3547 // Critical, after this call app should never have the permission. 3548 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3549 } 3550 3551 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3552 } 3553 3554 @Override 3555 public void resetRuntimePermissions() { 3556 mContext.enforceCallingOrSelfPermission( 3557 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3558 "revokeRuntimePermission"); 3559 3560 int callingUid = Binder.getCallingUid(); 3561 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3562 mContext.enforceCallingOrSelfPermission( 3563 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3564 "resetRuntimePermissions"); 3565 } 3566 3567 synchronized (mPackages) { 3568 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 3569 for (int userId : UserManagerService.getInstance().getUserIds()) { 3570 final int packageCount = mPackages.size(); 3571 for (int i = 0; i < packageCount; i++) { 3572 PackageParser.Package pkg = mPackages.valueAt(i); 3573 if (!(pkg.mExtras instanceof PackageSetting)) { 3574 continue; 3575 } 3576 PackageSetting ps = (PackageSetting) pkg.mExtras; 3577 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 3578 } 3579 } 3580 } 3581 } 3582 3583 @Override 3584 public int getPermissionFlags(String name, String packageName, int userId) { 3585 if (!sUserManager.exists(userId)) { 3586 return 0; 3587 } 3588 3589 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 3590 3591 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3592 "getPermissionFlags"); 3593 3594 synchronized (mPackages) { 3595 final PackageParser.Package pkg = mPackages.get(packageName); 3596 if (pkg == null) { 3597 throw new IllegalArgumentException("Unknown package: " + packageName); 3598 } 3599 3600 final BasePermission bp = mSettings.mPermissions.get(name); 3601 if (bp == null) { 3602 throw new IllegalArgumentException("Unknown permission: " + name); 3603 } 3604 3605 SettingBase sb = (SettingBase) pkg.mExtras; 3606 if (sb == null) { 3607 throw new IllegalArgumentException("Unknown package: " + packageName); 3608 } 3609 3610 PermissionsState permissionsState = sb.getPermissionsState(); 3611 return permissionsState.getPermissionFlags(name, userId); 3612 } 3613 } 3614 3615 @Override 3616 public void updatePermissionFlags(String name, String packageName, int flagMask, 3617 int flagValues, int userId) { 3618 if (!sUserManager.exists(userId)) { 3619 return; 3620 } 3621 3622 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 3623 3624 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3625 "updatePermissionFlags"); 3626 3627 // Only the system can change these flags and nothing else. 3628 if (getCallingUid() != Process.SYSTEM_UID) { 3629 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3630 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3631 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3632 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3633 } 3634 3635 synchronized (mPackages) { 3636 final PackageParser.Package pkg = mPackages.get(packageName); 3637 if (pkg == null) { 3638 throw new IllegalArgumentException("Unknown package: " + packageName); 3639 } 3640 3641 final BasePermission bp = mSettings.mPermissions.get(name); 3642 if (bp == null) { 3643 throw new IllegalArgumentException("Unknown permission: " + name); 3644 } 3645 3646 SettingBase sb = (SettingBase) pkg.mExtras; 3647 if (sb == null) { 3648 throw new IllegalArgumentException("Unknown package: " + packageName); 3649 } 3650 3651 PermissionsState permissionsState = sb.getPermissionsState(); 3652 3653 // Only the package manager can change flags for system component permissions. 3654 final int flags = permissionsState.getPermissionFlags(bp.name, userId); 3655 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3656 return; 3657 } 3658 3659 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 3660 3661 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3662 // Install and runtime permissions are stored in different places, 3663 // so figure out what permission changed and persist the change. 3664 if (permissionsState.getInstallPermissionState(name) != null) { 3665 scheduleWriteSettingsLocked(); 3666 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 3667 || hadState) { 3668 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3669 } 3670 } 3671 } 3672 } 3673 3674 /** 3675 * Update the permission flags for all packages and runtime permissions of a user in order 3676 * to allow device or profile owner to remove POLICY_FIXED. 3677 */ 3678 @Override 3679 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 3680 if (!sUserManager.exists(userId)) { 3681 return; 3682 } 3683 3684 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 3685 3686 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3687 "updatePermissionFlagsForAllApps"); 3688 3689 // Only the system can change system fixed flags. 3690 if (getCallingUid() != Process.SYSTEM_UID) { 3691 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3692 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3693 } 3694 3695 synchronized (mPackages) { 3696 boolean changed = false; 3697 final int packageCount = mPackages.size(); 3698 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 3699 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 3700 SettingBase sb = (SettingBase) pkg.mExtras; 3701 if (sb == null) { 3702 continue; 3703 } 3704 PermissionsState permissionsState = sb.getPermissionsState(); 3705 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 3706 userId, flagMask, flagValues); 3707 } 3708 if (changed) { 3709 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3710 } 3711 } 3712 } 3713 3714 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 3715 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 3716 != PackageManager.PERMISSION_GRANTED 3717 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 3718 != PackageManager.PERMISSION_GRANTED) { 3719 throw new SecurityException(message + " requires " 3720 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 3721 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 3722 } 3723 } 3724 3725 @Override 3726 public boolean shouldShowRequestPermissionRationale(String permissionName, 3727 String packageName, int userId) { 3728 if (UserHandle.getCallingUserId() != userId) { 3729 mContext.enforceCallingPermission( 3730 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3731 "canShowRequestPermissionRationale for user " + userId); 3732 } 3733 3734 final int uid = getPackageUid(packageName, userId); 3735 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 3736 return false; 3737 } 3738 3739 if (checkPermission(permissionName, packageName, userId) 3740 == PackageManager.PERMISSION_GRANTED) { 3741 return false; 3742 } 3743 3744 final int flags; 3745 3746 final long identity = Binder.clearCallingIdentity(); 3747 try { 3748 flags = getPermissionFlags(permissionName, 3749 packageName, userId); 3750 } finally { 3751 Binder.restoreCallingIdentity(identity); 3752 } 3753 3754 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 3755 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 3756 | PackageManager.FLAG_PERMISSION_USER_FIXED; 3757 3758 if ((flags & fixedFlags) != 0) { 3759 return false; 3760 } 3761 3762 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 3763 } 3764 3765 void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) { 3766 BasePermission bp = mSettings.mPermissions.get(permission); 3767 if (bp == null) { 3768 throw new SecurityException("Missing " + permission + " permission"); 3769 } 3770 3771 SettingBase sb = (SettingBase) pkg.mExtras; 3772 PermissionsState permissionsState = sb.getPermissionsState(); 3773 3774 if (permissionsState.grantInstallPermission(bp) != 3775 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3776 scheduleWriteSettingsLocked(); 3777 } 3778 } 3779 3780 @Override 3781 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3782 mContext.enforceCallingOrSelfPermission( 3783 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 3784 "addOnPermissionsChangeListener"); 3785 3786 synchronized (mPackages) { 3787 mOnPermissionChangeListeners.addListenerLocked(listener); 3788 } 3789 } 3790 3791 @Override 3792 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3793 synchronized (mPackages) { 3794 mOnPermissionChangeListeners.removeListenerLocked(listener); 3795 } 3796 } 3797 3798 @Override 3799 public boolean isProtectedBroadcast(String actionName) { 3800 synchronized (mPackages) { 3801 return mProtectedBroadcasts.contains(actionName); 3802 } 3803 } 3804 3805 @Override 3806 public int checkSignatures(String pkg1, String pkg2) { 3807 synchronized (mPackages) { 3808 final PackageParser.Package p1 = mPackages.get(pkg1); 3809 final PackageParser.Package p2 = mPackages.get(pkg2); 3810 if (p1 == null || p1.mExtras == null 3811 || p2 == null || p2.mExtras == null) { 3812 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3813 } 3814 return compareSignatures(p1.mSignatures, p2.mSignatures); 3815 } 3816 } 3817 3818 @Override 3819 public int checkUidSignatures(int uid1, int uid2) { 3820 // Map to base uids. 3821 uid1 = UserHandle.getAppId(uid1); 3822 uid2 = UserHandle.getAppId(uid2); 3823 // reader 3824 synchronized (mPackages) { 3825 Signature[] s1; 3826 Signature[] s2; 3827 Object obj = mSettings.getUserIdLPr(uid1); 3828 if (obj != null) { 3829 if (obj instanceof SharedUserSetting) { 3830 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3831 } else if (obj instanceof PackageSetting) { 3832 s1 = ((PackageSetting)obj).signatures.mSignatures; 3833 } else { 3834 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3835 } 3836 } else { 3837 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3838 } 3839 obj = mSettings.getUserIdLPr(uid2); 3840 if (obj != null) { 3841 if (obj instanceof SharedUserSetting) { 3842 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3843 } else if (obj instanceof PackageSetting) { 3844 s2 = ((PackageSetting)obj).signatures.mSignatures; 3845 } else { 3846 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3847 } 3848 } else { 3849 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3850 } 3851 return compareSignatures(s1, s2); 3852 } 3853 } 3854 3855 private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) { 3856 final long identity = Binder.clearCallingIdentity(); 3857 try { 3858 if (sb instanceof SharedUserSetting) { 3859 SharedUserSetting sus = (SharedUserSetting) sb; 3860 final int packageCount = sus.packages.size(); 3861 for (int i = 0; i < packageCount; i++) { 3862 PackageSetting susPs = sus.packages.valueAt(i); 3863 if (userId == UserHandle.USER_ALL) { 3864 killApplication(susPs.pkg.packageName, susPs.appId, reason); 3865 } else { 3866 final int uid = UserHandle.getUid(userId, susPs.appId); 3867 killUid(uid, reason); 3868 } 3869 } 3870 } else if (sb instanceof PackageSetting) { 3871 PackageSetting ps = (PackageSetting) sb; 3872 if (userId == UserHandle.USER_ALL) { 3873 killApplication(ps.pkg.packageName, ps.appId, reason); 3874 } else { 3875 final int uid = UserHandle.getUid(userId, ps.appId); 3876 killUid(uid, reason); 3877 } 3878 } 3879 } finally { 3880 Binder.restoreCallingIdentity(identity); 3881 } 3882 } 3883 3884 private static void killUid(int uid, String reason) { 3885 IActivityManager am = ActivityManagerNative.getDefault(); 3886 if (am != null) { 3887 try { 3888 am.killUid(uid, reason); 3889 } catch (RemoteException e) { 3890 /* ignore - same process */ 3891 } 3892 } 3893 } 3894 3895 /** 3896 * Compares two sets of signatures. Returns: 3897 * <br /> 3898 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3899 * <br /> 3900 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3901 * <br /> 3902 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3903 * <br /> 3904 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3905 * <br /> 3906 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3907 */ 3908 static int compareSignatures(Signature[] s1, Signature[] s2) { 3909 if (s1 == null) { 3910 return s2 == null 3911 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3912 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3913 } 3914 3915 if (s2 == null) { 3916 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3917 } 3918 3919 if (s1.length != s2.length) { 3920 return PackageManager.SIGNATURE_NO_MATCH; 3921 } 3922 3923 // Since both signature sets are of size 1, we can compare without HashSets. 3924 if (s1.length == 1) { 3925 return s1[0].equals(s2[0]) ? 3926 PackageManager.SIGNATURE_MATCH : 3927 PackageManager.SIGNATURE_NO_MATCH; 3928 } 3929 3930 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3931 for (Signature sig : s1) { 3932 set1.add(sig); 3933 } 3934 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3935 for (Signature sig : s2) { 3936 set2.add(sig); 3937 } 3938 // Make sure s2 contains all signatures in s1. 3939 if (set1.equals(set2)) { 3940 return PackageManager.SIGNATURE_MATCH; 3941 } 3942 return PackageManager.SIGNATURE_NO_MATCH; 3943 } 3944 3945 /** 3946 * If the database version for this type of package (internal storage or 3947 * external storage) is less than the version where package signatures 3948 * were updated, return true. 3949 */ 3950 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3951 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 3952 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 3953 } 3954 3955 /** 3956 * Used for backward compatibility to make sure any packages with 3957 * certificate chains get upgraded to the new style. {@code existingSigs} 3958 * will be in the old format (since they were stored on disk from before the 3959 * system upgrade) and {@code scannedSigs} will be in the newer format. 3960 */ 3961 private int compareSignaturesCompat(PackageSignatures existingSigs, 3962 PackageParser.Package scannedPkg) { 3963 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 3964 return PackageManager.SIGNATURE_NO_MATCH; 3965 } 3966 3967 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 3968 for (Signature sig : existingSigs.mSignatures) { 3969 existingSet.add(sig); 3970 } 3971 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 3972 for (Signature sig : scannedPkg.mSignatures) { 3973 try { 3974 Signature[] chainSignatures = sig.getChainSignatures(); 3975 for (Signature chainSig : chainSignatures) { 3976 scannedCompatSet.add(chainSig); 3977 } 3978 } catch (CertificateEncodingException e) { 3979 scannedCompatSet.add(sig); 3980 } 3981 } 3982 /* 3983 * Make sure the expanded scanned set contains all signatures in the 3984 * existing one. 3985 */ 3986 if (scannedCompatSet.equals(existingSet)) { 3987 // Migrate the old signatures to the new scheme. 3988 existingSigs.assignSignatures(scannedPkg.mSignatures); 3989 // The new KeySets will be re-added later in the scanning process. 3990 synchronized (mPackages) { 3991 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 3992 } 3993 return PackageManager.SIGNATURE_MATCH; 3994 } 3995 return PackageManager.SIGNATURE_NO_MATCH; 3996 } 3997 3998 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3999 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4000 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4001 } 4002 4003 private int compareSignaturesRecover(PackageSignatures existingSigs, 4004 PackageParser.Package scannedPkg) { 4005 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4006 return PackageManager.SIGNATURE_NO_MATCH; 4007 } 4008 4009 String msg = null; 4010 try { 4011 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4012 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4013 + scannedPkg.packageName); 4014 return PackageManager.SIGNATURE_MATCH; 4015 } 4016 } catch (CertificateException e) { 4017 msg = e.getMessage(); 4018 } 4019 4020 logCriticalInfo(Log.INFO, 4021 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4022 return PackageManager.SIGNATURE_NO_MATCH; 4023 } 4024 4025 @Override 4026 public String[] getPackagesForUid(int uid) { 4027 uid = UserHandle.getAppId(uid); 4028 // reader 4029 synchronized (mPackages) { 4030 Object obj = mSettings.getUserIdLPr(uid); 4031 if (obj instanceof SharedUserSetting) { 4032 final SharedUserSetting sus = (SharedUserSetting) obj; 4033 final int N = sus.packages.size(); 4034 final String[] res = new String[N]; 4035 final Iterator<PackageSetting> it = sus.packages.iterator(); 4036 int i = 0; 4037 while (it.hasNext()) { 4038 res[i++] = it.next().name; 4039 } 4040 return res; 4041 } else if (obj instanceof PackageSetting) { 4042 final PackageSetting ps = (PackageSetting) obj; 4043 return new String[] { ps.name }; 4044 } 4045 } 4046 return null; 4047 } 4048 4049 @Override 4050 public String getNameForUid(int uid) { 4051 // reader 4052 synchronized (mPackages) { 4053 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4054 if (obj instanceof SharedUserSetting) { 4055 final SharedUserSetting sus = (SharedUserSetting) obj; 4056 return sus.name + ":" + sus.userId; 4057 } else if (obj instanceof PackageSetting) { 4058 final PackageSetting ps = (PackageSetting) obj; 4059 return ps.name; 4060 } 4061 } 4062 return null; 4063 } 4064 4065 @Override 4066 public int getUidForSharedUser(String sharedUserName) { 4067 if(sharedUserName == null) { 4068 return -1; 4069 } 4070 // reader 4071 synchronized (mPackages) { 4072 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4073 if (suid == null) { 4074 return -1; 4075 } 4076 return suid.userId; 4077 } 4078 } 4079 4080 @Override 4081 public int getFlagsForUid(int uid) { 4082 synchronized (mPackages) { 4083 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4084 if (obj instanceof SharedUserSetting) { 4085 final SharedUserSetting sus = (SharedUserSetting) obj; 4086 return sus.pkgFlags; 4087 } else if (obj instanceof PackageSetting) { 4088 final PackageSetting ps = (PackageSetting) obj; 4089 return ps.pkgFlags; 4090 } 4091 } 4092 return 0; 4093 } 4094 4095 @Override 4096 public int getPrivateFlagsForUid(int uid) { 4097 synchronized (mPackages) { 4098 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4099 if (obj instanceof SharedUserSetting) { 4100 final SharedUserSetting sus = (SharedUserSetting) obj; 4101 return sus.pkgPrivateFlags; 4102 } else if (obj instanceof PackageSetting) { 4103 final PackageSetting ps = (PackageSetting) obj; 4104 return ps.pkgPrivateFlags; 4105 } 4106 } 4107 return 0; 4108 } 4109 4110 @Override 4111 public boolean isUidPrivileged(int uid) { 4112 uid = UserHandle.getAppId(uid); 4113 // reader 4114 synchronized (mPackages) { 4115 Object obj = mSettings.getUserIdLPr(uid); 4116 if (obj instanceof SharedUserSetting) { 4117 final SharedUserSetting sus = (SharedUserSetting) obj; 4118 final Iterator<PackageSetting> it = sus.packages.iterator(); 4119 while (it.hasNext()) { 4120 if (it.next().isPrivileged()) { 4121 return true; 4122 } 4123 } 4124 } else if (obj instanceof PackageSetting) { 4125 final PackageSetting ps = (PackageSetting) obj; 4126 return ps.isPrivileged(); 4127 } 4128 } 4129 return false; 4130 } 4131 4132 @Override 4133 public String[] getAppOpPermissionPackages(String permissionName) { 4134 synchronized (mPackages) { 4135 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4136 if (pkgs == null) { 4137 return null; 4138 } 4139 return pkgs.toArray(new String[pkgs.size()]); 4140 } 4141 } 4142 4143 @Override 4144 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4145 int flags, int userId) { 4146 if (!sUserManager.exists(userId)) return null; 4147 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 4148 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4149 return chooseBestActivity(intent, resolvedType, flags, query, userId); 4150 } 4151 4152 @Override 4153 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4154 IntentFilter filter, int match, ComponentName activity) { 4155 final int userId = UserHandle.getCallingUserId(); 4156 if (DEBUG_PREFERRED) { 4157 Log.v(TAG, "setLastChosenActivity intent=" + intent 4158 + " resolvedType=" + resolvedType 4159 + " flags=" + flags 4160 + " filter=" + filter 4161 + " match=" + match 4162 + " activity=" + activity); 4163 filter.dump(new PrintStreamPrinter(System.out), " "); 4164 } 4165 intent.setComponent(null); 4166 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4167 // Find any earlier preferred or last chosen entries and nuke them 4168 findPreferredActivity(intent, resolvedType, 4169 flags, query, 0, false, true, false, userId); 4170 // Add the new activity as the last chosen for this filter 4171 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4172 "Setting last chosen"); 4173 } 4174 4175 @Override 4176 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4177 final int userId = UserHandle.getCallingUserId(); 4178 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4179 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4180 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4181 false, false, false, userId); 4182 } 4183 4184 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4185 int flags, List<ResolveInfo> query, int userId) { 4186 if (query != null) { 4187 final int N = query.size(); 4188 if (N == 1) { 4189 return query.get(0); 4190 } else if (N > 1) { 4191 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4192 // If there is more than one activity with the same priority, 4193 // then let the user decide between them. 4194 ResolveInfo r0 = query.get(0); 4195 ResolveInfo r1 = query.get(1); 4196 if (DEBUG_INTENT_MATCHING || debug) { 4197 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4198 + r1.activityInfo.name + "=" + r1.priority); 4199 } 4200 // If the first activity has a higher priority, or a different 4201 // default, then it is always desireable to pick it. 4202 if (r0.priority != r1.priority 4203 || r0.preferredOrder != r1.preferredOrder 4204 || r0.isDefault != r1.isDefault) { 4205 return query.get(0); 4206 } 4207 // If we have saved a preference for a preferred activity for 4208 // this Intent, use that. 4209 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4210 flags, query, r0.priority, true, false, debug, userId); 4211 if (ri != null) { 4212 return ri; 4213 } 4214 if (userId != 0) { 4215 ri = new ResolveInfo(mResolveInfo); 4216 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4217 ri.activityInfo.applicationInfo = new ApplicationInfo( 4218 ri.activityInfo.applicationInfo); 4219 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4220 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4221 return ri; 4222 } 4223 return mResolveInfo; 4224 } 4225 } 4226 return null; 4227 } 4228 4229 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4230 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4231 final int N = query.size(); 4232 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4233 .get(userId); 4234 // Get the list of persistent preferred activities that handle the intent 4235 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4236 List<PersistentPreferredActivity> pprefs = ppir != null 4237 ? ppir.queryIntent(intent, resolvedType, 4238 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4239 : null; 4240 if (pprefs != null && pprefs.size() > 0) { 4241 final int M = pprefs.size(); 4242 for (int i=0; i<M; i++) { 4243 final PersistentPreferredActivity ppa = pprefs.get(i); 4244 if (DEBUG_PREFERRED || debug) { 4245 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4246 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4247 + "\n component=" + ppa.mComponent); 4248 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4249 } 4250 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4251 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4252 if (DEBUG_PREFERRED || debug) { 4253 Slog.v(TAG, "Found persistent preferred activity:"); 4254 if (ai != null) { 4255 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4256 } else { 4257 Slog.v(TAG, " null"); 4258 } 4259 } 4260 if (ai == null) { 4261 // This previously registered persistent preferred activity 4262 // component is no longer known. Ignore it and do NOT remove it. 4263 continue; 4264 } 4265 for (int j=0; j<N; j++) { 4266 final ResolveInfo ri = query.get(j); 4267 if (!ri.activityInfo.applicationInfo.packageName 4268 .equals(ai.applicationInfo.packageName)) { 4269 continue; 4270 } 4271 if (!ri.activityInfo.name.equals(ai.name)) { 4272 continue; 4273 } 4274 // Found a persistent preference that can handle the intent. 4275 if (DEBUG_PREFERRED || debug) { 4276 Slog.v(TAG, "Returning persistent preferred activity: " + 4277 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4278 } 4279 return ri; 4280 } 4281 } 4282 } 4283 return null; 4284 } 4285 4286 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4287 List<ResolveInfo> query, int priority, boolean always, 4288 boolean removeMatches, boolean debug, int userId) { 4289 if (!sUserManager.exists(userId)) return null; 4290 // writer 4291 synchronized (mPackages) { 4292 if (intent.getSelector() != null) { 4293 intent = intent.getSelector(); 4294 } 4295 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4296 4297 // Try to find a matching persistent preferred activity. 4298 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4299 debug, userId); 4300 4301 // If a persistent preferred activity matched, use it. 4302 if (pri != null) { 4303 return pri; 4304 } 4305 4306 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4307 // Get the list of preferred activities that handle the intent 4308 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4309 List<PreferredActivity> prefs = pir != null 4310 ? pir.queryIntent(intent, resolvedType, 4311 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4312 : null; 4313 if (prefs != null && prefs.size() > 0) { 4314 boolean changed = false; 4315 try { 4316 // First figure out how good the original match set is. 4317 // We will only allow preferred activities that came 4318 // from the same match quality. 4319 int match = 0; 4320 4321 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4322 4323 final int N = query.size(); 4324 for (int j=0; j<N; j++) { 4325 final ResolveInfo ri = query.get(j); 4326 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4327 + ": 0x" + Integer.toHexString(match)); 4328 if (ri.match > match) { 4329 match = ri.match; 4330 } 4331 } 4332 4333 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4334 + Integer.toHexString(match)); 4335 4336 match &= IntentFilter.MATCH_CATEGORY_MASK; 4337 final int M = prefs.size(); 4338 for (int i=0; i<M; i++) { 4339 final PreferredActivity pa = prefs.get(i); 4340 if (DEBUG_PREFERRED || debug) { 4341 Slog.v(TAG, "Checking PreferredActivity ds=" 4342 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4343 + "\n component=" + pa.mPref.mComponent); 4344 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4345 } 4346 if (pa.mPref.mMatch != match) { 4347 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4348 + Integer.toHexString(pa.mPref.mMatch)); 4349 continue; 4350 } 4351 // If it's not an "always" type preferred activity and that's what we're 4352 // looking for, skip it. 4353 if (always && !pa.mPref.mAlways) { 4354 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4355 continue; 4356 } 4357 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4358 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4359 if (DEBUG_PREFERRED || debug) { 4360 Slog.v(TAG, "Found preferred activity:"); 4361 if (ai != null) { 4362 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4363 } else { 4364 Slog.v(TAG, " null"); 4365 } 4366 } 4367 if (ai == null) { 4368 // This previously registered preferred activity 4369 // component is no longer known. Most likely an update 4370 // to the app was installed and in the new version this 4371 // component no longer exists. Clean it up by removing 4372 // it from the preferred activities list, and skip it. 4373 Slog.w(TAG, "Removing dangling preferred activity: " 4374 + pa.mPref.mComponent); 4375 pir.removeFilter(pa); 4376 changed = true; 4377 continue; 4378 } 4379 for (int j=0; j<N; j++) { 4380 final ResolveInfo ri = query.get(j); 4381 if (!ri.activityInfo.applicationInfo.packageName 4382 .equals(ai.applicationInfo.packageName)) { 4383 continue; 4384 } 4385 if (!ri.activityInfo.name.equals(ai.name)) { 4386 continue; 4387 } 4388 4389 if (removeMatches) { 4390 pir.removeFilter(pa); 4391 changed = true; 4392 if (DEBUG_PREFERRED) { 4393 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4394 } 4395 break; 4396 } 4397 4398 // Okay we found a previously set preferred or last chosen app. 4399 // If the result set is different from when this 4400 // was created, we need to clear it and re-ask the 4401 // user their preference, if we're looking for an "always" type entry. 4402 if (always && !pa.mPref.sameSet(query)) { 4403 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4404 + intent + " type " + resolvedType); 4405 if (DEBUG_PREFERRED) { 4406 Slog.v(TAG, "Removing preferred activity since set changed " 4407 + pa.mPref.mComponent); 4408 } 4409 pir.removeFilter(pa); 4410 // Re-add the filter as a "last chosen" entry (!always) 4411 PreferredActivity lastChosen = new PreferredActivity( 4412 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4413 pir.addFilter(lastChosen); 4414 changed = true; 4415 return null; 4416 } 4417 4418 // Yay! Either the set matched or we're looking for the last chosen 4419 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4420 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4421 return ri; 4422 } 4423 } 4424 } finally { 4425 if (changed) { 4426 if (DEBUG_PREFERRED) { 4427 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4428 } 4429 scheduleWritePackageRestrictionsLocked(userId); 4430 } 4431 } 4432 } 4433 } 4434 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4435 return null; 4436 } 4437 4438 /* 4439 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4440 */ 4441 @Override 4442 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4443 int targetUserId) { 4444 mContext.enforceCallingOrSelfPermission( 4445 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4446 List<CrossProfileIntentFilter> matches = 4447 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4448 if (matches != null) { 4449 int size = matches.size(); 4450 for (int i = 0; i < size; i++) { 4451 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4452 } 4453 } 4454 if (hasWebURI(intent)) { 4455 // cross-profile app linking works only towards the parent. 4456 final UserInfo parent = getProfileParent(sourceUserId); 4457 synchronized(mPackages) { 4458 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 4459 intent, resolvedType, 0, sourceUserId, parent.id); 4460 return xpDomainInfo != null; 4461 } 4462 } 4463 return false; 4464 } 4465 4466 private UserInfo getProfileParent(int userId) { 4467 final long identity = Binder.clearCallingIdentity(); 4468 try { 4469 return sUserManager.getProfileParent(userId); 4470 } finally { 4471 Binder.restoreCallingIdentity(identity); 4472 } 4473 } 4474 4475 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4476 String resolvedType, int userId) { 4477 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4478 if (resolver != null) { 4479 return resolver.queryIntent(intent, resolvedType, false, userId); 4480 } 4481 return null; 4482 } 4483 4484 @Override 4485 public List<ResolveInfo> queryIntentActivities(Intent intent, 4486 String resolvedType, int flags, int userId) { 4487 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4488 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4489 ComponentName comp = intent.getComponent(); 4490 if (comp == null) { 4491 if (intent.getSelector() != null) { 4492 intent = intent.getSelector(); 4493 comp = intent.getComponent(); 4494 } 4495 } 4496 4497 if (comp != null) { 4498 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4499 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4500 if (ai != null) { 4501 final ResolveInfo ri = new ResolveInfo(); 4502 ri.activityInfo = ai; 4503 list.add(ri); 4504 } 4505 return list; 4506 } 4507 4508 // reader 4509 synchronized (mPackages) { 4510 final String pkgName = intent.getPackage(); 4511 if (pkgName == null) { 4512 List<CrossProfileIntentFilter> matchingFilters = 4513 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4514 // Check for results that need to skip the current profile. 4515 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4516 resolvedType, flags, userId); 4517 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4518 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4519 result.add(xpResolveInfo); 4520 return filterIfNotPrimaryUser(result, userId); 4521 } 4522 4523 // Check for results in the current profile. 4524 List<ResolveInfo> result = mActivities.queryIntent( 4525 intent, resolvedType, flags, userId); 4526 4527 // Check for cross profile results. 4528 xpResolveInfo = queryCrossProfileIntents( 4529 matchingFilters, intent, resolvedType, flags, userId); 4530 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4531 result.add(xpResolveInfo); 4532 Collections.sort(result, mResolvePrioritySorter); 4533 } 4534 result = filterIfNotPrimaryUser(result, userId); 4535 if (hasWebURI(intent)) { 4536 CrossProfileDomainInfo xpDomainInfo = null; 4537 final UserInfo parent = getProfileParent(userId); 4538 if (parent != null) { 4539 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 4540 flags, userId, parent.id); 4541 } 4542 if (xpDomainInfo != null) { 4543 if (xpResolveInfo != null) { 4544 // If we didn't remove it, the cross-profile ResolveInfo would be twice 4545 // in the result. 4546 result.remove(xpResolveInfo); 4547 } 4548 if (result.size() == 0) { 4549 result.add(xpDomainInfo.resolveInfo); 4550 return result; 4551 } 4552 } else if (result.size() <= 1) { 4553 return result; 4554 } 4555 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 4556 xpDomainInfo, userId); 4557 Collections.sort(result, mResolvePrioritySorter); 4558 } 4559 return result; 4560 } 4561 final PackageParser.Package pkg = mPackages.get(pkgName); 4562 if (pkg != null) { 4563 return filterIfNotPrimaryUser( 4564 mActivities.queryIntentForPackage( 4565 intent, resolvedType, flags, pkg.activities, userId), 4566 userId); 4567 } 4568 return new ArrayList<ResolveInfo>(); 4569 } 4570 } 4571 4572 private static class CrossProfileDomainInfo { 4573 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 4574 ResolveInfo resolveInfo; 4575 /* Best domain verification status of the activities found in the other profile */ 4576 int bestDomainVerificationStatus; 4577 } 4578 4579 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 4580 String resolvedType, int flags, int sourceUserId, int parentUserId) { 4581 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 4582 sourceUserId)) { 4583 return null; 4584 } 4585 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4586 resolvedType, flags, parentUserId); 4587 4588 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 4589 return null; 4590 } 4591 CrossProfileDomainInfo result = null; 4592 int size = resultTargetUser.size(); 4593 for (int i = 0; i < size; i++) { 4594 ResolveInfo riTargetUser = resultTargetUser.get(i); 4595 // Intent filter verification is only for filters that specify a host. So don't return 4596 // those that handle all web uris. 4597 if (riTargetUser.handleAllWebDataURI) { 4598 continue; 4599 } 4600 String packageName = riTargetUser.activityInfo.packageName; 4601 PackageSetting ps = mSettings.mPackages.get(packageName); 4602 if (ps == null) { 4603 continue; 4604 } 4605 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 4606 int status = (int)(verificationState >> 32); 4607 if (result == null) { 4608 result = new CrossProfileDomainInfo(); 4609 result.resolveInfo = 4610 createForwardingResolveInfo(null, sourceUserId, parentUserId); 4611 result.bestDomainVerificationStatus = status; 4612 } else { 4613 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 4614 result.bestDomainVerificationStatus); 4615 } 4616 } 4617 // Don't consider matches with status NEVER across profiles. 4618 if (result != null && result.bestDomainVerificationStatus 4619 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4620 return null; 4621 } 4622 return result; 4623 } 4624 4625 /** 4626 * Verification statuses are ordered from the worse to the best, except for 4627 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 4628 */ 4629 private int bestDomainVerificationStatus(int status1, int status2) { 4630 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4631 return status2; 4632 } 4633 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4634 return status1; 4635 } 4636 return (int) MathUtils.max(status1, status2); 4637 } 4638 4639 private boolean isUserEnabled(int userId) { 4640 long callingId = Binder.clearCallingIdentity(); 4641 try { 4642 UserInfo userInfo = sUserManager.getUserInfo(userId); 4643 return userInfo != null && userInfo.isEnabled(); 4644 } finally { 4645 Binder.restoreCallingIdentity(callingId); 4646 } 4647 } 4648 4649 /** 4650 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 4651 * 4652 * @return filtered list 4653 */ 4654 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 4655 if (userId == UserHandle.USER_OWNER) { 4656 return resolveInfos; 4657 } 4658 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 4659 ResolveInfo info = resolveInfos.get(i); 4660 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 4661 resolveInfos.remove(i); 4662 } 4663 } 4664 return resolveInfos; 4665 } 4666 4667 private static boolean hasWebURI(Intent intent) { 4668 if (intent.getData() == null) { 4669 return false; 4670 } 4671 final String scheme = intent.getScheme(); 4672 if (TextUtils.isEmpty(scheme)) { 4673 return false; 4674 } 4675 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4676 } 4677 4678 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 4679 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 4680 int userId) { 4681 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 4682 4683 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4684 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 4685 candidates.size()); 4686 } 4687 4688 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4689 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 4690 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4691 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4692 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4693 4694 synchronized (mPackages) { 4695 final int count = candidates.size(); 4696 // First, try to use linked apps. Partition the candidates into four lists: 4697 // one for the final results, one for the "do not use ever", one for "undefined status" 4698 // and finally one for "browser app type". 4699 for (int n=0; n<count; n++) { 4700 ResolveInfo info = candidates.get(n); 4701 String packageName = info.activityInfo.packageName; 4702 PackageSetting ps = mSettings.mPackages.get(packageName); 4703 if (ps != null) { 4704 // Add to the special match all list (Browser use case) 4705 if (info.handleAllWebDataURI) { 4706 matchAllList.add(info); 4707 continue; 4708 } 4709 // Try to get the status from User settings first 4710 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4711 int status = (int)(packedStatus >> 32); 4712 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 4713 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4714 if (DEBUG_DOMAIN_VERIFICATION) { 4715 Slog.i(TAG, " + always: " + info.activityInfo.packageName 4716 + " : linkgen=" + linkGeneration); 4717 } 4718 // Use link-enabled generation as preferredOrder, i.e. 4719 // prefer newly-enabled over earlier-enabled. 4720 info.preferredOrder = linkGeneration; 4721 alwaysList.add(info); 4722 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4723 if (DEBUG_DOMAIN_VERIFICATION) { 4724 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 4725 } 4726 neverList.add(info); 4727 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 4728 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 4729 if (DEBUG_DOMAIN_VERIFICATION) { 4730 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 4731 } 4732 undefinedList.add(info); 4733 } 4734 } 4735 } 4736 // First try to add the "always" resolution(s) for the current user, if any 4737 if (alwaysList.size() > 0) { 4738 result.addAll(alwaysList); 4739 // if there is an "always" for the parent user, add it. 4740 } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus 4741 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4742 result.add(xpDomainInfo.resolveInfo); 4743 } else { 4744 // Add all undefined Apps as we want them to appear in the Disambiguation dialog. 4745 result.addAll(undefinedList); 4746 if (xpDomainInfo != null && ( 4747 xpDomainInfo.bestDomainVerificationStatus 4748 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 4749 || xpDomainInfo.bestDomainVerificationStatus 4750 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) { 4751 result.add(xpDomainInfo.resolveInfo); 4752 } 4753 // Also add Browsers (all of them or only the default one) 4754 if ((matchFlags & MATCH_ALL) != 0) { 4755 result.addAll(matchAllList); 4756 } else { 4757 // Browser/generic handling case. If there's a default browser, go straight 4758 // to that (but only if there is no other higher-priority match). 4759 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 4760 int maxMatchPrio = 0; 4761 ResolveInfo defaultBrowserMatch = null; 4762 final int numCandidates = matchAllList.size(); 4763 for (int n = 0; n < numCandidates; n++) { 4764 ResolveInfo info = matchAllList.get(n); 4765 // track the highest overall match priority... 4766 if (info.priority > maxMatchPrio) { 4767 maxMatchPrio = info.priority; 4768 } 4769 // ...and the highest-priority default browser match 4770 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4771 if (defaultBrowserMatch == null 4772 || (defaultBrowserMatch.priority < info.priority)) { 4773 if (debug) { 4774 Slog.v(TAG, "Considering default browser match " + info); 4775 } 4776 defaultBrowserMatch = info; 4777 } 4778 } 4779 } 4780 if (defaultBrowserMatch != null 4781 && defaultBrowserMatch.priority >= maxMatchPrio 4782 && !TextUtils.isEmpty(defaultBrowserPackageName)) 4783 { 4784 if (debug) { 4785 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 4786 } 4787 result.add(defaultBrowserMatch); 4788 } else { 4789 result.addAll(matchAllList); 4790 } 4791 } 4792 4793 // If there is nothing selected, add all candidates and remove the ones that the user 4794 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 4795 if (result.size() == 0) { 4796 result.addAll(candidates); 4797 result.removeAll(neverList); 4798 } 4799 } 4800 } 4801 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4802 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 4803 result.size()); 4804 for (ResolveInfo info : result) { 4805 Slog.v(TAG, " + " + info.activityInfo); 4806 } 4807 } 4808 return result; 4809 } 4810 4811 // Returns a packed value as a long: 4812 // 4813 // high 'int'-sized word: link status: undefined/ask/never/always. 4814 // low 'int'-sized word: relative priority among 'always' results. 4815 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4816 long result = ps.getDomainVerificationStatusForUser(userId); 4817 // if none available, get the master status 4818 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4819 if (ps.getIntentFilterVerificationInfo() != null) { 4820 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 4821 } 4822 } 4823 return result; 4824 } 4825 4826 private ResolveInfo querySkipCurrentProfileIntents( 4827 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4828 int flags, int sourceUserId) { 4829 if (matchingFilters != null) { 4830 int size = matchingFilters.size(); 4831 for (int i = 0; i < size; i ++) { 4832 CrossProfileIntentFilter filter = matchingFilters.get(i); 4833 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4834 // Checking if there are activities in the target user that can handle the 4835 // intent. 4836 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4837 flags, sourceUserId); 4838 if (resolveInfo != null) { 4839 return resolveInfo; 4840 } 4841 } 4842 } 4843 } 4844 return null; 4845 } 4846 4847 // Return matching ResolveInfo if any for skip current profile intent filters. 4848 private ResolveInfo queryCrossProfileIntents( 4849 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4850 int flags, int sourceUserId) { 4851 if (matchingFilters != null) { 4852 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4853 // match the same intent. For performance reasons, it is better not to 4854 // run queryIntent twice for the same userId 4855 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4856 int size = matchingFilters.size(); 4857 for (int i = 0; i < size; i++) { 4858 CrossProfileIntentFilter filter = matchingFilters.get(i); 4859 int targetUserId = filter.getTargetUserId(); 4860 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4861 && !alreadyTriedUserIds.get(targetUserId)) { 4862 // Checking if there are activities in the target user that can handle the 4863 // intent. 4864 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4865 flags, sourceUserId); 4866 if (resolveInfo != null) return resolveInfo; 4867 alreadyTriedUserIds.put(targetUserId, true); 4868 } 4869 } 4870 } 4871 return null; 4872 } 4873 4874 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 4875 String resolvedType, int flags, int sourceUserId) { 4876 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4877 resolvedType, flags, filter.getTargetUserId()); 4878 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4879 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4880 } 4881 return null; 4882 } 4883 4884 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4885 int sourceUserId, int targetUserId) { 4886 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4887 String className; 4888 if (targetUserId == UserHandle.USER_OWNER) { 4889 className = FORWARD_INTENT_TO_USER_OWNER; 4890 } else { 4891 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4892 } 4893 ComponentName forwardingActivityComponentName = new ComponentName( 4894 mAndroidApplication.packageName, className); 4895 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4896 sourceUserId); 4897 if (targetUserId == UserHandle.USER_OWNER) { 4898 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 4899 forwardingResolveInfo.noResourceId = true; 4900 } 4901 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4902 forwardingResolveInfo.priority = 0; 4903 forwardingResolveInfo.preferredOrder = 0; 4904 forwardingResolveInfo.match = 0; 4905 forwardingResolveInfo.isDefault = true; 4906 forwardingResolveInfo.filter = filter; 4907 forwardingResolveInfo.targetUserId = targetUserId; 4908 return forwardingResolveInfo; 4909 } 4910 4911 @Override 4912 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4913 Intent[] specifics, String[] specificTypes, Intent intent, 4914 String resolvedType, int flags, int userId) { 4915 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4916 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4917 false, "query intent activity options"); 4918 final String resultsAction = intent.getAction(); 4919 4920 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4921 | PackageManager.GET_RESOLVED_FILTER, userId); 4922 4923 if (DEBUG_INTENT_MATCHING) { 4924 Log.v(TAG, "Query " + intent + ": " + results); 4925 } 4926 4927 int specificsPos = 0; 4928 int N; 4929 4930 // todo: note that the algorithm used here is O(N^2). This 4931 // isn't a problem in our current environment, but if we start running 4932 // into situations where we have more than 5 or 10 matches then this 4933 // should probably be changed to something smarter... 4934 4935 // First we go through and resolve each of the specific items 4936 // that were supplied, taking care of removing any corresponding 4937 // duplicate items in the generic resolve list. 4938 if (specifics != null) { 4939 for (int i=0; i<specifics.length; i++) { 4940 final Intent sintent = specifics[i]; 4941 if (sintent == null) { 4942 continue; 4943 } 4944 4945 if (DEBUG_INTENT_MATCHING) { 4946 Log.v(TAG, "Specific #" + i + ": " + sintent); 4947 } 4948 4949 String action = sintent.getAction(); 4950 if (resultsAction != null && resultsAction.equals(action)) { 4951 // If this action was explicitly requested, then don't 4952 // remove things that have it. 4953 action = null; 4954 } 4955 4956 ResolveInfo ri = null; 4957 ActivityInfo ai = null; 4958 4959 ComponentName comp = sintent.getComponent(); 4960 if (comp == null) { 4961 ri = resolveIntent( 4962 sintent, 4963 specificTypes != null ? specificTypes[i] : null, 4964 flags, userId); 4965 if (ri == null) { 4966 continue; 4967 } 4968 if (ri == mResolveInfo) { 4969 // ACK! Must do something better with this. 4970 } 4971 ai = ri.activityInfo; 4972 comp = new ComponentName(ai.applicationInfo.packageName, 4973 ai.name); 4974 } else { 4975 ai = getActivityInfo(comp, flags, userId); 4976 if (ai == null) { 4977 continue; 4978 } 4979 } 4980 4981 // Look for any generic query activities that are duplicates 4982 // of this specific one, and remove them from the results. 4983 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 4984 N = results.size(); 4985 int j; 4986 for (j=specificsPos; j<N; j++) { 4987 ResolveInfo sri = results.get(j); 4988 if ((sri.activityInfo.name.equals(comp.getClassName()) 4989 && sri.activityInfo.applicationInfo.packageName.equals( 4990 comp.getPackageName())) 4991 || (action != null && sri.filter.matchAction(action))) { 4992 results.remove(j); 4993 if (DEBUG_INTENT_MATCHING) Log.v( 4994 TAG, "Removing duplicate item from " + j 4995 + " due to specific " + specificsPos); 4996 if (ri == null) { 4997 ri = sri; 4998 } 4999 j--; 5000 N--; 5001 } 5002 } 5003 5004 // Add this specific item to its proper place. 5005 if (ri == null) { 5006 ri = new ResolveInfo(); 5007 ri.activityInfo = ai; 5008 } 5009 results.add(specificsPos, ri); 5010 ri.specificIndex = i; 5011 specificsPos++; 5012 } 5013 } 5014 5015 // Now we go through the remaining generic results and remove any 5016 // duplicate actions that are found here. 5017 N = results.size(); 5018 for (int i=specificsPos; i<N-1; i++) { 5019 final ResolveInfo rii = results.get(i); 5020 if (rii.filter == null) { 5021 continue; 5022 } 5023 5024 // Iterate over all of the actions of this result's intent 5025 // filter... typically this should be just one. 5026 final Iterator<String> it = rii.filter.actionsIterator(); 5027 if (it == null) { 5028 continue; 5029 } 5030 while (it.hasNext()) { 5031 final String action = it.next(); 5032 if (resultsAction != null && resultsAction.equals(action)) { 5033 // If this action was explicitly requested, then don't 5034 // remove things that have it. 5035 continue; 5036 } 5037 for (int j=i+1; j<N; j++) { 5038 final ResolveInfo rij = results.get(j); 5039 if (rij.filter != null && rij.filter.hasAction(action)) { 5040 results.remove(j); 5041 if (DEBUG_INTENT_MATCHING) Log.v( 5042 TAG, "Removing duplicate item from " + j 5043 + " due to action " + action + " at " + i); 5044 j--; 5045 N--; 5046 } 5047 } 5048 } 5049 5050 // If the caller didn't request filter information, drop it now 5051 // so we don't have to marshall/unmarshall it. 5052 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5053 rii.filter = null; 5054 } 5055 } 5056 5057 // Filter out the caller activity if so requested. 5058 if (caller != null) { 5059 N = results.size(); 5060 for (int i=0; i<N; i++) { 5061 ActivityInfo ainfo = results.get(i).activityInfo; 5062 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5063 && caller.getClassName().equals(ainfo.name)) { 5064 results.remove(i); 5065 break; 5066 } 5067 } 5068 } 5069 5070 // If the caller didn't request filter information, 5071 // drop them now so we don't have to 5072 // marshall/unmarshall it. 5073 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5074 N = results.size(); 5075 for (int i=0; i<N; i++) { 5076 results.get(i).filter = null; 5077 } 5078 } 5079 5080 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5081 return results; 5082 } 5083 5084 @Override 5085 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 5086 int userId) { 5087 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5088 ComponentName comp = intent.getComponent(); 5089 if (comp == null) { 5090 if (intent.getSelector() != null) { 5091 intent = intent.getSelector(); 5092 comp = intent.getComponent(); 5093 } 5094 } 5095 if (comp != null) { 5096 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5097 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5098 if (ai != null) { 5099 ResolveInfo ri = new ResolveInfo(); 5100 ri.activityInfo = ai; 5101 list.add(ri); 5102 } 5103 return list; 5104 } 5105 5106 // reader 5107 synchronized (mPackages) { 5108 String pkgName = intent.getPackage(); 5109 if (pkgName == null) { 5110 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5111 } 5112 final PackageParser.Package pkg = mPackages.get(pkgName); 5113 if (pkg != null) { 5114 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5115 userId); 5116 } 5117 return null; 5118 } 5119 } 5120 5121 @Override 5122 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5123 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 5124 if (!sUserManager.exists(userId)) return null; 5125 if (query != null) { 5126 if (query.size() >= 1) { 5127 // If there is more than one service with the same priority, 5128 // just arbitrarily pick the first one. 5129 return query.get(0); 5130 } 5131 } 5132 return null; 5133 } 5134 5135 @Override 5136 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 5137 int userId) { 5138 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5139 ComponentName comp = intent.getComponent(); 5140 if (comp == null) { 5141 if (intent.getSelector() != null) { 5142 intent = intent.getSelector(); 5143 comp = intent.getComponent(); 5144 } 5145 } 5146 if (comp != null) { 5147 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5148 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5149 if (si != null) { 5150 final ResolveInfo ri = new ResolveInfo(); 5151 ri.serviceInfo = si; 5152 list.add(ri); 5153 } 5154 return list; 5155 } 5156 5157 // reader 5158 synchronized (mPackages) { 5159 String pkgName = intent.getPackage(); 5160 if (pkgName == null) { 5161 return mServices.queryIntent(intent, resolvedType, flags, userId); 5162 } 5163 final PackageParser.Package pkg = mPackages.get(pkgName); 5164 if (pkg != null) { 5165 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5166 userId); 5167 } 5168 return null; 5169 } 5170 } 5171 5172 @Override 5173 public List<ResolveInfo> queryIntentContentProviders( 5174 Intent intent, String resolvedType, int flags, int userId) { 5175 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5176 ComponentName comp = intent.getComponent(); 5177 if (comp == null) { 5178 if (intent.getSelector() != null) { 5179 intent = intent.getSelector(); 5180 comp = intent.getComponent(); 5181 } 5182 } 5183 if (comp != null) { 5184 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5185 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5186 if (pi != null) { 5187 final ResolveInfo ri = new ResolveInfo(); 5188 ri.providerInfo = pi; 5189 list.add(ri); 5190 } 5191 return list; 5192 } 5193 5194 // reader 5195 synchronized (mPackages) { 5196 String pkgName = intent.getPackage(); 5197 if (pkgName == null) { 5198 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5199 } 5200 final PackageParser.Package pkg = mPackages.get(pkgName); 5201 if (pkg != null) { 5202 return mProviders.queryIntentForPackage( 5203 intent, resolvedType, flags, pkg.providers, userId); 5204 } 5205 return null; 5206 } 5207 } 5208 5209 @Override 5210 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5211 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5212 5213 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 5214 5215 // writer 5216 synchronized (mPackages) { 5217 ArrayList<PackageInfo> list; 5218 if (listUninstalled) { 5219 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5220 for (PackageSetting ps : mSettings.mPackages.values()) { 5221 PackageInfo pi; 5222 if (ps.pkg != null) { 5223 pi = generatePackageInfo(ps.pkg, flags, userId); 5224 } else { 5225 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5226 } 5227 if (pi != null) { 5228 list.add(pi); 5229 } 5230 } 5231 } else { 5232 list = new ArrayList<PackageInfo>(mPackages.size()); 5233 for (PackageParser.Package p : mPackages.values()) { 5234 PackageInfo pi = generatePackageInfo(p, flags, userId); 5235 if (pi != null) { 5236 list.add(pi); 5237 } 5238 } 5239 } 5240 5241 return new ParceledListSlice<PackageInfo>(list); 5242 } 5243 } 5244 5245 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5246 String[] permissions, boolean[] tmp, int flags, int userId) { 5247 int numMatch = 0; 5248 final PermissionsState permissionsState = ps.getPermissionsState(); 5249 for (int i=0; i<permissions.length; i++) { 5250 final String permission = permissions[i]; 5251 if (permissionsState.hasPermission(permission, userId)) { 5252 tmp[i] = true; 5253 numMatch++; 5254 } else { 5255 tmp[i] = false; 5256 } 5257 } 5258 if (numMatch == 0) { 5259 return; 5260 } 5261 PackageInfo pi; 5262 if (ps.pkg != null) { 5263 pi = generatePackageInfo(ps.pkg, flags, userId); 5264 } else { 5265 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5266 } 5267 // The above might return null in cases of uninstalled apps or install-state 5268 // skew across users/profiles. 5269 if (pi != null) { 5270 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5271 if (numMatch == permissions.length) { 5272 pi.requestedPermissions = permissions; 5273 } else { 5274 pi.requestedPermissions = new String[numMatch]; 5275 numMatch = 0; 5276 for (int i=0; i<permissions.length; i++) { 5277 if (tmp[i]) { 5278 pi.requestedPermissions[numMatch] = permissions[i]; 5279 numMatch++; 5280 } 5281 } 5282 } 5283 } 5284 list.add(pi); 5285 } 5286 } 5287 5288 @Override 5289 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5290 String[] permissions, int flags, int userId) { 5291 if (!sUserManager.exists(userId)) return null; 5292 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5293 5294 // writer 5295 synchronized (mPackages) { 5296 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5297 boolean[] tmpBools = new boolean[permissions.length]; 5298 if (listUninstalled) { 5299 for (PackageSetting ps : mSettings.mPackages.values()) { 5300 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5301 } 5302 } else { 5303 for (PackageParser.Package pkg : mPackages.values()) { 5304 PackageSetting ps = (PackageSetting)pkg.mExtras; 5305 if (ps != null) { 5306 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5307 userId); 5308 } 5309 } 5310 } 5311 5312 return new ParceledListSlice<PackageInfo>(list); 5313 } 5314 } 5315 5316 @Override 5317 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5318 if (!sUserManager.exists(userId)) return null; 5319 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5320 5321 // writer 5322 synchronized (mPackages) { 5323 ArrayList<ApplicationInfo> list; 5324 if (listUninstalled) { 5325 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5326 for (PackageSetting ps : mSettings.mPackages.values()) { 5327 ApplicationInfo ai; 5328 if (ps.pkg != null) { 5329 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5330 ps.readUserState(userId), userId); 5331 } else { 5332 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5333 } 5334 if (ai != null) { 5335 list.add(ai); 5336 } 5337 } 5338 } else { 5339 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5340 for (PackageParser.Package p : mPackages.values()) { 5341 if (p.mExtras != null) { 5342 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5343 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5344 if (ai != null) { 5345 list.add(ai); 5346 } 5347 } 5348 } 5349 } 5350 5351 return new ParceledListSlice<ApplicationInfo>(list); 5352 } 5353 } 5354 5355 public List<ApplicationInfo> getPersistentApplications(int flags) { 5356 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 5357 5358 // reader 5359 synchronized (mPackages) { 5360 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 5361 final int userId = UserHandle.getCallingUserId(); 5362 while (i.hasNext()) { 5363 final PackageParser.Package p = i.next(); 5364 if (p.applicationInfo != null 5365 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 5366 && (!mSafeMode || isSystemApp(p))) { 5367 PackageSetting ps = mSettings.mPackages.get(p.packageName); 5368 if (ps != null) { 5369 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5370 ps.readUserState(userId), userId); 5371 if (ai != null) { 5372 finalList.add(ai); 5373 } 5374 } 5375 } 5376 } 5377 } 5378 5379 return finalList; 5380 } 5381 5382 @Override 5383 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 5384 if (!sUserManager.exists(userId)) return null; 5385 // reader 5386 synchronized (mPackages) { 5387 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 5388 PackageSetting ps = provider != null 5389 ? mSettings.mPackages.get(provider.owner.packageName) 5390 : null; 5391 return ps != null 5392 && mSettings.isEnabledLPr(provider.info, flags, userId) 5393 && (!mSafeMode || (provider.info.applicationInfo.flags 5394 &ApplicationInfo.FLAG_SYSTEM) != 0) 5395 ? PackageParser.generateProviderInfo(provider, flags, 5396 ps.readUserState(userId), userId) 5397 : null; 5398 } 5399 } 5400 5401 /** 5402 * @deprecated 5403 */ 5404 @Deprecated 5405 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 5406 // reader 5407 synchronized (mPackages) { 5408 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 5409 .entrySet().iterator(); 5410 final int userId = UserHandle.getCallingUserId(); 5411 while (i.hasNext()) { 5412 Map.Entry<String, PackageParser.Provider> entry = i.next(); 5413 PackageParser.Provider p = entry.getValue(); 5414 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5415 5416 if (ps != null && p.syncable 5417 && (!mSafeMode || (p.info.applicationInfo.flags 5418 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 5419 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 5420 ps.readUserState(userId), userId); 5421 if (info != null) { 5422 outNames.add(entry.getKey()); 5423 outInfo.add(info); 5424 } 5425 } 5426 } 5427 } 5428 } 5429 5430 @Override 5431 public List<ProviderInfo> queryContentProviders(String processName, 5432 int uid, int flags) { 5433 ArrayList<ProviderInfo> finalList = null; 5434 // reader 5435 synchronized (mPackages) { 5436 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 5437 final int userId = processName != null ? 5438 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 5439 while (i.hasNext()) { 5440 final PackageParser.Provider p = i.next(); 5441 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5442 if (ps != null && p.info.authority != null 5443 && (processName == null 5444 || (p.info.processName.equals(processName) 5445 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 5446 && mSettings.isEnabledLPr(p.info, flags, userId) 5447 && (!mSafeMode 5448 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 5449 if (finalList == null) { 5450 finalList = new ArrayList<ProviderInfo>(3); 5451 } 5452 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 5453 ps.readUserState(userId), userId); 5454 if (info != null) { 5455 finalList.add(info); 5456 } 5457 } 5458 } 5459 } 5460 5461 if (finalList != null) { 5462 Collections.sort(finalList, mProviderInitOrderSorter); 5463 } 5464 5465 return finalList; 5466 } 5467 5468 @Override 5469 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 5470 int flags) { 5471 // reader 5472 synchronized (mPackages) { 5473 final PackageParser.Instrumentation i = mInstrumentation.get(name); 5474 return PackageParser.generateInstrumentationInfo(i, flags); 5475 } 5476 } 5477 5478 @Override 5479 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 5480 int flags) { 5481 ArrayList<InstrumentationInfo> finalList = 5482 new ArrayList<InstrumentationInfo>(); 5483 5484 // reader 5485 synchronized (mPackages) { 5486 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 5487 while (i.hasNext()) { 5488 final PackageParser.Instrumentation p = i.next(); 5489 if (targetPackage == null 5490 || targetPackage.equals(p.info.targetPackage)) { 5491 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 5492 flags); 5493 if (ii != null) { 5494 finalList.add(ii); 5495 } 5496 } 5497 } 5498 } 5499 5500 return finalList; 5501 } 5502 5503 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 5504 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 5505 if (overlays == null) { 5506 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 5507 return; 5508 } 5509 for (PackageParser.Package opkg : overlays.values()) { 5510 // Not much to do if idmap fails: we already logged the error 5511 // and we certainly don't want to abort installation of pkg simply 5512 // because an overlay didn't fit properly. For these reasons, 5513 // ignore the return value of createIdmapForPackagePairLI. 5514 createIdmapForPackagePairLI(pkg, opkg); 5515 } 5516 } 5517 5518 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 5519 PackageParser.Package opkg) { 5520 if (!opkg.mTrustedOverlay) { 5521 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 5522 opkg.baseCodePath + ": overlay not trusted"); 5523 return false; 5524 } 5525 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 5526 if (overlaySet == null) { 5527 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 5528 opkg.baseCodePath + " but target package has no known overlays"); 5529 return false; 5530 } 5531 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 5532 // TODO: generate idmap for split APKs 5533 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 5534 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 5535 + opkg.baseCodePath); 5536 return false; 5537 } 5538 PackageParser.Package[] overlayArray = 5539 overlaySet.values().toArray(new PackageParser.Package[0]); 5540 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 5541 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 5542 return p1.mOverlayPriority - p2.mOverlayPriority; 5543 } 5544 }; 5545 Arrays.sort(overlayArray, cmp); 5546 5547 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 5548 int i = 0; 5549 for (PackageParser.Package p : overlayArray) { 5550 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 5551 } 5552 return true; 5553 } 5554 5555 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5556 final File[] files = dir.listFiles(); 5557 if (ArrayUtils.isEmpty(files)) { 5558 Log.d(TAG, "No files in app dir " + dir); 5559 return; 5560 } 5561 5562 if (DEBUG_PACKAGE_SCANNING) { 5563 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 5564 + " flags=0x" + Integer.toHexString(parseFlags)); 5565 } 5566 5567 for (File file : files) { 5568 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 5569 && !PackageInstallerService.isStageName(file.getName()); 5570 if (!isPackage) { 5571 // Ignore entries which are not packages 5572 continue; 5573 } 5574 try { 5575 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 5576 scanFlags, currentTime, null); 5577 } catch (PackageManagerException e) { 5578 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 5579 5580 // Delete invalid userdata apps 5581 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 5582 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 5583 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 5584 if (file.isDirectory()) { 5585 mInstaller.rmPackageDir(file.getAbsolutePath()); 5586 } else { 5587 file.delete(); 5588 } 5589 } 5590 } 5591 } 5592 } 5593 5594 private static File getSettingsProblemFile() { 5595 File dataDir = Environment.getDataDirectory(); 5596 File systemDir = new File(dataDir, "system"); 5597 File fname = new File(systemDir, "uiderrors.txt"); 5598 return fname; 5599 } 5600 5601 static void reportSettingsProblem(int priority, String msg) { 5602 logCriticalInfo(priority, msg); 5603 } 5604 5605 static void logCriticalInfo(int priority, String msg) { 5606 Slog.println(priority, TAG, msg); 5607 EventLogTags.writePmCriticalInfo(msg); 5608 try { 5609 File fname = getSettingsProblemFile(); 5610 FileOutputStream out = new FileOutputStream(fname, true); 5611 PrintWriter pw = new FastPrintWriter(out); 5612 SimpleDateFormat formatter = new SimpleDateFormat(); 5613 String dateString = formatter.format(new Date(System.currentTimeMillis())); 5614 pw.println(dateString + ": " + msg); 5615 pw.close(); 5616 FileUtils.setPermissions( 5617 fname.toString(), 5618 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 5619 -1, -1); 5620 } catch (java.io.IOException e) { 5621 } 5622 } 5623 5624 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 5625 PackageParser.Package pkg, File srcFile, int parseFlags) 5626 throws PackageManagerException { 5627 if (ps != null 5628 && ps.codePath.equals(srcFile) 5629 && ps.timeStamp == srcFile.lastModified() 5630 && !isCompatSignatureUpdateNeeded(pkg) 5631 && !isRecoverSignatureUpdateNeeded(pkg)) { 5632 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 5633 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5634 ArraySet<PublicKey> signingKs; 5635 synchronized (mPackages) { 5636 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 5637 } 5638 if (ps.signatures.mSignatures != null 5639 && ps.signatures.mSignatures.length != 0 5640 && signingKs != null) { 5641 // Optimization: reuse the existing cached certificates 5642 // if the package appears to be unchanged. 5643 pkg.mSignatures = ps.signatures.mSignatures; 5644 pkg.mSigningKeys = signingKs; 5645 return; 5646 } 5647 5648 Slog.w(TAG, "PackageSetting for " + ps.name 5649 + " is missing signatures. Collecting certs again to recover them."); 5650 } else { 5651 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 5652 } 5653 5654 try { 5655 pp.collectCertificates(pkg, parseFlags); 5656 pp.collectManifestDigest(pkg); 5657 } catch (PackageParserException e) { 5658 throw PackageManagerException.from(e); 5659 } 5660 } 5661 5662 /* 5663 * Scan a package and return the newly parsed package. 5664 * Returns null in case of errors and the error code is stored in mLastScanError 5665 */ 5666 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 5667 long currentTime, UserHandle user) throws PackageManagerException { 5668 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 5669 parseFlags |= mDefParseFlags; 5670 PackageParser pp = new PackageParser(); 5671 pp.setSeparateProcesses(mSeparateProcesses); 5672 pp.setOnlyCoreApps(mOnlyCore); 5673 pp.setDisplayMetrics(mMetrics); 5674 5675 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 5676 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 5677 } 5678 5679 final PackageParser.Package pkg; 5680 try { 5681 pkg = pp.parsePackage(scanFile, parseFlags); 5682 } catch (PackageParserException e) { 5683 throw PackageManagerException.from(e); 5684 } 5685 5686 PackageSetting ps = null; 5687 PackageSetting updatedPkg; 5688 // reader 5689 synchronized (mPackages) { 5690 // Look to see if we already know about this package. 5691 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 5692 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 5693 // This package has been renamed to its original name. Let's 5694 // use that. 5695 ps = mSettings.peekPackageLPr(oldName); 5696 } 5697 // If there was no original package, see one for the real package name. 5698 if (ps == null) { 5699 ps = mSettings.peekPackageLPr(pkg.packageName); 5700 } 5701 // Check to see if this package could be hiding/updating a system 5702 // package. Must look for it either under the original or real 5703 // package name depending on our state. 5704 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 5705 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 5706 } 5707 boolean updatedPkgBetter = false; 5708 // First check if this is a system package that may involve an update 5709 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5710 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5711 // it needs to drop FLAG_PRIVILEGED. 5712 if (locationIsPrivileged(scanFile)) { 5713 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5714 } else { 5715 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5716 } 5717 5718 if (ps != null && !ps.codePath.equals(scanFile)) { 5719 // The path has changed from what was last scanned... check the 5720 // version of the new path against what we have stored to determine 5721 // what to do. 5722 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5723 if (pkg.mVersionCode <= ps.versionCode) { 5724 // The system package has been updated and the code path does not match 5725 // Ignore entry. Skip it. 5726 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5727 + " ignored: updated version " + ps.versionCode 5728 + " better than this " + pkg.mVersionCode); 5729 if (!updatedPkg.codePath.equals(scanFile)) { 5730 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5731 + ps.name + " changing from " + updatedPkg.codePathString 5732 + " to " + scanFile); 5733 updatedPkg.codePath = scanFile; 5734 updatedPkg.codePathString = scanFile.toString(); 5735 updatedPkg.resourcePath = scanFile; 5736 updatedPkg.resourcePathString = scanFile.toString(); 5737 } 5738 updatedPkg.pkg = pkg; 5739 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5740 "Package " + ps.name + " at " + scanFile 5741 + " ignored: updated version " + ps.versionCode 5742 + " better than this " + pkg.mVersionCode); 5743 } else { 5744 // The current app on the system partition is better than 5745 // what we have updated to on the data partition; switch 5746 // back to the system partition version. 5747 // At this point, its safely assumed that package installation for 5748 // apps in system partition will go through. If not there won't be a working 5749 // version of the app 5750 // writer 5751 synchronized (mPackages) { 5752 // Just remove the loaded entries from package lists. 5753 mPackages.remove(ps.name); 5754 } 5755 5756 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5757 + " reverting from " + ps.codePathString 5758 + ": new version " + pkg.mVersionCode 5759 + " better than installed " + ps.versionCode); 5760 5761 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5762 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5763 synchronized (mInstallLock) { 5764 args.cleanUpResourcesLI(); 5765 } 5766 synchronized (mPackages) { 5767 mSettings.enableSystemPackageLPw(ps.name); 5768 } 5769 updatedPkgBetter = true; 5770 } 5771 } 5772 } 5773 5774 if (updatedPkg != null) { 5775 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5776 // initially 5777 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5778 5779 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5780 // flag set initially 5781 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5782 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5783 } 5784 } 5785 5786 // Verify certificates against what was last scanned 5787 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5788 5789 /* 5790 * A new system app appeared, but we already had a non-system one of the 5791 * same name installed earlier. 5792 */ 5793 boolean shouldHideSystemApp = false; 5794 if (updatedPkg == null && ps != null 5795 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5796 /* 5797 * Check to make sure the signatures match first. If they don't, 5798 * wipe the installed application and its data. 5799 */ 5800 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5801 != PackageManager.SIGNATURE_MATCH) { 5802 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5803 + " signatures don't match existing userdata copy; removing"); 5804 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5805 ps = null; 5806 } else { 5807 /* 5808 * If the newly-added system app is an older version than the 5809 * already installed version, hide it. It will be scanned later 5810 * and re-added like an update. 5811 */ 5812 if (pkg.mVersionCode <= ps.versionCode) { 5813 shouldHideSystemApp = true; 5814 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5815 + " but new version " + pkg.mVersionCode + " better than installed " 5816 + ps.versionCode + "; hiding system"); 5817 } else { 5818 /* 5819 * The newly found system app is a newer version that the 5820 * one previously installed. Simply remove the 5821 * already-installed application and replace it with our own 5822 * while keeping the application data. 5823 */ 5824 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5825 + " reverting from " + ps.codePathString + ": new version " 5826 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5827 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5828 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5829 synchronized (mInstallLock) { 5830 args.cleanUpResourcesLI(); 5831 } 5832 } 5833 } 5834 } 5835 5836 // The apk is forward locked (not public) if its code and resources 5837 // are kept in different files. (except for app in either system or 5838 // vendor path). 5839 // TODO grab this value from PackageSettings 5840 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5841 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5842 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5843 } 5844 } 5845 5846 // TODO: extend to support forward-locked splits 5847 String resourcePath = null; 5848 String baseResourcePath = null; 5849 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5850 if (ps != null && ps.resourcePathString != null) { 5851 resourcePath = ps.resourcePathString; 5852 baseResourcePath = ps.resourcePathString; 5853 } else { 5854 // Should not happen at all. Just log an error. 5855 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5856 } 5857 } else { 5858 resourcePath = pkg.codePath; 5859 baseResourcePath = pkg.baseCodePath; 5860 } 5861 5862 // Set application objects path explicitly. 5863 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5864 pkg.applicationInfo.setCodePath(pkg.codePath); 5865 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5866 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5867 pkg.applicationInfo.setResourcePath(resourcePath); 5868 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5869 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5870 5871 // Note that we invoke the following method only if we are about to unpack an application 5872 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5873 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5874 5875 /* 5876 * If the system app should be overridden by a previously installed 5877 * data, hide the system app now and let the /data/app scan pick it up 5878 * again. 5879 */ 5880 if (shouldHideSystemApp) { 5881 synchronized (mPackages) { 5882 /* 5883 * We have to grant systems permissions before we hide, because 5884 * grantPermissions will assume the package update is trying to 5885 * expand its permissions. 5886 */ 5887 grantPermissionsLPw(pkg, true, pkg.packageName); 5888 mSettings.disableSystemPackageLPw(pkg.packageName); 5889 } 5890 } 5891 5892 return scannedPkg; 5893 } 5894 5895 private static String fixProcessName(String defProcessName, 5896 String processName, int uid) { 5897 if (processName == null) { 5898 return defProcessName; 5899 } 5900 return processName; 5901 } 5902 5903 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 5904 throws PackageManagerException { 5905 if (pkgSetting.signatures.mSignatures != null) { 5906 // Already existing package. Make sure signatures match 5907 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 5908 == PackageManager.SIGNATURE_MATCH; 5909 if (!match) { 5910 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 5911 == PackageManager.SIGNATURE_MATCH; 5912 } 5913 if (!match) { 5914 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 5915 == PackageManager.SIGNATURE_MATCH; 5916 } 5917 if (!match) { 5918 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5919 + pkg.packageName + " signatures do not match the " 5920 + "previously installed version; ignoring!"); 5921 } 5922 } 5923 5924 // Check for shared user signatures 5925 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 5926 // Already existing package. Make sure signatures match 5927 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5928 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 5929 if (!match) { 5930 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 5931 == PackageManager.SIGNATURE_MATCH; 5932 } 5933 if (!match) { 5934 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 5935 == PackageManager.SIGNATURE_MATCH; 5936 } 5937 if (!match) { 5938 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 5939 "Package " + pkg.packageName 5940 + " has no signatures that match those in shared user " 5941 + pkgSetting.sharedUser.name + "; ignoring!"); 5942 } 5943 } 5944 } 5945 5946 /** 5947 * Enforces that only the system UID or root's UID can call a method exposed 5948 * via Binder. 5949 * 5950 * @param message used as message if SecurityException is thrown 5951 * @throws SecurityException if the caller is not system or root 5952 */ 5953 private static final void enforceSystemOrRoot(String message) { 5954 final int uid = Binder.getCallingUid(); 5955 if (uid != Process.SYSTEM_UID && uid != 0) { 5956 throw new SecurityException(message); 5957 } 5958 } 5959 5960 @Override 5961 public void performBootDexOpt() { 5962 enforceSystemOrRoot("Only the system can request dexopt be performed"); 5963 5964 // Before everything else, see whether we need to fstrim. 5965 try { 5966 IMountService ms = PackageHelper.getMountService(); 5967 if (ms != null) { 5968 final boolean isUpgrade = isUpgrade(); 5969 boolean doTrim = isUpgrade; 5970 if (doTrim) { 5971 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 5972 } else { 5973 final long interval = android.provider.Settings.Global.getLong( 5974 mContext.getContentResolver(), 5975 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 5976 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 5977 if (interval > 0) { 5978 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 5979 if (timeSinceLast > interval) { 5980 doTrim = true; 5981 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 5982 + "; running immediately"); 5983 } 5984 } 5985 } 5986 if (doTrim) { 5987 if (!isFirstBoot()) { 5988 try { 5989 ActivityManagerNative.getDefault().showBootMessage( 5990 mContext.getResources().getString( 5991 R.string.android_upgrading_fstrim), true); 5992 } catch (RemoteException e) { 5993 } 5994 } 5995 ms.runMaintenance(); 5996 } 5997 } else { 5998 Slog.e(TAG, "Mount service unavailable!"); 5999 } 6000 } catch (RemoteException e) { 6001 // Can't happen; MountService is local 6002 } 6003 6004 final ArraySet<PackageParser.Package> pkgs; 6005 synchronized (mPackages) { 6006 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 6007 } 6008 6009 if (pkgs != null) { 6010 // Sort apps by importance for dexopt ordering. Important apps are given more priority 6011 // in case the device runs out of space. 6012 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 6013 // Give priority to core apps. 6014 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6015 PackageParser.Package pkg = it.next(); 6016 if (pkg.coreApp) { 6017 if (DEBUG_DEXOPT) { 6018 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 6019 } 6020 sortedPkgs.add(pkg); 6021 it.remove(); 6022 } 6023 } 6024 // Give priority to system apps that listen for pre boot complete. 6025 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 6026 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 6027 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6028 PackageParser.Package pkg = it.next(); 6029 if (pkgNames.contains(pkg.packageName)) { 6030 if (DEBUG_DEXOPT) { 6031 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 6032 } 6033 sortedPkgs.add(pkg); 6034 it.remove(); 6035 } 6036 } 6037 // Give priority to system apps. 6038 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6039 PackageParser.Package pkg = it.next(); 6040 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 6041 if (DEBUG_DEXOPT) { 6042 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 6043 } 6044 sortedPkgs.add(pkg); 6045 it.remove(); 6046 } 6047 } 6048 // Give priority to updated system apps. 6049 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6050 PackageParser.Package pkg = it.next(); 6051 if (pkg.isUpdatedSystemApp()) { 6052 if (DEBUG_DEXOPT) { 6053 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 6054 } 6055 sortedPkgs.add(pkg); 6056 it.remove(); 6057 } 6058 } 6059 // Give priority to apps that listen for boot complete. 6060 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 6061 pkgNames = getPackageNamesForIntent(intent); 6062 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6063 PackageParser.Package pkg = it.next(); 6064 if (pkgNames.contains(pkg.packageName)) { 6065 if (DEBUG_DEXOPT) { 6066 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 6067 } 6068 sortedPkgs.add(pkg); 6069 it.remove(); 6070 } 6071 } 6072 // Filter out packages that aren't recently used. 6073 filterRecentlyUsedApps(pkgs); 6074 // Add all remaining apps. 6075 for (PackageParser.Package pkg : pkgs) { 6076 if (DEBUG_DEXOPT) { 6077 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 6078 } 6079 sortedPkgs.add(pkg); 6080 } 6081 6082 // If we want to be lazy, filter everything that wasn't recently used. 6083 if (mLazyDexOpt) { 6084 filterRecentlyUsedApps(sortedPkgs); 6085 } 6086 6087 int i = 0; 6088 int total = sortedPkgs.size(); 6089 File dataDir = Environment.getDataDirectory(); 6090 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 6091 if (lowThreshold == 0) { 6092 throw new IllegalStateException("Invalid low memory threshold"); 6093 } 6094 for (PackageParser.Package pkg : sortedPkgs) { 6095 long usableSpace = dataDir.getUsableSpace(); 6096 if (usableSpace < lowThreshold) { 6097 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 6098 break; 6099 } 6100 performBootDexOpt(pkg, ++i, total); 6101 } 6102 } 6103 } 6104 6105 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 6106 // Filter out packages that aren't recently used. 6107 // 6108 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 6109 // should do a full dexopt. 6110 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 6111 int total = pkgs.size(); 6112 int skipped = 0; 6113 long now = System.currentTimeMillis(); 6114 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 6115 PackageParser.Package pkg = i.next(); 6116 long then = pkg.mLastPackageUsageTimeInMills; 6117 if (then + mDexOptLRUThresholdInMills < now) { 6118 if (DEBUG_DEXOPT) { 6119 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 6120 ((then == 0) ? "never" : new Date(then))); 6121 } 6122 i.remove(); 6123 skipped++; 6124 } 6125 } 6126 if (DEBUG_DEXOPT) { 6127 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 6128 } 6129 } 6130 } 6131 6132 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 6133 List<ResolveInfo> ris = null; 6134 try { 6135 ris = AppGlobals.getPackageManager().queryIntentReceivers( 6136 intent, null, 0, UserHandle.USER_OWNER); 6137 } catch (RemoteException e) { 6138 } 6139 ArraySet<String> pkgNames = new ArraySet<String>(); 6140 if (ris != null) { 6141 for (ResolveInfo ri : ris) { 6142 pkgNames.add(ri.activityInfo.packageName); 6143 } 6144 } 6145 return pkgNames; 6146 } 6147 6148 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 6149 if (DEBUG_DEXOPT) { 6150 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 6151 } 6152 if (!isFirstBoot()) { 6153 try { 6154 ActivityManagerNative.getDefault().showBootMessage( 6155 mContext.getResources().getString(R.string.android_upgrading_apk, 6156 curr, total), true); 6157 } catch (RemoteException e) { 6158 } 6159 } 6160 PackageParser.Package p = pkg; 6161 synchronized (mInstallLock) { 6162 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 6163 false /* force dex */, false /* defer */, true /* include dependencies */); 6164 } 6165 } 6166 6167 @Override 6168 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6169 return performDexOpt(packageName, instructionSet, false); 6170 } 6171 6172 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 6173 boolean dexopt = mLazyDexOpt || backgroundDexopt; 6174 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 6175 if (!dexopt && !updateUsage) { 6176 // We aren't going to dexopt or update usage, so bail early. 6177 return false; 6178 } 6179 PackageParser.Package p; 6180 final String targetInstructionSet; 6181 synchronized (mPackages) { 6182 p = mPackages.get(packageName); 6183 if (p == null) { 6184 return false; 6185 } 6186 if (updateUsage) { 6187 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6188 } 6189 mPackageUsage.write(false); 6190 if (!dexopt) { 6191 // We aren't going to dexopt, so bail early. 6192 return false; 6193 } 6194 6195 targetInstructionSet = instructionSet != null ? instructionSet : 6196 getPrimaryInstructionSet(p.applicationInfo); 6197 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 6198 return false; 6199 } 6200 } 6201 long callingId = Binder.clearCallingIdentity(); 6202 try { 6203 synchronized (mInstallLock) { 6204 final String[] instructionSets = new String[] { targetInstructionSet }; 6205 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 6206 false /* forceDex */, false /* defer */, true /* inclDependencies */); 6207 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6208 } 6209 } finally { 6210 Binder.restoreCallingIdentity(callingId); 6211 } 6212 } 6213 6214 public ArraySet<String> getPackagesThatNeedDexOpt() { 6215 ArraySet<String> pkgs = null; 6216 synchronized (mPackages) { 6217 for (PackageParser.Package p : mPackages.values()) { 6218 if (DEBUG_DEXOPT) { 6219 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 6220 } 6221 if (!p.mDexOptPerformed.isEmpty()) { 6222 continue; 6223 } 6224 if (pkgs == null) { 6225 pkgs = new ArraySet<String>(); 6226 } 6227 pkgs.add(p.packageName); 6228 } 6229 } 6230 return pkgs; 6231 } 6232 6233 public void shutdown() { 6234 mPackageUsage.write(true); 6235 } 6236 6237 @Override 6238 public void forceDexOpt(String packageName) { 6239 enforceSystemOrRoot("forceDexOpt"); 6240 6241 PackageParser.Package pkg; 6242 synchronized (mPackages) { 6243 pkg = mPackages.get(packageName); 6244 if (pkg == null) { 6245 throw new IllegalArgumentException("Missing package: " + packageName); 6246 } 6247 } 6248 6249 synchronized (mInstallLock) { 6250 final String[] instructionSets = new String[] { 6251 getPrimaryInstructionSet(pkg.applicationInfo) }; 6252 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 6253 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 6254 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 6255 throw new IllegalStateException("Failed to dexopt: " + res); 6256 } 6257 } 6258 } 6259 6260 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 6261 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 6262 Slog.w(TAG, "Unable to update from " + oldPkg.name 6263 + " to " + newPkg.packageName 6264 + ": old package not in system partition"); 6265 return false; 6266 } else if (mPackages.get(oldPkg.name) != null) { 6267 Slog.w(TAG, "Unable to update from " + oldPkg.name 6268 + " to " + newPkg.packageName 6269 + ": old package still exists"); 6270 return false; 6271 } 6272 return true; 6273 } 6274 6275 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 6276 int[] users = sUserManager.getUserIds(); 6277 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 6278 if (res < 0) { 6279 return res; 6280 } 6281 for (int user : users) { 6282 if (user != 0) { 6283 res = mInstaller.createUserData(volumeUuid, packageName, 6284 UserHandle.getUid(user, uid), user, seinfo); 6285 if (res < 0) { 6286 return res; 6287 } 6288 } 6289 } 6290 return res; 6291 } 6292 6293 private int removeDataDirsLI(String volumeUuid, String packageName) { 6294 int[] users = sUserManager.getUserIds(); 6295 int res = 0; 6296 for (int user : users) { 6297 int resInner = mInstaller.remove(volumeUuid, packageName, user); 6298 if (resInner < 0) { 6299 res = resInner; 6300 } 6301 } 6302 6303 return res; 6304 } 6305 6306 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 6307 int[] users = sUserManager.getUserIds(); 6308 int res = 0; 6309 for (int user : users) { 6310 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 6311 if (resInner < 0) { 6312 res = resInner; 6313 } 6314 } 6315 return res; 6316 } 6317 6318 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 6319 PackageParser.Package changingLib) { 6320 if (file.path != null) { 6321 usesLibraryFiles.add(file.path); 6322 return; 6323 } 6324 PackageParser.Package p = mPackages.get(file.apk); 6325 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 6326 // If we are doing this while in the middle of updating a library apk, 6327 // then we need to make sure to use that new apk for determining the 6328 // dependencies here. (We haven't yet finished committing the new apk 6329 // to the package manager state.) 6330 if (p == null || p.packageName.equals(changingLib.packageName)) { 6331 p = changingLib; 6332 } 6333 } 6334 if (p != null) { 6335 usesLibraryFiles.addAll(p.getAllCodePaths()); 6336 } 6337 } 6338 6339 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 6340 PackageParser.Package changingLib) throws PackageManagerException { 6341 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 6342 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 6343 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 6344 for (int i=0; i<N; i++) { 6345 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 6346 if (file == null) { 6347 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 6348 "Package " + pkg.packageName + " requires unavailable shared library " 6349 + pkg.usesLibraries.get(i) + "; failing!"); 6350 } 6351 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6352 } 6353 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 6354 for (int i=0; i<N; i++) { 6355 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 6356 if (file == null) { 6357 Slog.w(TAG, "Package " + pkg.packageName 6358 + " desires unavailable shared library " 6359 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 6360 } else { 6361 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6362 } 6363 } 6364 N = usesLibraryFiles.size(); 6365 if (N > 0) { 6366 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 6367 } else { 6368 pkg.usesLibraryFiles = null; 6369 } 6370 } 6371 } 6372 6373 private static boolean hasString(List<String> list, List<String> which) { 6374 if (list == null) { 6375 return false; 6376 } 6377 for (int i=list.size()-1; i>=0; i--) { 6378 for (int j=which.size()-1; j>=0; j--) { 6379 if (which.get(j).equals(list.get(i))) { 6380 return true; 6381 } 6382 } 6383 } 6384 return false; 6385 } 6386 6387 private void updateAllSharedLibrariesLPw() { 6388 for (PackageParser.Package pkg : mPackages.values()) { 6389 try { 6390 updateSharedLibrariesLPw(pkg, null); 6391 } catch (PackageManagerException e) { 6392 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6393 } 6394 } 6395 } 6396 6397 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 6398 PackageParser.Package changingPkg) { 6399 ArrayList<PackageParser.Package> res = null; 6400 for (PackageParser.Package pkg : mPackages.values()) { 6401 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 6402 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 6403 if (res == null) { 6404 res = new ArrayList<PackageParser.Package>(); 6405 } 6406 res.add(pkg); 6407 try { 6408 updateSharedLibrariesLPw(pkg, changingPkg); 6409 } catch (PackageManagerException e) { 6410 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6411 } 6412 } 6413 } 6414 return res; 6415 } 6416 6417 /** 6418 * Derive the value of the {@code cpuAbiOverride} based on the provided 6419 * value and an optional stored value from the package settings. 6420 */ 6421 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 6422 String cpuAbiOverride = null; 6423 6424 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 6425 cpuAbiOverride = null; 6426 } else if (abiOverride != null) { 6427 cpuAbiOverride = abiOverride; 6428 } else if (settings != null) { 6429 cpuAbiOverride = settings.cpuAbiOverrideString; 6430 } 6431 6432 return cpuAbiOverride; 6433 } 6434 6435 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 6436 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6437 boolean success = false; 6438 try { 6439 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 6440 currentTime, user); 6441 success = true; 6442 return res; 6443 } finally { 6444 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 6445 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 6446 } 6447 } 6448 } 6449 6450 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 6451 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6452 final File scanFile = new File(pkg.codePath); 6453 if (pkg.applicationInfo.getCodePath() == null || 6454 pkg.applicationInfo.getResourcePath() == null) { 6455 // Bail out. The resource and code paths haven't been set. 6456 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 6457 "Code and resource paths haven't been set correctly"); 6458 } 6459 6460 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 6461 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 6462 } else { 6463 // Only allow system apps to be flagged as core apps. 6464 pkg.coreApp = false; 6465 } 6466 6467 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 6468 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6469 } 6470 6471 if (mCustomResolverComponentName != null && 6472 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 6473 setUpCustomResolverActivity(pkg); 6474 } 6475 6476 if (pkg.packageName.equals("android")) { 6477 synchronized (mPackages) { 6478 if (mAndroidApplication != null) { 6479 Slog.w(TAG, "*************************************************"); 6480 Slog.w(TAG, "Core android package being redefined. Skipping."); 6481 Slog.w(TAG, " file=" + scanFile); 6482 Slog.w(TAG, "*************************************************"); 6483 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6484 "Core android package being redefined. Skipping."); 6485 } 6486 6487 // Set up information for our fall-back user intent resolution activity. 6488 mPlatformPackage = pkg; 6489 pkg.mVersionCode = mSdkVersion; 6490 mAndroidApplication = pkg.applicationInfo; 6491 6492 if (!mResolverReplaced) { 6493 mResolveActivity.applicationInfo = mAndroidApplication; 6494 mResolveActivity.name = ResolverActivity.class.getName(); 6495 mResolveActivity.packageName = mAndroidApplication.packageName; 6496 mResolveActivity.processName = "system:ui"; 6497 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6498 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 6499 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 6500 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 6501 mResolveActivity.exported = true; 6502 mResolveActivity.enabled = true; 6503 mResolveInfo.activityInfo = mResolveActivity; 6504 mResolveInfo.priority = 0; 6505 mResolveInfo.preferredOrder = 0; 6506 mResolveInfo.match = 0; 6507 mResolveComponentName = new ComponentName( 6508 mAndroidApplication.packageName, mResolveActivity.name); 6509 } 6510 } 6511 } 6512 6513 if (DEBUG_PACKAGE_SCANNING) { 6514 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6515 Log.d(TAG, "Scanning package " + pkg.packageName); 6516 } 6517 6518 if (mPackages.containsKey(pkg.packageName) 6519 || mSharedLibraries.containsKey(pkg.packageName)) { 6520 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6521 "Application package " + pkg.packageName 6522 + " already installed. Skipping duplicate."); 6523 } 6524 6525 // If we're only installing presumed-existing packages, require that the 6526 // scanned APK is both already known and at the path previously established 6527 // for it. Previously unknown packages we pick up normally, but if we have an 6528 // a priori expectation about this package's install presence, enforce it. 6529 // With a singular exception for new system packages. When an OTA contains 6530 // a new system package, we allow the codepath to change from a system location 6531 // to the user-installed location. If we don't allow this change, any newer, 6532 // user-installed version of the application will be ignored. 6533 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 6534 if (mExpectingBetter.containsKey(pkg.packageName)) { 6535 logCriticalInfo(Log.WARN, 6536 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 6537 } else { 6538 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 6539 if (known != null) { 6540 if (DEBUG_PACKAGE_SCANNING) { 6541 Log.d(TAG, "Examining " + pkg.codePath 6542 + " and requiring known paths " + known.codePathString 6543 + " & " + known.resourcePathString); 6544 } 6545 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6546 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6547 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6548 "Application package " + pkg.packageName 6549 + " found at " + pkg.applicationInfo.getCodePath() 6550 + " but expected at " + known.codePathString + "; ignoring."); 6551 } 6552 } 6553 } 6554 } 6555 6556 // Initialize package source and resource directories 6557 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6558 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6559 6560 SharedUserSetting suid = null; 6561 PackageSetting pkgSetting = null; 6562 6563 if (!isSystemApp(pkg)) { 6564 // Only system apps can use these features. 6565 pkg.mOriginalPackages = null; 6566 pkg.mRealPackage = null; 6567 pkg.mAdoptPermissions = null; 6568 } 6569 6570 // writer 6571 synchronized (mPackages) { 6572 if (pkg.mSharedUserId != null) { 6573 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 6574 if (suid == null) { 6575 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6576 "Creating application package " + pkg.packageName 6577 + " for shared user failed"); 6578 } 6579 if (DEBUG_PACKAGE_SCANNING) { 6580 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6581 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 6582 + "): packages=" + suid.packages); 6583 } 6584 } 6585 6586 // Check if we are renaming from an original package name. 6587 PackageSetting origPackage = null; 6588 String realName = null; 6589 if (pkg.mOriginalPackages != null) { 6590 // This package may need to be renamed to a previously 6591 // installed name. Let's check on that... 6592 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 6593 if (pkg.mOriginalPackages.contains(renamed)) { 6594 // This package had originally been installed as the 6595 // original name, and we have already taken care of 6596 // transitioning to the new one. Just update the new 6597 // one to continue using the old name. 6598 realName = pkg.mRealPackage; 6599 if (!pkg.packageName.equals(renamed)) { 6600 // Callers into this function may have already taken 6601 // care of renaming the package; only do it here if 6602 // it is not already done. 6603 pkg.setPackageName(renamed); 6604 } 6605 6606 } else { 6607 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 6608 if ((origPackage = mSettings.peekPackageLPr( 6609 pkg.mOriginalPackages.get(i))) != null) { 6610 // We do have the package already installed under its 6611 // original name... should we use it? 6612 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 6613 // New package is not compatible with original. 6614 origPackage = null; 6615 continue; 6616 } else if (origPackage.sharedUser != null) { 6617 // Make sure uid is compatible between packages. 6618 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 6619 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 6620 + " to " + pkg.packageName + ": old uid " 6621 + origPackage.sharedUser.name 6622 + " differs from " + pkg.mSharedUserId); 6623 origPackage = null; 6624 continue; 6625 } 6626 } else { 6627 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6628 + pkg.packageName + " to old name " + origPackage.name); 6629 } 6630 break; 6631 } 6632 } 6633 } 6634 } 6635 6636 if (mTransferedPackages.contains(pkg.packageName)) { 6637 Slog.w(TAG, "Package " + pkg.packageName 6638 + " was transferred to another, but its .apk remains"); 6639 } 6640 6641 // Just create the setting, don't add it yet. For already existing packages 6642 // the PkgSetting exists already and doesn't have to be created. 6643 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6644 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6645 pkg.applicationInfo.primaryCpuAbi, 6646 pkg.applicationInfo.secondaryCpuAbi, 6647 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6648 user, false); 6649 if (pkgSetting == null) { 6650 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6651 "Creating application package " + pkg.packageName + " failed"); 6652 } 6653 6654 if (pkgSetting.origPackage != null) { 6655 // If we are first transitioning from an original package, 6656 // fix up the new package's name now. We need to do this after 6657 // looking up the package under its new name, so getPackageLP 6658 // can take care of fiddling things correctly. 6659 pkg.setPackageName(origPackage.name); 6660 6661 // File a report about this. 6662 String msg = "New package " + pkgSetting.realName 6663 + " renamed to replace old package " + pkgSetting.name; 6664 reportSettingsProblem(Log.WARN, msg); 6665 6666 // Make a note of it. 6667 mTransferedPackages.add(origPackage.name); 6668 6669 // No longer need to retain this. 6670 pkgSetting.origPackage = null; 6671 } 6672 6673 if (realName != null) { 6674 // Make a note of it. 6675 mTransferedPackages.add(pkg.packageName); 6676 } 6677 6678 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6679 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6680 } 6681 6682 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6683 // Check all shared libraries and map to their actual file path. 6684 // We only do this here for apps not on a system dir, because those 6685 // are the only ones that can fail an install due to this. We 6686 // will take care of the system apps by updating all of their 6687 // library paths after the scan is done. 6688 updateSharedLibrariesLPw(pkg, null); 6689 } 6690 6691 if (mFoundPolicyFile) { 6692 SELinuxMMAC.assignSeinfoValue(pkg); 6693 } 6694 6695 pkg.applicationInfo.uid = pkgSetting.appId; 6696 pkg.mExtras = pkgSetting; 6697 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 6698 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 6699 // We just determined the app is signed correctly, so bring 6700 // over the latest parsed certs. 6701 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6702 } else { 6703 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6704 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6705 "Package " + pkg.packageName + " upgrade keys do not match the " 6706 + "previously installed version"); 6707 } else { 6708 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6709 String msg = "System package " + pkg.packageName 6710 + " signature changed; retaining data."; 6711 reportSettingsProblem(Log.WARN, msg); 6712 } 6713 } 6714 } else { 6715 try { 6716 verifySignaturesLP(pkgSetting, pkg); 6717 // We just determined the app is signed correctly, so bring 6718 // over the latest parsed certs. 6719 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6720 } catch (PackageManagerException e) { 6721 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6722 throw e; 6723 } 6724 // The signature has changed, but this package is in the system 6725 // image... let's recover! 6726 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6727 // However... if this package is part of a shared user, but it 6728 // doesn't match the signature of the shared user, let's fail. 6729 // What this means is that you can't change the signatures 6730 // associated with an overall shared user, which doesn't seem all 6731 // that unreasonable. 6732 if (pkgSetting.sharedUser != null) { 6733 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6734 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 6735 throw new PackageManagerException( 6736 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6737 "Signature mismatch for shared user : " 6738 + pkgSetting.sharedUser); 6739 } 6740 } 6741 // File a report about this. 6742 String msg = "System package " + pkg.packageName 6743 + " signature changed; retaining data."; 6744 reportSettingsProblem(Log.WARN, msg); 6745 } 6746 } 6747 // Verify that this new package doesn't have any content providers 6748 // that conflict with existing packages. Only do this if the 6749 // package isn't already installed, since we don't want to break 6750 // things that are installed. 6751 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6752 final int N = pkg.providers.size(); 6753 int i; 6754 for (i=0; i<N; i++) { 6755 PackageParser.Provider p = pkg.providers.get(i); 6756 if (p.info.authority != null) { 6757 String names[] = p.info.authority.split(";"); 6758 for (int j = 0; j < names.length; j++) { 6759 if (mProvidersByAuthority.containsKey(names[j])) { 6760 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6761 final String otherPackageName = 6762 ((other != null && other.getComponentName() != null) ? 6763 other.getComponentName().getPackageName() : "?"); 6764 throw new PackageManagerException( 6765 INSTALL_FAILED_CONFLICTING_PROVIDER, 6766 "Can't install because provider name " + names[j] 6767 + " (in package " + pkg.applicationInfo.packageName 6768 + ") is already used by " + otherPackageName); 6769 } 6770 } 6771 } 6772 } 6773 } 6774 6775 if (pkg.mAdoptPermissions != null) { 6776 // This package wants to adopt ownership of permissions from 6777 // another package. 6778 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6779 final String origName = pkg.mAdoptPermissions.get(i); 6780 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6781 if (orig != null) { 6782 if (verifyPackageUpdateLPr(orig, pkg)) { 6783 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6784 + pkg.packageName); 6785 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6786 } 6787 } 6788 } 6789 } 6790 } 6791 6792 final String pkgName = pkg.packageName; 6793 6794 final long scanFileTime = scanFile.lastModified(); 6795 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6796 pkg.applicationInfo.processName = fixProcessName( 6797 pkg.applicationInfo.packageName, 6798 pkg.applicationInfo.processName, 6799 pkg.applicationInfo.uid); 6800 6801 File dataPath; 6802 if (mPlatformPackage == pkg) { 6803 // The system package is special. 6804 dataPath = new File(Environment.getDataDirectory(), "system"); 6805 6806 pkg.applicationInfo.dataDir = dataPath.getPath(); 6807 6808 } else { 6809 // This is a normal package, need to make its data directory. 6810 dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid, 6811 UserHandle.USER_OWNER, pkg.packageName); 6812 6813 boolean uidError = false; 6814 if (dataPath.exists()) { 6815 int currentUid = 0; 6816 try { 6817 StructStat stat = Os.stat(dataPath.getPath()); 6818 currentUid = stat.st_uid; 6819 } catch (ErrnoException e) { 6820 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6821 } 6822 6823 // If we have mismatched owners for the data path, we have a problem. 6824 if (currentUid != pkg.applicationInfo.uid) { 6825 boolean recovered = false; 6826 if (currentUid == 0) { 6827 // The directory somehow became owned by root. Wow. 6828 // This is probably because the system was stopped while 6829 // installd was in the middle of messing with its libs 6830 // directory. Ask installd to fix that. 6831 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6832 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6833 if (ret >= 0) { 6834 recovered = true; 6835 String msg = "Package " + pkg.packageName 6836 + " unexpectedly changed to uid 0; recovered to " + 6837 + pkg.applicationInfo.uid; 6838 reportSettingsProblem(Log.WARN, msg); 6839 } 6840 } 6841 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6842 || (scanFlags&SCAN_BOOTING) != 0)) { 6843 // If this is a system app, we can at least delete its 6844 // current data so the application will still work. 6845 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6846 if (ret >= 0) { 6847 // TODO: Kill the processes first 6848 // Old data gone! 6849 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6850 ? "System package " : "Third party package "; 6851 String msg = prefix + pkg.packageName 6852 + " has changed from uid: " 6853 + currentUid + " to " 6854 + pkg.applicationInfo.uid + "; old data erased"; 6855 reportSettingsProblem(Log.WARN, msg); 6856 recovered = true; 6857 6858 // And now re-install the app. 6859 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6860 pkg.applicationInfo.seinfo); 6861 if (ret == -1) { 6862 // Ack should not happen! 6863 msg = prefix + pkg.packageName 6864 + " could not have data directory re-created after delete."; 6865 reportSettingsProblem(Log.WARN, msg); 6866 throw new PackageManagerException( 6867 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6868 } 6869 } 6870 if (!recovered) { 6871 mHasSystemUidErrors = true; 6872 } 6873 } else if (!recovered) { 6874 // If we allow this install to proceed, we will be broken. 6875 // Abort, abort! 6876 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6877 "scanPackageLI"); 6878 } 6879 if (!recovered) { 6880 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6881 + pkg.applicationInfo.uid + "/fs_" 6882 + currentUid; 6883 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6884 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6885 String msg = "Package " + pkg.packageName 6886 + " has mismatched uid: " 6887 + currentUid + " on disk, " 6888 + pkg.applicationInfo.uid + " in settings"; 6889 // writer 6890 synchronized (mPackages) { 6891 mSettings.mReadMessages.append(msg); 6892 mSettings.mReadMessages.append('\n'); 6893 uidError = true; 6894 if (!pkgSetting.uidError) { 6895 reportSettingsProblem(Log.ERROR, msg); 6896 } 6897 } 6898 } 6899 } 6900 pkg.applicationInfo.dataDir = dataPath.getPath(); 6901 if (mShouldRestoreconData) { 6902 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6903 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 6904 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 6905 } 6906 } else { 6907 if (DEBUG_PACKAGE_SCANNING) { 6908 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6909 Log.v(TAG, "Want this data dir: " + dataPath); 6910 } 6911 //invoke installer to do the actual installation 6912 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6913 pkg.applicationInfo.seinfo); 6914 if (ret < 0) { 6915 // Error from installer 6916 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6917 "Unable to create data dirs [errorCode=" + ret + "]"); 6918 } 6919 6920 if (dataPath.exists()) { 6921 pkg.applicationInfo.dataDir = dataPath.getPath(); 6922 } else { 6923 Slog.w(TAG, "Unable to create data directory: " + dataPath); 6924 pkg.applicationInfo.dataDir = null; 6925 } 6926 } 6927 6928 pkgSetting.uidError = uidError; 6929 } 6930 6931 final String path = scanFile.getPath(); 6932 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6933 6934 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 6935 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 6936 6937 // Some system apps still use directory structure for native libraries 6938 // in which case we might end up not detecting abi solely based on apk 6939 // structure. Try to detect abi based on directory structure. 6940 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 6941 pkg.applicationInfo.primaryCpuAbi == null) { 6942 setBundledAppAbisAndRoots(pkg, pkgSetting); 6943 setNativeLibraryPaths(pkg); 6944 } 6945 6946 } else { 6947 if ((scanFlags & SCAN_MOVE) != 0) { 6948 // We haven't run dex-opt for this move (since we've moved the compiled output too) 6949 // but we already have this packages package info in the PackageSetting. We just 6950 // use that and derive the native library path based on the new codepath. 6951 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 6952 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 6953 } 6954 6955 // Set native library paths again. For moves, the path will be updated based on the 6956 // ABIs we've determined above. For non-moves, the path will be updated based on the 6957 // ABIs we determined during compilation, but the path will depend on the final 6958 // package path (after the rename away from the stage path). 6959 setNativeLibraryPaths(pkg); 6960 } 6961 6962 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 6963 final int[] userIds = sUserManager.getUserIds(); 6964 synchronized (mInstallLock) { 6965 // Make sure all user data directories are ready to roll; we're okay 6966 // if they already exist 6967 if (!TextUtils.isEmpty(pkg.volumeUuid)) { 6968 for (int userId : userIds) { 6969 if (userId != 0) { 6970 mInstaller.createUserData(pkg.volumeUuid, pkg.packageName, 6971 UserHandle.getUid(userId, pkg.applicationInfo.uid), userId, 6972 pkg.applicationInfo.seinfo); 6973 } 6974 } 6975 } 6976 6977 // Create a native library symlink only if we have native libraries 6978 // and if the native libraries are 32 bit libraries. We do not provide 6979 // this symlink for 64 bit libraries. 6980 if (pkg.applicationInfo.primaryCpuAbi != null && 6981 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 6982 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 6983 for (int userId : userIds) { 6984 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 6985 nativeLibPath, userId) < 0) { 6986 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6987 "Failed linking native library dir (user=" + userId + ")"); 6988 } 6989 } 6990 } 6991 } 6992 6993 // This is a special case for the "system" package, where the ABI is 6994 // dictated by the zygote configuration (and init.rc). We should keep track 6995 // of this ABI so that we can deal with "normal" applications that run under 6996 // the same UID correctly. 6997 if (mPlatformPackage == pkg) { 6998 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 6999 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 7000 } 7001 7002 // If there's a mismatch between the abi-override in the package setting 7003 // and the abiOverride specified for the install. Warn about this because we 7004 // would've already compiled the app without taking the package setting into 7005 // account. 7006 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 7007 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 7008 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 7009 " for package: " + pkg.packageName); 7010 } 7011 } 7012 7013 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7014 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7015 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 7016 7017 // Copy the derived override back to the parsed package, so that we can 7018 // update the package settings accordingly. 7019 pkg.cpuAbiOverride = cpuAbiOverride; 7020 7021 if (DEBUG_ABI_SELECTION) { 7022 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 7023 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 7024 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 7025 } 7026 7027 // Push the derived path down into PackageSettings so we know what to 7028 // clean up at uninstall time. 7029 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 7030 7031 if (DEBUG_ABI_SELECTION) { 7032 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 7033 " primary=" + pkg.applicationInfo.primaryCpuAbi + 7034 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 7035 } 7036 7037 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 7038 // We don't do this here during boot because we can do it all 7039 // at once after scanning all existing packages. 7040 // 7041 // We also do this *before* we perform dexopt on this package, so that 7042 // we can avoid redundant dexopts, and also to make sure we've got the 7043 // code and package path correct. 7044 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 7045 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 7046 } 7047 7048 if ((scanFlags & SCAN_NO_DEX) == 0) { 7049 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 7050 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 7051 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7052 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 7053 } 7054 } 7055 if (mFactoryTest && pkg.requestedPermissions.contains( 7056 android.Manifest.permission.FACTORY_TEST)) { 7057 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 7058 } 7059 7060 ArrayList<PackageParser.Package> clientLibPkgs = null; 7061 7062 // writer 7063 synchronized (mPackages) { 7064 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7065 // Only system apps can add new shared libraries. 7066 if (pkg.libraryNames != null) { 7067 for (int i=0; i<pkg.libraryNames.size(); i++) { 7068 String name = pkg.libraryNames.get(i); 7069 boolean allowed = false; 7070 if (pkg.isUpdatedSystemApp()) { 7071 // New library entries can only be added through the 7072 // system image. This is important to get rid of a lot 7073 // of nasty edge cases: for example if we allowed a non- 7074 // system update of the app to add a library, then uninstalling 7075 // the update would make the library go away, and assumptions 7076 // we made such as through app install filtering would now 7077 // have allowed apps on the device which aren't compatible 7078 // with it. Better to just have the restriction here, be 7079 // conservative, and create many fewer cases that can negatively 7080 // impact the user experience. 7081 final PackageSetting sysPs = mSettings 7082 .getDisabledSystemPkgLPr(pkg.packageName); 7083 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 7084 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 7085 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 7086 allowed = true; 7087 allowed = true; 7088 break; 7089 } 7090 } 7091 } 7092 } else { 7093 allowed = true; 7094 } 7095 if (allowed) { 7096 if (!mSharedLibraries.containsKey(name)) { 7097 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 7098 } else if (!name.equals(pkg.packageName)) { 7099 Slog.w(TAG, "Package " + pkg.packageName + " library " 7100 + name + " already exists; skipping"); 7101 } 7102 } else { 7103 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 7104 + name + " that is not declared on system image; skipping"); 7105 } 7106 } 7107 if ((scanFlags&SCAN_BOOTING) == 0) { 7108 // If we are not booting, we need to update any applications 7109 // that are clients of our shared library. If we are booting, 7110 // this will all be done once the scan is complete. 7111 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 7112 } 7113 } 7114 } 7115 } 7116 7117 // We also need to dexopt any apps that are dependent on this library. Note that 7118 // if these fail, we should abort the install since installing the library will 7119 // result in some apps being broken. 7120 if (clientLibPkgs != null) { 7121 if ((scanFlags & SCAN_NO_DEX) == 0) { 7122 for (int i = 0; i < clientLibPkgs.size(); i++) { 7123 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7124 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 7125 null /* instruction sets */, forceDex, 7126 (scanFlags & SCAN_DEFER_DEX) != 0, false); 7127 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7128 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 7129 "scanPackageLI failed to dexopt clientLibPkgs"); 7130 } 7131 } 7132 } 7133 } 7134 7135 // Request the ActivityManager to kill the process(only for existing packages) 7136 // so that we do not end up in a confused state while the user is still using the older 7137 // version of the application while the new one gets installed. 7138 if ((scanFlags & SCAN_REPLACING) != 0) { 7139 killApplication(pkg.applicationInfo.packageName, 7140 pkg.applicationInfo.uid, "replace pkg"); 7141 } 7142 7143 // Also need to kill any apps that are dependent on the library. 7144 if (clientLibPkgs != null) { 7145 for (int i=0; i<clientLibPkgs.size(); i++) { 7146 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7147 killApplication(clientPkg.applicationInfo.packageName, 7148 clientPkg.applicationInfo.uid, "update lib"); 7149 } 7150 } 7151 7152 // Make sure we're not adding any bogus keyset info 7153 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7154 ksms.assertScannedPackageValid(pkg); 7155 7156 // writer 7157 synchronized (mPackages) { 7158 // We don't expect installation to fail beyond this point 7159 7160 // Add the new setting to mSettings 7161 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 7162 // Add the new setting to mPackages 7163 mPackages.put(pkg.applicationInfo.packageName, pkg); 7164 // Make sure we don't accidentally delete its data. 7165 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 7166 while (iter.hasNext()) { 7167 PackageCleanItem item = iter.next(); 7168 if (pkgName.equals(item.packageName)) { 7169 iter.remove(); 7170 } 7171 } 7172 7173 // Take care of first install / last update times. 7174 if (currentTime != 0) { 7175 if (pkgSetting.firstInstallTime == 0) { 7176 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7177 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7178 pkgSetting.lastUpdateTime = currentTime; 7179 } 7180 } else if (pkgSetting.firstInstallTime == 0) { 7181 // We need *something*. Take time time stamp of the file. 7182 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7183 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7184 if (scanFileTime != pkgSetting.timeStamp) { 7185 // A package on the system image has changed; consider this 7186 // to be an update. 7187 pkgSetting.lastUpdateTime = scanFileTime; 7188 } 7189 } 7190 7191 // Add the package's KeySets to the global KeySetManagerService 7192 ksms.addScannedPackageLPw(pkg); 7193 7194 int N = pkg.providers.size(); 7195 StringBuilder r = null; 7196 int i; 7197 for (i=0; i<N; i++) { 7198 PackageParser.Provider p = pkg.providers.get(i); 7199 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7200 p.info.processName, pkg.applicationInfo.uid); 7201 mProviders.addProvider(p); 7202 p.syncable = p.info.isSyncable; 7203 if (p.info.authority != null) { 7204 String names[] = p.info.authority.split(";"); 7205 p.info.authority = null; 7206 for (int j = 0; j < names.length; j++) { 7207 if (j == 1 && p.syncable) { 7208 // We only want the first authority for a provider to possibly be 7209 // syncable, so if we already added this provider using a different 7210 // authority clear the syncable flag. We copy the provider before 7211 // changing it because the mProviders object contains a reference 7212 // to a provider that we don't want to change. 7213 // Only do this for the second authority since the resulting provider 7214 // object can be the same for all future authorities for this provider. 7215 p = new PackageParser.Provider(p); 7216 p.syncable = false; 7217 } 7218 if (!mProvidersByAuthority.containsKey(names[j])) { 7219 mProvidersByAuthority.put(names[j], p); 7220 if (p.info.authority == null) { 7221 p.info.authority = names[j]; 7222 } else { 7223 p.info.authority = p.info.authority + ";" + names[j]; 7224 } 7225 if (DEBUG_PACKAGE_SCANNING) { 7226 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7227 Log.d(TAG, "Registered content provider: " + names[j] 7228 + ", className = " + p.info.name + ", isSyncable = " 7229 + p.info.isSyncable); 7230 } 7231 } else { 7232 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7233 Slog.w(TAG, "Skipping provider name " + names[j] + 7234 " (in package " + pkg.applicationInfo.packageName + 7235 "): name already used by " 7236 + ((other != null && other.getComponentName() != null) 7237 ? other.getComponentName().getPackageName() : "?")); 7238 } 7239 } 7240 } 7241 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7242 if (r == null) { 7243 r = new StringBuilder(256); 7244 } else { 7245 r.append(' '); 7246 } 7247 r.append(p.info.name); 7248 } 7249 } 7250 if (r != null) { 7251 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7252 } 7253 7254 N = pkg.services.size(); 7255 r = null; 7256 for (i=0; i<N; i++) { 7257 PackageParser.Service s = pkg.services.get(i); 7258 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 7259 s.info.processName, pkg.applicationInfo.uid); 7260 mServices.addService(s); 7261 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7262 if (r == null) { 7263 r = new StringBuilder(256); 7264 } else { 7265 r.append(' '); 7266 } 7267 r.append(s.info.name); 7268 } 7269 } 7270 if (r != null) { 7271 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 7272 } 7273 7274 N = pkg.receivers.size(); 7275 r = null; 7276 for (i=0; i<N; i++) { 7277 PackageParser.Activity a = pkg.receivers.get(i); 7278 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7279 a.info.processName, pkg.applicationInfo.uid); 7280 mReceivers.addActivity(a, "receiver"); 7281 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7282 if (r == null) { 7283 r = new StringBuilder(256); 7284 } else { 7285 r.append(' '); 7286 } 7287 r.append(a.info.name); 7288 } 7289 } 7290 if (r != null) { 7291 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 7292 } 7293 7294 N = pkg.activities.size(); 7295 r = null; 7296 for (i=0; i<N; i++) { 7297 PackageParser.Activity a = pkg.activities.get(i); 7298 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7299 a.info.processName, pkg.applicationInfo.uid); 7300 mActivities.addActivity(a, "activity"); 7301 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7302 if (r == null) { 7303 r = new StringBuilder(256); 7304 } else { 7305 r.append(' '); 7306 } 7307 r.append(a.info.name); 7308 } 7309 } 7310 if (r != null) { 7311 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 7312 } 7313 7314 N = pkg.permissionGroups.size(); 7315 r = null; 7316 for (i=0; i<N; i++) { 7317 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 7318 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 7319 if (cur == null) { 7320 mPermissionGroups.put(pg.info.name, pg); 7321 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7322 if (r == null) { 7323 r = new StringBuilder(256); 7324 } else { 7325 r.append(' '); 7326 } 7327 r.append(pg.info.name); 7328 } 7329 } else { 7330 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 7331 + pg.info.packageName + " ignored: original from " 7332 + cur.info.packageName); 7333 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7334 if (r == null) { 7335 r = new StringBuilder(256); 7336 } else { 7337 r.append(' '); 7338 } 7339 r.append("DUP:"); 7340 r.append(pg.info.name); 7341 } 7342 } 7343 } 7344 if (r != null) { 7345 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 7346 } 7347 7348 N = pkg.permissions.size(); 7349 r = null; 7350 for (i=0; i<N; i++) { 7351 PackageParser.Permission p = pkg.permissions.get(i); 7352 7353 // Assume by default that we did not install this permission into the system. 7354 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 7355 7356 // Now that permission groups have a special meaning, we ignore permission 7357 // groups for legacy apps to prevent unexpected behavior. In particular, 7358 // permissions for one app being granted to someone just becuase they happen 7359 // to be in a group defined by another app (before this had no implications). 7360 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 7361 p.group = mPermissionGroups.get(p.info.group); 7362 // Warn for a permission in an unknown group. 7363 if (p.info.group != null && p.group == null) { 7364 Slog.w(TAG, "Permission " + p.info.name + " from package " 7365 + p.info.packageName + " in an unknown group " + p.info.group); 7366 } 7367 } 7368 7369 ArrayMap<String, BasePermission> permissionMap = 7370 p.tree ? mSettings.mPermissionTrees 7371 : mSettings.mPermissions; 7372 BasePermission bp = permissionMap.get(p.info.name); 7373 7374 // Allow system apps to redefine non-system permissions 7375 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 7376 final boolean currentOwnerIsSystem = (bp.perm != null 7377 && isSystemApp(bp.perm.owner)); 7378 if (isSystemApp(p.owner)) { 7379 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 7380 // It's a built-in permission and no owner, take ownership now 7381 bp.packageSetting = pkgSetting; 7382 bp.perm = p; 7383 bp.uid = pkg.applicationInfo.uid; 7384 bp.sourcePackage = p.info.packageName; 7385 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7386 } else if (!currentOwnerIsSystem) { 7387 String msg = "New decl " + p.owner + " of permission " 7388 + p.info.name + " is system; overriding " + bp.sourcePackage; 7389 reportSettingsProblem(Log.WARN, msg); 7390 bp = null; 7391 } 7392 } 7393 } 7394 7395 if (bp == null) { 7396 bp = new BasePermission(p.info.name, p.info.packageName, 7397 BasePermission.TYPE_NORMAL); 7398 permissionMap.put(p.info.name, bp); 7399 } 7400 7401 if (bp.perm == null) { 7402 if (bp.sourcePackage == null 7403 || bp.sourcePackage.equals(p.info.packageName)) { 7404 BasePermission tree = findPermissionTreeLP(p.info.name); 7405 if (tree == null 7406 || tree.sourcePackage.equals(p.info.packageName)) { 7407 bp.packageSetting = pkgSetting; 7408 bp.perm = p; 7409 bp.uid = pkg.applicationInfo.uid; 7410 bp.sourcePackage = p.info.packageName; 7411 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7412 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7413 if (r == null) { 7414 r = new StringBuilder(256); 7415 } else { 7416 r.append(' '); 7417 } 7418 r.append(p.info.name); 7419 } 7420 } else { 7421 Slog.w(TAG, "Permission " + p.info.name + " from package " 7422 + p.info.packageName + " ignored: base tree " 7423 + tree.name + " is from package " 7424 + tree.sourcePackage); 7425 } 7426 } else { 7427 Slog.w(TAG, "Permission " + p.info.name + " from package " 7428 + p.info.packageName + " ignored: original from " 7429 + bp.sourcePackage); 7430 } 7431 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7432 if (r == null) { 7433 r = new StringBuilder(256); 7434 } else { 7435 r.append(' '); 7436 } 7437 r.append("DUP:"); 7438 r.append(p.info.name); 7439 } 7440 if (bp.perm == p) { 7441 bp.protectionLevel = p.info.protectionLevel; 7442 } 7443 } 7444 7445 if (r != null) { 7446 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 7447 } 7448 7449 N = pkg.instrumentation.size(); 7450 r = null; 7451 for (i=0; i<N; i++) { 7452 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7453 a.info.packageName = pkg.applicationInfo.packageName; 7454 a.info.sourceDir = pkg.applicationInfo.sourceDir; 7455 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 7456 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 7457 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 7458 a.info.dataDir = pkg.applicationInfo.dataDir; 7459 7460 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 7461 // need other information about the application, like the ABI and what not ? 7462 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 7463 mInstrumentation.put(a.getComponentName(), a); 7464 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7465 if (r == null) { 7466 r = new StringBuilder(256); 7467 } else { 7468 r.append(' '); 7469 } 7470 r.append(a.info.name); 7471 } 7472 } 7473 if (r != null) { 7474 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 7475 } 7476 7477 if (pkg.protectedBroadcasts != null) { 7478 N = pkg.protectedBroadcasts.size(); 7479 for (i=0; i<N; i++) { 7480 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 7481 } 7482 } 7483 7484 pkgSetting.setTimeStamp(scanFileTime); 7485 7486 // Create idmap files for pairs of (packages, overlay packages). 7487 // Note: "android", ie framework-res.apk, is handled by native layers. 7488 if (pkg.mOverlayTarget != null) { 7489 // This is an overlay package. 7490 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 7491 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 7492 mOverlays.put(pkg.mOverlayTarget, 7493 new ArrayMap<String, PackageParser.Package>()); 7494 } 7495 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 7496 map.put(pkg.packageName, pkg); 7497 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 7498 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 7499 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7500 "scanPackageLI failed to createIdmap"); 7501 } 7502 } 7503 } else if (mOverlays.containsKey(pkg.packageName) && 7504 !pkg.packageName.equals("android")) { 7505 // This is a regular package, with one or more known overlay packages. 7506 createIdmapsForPackageLI(pkg); 7507 } 7508 } 7509 7510 return pkg; 7511 } 7512 7513 /** 7514 * Derive the ABI of a non-system package located at {@code scanFile}. This information 7515 * is derived purely on the basis of the contents of {@code scanFile} and 7516 * {@code cpuAbiOverride}. 7517 * 7518 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 7519 */ 7520 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 7521 String cpuAbiOverride, boolean extractLibs) 7522 throws PackageManagerException { 7523 // TODO: We can probably be smarter about this stuff. For installed apps, 7524 // we can calculate this information at install time once and for all. For 7525 // system apps, we can probably assume that this information doesn't change 7526 // after the first boot scan. As things stand, we do lots of unnecessary work. 7527 7528 // Give ourselves some initial paths; we'll come back for another 7529 // pass once we've determined ABI below. 7530 setNativeLibraryPaths(pkg); 7531 7532 // We would never need to extract libs for forward-locked and external packages, 7533 // since the container service will do it for us. We shouldn't attempt to 7534 // extract libs from system app when it was not updated. 7535 if (pkg.isForwardLocked() || isExternal(pkg) || 7536 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) { 7537 extractLibs = false; 7538 } 7539 7540 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7541 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7542 7543 NativeLibraryHelper.Handle handle = null; 7544 try { 7545 handle = NativeLibraryHelper.Handle.create(scanFile); 7546 // TODO(multiArch): This can be null for apps that didn't go through the 7547 // usual installation process. We can calculate it again, like we 7548 // do during install time. 7549 // 7550 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7551 // unnecessary. 7552 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7553 7554 // Null out the abis so that they can be recalculated. 7555 pkg.applicationInfo.primaryCpuAbi = null; 7556 pkg.applicationInfo.secondaryCpuAbi = null; 7557 if (isMultiArch(pkg.applicationInfo)) { 7558 // Warn if we've set an abiOverride for multi-lib packages.. 7559 // By definition, we need to copy both 32 and 64 bit libraries for 7560 // such packages. 7561 if (pkg.cpuAbiOverride != null 7562 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7563 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7564 } 7565 7566 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7567 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7568 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7569 if (extractLibs) { 7570 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7571 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7572 useIsaSpecificSubdirs); 7573 } else { 7574 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7575 } 7576 } 7577 7578 maybeThrowExceptionForMultiArchCopy( 7579 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7580 7581 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7582 if (extractLibs) { 7583 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7584 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7585 useIsaSpecificSubdirs); 7586 } else { 7587 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7588 } 7589 } 7590 7591 maybeThrowExceptionForMultiArchCopy( 7592 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7593 7594 if (abi64 >= 0) { 7595 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7596 } 7597 7598 if (abi32 >= 0) { 7599 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7600 if (abi64 >= 0) { 7601 pkg.applicationInfo.secondaryCpuAbi = abi; 7602 } else { 7603 pkg.applicationInfo.primaryCpuAbi = abi; 7604 } 7605 } 7606 } else { 7607 String[] abiList = (cpuAbiOverride != null) ? 7608 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7609 7610 // Enable gross and lame hacks for apps that are built with old 7611 // SDK tools. We must scan their APKs for renderscript bitcode and 7612 // not launch them if it's present. Don't bother checking on devices 7613 // that don't have 64 bit support. 7614 boolean needsRenderScriptOverride = false; 7615 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7616 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7617 abiList = Build.SUPPORTED_32_BIT_ABIS; 7618 needsRenderScriptOverride = true; 7619 } 7620 7621 final int copyRet; 7622 if (extractLibs) { 7623 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7624 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7625 } else { 7626 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7627 } 7628 7629 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7630 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7631 "Error unpackaging native libs for app, errorCode=" + copyRet); 7632 } 7633 7634 if (copyRet >= 0) { 7635 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7636 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7637 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7638 } else if (needsRenderScriptOverride) { 7639 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7640 } 7641 } 7642 } catch (IOException ioe) { 7643 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7644 } finally { 7645 IoUtils.closeQuietly(handle); 7646 } 7647 7648 // Now that we've calculated the ABIs and determined if it's an internal app, 7649 // we will go ahead and populate the nativeLibraryPath. 7650 setNativeLibraryPaths(pkg); 7651 } 7652 7653 /** 7654 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7655 * i.e, so that all packages can be run inside a single process if required. 7656 * 7657 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7658 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7659 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7660 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7661 * updating a package that belongs to a shared user. 7662 * 7663 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7664 * adds unnecessary complexity. 7665 */ 7666 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7667 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 7668 String requiredInstructionSet = null; 7669 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7670 requiredInstructionSet = VMRuntime.getInstructionSet( 7671 scannedPackage.applicationInfo.primaryCpuAbi); 7672 } 7673 7674 PackageSetting requirer = null; 7675 for (PackageSetting ps : packagesForUser) { 7676 // If packagesForUser contains scannedPackage, we skip it. This will happen 7677 // when scannedPackage is an update of an existing package. Without this check, 7678 // we will never be able to change the ABI of any package belonging to a shared 7679 // user, even if it's compatible with other packages. 7680 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7681 if (ps.primaryCpuAbiString == null) { 7682 continue; 7683 } 7684 7685 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7686 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7687 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7688 // this but there's not much we can do. 7689 String errorMessage = "Instruction set mismatch, " 7690 + ((requirer == null) ? "[caller]" : requirer) 7691 + " requires " + requiredInstructionSet + " whereas " + ps 7692 + " requires " + instructionSet; 7693 Slog.w(TAG, errorMessage); 7694 } 7695 7696 if (requiredInstructionSet == null) { 7697 requiredInstructionSet = instructionSet; 7698 requirer = ps; 7699 } 7700 } 7701 } 7702 7703 if (requiredInstructionSet != null) { 7704 String adjustedAbi; 7705 if (requirer != null) { 7706 // requirer != null implies that either scannedPackage was null or that scannedPackage 7707 // did not require an ABI, in which case we have to adjust scannedPackage to match 7708 // the ABI of the set (which is the same as requirer's ABI) 7709 adjustedAbi = requirer.primaryCpuAbiString; 7710 if (scannedPackage != null) { 7711 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7712 } 7713 } else { 7714 // requirer == null implies that we're updating all ABIs in the set to 7715 // match scannedPackage. 7716 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7717 } 7718 7719 for (PackageSetting ps : packagesForUser) { 7720 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7721 if (ps.primaryCpuAbiString != null) { 7722 continue; 7723 } 7724 7725 ps.primaryCpuAbiString = adjustedAbi; 7726 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7727 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7728 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7729 7730 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 7731 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 7732 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7733 ps.primaryCpuAbiString = null; 7734 ps.pkg.applicationInfo.primaryCpuAbi = null; 7735 return; 7736 } else { 7737 mInstaller.rmdex(ps.codePathString, 7738 getDexCodeInstructionSet(getPreferredInstructionSet())); 7739 } 7740 } 7741 } 7742 } 7743 } 7744 } 7745 7746 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7747 synchronized (mPackages) { 7748 mResolverReplaced = true; 7749 // Set up information for custom user intent resolution activity. 7750 mResolveActivity.applicationInfo = pkg.applicationInfo; 7751 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7752 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7753 mResolveActivity.processName = pkg.applicationInfo.packageName; 7754 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7755 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7756 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7757 mResolveActivity.theme = 0; 7758 mResolveActivity.exported = true; 7759 mResolveActivity.enabled = true; 7760 mResolveInfo.activityInfo = mResolveActivity; 7761 mResolveInfo.priority = 0; 7762 mResolveInfo.preferredOrder = 0; 7763 mResolveInfo.match = 0; 7764 mResolveComponentName = mCustomResolverComponentName; 7765 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7766 mResolveComponentName); 7767 } 7768 } 7769 7770 private static String calculateBundledApkRoot(final String codePathString) { 7771 final File codePath = new File(codePathString); 7772 final File codeRoot; 7773 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 7774 codeRoot = Environment.getRootDirectory(); 7775 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7776 codeRoot = Environment.getOemDirectory(); 7777 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7778 codeRoot = Environment.getVendorDirectory(); 7779 } else { 7780 // Unrecognized code path; take its top real segment as the apk root: 7781 // e.g. /something/app/blah.apk => /something 7782 try { 7783 File f = codePath.getCanonicalFile(); 7784 File parent = f.getParentFile(); // non-null because codePath is a file 7785 File tmp; 7786 while ((tmp = parent.getParentFile()) != null) { 7787 f = parent; 7788 parent = tmp; 7789 } 7790 codeRoot = f; 7791 Slog.w(TAG, "Unrecognized code path " 7792 + codePath + " - using " + codeRoot); 7793 } catch (IOException e) { 7794 // Can't canonicalize the code path -- shenanigans? 7795 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7796 return Environment.getRootDirectory().getPath(); 7797 } 7798 } 7799 return codeRoot.getPath(); 7800 } 7801 7802 /** 7803 * Derive and set the location of native libraries for the given package, 7804 * which varies depending on where and how the package was installed. 7805 */ 7806 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7807 final ApplicationInfo info = pkg.applicationInfo; 7808 final String codePath = pkg.codePath; 7809 final File codeFile = new File(codePath); 7810 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7811 final boolean asecApp = info.isForwardLocked() || isExternal(info); 7812 7813 info.nativeLibraryRootDir = null; 7814 info.nativeLibraryRootRequiresIsa = false; 7815 info.nativeLibraryDir = null; 7816 info.secondaryNativeLibraryDir = null; 7817 7818 if (isApkFile(codeFile)) { 7819 // Monolithic install 7820 if (bundledApp) { 7821 // If "/system/lib64/apkname" exists, assume that is the per-package 7822 // native library directory to use; otherwise use "/system/lib/apkname". 7823 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7824 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7825 getPrimaryInstructionSet(info)); 7826 7827 // This is a bundled system app so choose the path based on the ABI. 7828 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7829 // is just the default path. 7830 final String apkName = deriveCodePathName(codePath); 7831 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7832 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7833 apkName).getAbsolutePath(); 7834 7835 if (info.secondaryCpuAbi != null) { 7836 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7837 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7838 secondaryLibDir, apkName).getAbsolutePath(); 7839 } 7840 } else if (asecApp) { 7841 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 7842 .getAbsolutePath(); 7843 } else { 7844 final String apkName = deriveCodePathName(codePath); 7845 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 7846 .getAbsolutePath(); 7847 } 7848 7849 info.nativeLibraryRootRequiresIsa = false; 7850 info.nativeLibraryDir = info.nativeLibraryRootDir; 7851 } else { 7852 // Cluster install 7853 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 7854 info.nativeLibraryRootRequiresIsa = true; 7855 7856 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 7857 getPrimaryInstructionSet(info)).getAbsolutePath(); 7858 7859 if (info.secondaryCpuAbi != null) { 7860 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 7861 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 7862 } 7863 } 7864 } 7865 7866 /** 7867 * Calculate the abis and roots for a bundled app. These can uniquely 7868 * be determined from the contents of the system partition, i.e whether 7869 * it contains 64 or 32 bit shared libraries etc. We do not validate any 7870 * of this information, and instead assume that the system was built 7871 * sensibly. 7872 */ 7873 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 7874 PackageSetting pkgSetting) { 7875 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 7876 7877 // If "/system/lib64/apkname" exists, assume that is the per-package 7878 // native library directory to use; otherwise use "/system/lib/apkname". 7879 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 7880 setBundledAppAbi(pkg, apkRoot, apkName); 7881 // pkgSetting might be null during rescan following uninstall of updates 7882 // to a bundled app, so accommodate that possibility. The settings in 7883 // that case will be established later from the parsed package. 7884 // 7885 // If the settings aren't null, sync them up with what we've just derived. 7886 // note that apkRoot isn't stored in the package settings. 7887 if (pkgSetting != null) { 7888 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7889 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7890 } 7891 } 7892 7893 /** 7894 * Deduces the ABI of a bundled app and sets the relevant fields on the 7895 * parsed pkg object. 7896 * 7897 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 7898 * under which system libraries are installed. 7899 * @param apkName the name of the installed package. 7900 */ 7901 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 7902 final File codeFile = new File(pkg.codePath); 7903 7904 final boolean has64BitLibs; 7905 final boolean has32BitLibs; 7906 if (isApkFile(codeFile)) { 7907 // Monolithic install 7908 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 7909 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7910 } else { 7911 // Cluster install 7912 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7913 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7914 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7915 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7916 has64BitLibs = (new File(rootDir, isa)).exists(); 7917 } else { 7918 has64BitLibs = false; 7919 } 7920 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7921 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 7922 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 7923 has32BitLibs = (new File(rootDir, isa)).exists(); 7924 } else { 7925 has32BitLibs = false; 7926 } 7927 } 7928 7929 if (has64BitLibs && !has32BitLibs) { 7930 // The package has 64 bit libs, but not 32 bit libs. Its primary 7931 // ABI should be 64 bit. We can safely assume here that the bundled 7932 // native libraries correspond to the most preferred ABI in the list. 7933 7934 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7935 pkg.applicationInfo.secondaryCpuAbi = null; 7936 } else if (has32BitLibs && !has64BitLibs) { 7937 // The package has 32 bit libs but not 64 bit libs. Its primary 7938 // ABI should be 32 bit. 7939 7940 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7941 pkg.applicationInfo.secondaryCpuAbi = null; 7942 } else if (has32BitLibs && has64BitLibs) { 7943 // The application has both 64 and 32 bit bundled libraries. We check 7944 // here that the app declares multiArch support, and warn if it doesn't. 7945 // 7946 // We will be lenient here and record both ABIs. The primary will be the 7947 // ABI that's higher on the list, i.e, a device that's configured to prefer 7948 // 64 bit apps will see a 64 bit primary ABI, 7949 7950 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 7951 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 7952 } 7953 7954 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 7955 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7956 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7957 } else { 7958 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7959 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7960 } 7961 } else { 7962 pkg.applicationInfo.primaryCpuAbi = null; 7963 pkg.applicationInfo.secondaryCpuAbi = null; 7964 } 7965 } 7966 7967 private void killApplication(String pkgName, int appId, String reason) { 7968 // Request the ActivityManager to kill the process(only for existing packages) 7969 // so that we do not end up in a confused state while the user is still using the older 7970 // version of the application while the new one gets installed. 7971 IActivityManager am = ActivityManagerNative.getDefault(); 7972 if (am != null) { 7973 try { 7974 am.killApplicationWithAppId(pkgName, appId, reason); 7975 } catch (RemoteException e) { 7976 } 7977 } 7978 } 7979 7980 void removePackageLI(PackageSetting ps, boolean chatty) { 7981 if (DEBUG_INSTALL) { 7982 if (chatty) 7983 Log.d(TAG, "Removing package " + ps.name); 7984 } 7985 7986 // writer 7987 synchronized (mPackages) { 7988 mPackages.remove(ps.name); 7989 final PackageParser.Package pkg = ps.pkg; 7990 if (pkg != null) { 7991 cleanPackageDataStructuresLILPw(pkg, chatty); 7992 } 7993 } 7994 } 7995 7996 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 7997 if (DEBUG_INSTALL) { 7998 if (chatty) 7999 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 8000 } 8001 8002 // writer 8003 synchronized (mPackages) { 8004 mPackages.remove(pkg.applicationInfo.packageName); 8005 cleanPackageDataStructuresLILPw(pkg, chatty); 8006 } 8007 } 8008 8009 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 8010 int N = pkg.providers.size(); 8011 StringBuilder r = null; 8012 int i; 8013 for (i=0; i<N; i++) { 8014 PackageParser.Provider p = pkg.providers.get(i); 8015 mProviders.removeProvider(p); 8016 if (p.info.authority == null) { 8017 8018 /* There was another ContentProvider with this authority when 8019 * this app was installed so this authority is null, 8020 * Ignore it as we don't have to unregister the provider. 8021 */ 8022 continue; 8023 } 8024 String names[] = p.info.authority.split(";"); 8025 for (int j = 0; j < names.length; j++) { 8026 if (mProvidersByAuthority.get(names[j]) == p) { 8027 mProvidersByAuthority.remove(names[j]); 8028 if (DEBUG_REMOVE) { 8029 if (chatty) 8030 Log.d(TAG, "Unregistered content provider: " + names[j] 8031 + ", className = " + p.info.name + ", isSyncable = " 8032 + p.info.isSyncable); 8033 } 8034 } 8035 } 8036 if (DEBUG_REMOVE && chatty) { 8037 if (r == null) { 8038 r = new StringBuilder(256); 8039 } else { 8040 r.append(' '); 8041 } 8042 r.append(p.info.name); 8043 } 8044 } 8045 if (r != null) { 8046 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 8047 } 8048 8049 N = pkg.services.size(); 8050 r = null; 8051 for (i=0; i<N; i++) { 8052 PackageParser.Service s = pkg.services.get(i); 8053 mServices.removeService(s); 8054 if (chatty) { 8055 if (r == null) { 8056 r = new StringBuilder(256); 8057 } else { 8058 r.append(' '); 8059 } 8060 r.append(s.info.name); 8061 } 8062 } 8063 if (r != null) { 8064 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 8065 } 8066 8067 N = pkg.receivers.size(); 8068 r = null; 8069 for (i=0; i<N; i++) { 8070 PackageParser.Activity a = pkg.receivers.get(i); 8071 mReceivers.removeActivity(a, "receiver"); 8072 if (DEBUG_REMOVE && chatty) { 8073 if (r == null) { 8074 r = new StringBuilder(256); 8075 } else { 8076 r.append(' '); 8077 } 8078 r.append(a.info.name); 8079 } 8080 } 8081 if (r != null) { 8082 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 8083 } 8084 8085 N = pkg.activities.size(); 8086 r = null; 8087 for (i=0; i<N; i++) { 8088 PackageParser.Activity a = pkg.activities.get(i); 8089 mActivities.removeActivity(a, "activity"); 8090 if (DEBUG_REMOVE && chatty) { 8091 if (r == null) { 8092 r = new StringBuilder(256); 8093 } else { 8094 r.append(' '); 8095 } 8096 r.append(a.info.name); 8097 } 8098 } 8099 if (r != null) { 8100 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 8101 } 8102 8103 N = pkg.permissions.size(); 8104 r = null; 8105 for (i=0; i<N; i++) { 8106 PackageParser.Permission p = pkg.permissions.get(i); 8107 BasePermission bp = mSettings.mPermissions.get(p.info.name); 8108 if (bp == null) { 8109 bp = mSettings.mPermissionTrees.get(p.info.name); 8110 } 8111 if (bp != null && bp.perm == p) { 8112 bp.perm = null; 8113 if (DEBUG_REMOVE && chatty) { 8114 if (r == null) { 8115 r = new StringBuilder(256); 8116 } else { 8117 r.append(' '); 8118 } 8119 r.append(p.info.name); 8120 } 8121 } 8122 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8123 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 8124 if (appOpPerms != null) { 8125 appOpPerms.remove(pkg.packageName); 8126 } 8127 } 8128 } 8129 if (r != null) { 8130 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8131 } 8132 8133 N = pkg.requestedPermissions.size(); 8134 r = null; 8135 for (i=0; i<N; i++) { 8136 String perm = pkg.requestedPermissions.get(i); 8137 BasePermission bp = mSettings.mPermissions.get(perm); 8138 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8139 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 8140 if (appOpPerms != null) { 8141 appOpPerms.remove(pkg.packageName); 8142 if (appOpPerms.isEmpty()) { 8143 mAppOpPermissionPackages.remove(perm); 8144 } 8145 } 8146 } 8147 } 8148 if (r != null) { 8149 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8150 } 8151 8152 N = pkg.instrumentation.size(); 8153 r = null; 8154 for (i=0; i<N; i++) { 8155 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8156 mInstrumentation.remove(a.getComponentName()); 8157 if (DEBUG_REMOVE && chatty) { 8158 if (r == null) { 8159 r = new StringBuilder(256); 8160 } else { 8161 r.append(' '); 8162 } 8163 r.append(a.info.name); 8164 } 8165 } 8166 if (r != null) { 8167 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 8168 } 8169 8170 r = null; 8171 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8172 // Only system apps can hold shared libraries. 8173 if (pkg.libraryNames != null) { 8174 for (i=0; i<pkg.libraryNames.size(); i++) { 8175 String name = pkg.libraryNames.get(i); 8176 SharedLibraryEntry cur = mSharedLibraries.get(name); 8177 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 8178 mSharedLibraries.remove(name); 8179 if (DEBUG_REMOVE && chatty) { 8180 if (r == null) { 8181 r = new StringBuilder(256); 8182 } else { 8183 r.append(' '); 8184 } 8185 r.append(name); 8186 } 8187 } 8188 } 8189 } 8190 } 8191 if (r != null) { 8192 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 8193 } 8194 } 8195 8196 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 8197 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 8198 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 8199 return true; 8200 } 8201 } 8202 return false; 8203 } 8204 8205 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 8206 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 8207 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 8208 8209 private void updatePermissionsLPw(String changingPkg, 8210 PackageParser.Package pkgInfo, int flags) { 8211 // Make sure there are no dangling permission trees. 8212 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 8213 while (it.hasNext()) { 8214 final BasePermission bp = it.next(); 8215 if (bp.packageSetting == null) { 8216 // We may not yet have parsed the package, so just see if 8217 // we still know about its settings. 8218 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8219 } 8220 if (bp.packageSetting == null) { 8221 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 8222 + " from package " + bp.sourcePackage); 8223 it.remove(); 8224 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8225 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8226 Slog.i(TAG, "Removing old permission tree: " + bp.name 8227 + " from package " + bp.sourcePackage); 8228 flags |= UPDATE_PERMISSIONS_ALL; 8229 it.remove(); 8230 } 8231 } 8232 } 8233 8234 // Make sure all dynamic permissions have been assigned to a package, 8235 // and make sure there are no dangling permissions. 8236 it = mSettings.mPermissions.values().iterator(); 8237 while (it.hasNext()) { 8238 final BasePermission bp = it.next(); 8239 if (bp.type == BasePermission.TYPE_DYNAMIC) { 8240 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 8241 + bp.name + " pkg=" + bp.sourcePackage 8242 + " info=" + bp.pendingInfo); 8243 if (bp.packageSetting == null && bp.pendingInfo != null) { 8244 final BasePermission tree = findPermissionTreeLP(bp.name); 8245 if (tree != null && tree.perm != null) { 8246 bp.packageSetting = tree.packageSetting; 8247 bp.perm = new PackageParser.Permission(tree.perm.owner, 8248 new PermissionInfo(bp.pendingInfo)); 8249 bp.perm.info.packageName = tree.perm.info.packageName; 8250 bp.perm.info.name = bp.name; 8251 bp.uid = tree.uid; 8252 } 8253 } 8254 } 8255 if (bp.packageSetting == null) { 8256 // We may not yet have parsed the package, so just see if 8257 // we still know about its settings. 8258 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8259 } 8260 if (bp.packageSetting == null) { 8261 Slog.w(TAG, "Removing dangling permission: " + bp.name 8262 + " from package " + bp.sourcePackage); 8263 it.remove(); 8264 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8265 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8266 Slog.i(TAG, "Removing old permission: " + bp.name 8267 + " from package " + bp.sourcePackage); 8268 flags |= UPDATE_PERMISSIONS_ALL; 8269 it.remove(); 8270 } 8271 } 8272 } 8273 8274 // Now update the permissions for all packages, in particular 8275 // replace the granted permissions of the system packages. 8276 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 8277 for (PackageParser.Package pkg : mPackages.values()) { 8278 if (pkg != pkgInfo) { 8279 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 8280 changingPkg); 8281 } 8282 } 8283 } 8284 8285 if (pkgInfo != null) { 8286 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 8287 } 8288 } 8289 8290 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 8291 String packageOfInterest) { 8292 // IMPORTANT: There are two types of permissions: install and runtime. 8293 // Install time permissions are granted when the app is installed to 8294 // all device users and users added in the future. Runtime permissions 8295 // are granted at runtime explicitly to specific users. Normal and signature 8296 // protected permissions are install time permissions. Dangerous permissions 8297 // are install permissions if the app's target SDK is Lollipop MR1 or older, 8298 // otherwise they are runtime permissions. This function does not manage 8299 // runtime permissions except for the case an app targeting Lollipop MR1 8300 // being upgraded to target a newer SDK, in which case dangerous permissions 8301 // are transformed from install time to runtime ones. 8302 8303 final PackageSetting ps = (PackageSetting) pkg.mExtras; 8304 if (ps == null) { 8305 return; 8306 } 8307 8308 PermissionsState permissionsState = ps.getPermissionsState(); 8309 PermissionsState origPermissions = permissionsState; 8310 8311 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 8312 8313 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 8314 8315 boolean changedInstallPermission = false; 8316 8317 if (replace) { 8318 ps.installPermissionsFixed = false; 8319 if (!ps.isSharedUser()) { 8320 origPermissions = new PermissionsState(permissionsState); 8321 permissionsState.reset(); 8322 } 8323 } 8324 8325 permissionsState.setGlobalGids(mGlobalGids); 8326 8327 final int N = pkg.requestedPermissions.size(); 8328 for (int i=0; i<N; i++) { 8329 final String name = pkg.requestedPermissions.get(i); 8330 final BasePermission bp = mSettings.mPermissions.get(name); 8331 8332 if (DEBUG_INSTALL) { 8333 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 8334 } 8335 8336 if (bp == null || bp.packageSetting == null) { 8337 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8338 Slog.w(TAG, "Unknown permission " + name 8339 + " in package " + pkg.packageName); 8340 } 8341 continue; 8342 } 8343 8344 final String perm = bp.name; 8345 boolean allowedSig = false; 8346 int grant = GRANT_DENIED; 8347 8348 // Keep track of app op permissions. 8349 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8350 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 8351 if (pkgs == null) { 8352 pkgs = new ArraySet<>(); 8353 mAppOpPermissionPackages.put(bp.name, pkgs); 8354 } 8355 pkgs.add(pkg.packageName); 8356 } 8357 8358 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 8359 switch (level) { 8360 case PermissionInfo.PROTECTION_NORMAL: { 8361 // For all apps normal permissions are install time ones. 8362 grant = GRANT_INSTALL; 8363 } break; 8364 8365 case PermissionInfo.PROTECTION_DANGEROUS: { 8366 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 8367 // For legacy apps dangerous permissions are install time ones. 8368 grant = GRANT_INSTALL_LEGACY; 8369 } else if (origPermissions.hasInstallPermission(bp.name)) { 8370 // For legacy apps that became modern, install becomes runtime. 8371 grant = GRANT_UPGRADE; 8372 } else { 8373 // For modern apps keep runtime permissions unchanged. 8374 grant = GRANT_RUNTIME; 8375 } 8376 } break; 8377 8378 case PermissionInfo.PROTECTION_SIGNATURE: { 8379 // For all apps signature permissions are install time ones. 8380 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 8381 if (allowedSig) { 8382 grant = GRANT_INSTALL; 8383 } 8384 } break; 8385 } 8386 8387 if (DEBUG_INSTALL) { 8388 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 8389 } 8390 8391 if (grant != GRANT_DENIED) { 8392 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 8393 // If this is an existing, non-system package, then 8394 // we can't add any new permissions to it. 8395 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 8396 // Except... if this is a permission that was added 8397 // to the platform (note: need to only do this when 8398 // updating the platform). 8399 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 8400 grant = GRANT_DENIED; 8401 } 8402 } 8403 } 8404 8405 switch (grant) { 8406 case GRANT_INSTALL: { 8407 // Revoke this as runtime permission to handle the case of 8408 // a runtime permission being downgraded to an install one. 8409 for (int userId : UserManagerService.getInstance().getUserIds()) { 8410 if (origPermissions.getRuntimePermissionState( 8411 bp.name, userId) != null) { 8412 // Revoke the runtime permission and clear the flags. 8413 origPermissions.revokeRuntimePermission(bp, userId); 8414 origPermissions.updatePermissionFlags(bp, userId, 8415 PackageManager.MASK_PERMISSION_FLAGS, 0); 8416 // If we revoked a permission permission, we have to write. 8417 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8418 changedRuntimePermissionUserIds, userId); 8419 } 8420 } 8421 // Grant an install permission. 8422 if (permissionsState.grantInstallPermission(bp) != 8423 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8424 changedInstallPermission = true; 8425 } 8426 } break; 8427 8428 case GRANT_INSTALL_LEGACY: { 8429 // Grant an install permission. 8430 if (permissionsState.grantInstallPermission(bp) != 8431 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8432 changedInstallPermission = true; 8433 } 8434 } break; 8435 8436 case GRANT_RUNTIME: { 8437 // Grant previously granted runtime permissions. 8438 for (int userId : UserManagerService.getInstance().getUserIds()) { 8439 PermissionState permissionState = origPermissions 8440 .getRuntimePermissionState(bp.name, userId); 8441 final int flags = permissionState != null 8442 ? permissionState.getFlags() : 0; 8443 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8444 if (permissionsState.grantRuntimePermission(bp, userId) == 8445 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8446 // If we cannot put the permission as it was, we have to write. 8447 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8448 changedRuntimePermissionUserIds, userId); 8449 } 8450 } 8451 // Propagate the permission flags. 8452 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 8453 } 8454 } break; 8455 8456 case GRANT_UPGRADE: { 8457 // Grant runtime permissions for a previously held install permission. 8458 PermissionState permissionState = origPermissions 8459 .getInstallPermissionState(bp.name); 8460 final int flags = permissionState != null ? permissionState.getFlags() : 0; 8461 8462 if (origPermissions.revokeInstallPermission(bp) 8463 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 8464 // We will be transferring the permission flags, so clear them. 8465 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 8466 PackageManager.MASK_PERMISSION_FLAGS, 0); 8467 changedInstallPermission = true; 8468 } 8469 8470 // If the permission is not to be promoted to runtime we ignore it and 8471 // also its other flags as they are not applicable to install permissions. 8472 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 8473 for (int userId : currentUserIds) { 8474 if (permissionsState.grantRuntimePermission(bp, userId) != 8475 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8476 // Transfer the permission flags. 8477 permissionsState.updatePermissionFlags(bp, userId, 8478 flags, flags); 8479 // If we granted the permission, we have to write. 8480 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8481 changedRuntimePermissionUserIds, userId); 8482 } 8483 } 8484 } 8485 } break; 8486 8487 default: { 8488 if (packageOfInterest == null 8489 || packageOfInterest.equals(pkg.packageName)) { 8490 Slog.w(TAG, "Not granting permission " + perm 8491 + " to package " + pkg.packageName 8492 + " because it was previously installed without"); 8493 } 8494 } break; 8495 } 8496 } else { 8497 if (permissionsState.revokeInstallPermission(bp) != 8498 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8499 // Also drop the permission flags. 8500 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 8501 PackageManager.MASK_PERMISSION_FLAGS, 0); 8502 changedInstallPermission = true; 8503 Slog.i(TAG, "Un-granting permission " + perm 8504 + " from package " + pkg.packageName 8505 + " (protectionLevel=" + bp.protectionLevel 8506 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8507 + ")"); 8508 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 8509 // Don't print warning for app op permissions, since it is fine for them 8510 // not to be granted, there is a UI for the user to decide. 8511 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8512 Slog.w(TAG, "Not granting permission " + perm 8513 + " to package " + pkg.packageName 8514 + " (protectionLevel=" + bp.protectionLevel 8515 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8516 + ")"); 8517 } 8518 } 8519 } 8520 } 8521 8522 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 8523 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 8524 // This is the first that we have heard about this package, so the 8525 // permissions we have now selected are fixed until explicitly 8526 // changed. 8527 ps.installPermissionsFixed = true; 8528 } 8529 8530 // Persist the runtime permissions state for users with changes. 8531 for (int userId : changedRuntimePermissionUserIds) { 8532 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 8533 } 8534 } 8535 8536 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8537 boolean allowed = false; 8538 final int NP = PackageParser.NEW_PERMISSIONS.length; 8539 for (int ip=0; ip<NP; ip++) { 8540 final PackageParser.NewPermissionInfo npi 8541 = PackageParser.NEW_PERMISSIONS[ip]; 8542 if (npi.name.equals(perm) 8543 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8544 allowed = true; 8545 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8546 + pkg.packageName); 8547 break; 8548 } 8549 } 8550 return allowed; 8551 } 8552 8553 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 8554 BasePermission bp, PermissionsState origPermissions) { 8555 boolean allowed; 8556 allowed = (compareSignatures( 8557 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 8558 == PackageManager.SIGNATURE_MATCH) 8559 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 8560 == PackageManager.SIGNATURE_MATCH); 8561 if (!allowed && (bp.protectionLevel 8562 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 8563 if (isSystemApp(pkg)) { 8564 // For updated system applications, a system permission 8565 // is granted only if it had been defined by the original application. 8566 if (pkg.isUpdatedSystemApp()) { 8567 final PackageSetting sysPs = mSettings 8568 .getDisabledSystemPkgLPr(pkg.packageName); 8569 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 8570 // If the original was granted this permission, we take 8571 // that grant decision as read and propagate it to the 8572 // update. 8573 if (sysPs.isPrivileged()) { 8574 allowed = true; 8575 } 8576 } else { 8577 // The system apk may have been updated with an older 8578 // version of the one on the data partition, but which 8579 // granted a new system permission that it didn't have 8580 // before. In this case we do want to allow the app to 8581 // now get the new permission if the ancestral apk is 8582 // privileged to get it. 8583 if (sysPs.pkg != null && sysPs.isPrivileged()) { 8584 for (int j=0; 8585 j<sysPs.pkg.requestedPermissions.size(); j++) { 8586 if (perm.equals( 8587 sysPs.pkg.requestedPermissions.get(j))) { 8588 allowed = true; 8589 break; 8590 } 8591 } 8592 } 8593 } 8594 } else { 8595 allowed = isPrivilegedApp(pkg); 8596 } 8597 } 8598 } 8599 if (!allowed) { 8600 if (!allowed && (bp.protectionLevel 8601 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 8602 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.MNC) { 8603 // If this was a previously normal/dangerous permission that got moved 8604 // to a system permission as part of the runtime permission redesign, then 8605 // we still want to blindly grant it to old apps. 8606 allowed = true; 8607 } 8608 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 8609 && pkg.packageName.equals(mRequiredInstallerPackage)) { 8610 // If this permission is to be granted to the system installer and 8611 // this app is an installer, then it gets the permission. 8612 allowed = true; 8613 } 8614 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 8615 && pkg.packageName.equals(mRequiredVerifierPackage)) { 8616 // If this permission is to be granted to the system verifier and 8617 // this app is a verifier, then it gets the permission. 8618 allowed = true; 8619 } 8620 if (!allowed && (bp.protectionLevel 8621 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 8622 && isSystemApp(pkg)) { 8623 // Any pre-installed system app is allowed to get this permission. 8624 allowed = true; 8625 } 8626 if (!allowed && (bp.protectionLevel 8627 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 8628 // For development permissions, a development permission 8629 // is granted only if it was already granted. 8630 allowed = origPermissions.hasInstallPermission(perm); 8631 } 8632 } 8633 return allowed; 8634 } 8635 8636 final class ActivityIntentResolver 8637 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 8638 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8639 boolean defaultOnly, int userId) { 8640 if (!sUserManager.exists(userId)) return null; 8641 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8642 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8643 } 8644 8645 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8646 int userId) { 8647 if (!sUserManager.exists(userId)) return null; 8648 mFlags = flags; 8649 return super.queryIntent(intent, resolvedType, 8650 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8651 } 8652 8653 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8654 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 8655 if (!sUserManager.exists(userId)) return null; 8656 if (packageActivities == null) { 8657 return null; 8658 } 8659 mFlags = flags; 8660 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8661 final int N = packageActivities.size(); 8662 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 8663 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 8664 8665 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 8666 for (int i = 0; i < N; ++i) { 8667 intentFilters = packageActivities.get(i).intents; 8668 if (intentFilters != null && intentFilters.size() > 0) { 8669 PackageParser.ActivityIntentInfo[] array = 8670 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 8671 intentFilters.toArray(array); 8672 listCut.add(array); 8673 } 8674 } 8675 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8676 } 8677 8678 public final void addActivity(PackageParser.Activity a, String type) { 8679 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 8680 mActivities.put(a.getComponentName(), a); 8681 if (DEBUG_SHOW_INFO) 8682 Log.v( 8683 TAG, " " + type + " " + 8684 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 8685 if (DEBUG_SHOW_INFO) 8686 Log.v(TAG, " Class=" + a.info.name); 8687 final int NI = a.intents.size(); 8688 for (int j=0; j<NI; j++) { 8689 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8690 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 8691 intent.setPriority(0); 8692 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 8693 + a.className + " with priority > 0, forcing to 0"); 8694 } 8695 if (DEBUG_SHOW_INFO) { 8696 Log.v(TAG, " IntentFilter:"); 8697 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8698 } 8699 if (!intent.debugCheck()) { 8700 Log.w(TAG, "==> For Activity " + a.info.name); 8701 } 8702 addFilter(intent); 8703 } 8704 } 8705 8706 public final void removeActivity(PackageParser.Activity a, String type) { 8707 mActivities.remove(a.getComponentName()); 8708 if (DEBUG_SHOW_INFO) { 8709 Log.v(TAG, " " + type + " " 8710 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 8711 : a.info.name) + ":"); 8712 Log.v(TAG, " Class=" + a.info.name); 8713 } 8714 final int NI = a.intents.size(); 8715 for (int j=0; j<NI; j++) { 8716 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8717 if (DEBUG_SHOW_INFO) { 8718 Log.v(TAG, " IntentFilter:"); 8719 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8720 } 8721 removeFilter(intent); 8722 } 8723 } 8724 8725 @Override 8726 protected boolean allowFilterResult( 8727 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 8728 ActivityInfo filterAi = filter.activity.info; 8729 for (int i=dest.size()-1; i>=0; i--) { 8730 ActivityInfo destAi = dest.get(i).activityInfo; 8731 if (destAi.name == filterAi.name 8732 && destAi.packageName == filterAi.packageName) { 8733 return false; 8734 } 8735 } 8736 return true; 8737 } 8738 8739 @Override 8740 protected ActivityIntentInfo[] newArray(int size) { 8741 return new ActivityIntentInfo[size]; 8742 } 8743 8744 @Override 8745 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 8746 if (!sUserManager.exists(userId)) return true; 8747 PackageParser.Package p = filter.activity.owner; 8748 if (p != null) { 8749 PackageSetting ps = (PackageSetting)p.mExtras; 8750 if (ps != null) { 8751 // System apps are never considered stopped for purposes of 8752 // filtering, because there may be no way for the user to 8753 // actually re-launch them. 8754 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 8755 && ps.getStopped(userId); 8756 } 8757 } 8758 return false; 8759 } 8760 8761 @Override 8762 protected boolean isPackageForFilter(String packageName, 8763 PackageParser.ActivityIntentInfo info) { 8764 return packageName.equals(info.activity.owner.packageName); 8765 } 8766 8767 @Override 8768 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 8769 int match, int userId) { 8770 if (!sUserManager.exists(userId)) return null; 8771 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 8772 return null; 8773 } 8774 final PackageParser.Activity activity = info.activity; 8775 if (mSafeMode && (activity.info.applicationInfo.flags 8776 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8777 return null; 8778 } 8779 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 8780 if (ps == null) { 8781 return null; 8782 } 8783 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 8784 ps.readUserState(userId), userId); 8785 if (ai == null) { 8786 return null; 8787 } 8788 final ResolveInfo res = new ResolveInfo(); 8789 res.activityInfo = ai; 8790 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8791 res.filter = info; 8792 } 8793 if (info != null) { 8794 res.handleAllWebDataURI = info.handleAllWebDataURI(); 8795 } 8796 res.priority = info.getPriority(); 8797 res.preferredOrder = activity.owner.mPreferredOrder; 8798 //System.out.println("Result: " + res.activityInfo.className + 8799 // " = " + res.priority); 8800 res.match = match; 8801 res.isDefault = info.hasDefault; 8802 res.labelRes = info.labelRes; 8803 res.nonLocalizedLabel = info.nonLocalizedLabel; 8804 if (userNeedsBadging(userId)) { 8805 res.noResourceId = true; 8806 } else { 8807 res.icon = info.icon; 8808 } 8809 res.iconResourceId = info.icon; 8810 res.system = res.activityInfo.applicationInfo.isSystemApp(); 8811 return res; 8812 } 8813 8814 @Override 8815 protected void sortResults(List<ResolveInfo> results) { 8816 Collections.sort(results, mResolvePrioritySorter); 8817 } 8818 8819 @Override 8820 protected void dumpFilter(PrintWriter out, String prefix, 8821 PackageParser.ActivityIntentInfo filter) { 8822 out.print(prefix); out.print( 8823 Integer.toHexString(System.identityHashCode(filter.activity))); 8824 out.print(' '); 8825 filter.activity.printComponentShortName(out); 8826 out.print(" filter "); 8827 out.println(Integer.toHexString(System.identityHashCode(filter))); 8828 } 8829 8830 @Override 8831 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 8832 return filter.activity; 8833 } 8834 8835 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8836 PackageParser.Activity activity = (PackageParser.Activity)label; 8837 out.print(prefix); out.print( 8838 Integer.toHexString(System.identityHashCode(activity))); 8839 out.print(' '); 8840 activity.printComponentShortName(out); 8841 if (count > 1) { 8842 out.print(" ("); out.print(count); out.print(" filters)"); 8843 } 8844 out.println(); 8845 } 8846 8847// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8848// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8849// final List<ResolveInfo> retList = Lists.newArrayList(); 8850// while (i.hasNext()) { 8851// final ResolveInfo resolveInfo = i.next(); 8852// if (isEnabledLP(resolveInfo.activityInfo)) { 8853// retList.add(resolveInfo); 8854// } 8855// } 8856// return retList; 8857// } 8858 8859 // Keys are String (activity class name), values are Activity. 8860 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 8861 = new ArrayMap<ComponentName, PackageParser.Activity>(); 8862 private int mFlags; 8863 } 8864 8865 private final class ServiceIntentResolver 8866 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 8867 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8868 boolean defaultOnly, int userId) { 8869 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8870 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8871 } 8872 8873 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8874 int userId) { 8875 if (!sUserManager.exists(userId)) return null; 8876 mFlags = flags; 8877 return super.queryIntent(intent, resolvedType, 8878 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8879 } 8880 8881 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8882 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 8883 if (!sUserManager.exists(userId)) return null; 8884 if (packageServices == null) { 8885 return null; 8886 } 8887 mFlags = flags; 8888 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8889 final int N = packageServices.size(); 8890 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 8891 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 8892 8893 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 8894 for (int i = 0; i < N; ++i) { 8895 intentFilters = packageServices.get(i).intents; 8896 if (intentFilters != null && intentFilters.size() > 0) { 8897 PackageParser.ServiceIntentInfo[] array = 8898 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 8899 intentFilters.toArray(array); 8900 listCut.add(array); 8901 } 8902 } 8903 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8904 } 8905 8906 public final void addService(PackageParser.Service s) { 8907 mServices.put(s.getComponentName(), s); 8908 if (DEBUG_SHOW_INFO) { 8909 Log.v(TAG, " " 8910 + (s.info.nonLocalizedLabel != null 8911 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8912 Log.v(TAG, " Class=" + s.info.name); 8913 } 8914 final int NI = s.intents.size(); 8915 int j; 8916 for (j=0; j<NI; j++) { 8917 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8918 if (DEBUG_SHOW_INFO) { 8919 Log.v(TAG, " IntentFilter:"); 8920 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8921 } 8922 if (!intent.debugCheck()) { 8923 Log.w(TAG, "==> For Service " + s.info.name); 8924 } 8925 addFilter(intent); 8926 } 8927 } 8928 8929 public final void removeService(PackageParser.Service s) { 8930 mServices.remove(s.getComponentName()); 8931 if (DEBUG_SHOW_INFO) { 8932 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 8933 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8934 Log.v(TAG, " Class=" + s.info.name); 8935 } 8936 final int NI = s.intents.size(); 8937 int j; 8938 for (j=0; j<NI; j++) { 8939 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8940 if (DEBUG_SHOW_INFO) { 8941 Log.v(TAG, " IntentFilter:"); 8942 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8943 } 8944 removeFilter(intent); 8945 } 8946 } 8947 8948 @Override 8949 protected boolean allowFilterResult( 8950 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 8951 ServiceInfo filterSi = filter.service.info; 8952 for (int i=dest.size()-1; i>=0; i--) { 8953 ServiceInfo destAi = dest.get(i).serviceInfo; 8954 if (destAi.name == filterSi.name 8955 && destAi.packageName == filterSi.packageName) { 8956 return false; 8957 } 8958 } 8959 return true; 8960 } 8961 8962 @Override 8963 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 8964 return new PackageParser.ServiceIntentInfo[size]; 8965 } 8966 8967 @Override 8968 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 8969 if (!sUserManager.exists(userId)) return true; 8970 PackageParser.Package p = filter.service.owner; 8971 if (p != null) { 8972 PackageSetting ps = (PackageSetting)p.mExtras; 8973 if (ps != null) { 8974 // System apps are never considered stopped for purposes of 8975 // filtering, because there may be no way for the user to 8976 // actually re-launch them. 8977 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8978 && ps.getStopped(userId); 8979 } 8980 } 8981 return false; 8982 } 8983 8984 @Override 8985 protected boolean isPackageForFilter(String packageName, 8986 PackageParser.ServiceIntentInfo info) { 8987 return packageName.equals(info.service.owner.packageName); 8988 } 8989 8990 @Override 8991 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 8992 int match, int userId) { 8993 if (!sUserManager.exists(userId)) return null; 8994 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 8995 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 8996 return null; 8997 } 8998 final PackageParser.Service service = info.service; 8999 if (mSafeMode && (service.info.applicationInfo.flags 9000 &ApplicationInfo.FLAG_SYSTEM) == 0) { 9001 return null; 9002 } 9003 PackageSetting ps = (PackageSetting) service.owner.mExtras; 9004 if (ps == null) { 9005 return null; 9006 } 9007 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 9008 ps.readUserState(userId), userId); 9009 if (si == null) { 9010 return null; 9011 } 9012 final ResolveInfo res = new ResolveInfo(); 9013 res.serviceInfo = si; 9014 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9015 res.filter = filter; 9016 } 9017 res.priority = info.getPriority(); 9018 res.preferredOrder = service.owner.mPreferredOrder; 9019 res.match = match; 9020 res.isDefault = info.hasDefault; 9021 res.labelRes = info.labelRes; 9022 res.nonLocalizedLabel = info.nonLocalizedLabel; 9023 res.icon = info.icon; 9024 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 9025 return res; 9026 } 9027 9028 @Override 9029 protected void sortResults(List<ResolveInfo> results) { 9030 Collections.sort(results, mResolvePrioritySorter); 9031 } 9032 9033 @Override 9034 protected void dumpFilter(PrintWriter out, String prefix, 9035 PackageParser.ServiceIntentInfo filter) { 9036 out.print(prefix); out.print( 9037 Integer.toHexString(System.identityHashCode(filter.service))); 9038 out.print(' '); 9039 filter.service.printComponentShortName(out); 9040 out.print(" filter "); 9041 out.println(Integer.toHexString(System.identityHashCode(filter))); 9042 } 9043 9044 @Override 9045 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 9046 return filter.service; 9047 } 9048 9049 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9050 PackageParser.Service service = (PackageParser.Service)label; 9051 out.print(prefix); out.print( 9052 Integer.toHexString(System.identityHashCode(service))); 9053 out.print(' '); 9054 service.printComponentShortName(out); 9055 if (count > 1) { 9056 out.print(" ("); out.print(count); out.print(" filters)"); 9057 } 9058 out.println(); 9059 } 9060 9061// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9062// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9063// final List<ResolveInfo> retList = Lists.newArrayList(); 9064// while (i.hasNext()) { 9065// final ResolveInfo resolveInfo = (ResolveInfo) i; 9066// if (isEnabledLP(resolveInfo.serviceInfo)) { 9067// retList.add(resolveInfo); 9068// } 9069// } 9070// return retList; 9071// } 9072 9073 // Keys are String (activity class name), values are Activity. 9074 private final ArrayMap<ComponentName, PackageParser.Service> mServices 9075 = new ArrayMap<ComponentName, PackageParser.Service>(); 9076 private int mFlags; 9077 }; 9078 9079 private final class ProviderIntentResolver 9080 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 9081 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9082 boolean defaultOnly, int userId) { 9083 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9084 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9085 } 9086 9087 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9088 int userId) { 9089 if (!sUserManager.exists(userId)) 9090 return null; 9091 mFlags = flags; 9092 return super.queryIntent(intent, resolvedType, 9093 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9094 } 9095 9096 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9097 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 9098 if (!sUserManager.exists(userId)) 9099 return null; 9100 if (packageProviders == null) { 9101 return null; 9102 } 9103 mFlags = flags; 9104 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 9105 final int N = packageProviders.size(); 9106 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 9107 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 9108 9109 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 9110 for (int i = 0; i < N; ++i) { 9111 intentFilters = packageProviders.get(i).intents; 9112 if (intentFilters != null && intentFilters.size() > 0) { 9113 PackageParser.ProviderIntentInfo[] array = 9114 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 9115 intentFilters.toArray(array); 9116 listCut.add(array); 9117 } 9118 } 9119 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9120 } 9121 9122 public final void addProvider(PackageParser.Provider p) { 9123 if (mProviders.containsKey(p.getComponentName())) { 9124 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 9125 return; 9126 } 9127 9128 mProviders.put(p.getComponentName(), p); 9129 if (DEBUG_SHOW_INFO) { 9130 Log.v(TAG, " " 9131 + (p.info.nonLocalizedLabel != null 9132 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9133 Log.v(TAG, " Class=" + p.info.name); 9134 } 9135 final int NI = p.intents.size(); 9136 int j; 9137 for (j = 0; j < NI; j++) { 9138 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9139 if (DEBUG_SHOW_INFO) { 9140 Log.v(TAG, " IntentFilter:"); 9141 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9142 } 9143 if (!intent.debugCheck()) { 9144 Log.w(TAG, "==> For Provider " + p.info.name); 9145 } 9146 addFilter(intent); 9147 } 9148 } 9149 9150 public final void removeProvider(PackageParser.Provider p) { 9151 mProviders.remove(p.getComponentName()); 9152 if (DEBUG_SHOW_INFO) { 9153 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 9154 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9155 Log.v(TAG, " Class=" + p.info.name); 9156 } 9157 final int NI = p.intents.size(); 9158 int j; 9159 for (j = 0; j < NI; j++) { 9160 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9161 if (DEBUG_SHOW_INFO) { 9162 Log.v(TAG, " IntentFilter:"); 9163 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9164 } 9165 removeFilter(intent); 9166 } 9167 } 9168 9169 @Override 9170 protected boolean allowFilterResult( 9171 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 9172 ProviderInfo filterPi = filter.provider.info; 9173 for (int i = dest.size() - 1; i >= 0; i--) { 9174 ProviderInfo destPi = dest.get(i).providerInfo; 9175 if (destPi.name == filterPi.name 9176 && destPi.packageName == filterPi.packageName) { 9177 return false; 9178 } 9179 } 9180 return true; 9181 } 9182 9183 @Override 9184 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 9185 return new PackageParser.ProviderIntentInfo[size]; 9186 } 9187 9188 @Override 9189 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 9190 if (!sUserManager.exists(userId)) 9191 return true; 9192 PackageParser.Package p = filter.provider.owner; 9193 if (p != null) { 9194 PackageSetting ps = (PackageSetting) p.mExtras; 9195 if (ps != null) { 9196 // System apps are never considered stopped for purposes of 9197 // filtering, because there may be no way for the user to 9198 // actually re-launch them. 9199 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9200 && ps.getStopped(userId); 9201 } 9202 } 9203 return false; 9204 } 9205 9206 @Override 9207 protected boolean isPackageForFilter(String packageName, 9208 PackageParser.ProviderIntentInfo info) { 9209 return packageName.equals(info.provider.owner.packageName); 9210 } 9211 9212 @Override 9213 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 9214 int match, int userId) { 9215 if (!sUserManager.exists(userId)) 9216 return null; 9217 final PackageParser.ProviderIntentInfo info = filter; 9218 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 9219 return null; 9220 } 9221 final PackageParser.Provider provider = info.provider; 9222 if (mSafeMode && (provider.info.applicationInfo.flags 9223 & ApplicationInfo.FLAG_SYSTEM) == 0) { 9224 return null; 9225 } 9226 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 9227 if (ps == null) { 9228 return null; 9229 } 9230 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 9231 ps.readUserState(userId), userId); 9232 if (pi == null) { 9233 return null; 9234 } 9235 final ResolveInfo res = new ResolveInfo(); 9236 res.providerInfo = pi; 9237 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 9238 res.filter = filter; 9239 } 9240 res.priority = info.getPriority(); 9241 res.preferredOrder = provider.owner.mPreferredOrder; 9242 res.match = match; 9243 res.isDefault = info.hasDefault; 9244 res.labelRes = info.labelRes; 9245 res.nonLocalizedLabel = info.nonLocalizedLabel; 9246 res.icon = info.icon; 9247 res.system = res.providerInfo.applicationInfo.isSystemApp(); 9248 return res; 9249 } 9250 9251 @Override 9252 protected void sortResults(List<ResolveInfo> results) { 9253 Collections.sort(results, mResolvePrioritySorter); 9254 } 9255 9256 @Override 9257 protected void dumpFilter(PrintWriter out, String prefix, 9258 PackageParser.ProviderIntentInfo filter) { 9259 out.print(prefix); 9260 out.print( 9261 Integer.toHexString(System.identityHashCode(filter.provider))); 9262 out.print(' '); 9263 filter.provider.printComponentShortName(out); 9264 out.print(" filter "); 9265 out.println(Integer.toHexString(System.identityHashCode(filter))); 9266 } 9267 9268 @Override 9269 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 9270 return filter.provider; 9271 } 9272 9273 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9274 PackageParser.Provider provider = (PackageParser.Provider)label; 9275 out.print(prefix); out.print( 9276 Integer.toHexString(System.identityHashCode(provider))); 9277 out.print(' '); 9278 provider.printComponentShortName(out); 9279 if (count > 1) { 9280 out.print(" ("); out.print(count); out.print(" filters)"); 9281 } 9282 out.println(); 9283 } 9284 9285 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 9286 = new ArrayMap<ComponentName, PackageParser.Provider>(); 9287 private int mFlags; 9288 }; 9289 9290 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 9291 new Comparator<ResolveInfo>() { 9292 public int compare(ResolveInfo r1, ResolveInfo r2) { 9293 int v1 = r1.priority; 9294 int v2 = r2.priority; 9295 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 9296 if (v1 != v2) { 9297 return (v1 > v2) ? -1 : 1; 9298 } 9299 v1 = r1.preferredOrder; 9300 v2 = r2.preferredOrder; 9301 if (v1 != v2) { 9302 return (v1 > v2) ? -1 : 1; 9303 } 9304 if (r1.isDefault != r2.isDefault) { 9305 return r1.isDefault ? -1 : 1; 9306 } 9307 v1 = r1.match; 9308 v2 = r2.match; 9309 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 9310 if (v1 != v2) { 9311 return (v1 > v2) ? -1 : 1; 9312 } 9313 if (r1.system != r2.system) { 9314 return r1.system ? -1 : 1; 9315 } 9316 return 0; 9317 } 9318 }; 9319 9320 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 9321 new Comparator<ProviderInfo>() { 9322 public int compare(ProviderInfo p1, ProviderInfo p2) { 9323 final int v1 = p1.initOrder; 9324 final int v2 = p2.initOrder; 9325 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 9326 } 9327 }; 9328 9329 final void sendPackageBroadcast(final String action, final String pkg, 9330 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 9331 final int[] userIds) { 9332 mHandler.post(new Runnable() { 9333 @Override 9334 public void run() { 9335 try { 9336 final IActivityManager am = ActivityManagerNative.getDefault(); 9337 if (am == null) return; 9338 final int[] resolvedUserIds; 9339 if (userIds == null) { 9340 resolvedUserIds = am.getRunningUserIds(); 9341 } else { 9342 resolvedUserIds = userIds; 9343 } 9344 for (int id : resolvedUserIds) { 9345 final Intent intent = new Intent(action, 9346 pkg != null ? Uri.fromParts("package", pkg, null) : null); 9347 if (extras != null) { 9348 intent.putExtras(extras); 9349 } 9350 if (targetPkg != null) { 9351 intent.setPackage(targetPkg); 9352 } 9353 // Modify the UID when posting to other users 9354 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 9355 if (uid > 0 && UserHandle.getUserId(uid) != id) { 9356 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 9357 intent.putExtra(Intent.EXTRA_UID, uid); 9358 } 9359 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 9360 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 9361 if (DEBUG_BROADCASTS) { 9362 RuntimeException here = new RuntimeException("here"); 9363 here.fillInStackTrace(); 9364 Slog.d(TAG, "Sending to user " + id + ": " 9365 + intent.toShortString(false, true, false, false) 9366 + " " + intent.getExtras(), here); 9367 } 9368 am.broadcastIntent(null, intent, null, finishedReceiver, 9369 0, null, null, null, android.app.AppOpsManager.OP_NONE, 9370 null, finishedReceiver != null, false, id); 9371 } 9372 } catch (RemoteException ex) { 9373 } 9374 } 9375 }); 9376 } 9377 9378 /** 9379 * Check if the external storage media is available. This is true if there 9380 * is a mounted external storage medium or if the external storage is 9381 * emulated. 9382 */ 9383 private boolean isExternalMediaAvailable() { 9384 return mMediaMounted || Environment.isExternalStorageEmulated(); 9385 } 9386 9387 @Override 9388 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 9389 // writer 9390 synchronized (mPackages) { 9391 if (!isExternalMediaAvailable()) { 9392 // If the external storage is no longer mounted at this point, 9393 // the caller may not have been able to delete all of this 9394 // packages files and can not delete any more. Bail. 9395 return null; 9396 } 9397 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 9398 if (lastPackage != null) { 9399 pkgs.remove(lastPackage); 9400 } 9401 if (pkgs.size() > 0) { 9402 return pkgs.get(0); 9403 } 9404 } 9405 return null; 9406 } 9407 9408 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 9409 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 9410 userId, andCode ? 1 : 0, packageName); 9411 if (mSystemReady) { 9412 msg.sendToTarget(); 9413 } else { 9414 if (mPostSystemReadyMessages == null) { 9415 mPostSystemReadyMessages = new ArrayList<>(); 9416 } 9417 mPostSystemReadyMessages.add(msg); 9418 } 9419 } 9420 9421 void startCleaningPackages() { 9422 // reader 9423 synchronized (mPackages) { 9424 if (!isExternalMediaAvailable()) { 9425 return; 9426 } 9427 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 9428 return; 9429 } 9430 } 9431 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 9432 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 9433 IActivityManager am = ActivityManagerNative.getDefault(); 9434 if (am != null) { 9435 try { 9436 am.startService(null, intent, null, mContext.getOpPackageName(), 9437 UserHandle.USER_OWNER); 9438 } catch (RemoteException e) { 9439 } 9440 } 9441 } 9442 9443 @Override 9444 public void installPackage(String originPath, IPackageInstallObserver2 observer, 9445 int installFlags, String installerPackageName, VerificationParams verificationParams, 9446 String packageAbiOverride) { 9447 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 9448 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 9449 } 9450 9451 @Override 9452 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 9453 int installFlags, String installerPackageName, VerificationParams verificationParams, 9454 String packageAbiOverride, int userId) { 9455 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 9456 9457 final int callingUid = Binder.getCallingUid(); 9458 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 9459 9460 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9461 try { 9462 if (observer != null) { 9463 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 9464 } 9465 } catch (RemoteException re) { 9466 } 9467 return; 9468 } 9469 9470 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 9471 installFlags |= PackageManager.INSTALL_FROM_ADB; 9472 9473 } else { 9474 // Caller holds INSTALL_PACKAGES permission, so we're less strict 9475 // about installerPackageName. 9476 9477 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 9478 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 9479 } 9480 9481 UserHandle user; 9482 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 9483 user = UserHandle.ALL; 9484 } else { 9485 user = new UserHandle(userId); 9486 } 9487 9488 // Only system components can circumvent runtime permissions when installing. 9489 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 9490 && mContext.checkCallingOrSelfPermission(Manifest.permission 9491 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 9492 throw new SecurityException("You need the " 9493 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 9494 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 9495 } 9496 9497 verificationParams.setInstallerUid(callingUid); 9498 9499 final File originFile = new File(originPath); 9500 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 9501 9502 final Message msg = mHandler.obtainMessage(INIT_COPY); 9503 msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName, 9504 null, verificationParams, user, packageAbiOverride, null); 9505 mHandler.sendMessage(msg); 9506 } 9507 9508 void installStage(String packageName, File stagedDir, String stagedCid, 9509 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 9510 String installerPackageName, int installerUid, UserHandle user) { 9511 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 9512 params.referrerUri, installerUid, null); 9513 verifParams.setInstallerUid(installerUid); 9514 9515 final OriginInfo origin; 9516 if (stagedDir != null) { 9517 origin = OriginInfo.fromStagedFile(stagedDir); 9518 } else { 9519 origin = OriginInfo.fromStagedContainer(stagedCid); 9520 } 9521 9522 final Message msg = mHandler.obtainMessage(INIT_COPY); 9523 msg.obj = new InstallParams(origin, null, observer, params.installFlags, 9524 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride, 9525 params.grantedRuntimePermissions); 9526 mHandler.sendMessage(msg); 9527 } 9528 9529 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 9530 Bundle extras = new Bundle(1); 9531 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 9532 9533 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 9534 packageName, extras, null, null, new int[] {userId}); 9535 try { 9536 IActivityManager am = ActivityManagerNative.getDefault(); 9537 final boolean isSystem = 9538 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 9539 if (isSystem && am.isUserRunning(userId, false)) { 9540 // The just-installed/enabled app is bundled on the system, so presumed 9541 // to be able to run automatically without needing an explicit launch. 9542 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 9543 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 9544 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 9545 .setPackage(packageName); 9546 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 9547 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 9548 } 9549 } catch (RemoteException e) { 9550 // shouldn't happen 9551 Slog.w(TAG, "Unable to bootstrap installed package", e); 9552 } 9553 } 9554 9555 @Override 9556 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 9557 int userId) { 9558 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9559 PackageSetting pkgSetting; 9560 final int uid = Binder.getCallingUid(); 9561 enforceCrossUserPermission(uid, userId, true, true, 9562 "setApplicationHiddenSetting for user " + userId); 9563 9564 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 9565 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 9566 return false; 9567 } 9568 9569 long callingId = Binder.clearCallingIdentity(); 9570 try { 9571 boolean sendAdded = false; 9572 boolean sendRemoved = false; 9573 // writer 9574 synchronized (mPackages) { 9575 pkgSetting = mSettings.mPackages.get(packageName); 9576 if (pkgSetting == null) { 9577 return false; 9578 } 9579 if (pkgSetting.getHidden(userId) != hidden) { 9580 pkgSetting.setHidden(hidden, userId); 9581 mSettings.writePackageRestrictionsLPr(userId); 9582 if (hidden) { 9583 sendRemoved = true; 9584 } else { 9585 sendAdded = true; 9586 } 9587 } 9588 } 9589 if (sendAdded) { 9590 sendPackageAddedForUser(packageName, pkgSetting, userId); 9591 return true; 9592 } 9593 if (sendRemoved) { 9594 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 9595 "hiding pkg"); 9596 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 9597 } 9598 } finally { 9599 Binder.restoreCallingIdentity(callingId); 9600 } 9601 return false; 9602 } 9603 9604 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 9605 int userId) { 9606 final PackageRemovedInfo info = new PackageRemovedInfo(); 9607 info.removedPackage = packageName; 9608 info.removedUsers = new int[] {userId}; 9609 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 9610 info.sendBroadcast(false, false, false); 9611 } 9612 9613 /** 9614 * Returns true if application is not found or there was an error. Otherwise it returns 9615 * the hidden state of the package for the given user. 9616 */ 9617 @Override 9618 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 9619 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9620 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 9621 false, "getApplicationHidden for user " + userId); 9622 PackageSetting pkgSetting; 9623 long callingId = Binder.clearCallingIdentity(); 9624 try { 9625 // writer 9626 synchronized (mPackages) { 9627 pkgSetting = mSettings.mPackages.get(packageName); 9628 if (pkgSetting == null) { 9629 return true; 9630 } 9631 return pkgSetting.getHidden(userId); 9632 } 9633 } finally { 9634 Binder.restoreCallingIdentity(callingId); 9635 } 9636 } 9637 9638 /** 9639 * @hide 9640 */ 9641 @Override 9642 public int installExistingPackageAsUser(String packageName, int userId) { 9643 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 9644 null); 9645 PackageSetting pkgSetting; 9646 final int uid = Binder.getCallingUid(); 9647 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 9648 + userId); 9649 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9650 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 9651 } 9652 9653 long callingId = Binder.clearCallingIdentity(); 9654 try { 9655 boolean sendAdded = false; 9656 9657 // writer 9658 synchronized (mPackages) { 9659 pkgSetting = mSettings.mPackages.get(packageName); 9660 if (pkgSetting == null) { 9661 return PackageManager.INSTALL_FAILED_INVALID_URI; 9662 } 9663 if (!pkgSetting.getInstalled(userId)) { 9664 pkgSetting.setInstalled(true, userId); 9665 pkgSetting.setHidden(false, userId); 9666 mSettings.writePackageRestrictionsLPr(userId); 9667 sendAdded = true; 9668 } 9669 } 9670 9671 if (sendAdded) { 9672 sendPackageAddedForUser(packageName, pkgSetting, userId); 9673 } 9674 } finally { 9675 Binder.restoreCallingIdentity(callingId); 9676 } 9677 9678 return PackageManager.INSTALL_SUCCEEDED; 9679 } 9680 9681 boolean isUserRestricted(int userId, String restrictionKey) { 9682 Bundle restrictions = sUserManager.getUserRestrictions(userId); 9683 if (restrictions.getBoolean(restrictionKey, false)) { 9684 Log.w(TAG, "User is restricted: " + restrictionKey); 9685 return true; 9686 } 9687 return false; 9688 } 9689 9690 @Override 9691 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 9692 mContext.enforceCallingOrSelfPermission( 9693 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9694 "Only package verification agents can verify applications"); 9695 9696 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9697 final PackageVerificationResponse response = new PackageVerificationResponse( 9698 verificationCode, Binder.getCallingUid()); 9699 msg.arg1 = id; 9700 msg.obj = response; 9701 mHandler.sendMessage(msg); 9702 } 9703 9704 @Override 9705 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 9706 long millisecondsToDelay) { 9707 mContext.enforceCallingOrSelfPermission( 9708 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9709 "Only package verification agents can extend verification timeouts"); 9710 9711 final PackageVerificationState state = mPendingVerification.get(id); 9712 final PackageVerificationResponse response = new PackageVerificationResponse( 9713 verificationCodeAtTimeout, Binder.getCallingUid()); 9714 9715 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 9716 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 9717 } 9718 if (millisecondsToDelay < 0) { 9719 millisecondsToDelay = 0; 9720 } 9721 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 9722 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 9723 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 9724 } 9725 9726 if ((state != null) && !state.timeoutExtended()) { 9727 state.extendTimeout(); 9728 9729 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9730 msg.arg1 = id; 9731 msg.obj = response; 9732 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 9733 } 9734 } 9735 9736 private void broadcastPackageVerified(int verificationId, Uri packageUri, 9737 int verificationCode, UserHandle user) { 9738 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 9739 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 9740 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9741 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9742 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 9743 9744 mContext.sendBroadcastAsUser(intent, user, 9745 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 9746 } 9747 9748 private ComponentName matchComponentForVerifier(String packageName, 9749 List<ResolveInfo> receivers) { 9750 ActivityInfo targetReceiver = null; 9751 9752 final int NR = receivers.size(); 9753 for (int i = 0; i < NR; i++) { 9754 final ResolveInfo info = receivers.get(i); 9755 if (info.activityInfo == null) { 9756 continue; 9757 } 9758 9759 if (packageName.equals(info.activityInfo.packageName)) { 9760 targetReceiver = info.activityInfo; 9761 break; 9762 } 9763 } 9764 9765 if (targetReceiver == null) { 9766 return null; 9767 } 9768 9769 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 9770 } 9771 9772 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 9773 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 9774 if (pkgInfo.verifiers.length == 0) { 9775 return null; 9776 } 9777 9778 final int N = pkgInfo.verifiers.length; 9779 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 9780 for (int i = 0; i < N; i++) { 9781 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 9782 9783 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 9784 receivers); 9785 if (comp == null) { 9786 continue; 9787 } 9788 9789 final int verifierUid = getUidForVerifier(verifierInfo); 9790 if (verifierUid == -1) { 9791 continue; 9792 } 9793 9794 if (DEBUG_VERIFY) { 9795 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 9796 + " with the correct signature"); 9797 } 9798 sufficientVerifiers.add(comp); 9799 verificationState.addSufficientVerifier(verifierUid); 9800 } 9801 9802 return sufficientVerifiers; 9803 } 9804 9805 private int getUidForVerifier(VerifierInfo verifierInfo) { 9806 synchronized (mPackages) { 9807 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 9808 if (pkg == null) { 9809 return -1; 9810 } else if (pkg.mSignatures.length != 1) { 9811 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9812 + " has more than one signature; ignoring"); 9813 return -1; 9814 } 9815 9816 /* 9817 * If the public key of the package's signature does not match 9818 * our expected public key, then this is a different package and 9819 * we should skip. 9820 */ 9821 9822 final byte[] expectedPublicKey; 9823 try { 9824 final Signature verifierSig = pkg.mSignatures[0]; 9825 final PublicKey publicKey = verifierSig.getPublicKey(); 9826 expectedPublicKey = publicKey.getEncoded(); 9827 } catch (CertificateException e) { 9828 return -1; 9829 } 9830 9831 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 9832 9833 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 9834 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9835 + " does not have the expected public key; ignoring"); 9836 return -1; 9837 } 9838 9839 return pkg.applicationInfo.uid; 9840 } 9841 } 9842 9843 @Override 9844 public void finishPackageInstall(int token) { 9845 enforceSystemOrRoot("Only the system is allowed to finish installs"); 9846 9847 if (DEBUG_INSTALL) { 9848 Slog.v(TAG, "BM finishing package install for " + token); 9849 } 9850 9851 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9852 mHandler.sendMessage(msg); 9853 } 9854 9855 /** 9856 * Get the verification agent timeout. 9857 * 9858 * @return verification timeout in milliseconds 9859 */ 9860 private long getVerificationTimeout() { 9861 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 9862 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 9863 DEFAULT_VERIFICATION_TIMEOUT); 9864 } 9865 9866 /** 9867 * Get the default verification agent response code. 9868 * 9869 * @return default verification response code 9870 */ 9871 private int getDefaultVerificationResponse() { 9872 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9873 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 9874 DEFAULT_VERIFICATION_RESPONSE); 9875 } 9876 9877 /** 9878 * Check whether or not package verification has been enabled. 9879 * 9880 * @return true if verification should be performed 9881 */ 9882 private boolean isVerificationEnabled(int userId, int installFlags) { 9883 if (!DEFAULT_VERIFY_ENABLE) { 9884 return false; 9885 } 9886 9887 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 9888 9889 // Check if installing from ADB 9890 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 9891 // Do not run verification in a test harness environment 9892 if (ActivityManager.isRunningInTestHarness()) { 9893 return false; 9894 } 9895 if (ensureVerifyAppsEnabled) { 9896 return true; 9897 } 9898 // Check if the developer does not want package verification for ADB installs 9899 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9900 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 9901 return false; 9902 } 9903 } 9904 9905 if (ensureVerifyAppsEnabled) { 9906 return true; 9907 } 9908 9909 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9910 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 9911 } 9912 9913 @Override 9914 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 9915 throws RemoteException { 9916 mContext.enforceCallingOrSelfPermission( 9917 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 9918 "Only intentfilter verification agents can verify applications"); 9919 9920 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 9921 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 9922 Binder.getCallingUid(), verificationCode, failedDomains); 9923 msg.arg1 = id; 9924 msg.obj = response; 9925 mHandler.sendMessage(msg); 9926 } 9927 9928 @Override 9929 public int getIntentVerificationStatus(String packageName, int userId) { 9930 synchronized (mPackages) { 9931 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 9932 } 9933 } 9934 9935 @Override 9936 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 9937 mContext.enforceCallingOrSelfPermission( 9938 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 9939 9940 boolean result = false; 9941 synchronized (mPackages) { 9942 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 9943 } 9944 if (result) { 9945 scheduleWritePackageRestrictionsLocked(userId); 9946 } 9947 return result; 9948 } 9949 9950 @Override 9951 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 9952 synchronized (mPackages) { 9953 return mSettings.getIntentFilterVerificationsLPr(packageName); 9954 } 9955 } 9956 9957 @Override 9958 public List<IntentFilter> getAllIntentFilters(String packageName) { 9959 if (TextUtils.isEmpty(packageName)) { 9960 return Collections.<IntentFilter>emptyList(); 9961 } 9962 synchronized (mPackages) { 9963 PackageParser.Package pkg = mPackages.get(packageName); 9964 if (pkg == null || pkg.activities == null) { 9965 return Collections.<IntentFilter>emptyList(); 9966 } 9967 final int count = pkg.activities.size(); 9968 ArrayList<IntentFilter> result = new ArrayList<>(); 9969 for (int n=0; n<count; n++) { 9970 PackageParser.Activity activity = pkg.activities.get(n); 9971 if (activity.intents != null || activity.intents.size() > 0) { 9972 result.addAll(activity.intents); 9973 } 9974 } 9975 return result; 9976 } 9977 } 9978 9979 @Override 9980 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 9981 mContext.enforceCallingOrSelfPermission( 9982 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 9983 9984 synchronized (mPackages) { 9985 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 9986 if (packageName != null) { 9987 result |= updateIntentVerificationStatus(packageName, 9988 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 9989 userId); 9990 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 9991 packageName, userId); 9992 } 9993 return result; 9994 } 9995 } 9996 9997 @Override 9998 public String getDefaultBrowserPackageName(int userId) { 9999 synchronized (mPackages) { 10000 return mSettings.getDefaultBrowserPackageNameLPw(userId); 10001 } 10002 } 10003 10004 /** 10005 * Get the "allow unknown sources" setting. 10006 * 10007 * @return the current "allow unknown sources" setting 10008 */ 10009 private int getUnknownSourcesSettings() { 10010 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10011 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 10012 -1); 10013 } 10014 10015 @Override 10016 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 10017 final int uid = Binder.getCallingUid(); 10018 // writer 10019 synchronized (mPackages) { 10020 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 10021 if (targetPackageSetting == null) { 10022 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 10023 } 10024 10025 PackageSetting installerPackageSetting; 10026 if (installerPackageName != null) { 10027 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 10028 if (installerPackageSetting == null) { 10029 throw new IllegalArgumentException("Unknown installer package: " 10030 + installerPackageName); 10031 } 10032 } else { 10033 installerPackageSetting = null; 10034 } 10035 10036 Signature[] callerSignature; 10037 Object obj = mSettings.getUserIdLPr(uid); 10038 if (obj != null) { 10039 if (obj instanceof SharedUserSetting) { 10040 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 10041 } else if (obj instanceof PackageSetting) { 10042 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 10043 } else { 10044 throw new SecurityException("Bad object " + obj + " for uid " + uid); 10045 } 10046 } else { 10047 throw new SecurityException("Unknown calling uid " + uid); 10048 } 10049 10050 // Verify: can't set installerPackageName to a package that is 10051 // not signed with the same cert as the caller. 10052 if (installerPackageSetting != null) { 10053 if (compareSignatures(callerSignature, 10054 installerPackageSetting.signatures.mSignatures) 10055 != PackageManager.SIGNATURE_MATCH) { 10056 throw new SecurityException( 10057 "Caller does not have same cert as new installer package " 10058 + installerPackageName); 10059 } 10060 } 10061 10062 // Verify: if target already has an installer package, it must 10063 // be signed with the same cert as the caller. 10064 if (targetPackageSetting.installerPackageName != null) { 10065 PackageSetting setting = mSettings.mPackages.get( 10066 targetPackageSetting.installerPackageName); 10067 // If the currently set package isn't valid, then it's always 10068 // okay to change it. 10069 if (setting != null) { 10070 if (compareSignatures(callerSignature, 10071 setting.signatures.mSignatures) 10072 != PackageManager.SIGNATURE_MATCH) { 10073 throw new SecurityException( 10074 "Caller does not have same cert as old installer package " 10075 + targetPackageSetting.installerPackageName); 10076 } 10077 } 10078 } 10079 10080 // Okay! 10081 targetPackageSetting.installerPackageName = installerPackageName; 10082 scheduleWriteSettingsLocked(); 10083 } 10084 } 10085 10086 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 10087 // Queue up an async operation since the package installation may take a little while. 10088 mHandler.post(new Runnable() { 10089 public void run() { 10090 mHandler.removeCallbacks(this); 10091 // Result object to be returned 10092 PackageInstalledInfo res = new PackageInstalledInfo(); 10093 res.returnCode = currentStatus; 10094 res.uid = -1; 10095 res.pkg = null; 10096 res.removedInfo = new PackageRemovedInfo(); 10097 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10098 args.doPreInstall(res.returnCode); 10099 synchronized (mInstallLock) { 10100 installPackageLI(args, res); 10101 } 10102 args.doPostInstall(res.returnCode, res.uid); 10103 } 10104 10105 // A restore should be performed at this point if (a) the install 10106 // succeeded, (b) the operation is not an update, and (c) the new 10107 // package has not opted out of backup participation. 10108 final boolean update = res.removedInfo.removedPackage != null; 10109 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 10110 boolean doRestore = !update 10111 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 10112 10113 // Set up the post-install work request bookkeeping. This will be used 10114 // and cleaned up by the post-install event handling regardless of whether 10115 // there's a restore pass performed. Token values are >= 1. 10116 int token; 10117 if (mNextInstallToken < 0) mNextInstallToken = 1; 10118 token = mNextInstallToken++; 10119 10120 PostInstallData data = new PostInstallData(args, res); 10121 mRunningInstalls.put(token, data); 10122 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 10123 10124 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 10125 // Pass responsibility to the Backup Manager. It will perform a 10126 // restore if appropriate, then pass responsibility back to the 10127 // Package Manager to run the post-install observer callbacks 10128 // and broadcasts. 10129 IBackupManager bm = IBackupManager.Stub.asInterface( 10130 ServiceManager.getService(Context.BACKUP_SERVICE)); 10131 if (bm != null) { 10132 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 10133 + " to BM for possible restore"); 10134 try { 10135 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 10136 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 10137 } else { 10138 doRestore = false; 10139 } 10140 } catch (RemoteException e) { 10141 // can't happen; the backup manager is local 10142 } catch (Exception e) { 10143 Slog.e(TAG, "Exception trying to enqueue restore", e); 10144 doRestore = false; 10145 } 10146 } else { 10147 Slog.e(TAG, "Backup Manager not found!"); 10148 doRestore = false; 10149 } 10150 } 10151 10152 if (!doRestore) { 10153 // No restore possible, or the Backup Manager was mysteriously not 10154 // available -- just fire the post-install work request directly. 10155 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 10156 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10157 mHandler.sendMessage(msg); 10158 } 10159 } 10160 }); 10161 } 10162 10163 private abstract class HandlerParams { 10164 private static final int MAX_RETRIES = 4; 10165 10166 /** 10167 * Number of times startCopy() has been attempted and had a non-fatal 10168 * error. 10169 */ 10170 private int mRetries = 0; 10171 10172 /** User handle for the user requesting the information or installation. */ 10173 private final UserHandle mUser; 10174 10175 HandlerParams(UserHandle user) { 10176 mUser = user; 10177 } 10178 10179 UserHandle getUser() { 10180 return mUser; 10181 } 10182 10183 final boolean startCopy() { 10184 boolean res; 10185 try { 10186 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 10187 10188 if (++mRetries > MAX_RETRIES) { 10189 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 10190 mHandler.sendEmptyMessage(MCS_GIVE_UP); 10191 handleServiceError(); 10192 return false; 10193 } else { 10194 handleStartCopy(); 10195 res = true; 10196 } 10197 } catch (RemoteException e) { 10198 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 10199 mHandler.sendEmptyMessage(MCS_RECONNECT); 10200 res = false; 10201 } 10202 handleReturnCode(); 10203 return res; 10204 } 10205 10206 final void serviceError() { 10207 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 10208 handleServiceError(); 10209 handleReturnCode(); 10210 } 10211 10212 abstract void handleStartCopy() throws RemoteException; 10213 abstract void handleServiceError(); 10214 abstract void handleReturnCode(); 10215 } 10216 10217 class MeasureParams extends HandlerParams { 10218 private final PackageStats mStats; 10219 private boolean mSuccess; 10220 10221 private final IPackageStatsObserver mObserver; 10222 10223 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 10224 super(new UserHandle(stats.userHandle)); 10225 mObserver = observer; 10226 mStats = stats; 10227 } 10228 10229 @Override 10230 public String toString() { 10231 return "MeasureParams{" 10232 + Integer.toHexString(System.identityHashCode(this)) 10233 + " " + mStats.packageName + "}"; 10234 } 10235 10236 @Override 10237 void handleStartCopy() throws RemoteException { 10238 synchronized (mInstallLock) { 10239 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 10240 } 10241 10242 if (mSuccess) { 10243 final boolean mounted; 10244 if (Environment.isExternalStorageEmulated()) { 10245 mounted = true; 10246 } else { 10247 final String status = Environment.getExternalStorageState(); 10248 mounted = (Environment.MEDIA_MOUNTED.equals(status) 10249 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 10250 } 10251 10252 if (mounted) { 10253 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 10254 10255 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 10256 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 10257 10258 mStats.externalDataSize = calculateDirectorySize(mContainerService, 10259 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 10260 10261 // Always subtract cache size, since it's a subdirectory 10262 mStats.externalDataSize -= mStats.externalCacheSize; 10263 10264 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 10265 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 10266 10267 mStats.externalObbSize = calculateDirectorySize(mContainerService, 10268 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 10269 } 10270 } 10271 } 10272 10273 @Override 10274 void handleReturnCode() { 10275 if (mObserver != null) { 10276 try { 10277 mObserver.onGetStatsCompleted(mStats, mSuccess); 10278 } catch (RemoteException e) { 10279 Slog.i(TAG, "Observer no longer exists."); 10280 } 10281 } 10282 } 10283 10284 @Override 10285 void handleServiceError() { 10286 Slog.e(TAG, "Could not measure application " + mStats.packageName 10287 + " external storage"); 10288 } 10289 } 10290 10291 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 10292 throws RemoteException { 10293 long result = 0; 10294 for (File path : paths) { 10295 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 10296 } 10297 return result; 10298 } 10299 10300 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 10301 for (File path : paths) { 10302 try { 10303 mcs.clearDirectory(path.getAbsolutePath()); 10304 } catch (RemoteException e) { 10305 } 10306 } 10307 } 10308 10309 static class OriginInfo { 10310 /** 10311 * Location where install is coming from, before it has been 10312 * copied/renamed into place. This could be a single monolithic APK 10313 * file, or a cluster directory. This location may be untrusted. 10314 */ 10315 final File file; 10316 final String cid; 10317 10318 /** 10319 * Flag indicating that {@link #file} or {@link #cid} has already been 10320 * staged, meaning downstream users don't need to defensively copy the 10321 * contents. 10322 */ 10323 final boolean staged; 10324 10325 /** 10326 * Flag indicating that {@link #file} or {@link #cid} is an already 10327 * installed app that is being moved. 10328 */ 10329 final boolean existing; 10330 10331 final String resolvedPath; 10332 final File resolvedFile; 10333 10334 static OriginInfo fromNothing() { 10335 return new OriginInfo(null, null, false, false); 10336 } 10337 10338 static OriginInfo fromUntrustedFile(File file) { 10339 return new OriginInfo(file, null, false, false); 10340 } 10341 10342 static OriginInfo fromExistingFile(File file) { 10343 return new OriginInfo(file, null, false, true); 10344 } 10345 10346 static OriginInfo fromStagedFile(File file) { 10347 return new OriginInfo(file, null, true, false); 10348 } 10349 10350 static OriginInfo fromStagedContainer(String cid) { 10351 return new OriginInfo(null, cid, true, false); 10352 } 10353 10354 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 10355 this.file = file; 10356 this.cid = cid; 10357 this.staged = staged; 10358 this.existing = existing; 10359 10360 if (cid != null) { 10361 resolvedPath = PackageHelper.getSdDir(cid); 10362 resolvedFile = new File(resolvedPath); 10363 } else if (file != null) { 10364 resolvedPath = file.getAbsolutePath(); 10365 resolvedFile = file; 10366 } else { 10367 resolvedPath = null; 10368 resolvedFile = null; 10369 } 10370 } 10371 } 10372 10373 class MoveInfo { 10374 final int moveId; 10375 final String fromUuid; 10376 final String toUuid; 10377 final String packageName; 10378 final String dataAppName; 10379 final int appId; 10380 final String seinfo; 10381 10382 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 10383 String dataAppName, int appId, String seinfo) { 10384 this.moveId = moveId; 10385 this.fromUuid = fromUuid; 10386 this.toUuid = toUuid; 10387 this.packageName = packageName; 10388 this.dataAppName = dataAppName; 10389 this.appId = appId; 10390 this.seinfo = seinfo; 10391 } 10392 } 10393 10394 class InstallParams extends HandlerParams { 10395 final OriginInfo origin; 10396 final MoveInfo move; 10397 final IPackageInstallObserver2 observer; 10398 int installFlags; 10399 final String installerPackageName; 10400 final String volumeUuid; 10401 final VerificationParams verificationParams; 10402 private InstallArgs mArgs; 10403 private int mRet; 10404 final String packageAbiOverride; 10405 final String[] grantedRuntimePermissions; 10406 10407 10408 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10409 int installFlags, String installerPackageName, String volumeUuid, 10410 VerificationParams verificationParams, UserHandle user, String packageAbiOverride, 10411 String[] grantedPermissions) { 10412 super(user); 10413 this.origin = origin; 10414 this.move = move; 10415 this.observer = observer; 10416 this.installFlags = installFlags; 10417 this.installerPackageName = installerPackageName; 10418 this.volumeUuid = volumeUuid; 10419 this.verificationParams = verificationParams; 10420 this.packageAbiOverride = packageAbiOverride; 10421 this.grantedRuntimePermissions = grantedPermissions; 10422 } 10423 10424 @Override 10425 public String toString() { 10426 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 10427 + " file=" + origin.file + " cid=" + origin.cid + "}"; 10428 } 10429 10430 public ManifestDigest getManifestDigest() { 10431 if (verificationParams == null) { 10432 return null; 10433 } 10434 return verificationParams.getManifestDigest(); 10435 } 10436 10437 private int installLocationPolicy(PackageInfoLite pkgLite) { 10438 String packageName = pkgLite.packageName; 10439 int installLocation = pkgLite.installLocation; 10440 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10441 // reader 10442 synchronized (mPackages) { 10443 PackageParser.Package pkg = mPackages.get(packageName); 10444 if (pkg != null) { 10445 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10446 // Check for downgrading. 10447 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 10448 try { 10449 checkDowngrade(pkg, pkgLite); 10450 } catch (PackageManagerException e) { 10451 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 10452 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 10453 } 10454 } 10455 // Check for updated system application. 10456 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10457 if (onSd) { 10458 Slog.w(TAG, "Cannot install update to system app on sdcard"); 10459 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 10460 } 10461 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10462 } else { 10463 if (onSd) { 10464 // Install flag overrides everything. 10465 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10466 } 10467 // If current upgrade specifies particular preference 10468 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 10469 // Application explicitly specified internal. 10470 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10471 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 10472 // App explictly prefers external. Let policy decide 10473 } else { 10474 // Prefer previous location 10475 if (isExternal(pkg)) { 10476 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10477 } 10478 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10479 } 10480 } 10481 } else { 10482 // Invalid install. Return error code 10483 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 10484 } 10485 } 10486 } 10487 // All the special cases have been taken care of. 10488 // Return result based on recommended install location. 10489 if (onSd) { 10490 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10491 } 10492 return pkgLite.recommendedInstallLocation; 10493 } 10494 10495 /* 10496 * Invoke remote method to get package information and install 10497 * location values. Override install location based on default 10498 * policy if needed and then create install arguments based 10499 * on the install location. 10500 */ 10501 public void handleStartCopy() throws RemoteException { 10502 int ret = PackageManager.INSTALL_SUCCEEDED; 10503 10504 // If we're already staged, we've firmly committed to an install location 10505 if (origin.staged) { 10506 if (origin.file != null) { 10507 installFlags |= PackageManager.INSTALL_INTERNAL; 10508 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10509 } else if (origin.cid != null) { 10510 installFlags |= PackageManager.INSTALL_EXTERNAL; 10511 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10512 } else { 10513 throw new IllegalStateException("Invalid stage location"); 10514 } 10515 } 10516 10517 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10518 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 10519 10520 PackageInfoLite pkgLite = null; 10521 10522 if (onInt && onSd) { 10523 // Check if both bits are set. 10524 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 10525 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10526 } else { 10527 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 10528 packageAbiOverride); 10529 10530 /* 10531 * If we have too little free space, try to free cache 10532 * before giving up. 10533 */ 10534 if (!origin.staged && pkgLite.recommendedInstallLocation 10535 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10536 // TODO: focus freeing disk space on the target device 10537 final StorageManager storage = StorageManager.from(mContext); 10538 final long lowThreshold = storage.getStorageLowBytes( 10539 Environment.getDataDirectory()); 10540 10541 final long sizeBytes = mContainerService.calculateInstalledSize( 10542 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 10543 10544 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 10545 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 10546 installFlags, packageAbiOverride); 10547 } 10548 10549 /* 10550 * The cache free must have deleted the file we 10551 * downloaded to install. 10552 * 10553 * TODO: fix the "freeCache" call to not delete 10554 * the file we care about. 10555 */ 10556 if (pkgLite.recommendedInstallLocation 10557 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10558 pkgLite.recommendedInstallLocation 10559 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 10560 } 10561 } 10562 } 10563 10564 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10565 int loc = pkgLite.recommendedInstallLocation; 10566 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 10567 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10568 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 10569 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 10570 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10571 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10572 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 10573 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 10574 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10575 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 10576 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 10577 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 10578 } else { 10579 // Override with defaults if needed. 10580 loc = installLocationPolicy(pkgLite); 10581 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 10582 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 10583 } else if (!onSd && !onInt) { 10584 // Override install location with flags 10585 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 10586 // Set the flag to install on external media. 10587 installFlags |= PackageManager.INSTALL_EXTERNAL; 10588 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10589 } else { 10590 // Make sure the flag for installing on external 10591 // media is unset 10592 installFlags |= PackageManager.INSTALL_INTERNAL; 10593 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10594 } 10595 } 10596 } 10597 } 10598 10599 final InstallArgs args = createInstallArgs(this); 10600 mArgs = args; 10601 10602 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10603 /* 10604 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 10605 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 10606 */ 10607 int userIdentifier = getUser().getIdentifier(); 10608 if (userIdentifier == UserHandle.USER_ALL 10609 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 10610 userIdentifier = UserHandle.USER_OWNER; 10611 } 10612 10613 /* 10614 * Determine if we have any installed package verifiers. If we 10615 * do, then we'll defer to them to verify the packages. 10616 */ 10617 final int requiredUid = mRequiredVerifierPackage == null ? -1 10618 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 10619 if (!origin.existing && requiredUid != -1 10620 && isVerificationEnabled(userIdentifier, installFlags)) { 10621 final Intent verification = new Intent( 10622 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 10623 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 10624 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 10625 PACKAGE_MIME_TYPE); 10626 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10627 10628 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 10629 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 10630 0 /* TODO: Which userId? */); 10631 10632 if (DEBUG_VERIFY) { 10633 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 10634 + verification.toString() + " with " + pkgLite.verifiers.length 10635 + " optional verifiers"); 10636 } 10637 10638 final int verificationId = mPendingVerificationToken++; 10639 10640 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10641 10642 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 10643 installerPackageName); 10644 10645 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 10646 installFlags); 10647 10648 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 10649 pkgLite.packageName); 10650 10651 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 10652 pkgLite.versionCode); 10653 10654 if (verificationParams != null) { 10655 if (verificationParams.getVerificationURI() != null) { 10656 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 10657 verificationParams.getVerificationURI()); 10658 } 10659 if (verificationParams.getOriginatingURI() != null) { 10660 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 10661 verificationParams.getOriginatingURI()); 10662 } 10663 if (verificationParams.getReferrer() != null) { 10664 verification.putExtra(Intent.EXTRA_REFERRER, 10665 verificationParams.getReferrer()); 10666 } 10667 if (verificationParams.getOriginatingUid() >= 0) { 10668 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 10669 verificationParams.getOriginatingUid()); 10670 } 10671 if (verificationParams.getInstallerUid() >= 0) { 10672 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 10673 verificationParams.getInstallerUid()); 10674 } 10675 } 10676 10677 final PackageVerificationState verificationState = new PackageVerificationState( 10678 requiredUid, args); 10679 10680 mPendingVerification.append(verificationId, verificationState); 10681 10682 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 10683 receivers, verificationState); 10684 10685 // Apps installed for "all" users use the device owner to verify the app 10686 UserHandle verifierUser = getUser(); 10687 if (verifierUser == UserHandle.ALL) { 10688 verifierUser = UserHandle.OWNER; 10689 } 10690 10691 /* 10692 * If any sufficient verifiers were listed in the package 10693 * manifest, attempt to ask them. 10694 */ 10695 if (sufficientVerifiers != null) { 10696 final int N = sufficientVerifiers.size(); 10697 if (N == 0) { 10698 Slog.i(TAG, "Additional verifiers required, but none installed."); 10699 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 10700 } else { 10701 for (int i = 0; i < N; i++) { 10702 final ComponentName verifierComponent = sufficientVerifiers.get(i); 10703 10704 final Intent sufficientIntent = new Intent(verification); 10705 sufficientIntent.setComponent(verifierComponent); 10706 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 10707 } 10708 } 10709 } 10710 10711 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 10712 mRequiredVerifierPackage, receivers); 10713 if (ret == PackageManager.INSTALL_SUCCEEDED 10714 && mRequiredVerifierPackage != null) { 10715 /* 10716 * Send the intent to the required verification agent, 10717 * but only start the verification timeout after the 10718 * target BroadcastReceivers have run. 10719 */ 10720 verification.setComponent(requiredVerifierComponent); 10721 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 10722 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10723 new BroadcastReceiver() { 10724 @Override 10725 public void onReceive(Context context, Intent intent) { 10726 final Message msg = mHandler 10727 .obtainMessage(CHECK_PENDING_VERIFICATION); 10728 msg.arg1 = verificationId; 10729 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 10730 } 10731 }, null, 0, null, null); 10732 10733 /* 10734 * We don't want the copy to proceed until verification 10735 * succeeds, so null out this field. 10736 */ 10737 mArgs = null; 10738 } 10739 } else { 10740 /* 10741 * No package verification is enabled, so immediately start 10742 * the remote call to initiate copy using temporary file. 10743 */ 10744 ret = args.copyApk(mContainerService, true); 10745 } 10746 } 10747 10748 mRet = ret; 10749 } 10750 10751 @Override 10752 void handleReturnCode() { 10753 // If mArgs is null, then MCS couldn't be reached. When it 10754 // reconnects, it will try again to install. At that point, this 10755 // will succeed. 10756 if (mArgs != null) { 10757 processPendingInstall(mArgs, mRet); 10758 } 10759 } 10760 10761 @Override 10762 void handleServiceError() { 10763 mArgs = createInstallArgs(this); 10764 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10765 } 10766 10767 public boolean isForwardLocked() { 10768 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10769 } 10770 } 10771 10772 /** 10773 * Used during creation of InstallArgs 10774 * 10775 * @param installFlags package installation flags 10776 * @return true if should be installed on external storage 10777 */ 10778 private static boolean installOnExternalAsec(int installFlags) { 10779 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 10780 return false; 10781 } 10782 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 10783 return true; 10784 } 10785 return false; 10786 } 10787 10788 /** 10789 * Used during creation of InstallArgs 10790 * 10791 * @param installFlags package installation flags 10792 * @return true if should be installed as forward locked 10793 */ 10794 private static boolean installForwardLocked(int installFlags) { 10795 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10796 } 10797 10798 private InstallArgs createInstallArgs(InstallParams params) { 10799 if (params.move != null) { 10800 return new MoveInstallArgs(params); 10801 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 10802 return new AsecInstallArgs(params); 10803 } else { 10804 return new FileInstallArgs(params); 10805 } 10806 } 10807 10808 /** 10809 * Create args that describe an existing installed package. Typically used 10810 * when cleaning up old installs, or used as a move source. 10811 */ 10812 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 10813 String resourcePath, String[] instructionSets) { 10814 final boolean isInAsec; 10815 if (installOnExternalAsec(installFlags)) { 10816 /* Apps on SD card are always in ASEC containers. */ 10817 isInAsec = true; 10818 } else if (installForwardLocked(installFlags) 10819 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 10820 /* 10821 * Forward-locked apps are only in ASEC containers if they're the 10822 * new style 10823 */ 10824 isInAsec = true; 10825 } else { 10826 isInAsec = false; 10827 } 10828 10829 if (isInAsec) { 10830 return new AsecInstallArgs(codePath, instructionSets, 10831 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 10832 } else { 10833 return new FileInstallArgs(codePath, resourcePath, instructionSets); 10834 } 10835 } 10836 10837 static abstract class InstallArgs { 10838 /** @see InstallParams#origin */ 10839 final OriginInfo origin; 10840 /** @see InstallParams#move */ 10841 final MoveInfo move; 10842 10843 final IPackageInstallObserver2 observer; 10844 // Always refers to PackageManager flags only 10845 final int installFlags; 10846 final String installerPackageName; 10847 final String volumeUuid; 10848 final ManifestDigest manifestDigest; 10849 final UserHandle user; 10850 final String abiOverride; 10851 final String[] installGrantPermissions; 10852 10853 // The list of instruction sets supported by this app. This is currently 10854 // only used during the rmdex() phase to clean up resources. We can get rid of this 10855 // if we move dex files under the common app path. 10856 /* nullable */ String[] instructionSets; 10857 10858 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10859 int installFlags, String installerPackageName, String volumeUuid, 10860 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 10861 String abiOverride, String[] installGrantPermissions) { 10862 this.origin = origin; 10863 this.move = move; 10864 this.installFlags = installFlags; 10865 this.observer = observer; 10866 this.installerPackageName = installerPackageName; 10867 this.volumeUuid = volumeUuid; 10868 this.manifestDigest = manifestDigest; 10869 this.user = user; 10870 this.instructionSets = instructionSets; 10871 this.abiOverride = abiOverride; 10872 this.installGrantPermissions = installGrantPermissions; 10873 } 10874 10875 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 10876 abstract int doPreInstall(int status); 10877 10878 /** 10879 * Rename package into final resting place. All paths on the given 10880 * scanned package should be updated to reflect the rename. 10881 */ 10882 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 10883 abstract int doPostInstall(int status, int uid); 10884 10885 /** @see PackageSettingBase#codePathString */ 10886 abstract String getCodePath(); 10887 /** @see PackageSettingBase#resourcePathString */ 10888 abstract String getResourcePath(); 10889 10890 // Need installer lock especially for dex file removal. 10891 abstract void cleanUpResourcesLI(); 10892 abstract boolean doPostDeleteLI(boolean delete); 10893 10894 /** 10895 * Called before the source arguments are copied. This is used mostly 10896 * for MoveParams when it needs to read the source file to put it in the 10897 * destination. 10898 */ 10899 int doPreCopy() { 10900 return PackageManager.INSTALL_SUCCEEDED; 10901 } 10902 10903 /** 10904 * Called after the source arguments are copied. This is used mostly for 10905 * MoveParams when it needs to read the source file to put it in the 10906 * destination. 10907 * 10908 * @return 10909 */ 10910 int doPostCopy(int uid) { 10911 return PackageManager.INSTALL_SUCCEEDED; 10912 } 10913 10914 protected boolean isFwdLocked() { 10915 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10916 } 10917 10918 protected boolean isExternalAsec() { 10919 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10920 } 10921 10922 UserHandle getUser() { 10923 return user; 10924 } 10925 } 10926 10927 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 10928 if (!allCodePaths.isEmpty()) { 10929 if (instructionSets == null) { 10930 throw new IllegalStateException("instructionSet == null"); 10931 } 10932 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 10933 for (String codePath : allCodePaths) { 10934 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 10935 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 10936 if (retCode < 0) { 10937 Slog.w(TAG, "Couldn't remove dex file for package: " 10938 + " at location " + codePath + ", retcode=" + retCode); 10939 // we don't consider this to be a failure of the core package deletion 10940 } 10941 } 10942 } 10943 } 10944 } 10945 10946 /** 10947 * Logic to handle installation of non-ASEC applications, including copying 10948 * and renaming logic. 10949 */ 10950 class FileInstallArgs extends InstallArgs { 10951 private File codeFile; 10952 private File resourceFile; 10953 10954 // Example topology: 10955 // /data/app/com.example/base.apk 10956 // /data/app/com.example/split_foo.apk 10957 // /data/app/com.example/lib/arm/libfoo.so 10958 // /data/app/com.example/lib/arm64/libfoo.so 10959 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 10960 10961 /** New install */ 10962 FileInstallArgs(InstallParams params) { 10963 super(params.origin, params.move, params.observer, params.installFlags, 10964 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10965 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 10966 params.grantedRuntimePermissions); 10967 if (isFwdLocked()) { 10968 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 10969 } 10970 } 10971 10972 /** Existing install */ 10973 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 10974 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 10975 null, null); 10976 this.codeFile = (codePath != null) ? new File(codePath) : null; 10977 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 10978 } 10979 10980 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10981 if (origin.staged) { 10982 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 10983 codeFile = origin.file; 10984 resourceFile = origin.file; 10985 return PackageManager.INSTALL_SUCCEEDED; 10986 } 10987 10988 try { 10989 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 10990 codeFile = tempDir; 10991 resourceFile = tempDir; 10992 } catch (IOException e) { 10993 Slog.w(TAG, "Failed to create copy file: " + e); 10994 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10995 } 10996 10997 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 10998 @Override 10999 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 11000 if (!FileUtils.isValidExtFilename(name)) { 11001 throw new IllegalArgumentException("Invalid filename: " + name); 11002 } 11003 try { 11004 final File file = new File(codeFile, name); 11005 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 11006 O_RDWR | O_CREAT, 0644); 11007 Os.chmod(file.getAbsolutePath(), 0644); 11008 return new ParcelFileDescriptor(fd); 11009 } catch (ErrnoException e) { 11010 throw new RemoteException("Failed to open: " + e.getMessage()); 11011 } 11012 } 11013 }; 11014 11015 int ret = PackageManager.INSTALL_SUCCEEDED; 11016 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 11017 if (ret != PackageManager.INSTALL_SUCCEEDED) { 11018 Slog.e(TAG, "Failed to copy package"); 11019 return ret; 11020 } 11021 11022 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 11023 NativeLibraryHelper.Handle handle = null; 11024 try { 11025 handle = NativeLibraryHelper.Handle.create(codeFile); 11026 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 11027 abiOverride); 11028 } catch (IOException e) { 11029 Slog.e(TAG, "Copying native libraries failed", e); 11030 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11031 } finally { 11032 IoUtils.closeQuietly(handle); 11033 } 11034 11035 return ret; 11036 } 11037 11038 int doPreInstall(int status) { 11039 if (status != PackageManager.INSTALL_SUCCEEDED) { 11040 cleanUp(); 11041 } 11042 return status; 11043 } 11044 11045 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11046 if (status != PackageManager.INSTALL_SUCCEEDED) { 11047 cleanUp(); 11048 return false; 11049 } 11050 11051 final File targetDir = codeFile.getParentFile(); 11052 final File beforeCodeFile = codeFile; 11053 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 11054 11055 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 11056 try { 11057 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 11058 } catch (ErrnoException e) { 11059 Slog.w(TAG, "Failed to rename", e); 11060 return false; 11061 } 11062 11063 if (!SELinux.restoreconRecursive(afterCodeFile)) { 11064 Slog.w(TAG, "Failed to restorecon"); 11065 return false; 11066 } 11067 11068 // Reflect the rename internally 11069 codeFile = afterCodeFile; 11070 resourceFile = afterCodeFile; 11071 11072 // Reflect the rename in scanned details 11073 pkg.codePath = afterCodeFile.getAbsolutePath(); 11074 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11075 pkg.baseCodePath); 11076 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11077 pkg.splitCodePaths); 11078 11079 // Reflect the rename in app info 11080 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11081 pkg.applicationInfo.setCodePath(pkg.codePath); 11082 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11083 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11084 pkg.applicationInfo.setResourcePath(pkg.codePath); 11085 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11086 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11087 11088 return true; 11089 } 11090 11091 int doPostInstall(int status, int uid) { 11092 if (status != PackageManager.INSTALL_SUCCEEDED) { 11093 cleanUp(); 11094 } 11095 return status; 11096 } 11097 11098 @Override 11099 String getCodePath() { 11100 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11101 } 11102 11103 @Override 11104 String getResourcePath() { 11105 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11106 } 11107 11108 private boolean cleanUp() { 11109 if (codeFile == null || !codeFile.exists()) { 11110 return false; 11111 } 11112 11113 if (codeFile.isDirectory()) { 11114 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11115 } else { 11116 codeFile.delete(); 11117 } 11118 11119 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 11120 resourceFile.delete(); 11121 } 11122 11123 return true; 11124 } 11125 11126 void cleanUpResourcesLI() { 11127 // Try enumerating all code paths before deleting 11128 List<String> allCodePaths = Collections.EMPTY_LIST; 11129 if (codeFile != null && codeFile.exists()) { 11130 try { 11131 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11132 allCodePaths = pkg.getAllCodePaths(); 11133 } catch (PackageParserException e) { 11134 // Ignored; we tried our best 11135 } 11136 } 11137 11138 cleanUp(); 11139 removeDexFiles(allCodePaths, instructionSets); 11140 } 11141 11142 boolean doPostDeleteLI(boolean delete) { 11143 // XXX err, shouldn't we respect the delete flag? 11144 cleanUpResourcesLI(); 11145 return true; 11146 } 11147 } 11148 11149 private boolean isAsecExternal(String cid) { 11150 final String asecPath = PackageHelper.getSdFilesystem(cid); 11151 return !asecPath.startsWith(mAsecInternalPath); 11152 } 11153 11154 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 11155 PackageManagerException { 11156 if (copyRet < 0) { 11157 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 11158 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 11159 throw new PackageManagerException(copyRet, message); 11160 } 11161 } 11162 } 11163 11164 /** 11165 * Extract the MountService "container ID" from the full code path of an 11166 * .apk. 11167 */ 11168 static String cidFromCodePath(String fullCodePath) { 11169 int eidx = fullCodePath.lastIndexOf("/"); 11170 String subStr1 = fullCodePath.substring(0, eidx); 11171 int sidx = subStr1.lastIndexOf("/"); 11172 return subStr1.substring(sidx+1, eidx); 11173 } 11174 11175 /** 11176 * Logic to handle installation of ASEC applications, including copying and 11177 * renaming logic. 11178 */ 11179 class AsecInstallArgs extends InstallArgs { 11180 static final String RES_FILE_NAME = "pkg.apk"; 11181 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 11182 11183 String cid; 11184 String packagePath; 11185 String resourcePath; 11186 11187 /** New install */ 11188 AsecInstallArgs(InstallParams params) { 11189 super(params.origin, params.move, params.observer, params.installFlags, 11190 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11191 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11192 params.grantedRuntimePermissions); 11193 } 11194 11195 /** Existing install */ 11196 AsecInstallArgs(String fullCodePath, String[] instructionSets, 11197 boolean isExternal, boolean isForwardLocked) { 11198 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 11199 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11200 instructionSets, null, null); 11201 // Hackily pretend we're still looking at a full code path 11202 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 11203 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 11204 } 11205 11206 // Extract cid from fullCodePath 11207 int eidx = fullCodePath.lastIndexOf("/"); 11208 String subStr1 = fullCodePath.substring(0, eidx); 11209 int sidx = subStr1.lastIndexOf("/"); 11210 cid = subStr1.substring(sidx+1, eidx); 11211 setMountPath(subStr1); 11212 } 11213 11214 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 11215 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 11216 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11217 instructionSets, null, null); 11218 this.cid = cid; 11219 setMountPath(PackageHelper.getSdDir(cid)); 11220 } 11221 11222 void createCopyFile() { 11223 cid = mInstallerService.allocateExternalStageCidLegacy(); 11224 } 11225 11226 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11227 if (origin.staged) { 11228 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 11229 cid = origin.cid; 11230 setMountPath(PackageHelper.getSdDir(cid)); 11231 return PackageManager.INSTALL_SUCCEEDED; 11232 } 11233 11234 if (temp) { 11235 createCopyFile(); 11236 } else { 11237 /* 11238 * Pre-emptively destroy the container since it's destroyed if 11239 * copying fails due to it existing anyway. 11240 */ 11241 PackageHelper.destroySdDir(cid); 11242 } 11243 11244 final String newMountPath = imcs.copyPackageToContainer( 11245 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 11246 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 11247 11248 if (newMountPath != null) { 11249 setMountPath(newMountPath); 11250 return PackageManager.INSTALL_SUCCEEDED; 11251 } else { 11252 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11253 } 11254 } 11255 11256 @Override 11257 String getCodePath() { 11258 return packagePath; 11259 } 11260 11261 @Override 11262 String getResourcePath() { 11263 return resourcePath; 11264 } 11265 11266 int doPreInstall(int status) { 11267 if (status != PackageManager.INSTALL_SUCCEEDED) { 11268 // Destroy container 11269 PackageHelper.destroySdDir(cid); 11270 } else { 11271 boolean mounted = PackageHelper.isContainerMounted(cid); 11272 if (!mounted) { 11273 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 11274 Process.SYSTEM_UID); 11275 if (newMountPath != null) { 11276 setMountPath(newMountPath); 11277 } else { 11278 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11279 } 11280 } 11281 } 11282 return status; 11283 } 11284 11285 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11286 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 11287 String newMountPath = null; 11288 if (PackageHelper.isContainerMounted(cid)) { 11289 // Unmount the container 11290 if (!PackageHelper.unMountSdDir(cid)) { 11291 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 11292 return false; 11293 } 11294 } 11295 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11296 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 11297 " which might be stale. Will try to clean up."); 11298 // Clean up the stale container and proceed to recreate. 11299 if (!PackageHelper.destroySdDir(newCacheId)) { 11300 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 11301 return false; 11302 } 11303 // Successfully cleaned up stale container. Try to rename again. 11304 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11305 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 11306 + " inspite of cleaning it up."); 11307 return false; 11308 } 11309 } 11310 if (!PackageHelper.isContainerMounted(newCacheId)) { 11311 Slog.w(TAG, "Mounting container " + newCacheId); 11312 newMountPath = PackageHelper.mountSdDir(newCacheId, 11313 getEncryptKey(), Process.SYSTEM_UID); 11314 } else { 11315 newMountPath = PackageHelper.getSdDir(newCacheId); 11316 } 11317 if (newMountPath == null) { 11318 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 11319 return false; 11320 } 11321 Log.i(TAG, "Succesfully renamed " + cid + 11322 " to " + newCacheId + 11323 " at new path: " + newMountPath); 11324 cid = newCacheId; 11325 11326 final File beforeCodeFile = new File(packagePath); 11327 setMountPath(newMountPath); 11328 final File afterCodeFile = new File(packagePath); 11329 11330 // Reflect the rename in scanned details 11331 pkg.codePath = afterCodeFile.getAbsolutePath(); 11332 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11333 pkg.baseCodePath); 11334 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11335 pkg.splitCodePaths); 11336 11337 // Reflect the rename in app info 11338 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11339 pkg.applicationInfo.setCodePath(pkg.codePath); 11340 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11341 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11342 pkg.applicationInfo.setResourcePath(pkg.codePath); 11343 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11344 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11345 11346 return true; 11347 } 11348 11349 private void setMountPath(String mountPath) { 11350 final File mountFile = new File(mountPath); 11351 11352 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 11353 if (monolithicFile.exists()) { 11354 packagePath = monolithicFile.getAbsolutePath(); 11355 if (isFwdLocked()) { 11356 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 11357 } else { 11358 resourcePath = packagePath; 11359 } 11360 } else { 11361 packagePath = mountFile.getAbsolutePath(); 11362 resourcePath = packagePath; 11363 } 11364 } 11365 11366 int doPostInstall(int status, int uid) { 11367 if (status != PackageManager.INSTALL_SUCCEEDED) { 11368 cleanUp(); 11369 } else { 11370 final int groupOwner; 11371 final String protectedFile; 11372 if (isFwdLocked()) { 11373 groupOwner = UserHandle.getSharedAppGid(uid); 11374 protectedFile = RES_FILE_NAME; 11375 } else { 11376 groupOwner = -1; 11377 protectedFile = null; 11378 } 11379 11380 if (uid < Process.FIRST_APPLICATION_UID 11381 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 11382 Slog.e(TAG, "Failed to finalize " + cid); 11383 PackageHelper.destroySdDir(cid); 11384 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11385 } 11386 11387 boolean mounted = PackageHelper.isContainerMounted(cid); 11388 if (!mounted) { 11389 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 11390 } 11391 } 11392 return status; 11393 } 11394 11395 private void cleanUp() { 11396 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 11397 11398 // Destroy secure container 11399 PackageHelper.destroySdDir(cid); 11400 } 11401 11402 private List<String> getAllCodePaths() { 11403 final File codeFile = new File(getCodePath()); 11404 if (codeFile != null && codeFile.exists()) { 11405 try { 11406 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11407 return pkg.getAllCodePaths(); 11408 } catch (PackageParserException e) { 11409 // Ignored; we tried our best 11410 } 11411 } 11412 return Collections.EMPTY_LIST; 11413 } 11414 11415 void cleanUpResourcesLI() { 11416 // Enumerate all code paths before deleting 11417 cleanUpResourcesLI(getAllCodePaths()); 11418 } 11419 11420 private void cleanUpResourcesLI(List<String> allCodePaths) { 11421 cleanUp(); 11422 removeDexFiles(allCodePaths, instructionSets); 11423 } 11424 11425 String getPackageName() { 11426 return getAsecPackageName(cid); 11427 } 11428 11429 boolean doPostDeleteLI(boolean delete) { 11430 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 11431 final List<String> allCodePaths = getAllCodePaths(); 11432 boolean mounted = PackageHelper.isContainerMounted(cid); 11433 if (mounted) { 11434 // Unmount first 11435 if (PackageHelper.unMountSdDir(cid)) { 11436 mounted = false; 11437 } 11438 } 11439 if (!mounted && delete) { 11440 cleanUpResourcesLI(allCodePaths); 11441 } 11442 return !mounted; 11443 } 11444 11445 @Override 11446 int doPreCopy() { 11447 if (isFwdLocked()) { 11448 if (!PackageHelper.fixSdPermissions(cid, 11449 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 11450 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11451 } 11452 } 11453 11454 return PackageManager.INSTALL_SUCCEEDED; 11455 } 11456 11457 @Override 11458 int doPostCopy(int uid) { 11459 if (isFwdLocked()) { 11460 if (uid < Process.FIRST_APPLICATION_UID 11461 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 11462 RES_FILE_NAME)) { 11463 Slog.e(TAG, "Failed to finalize " + cid); 11464 PackageHelper.destroySdDir(cid); 11465 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11466 } 11467 } 11468 11469 return PackageManager.INSTALL_SUCCEEDED; 11470 } 11471 } 11472 11473 /** 11474 * Logic to handle movement of existing installed applications. 11475 */ 11476 class MoveInstallArgs extends InstallArgs { 11477 private File codeFile; 11478 private File resourceFile; 11479 11480 /** New install */ 11481 MoveInstallArgs(InstallParams params) { 11482 super(params.origin, params.move, params.observer, params.installFlags, 11483 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11484 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11485 params.grantedRuntimePermissions); 11486 } 11487 11488 int copyApk(IMediaContainerService imcs, boolean temp) { 11489 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 11490 + move.fromUuid + " to " + move.toUuid); 11491 synchronized (mInstaller) { 11492 if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName, 11493 move.dataAppName, move.appId, move.seinfo) != 0) { 11494 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11495 } 11496 } 11497 11498 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 11499 resourceFile = codeFile; 11500 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 11501 11502 return PackageManager.INSTALL_SUCCEEDED; 11503 } 11504 11505 int doPreInstall(int status) { 11506 if (status != PackageManager.INSTALL_SUCCEEDED) { 11507 cleanUp(move.toUuid); 11508 } 11509 return status; 11510 } 11511 11512 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11513 if (status != PackageManager.INSTALL_SUCCEEDED) { 11514 cleanUp(move.toUuid); 11515 return false; 11516 } 11517 11518 // Reflect the move in app info 11519 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11520 pkg.applicationInfo.setCodePath(pkg.codePath); 11521 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11522 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11523 pkg.applicationInfo.setResourcePath(pkg.codePath); 11524 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11525 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11526 11527 return true; 11528 } 11529 11530 int doPostInstall(int status, int uid) { 11531 if (status == PackageManager.INSTALL_SUCCEEDED) { 11532 cleanUp(move.fromUuid); 11533 } else { 11534 cleanUp(move.toUuid); 11535 } 11536 return status; 11537 } 11538 11539 @Override 11540 String getCodePath() { 11541 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11542 } 11543 11544 @Override 11545 String getResourcePath() { 11546 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11547 } 11548 11549 private boolean cleanUp(String volumeUuid) { 11550 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 11551 move.dataAppName); 11552 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 11553 synchronized (mInstallLock) { 11554 // Clean up both app data and code 11555 removeDataDirsLI(volumeUuid, move.packageName); 11556 if (codeFile.isDirectory()) { 11557 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11558 } else { 11559 codeFile.delete(); 11560 } 11561 } 11562 return true; 11563 } 11564 11565 void cleanUpResourcesLI() { 11566 throw new UnsupportedOperationException(); 11567 } 11568 11569 boolean doPostDeleteLI(boolean delete) { 11570 throw new UnsupportedOperationException(); 11571 } 11572 } 11573 11574 static String getAsecPackageName(String packageCid) { 11575 int idx = packageCid.lastIndexOf("-"); 11576 if (idx == -1) { 11577 return packageCid; 11578 } 11579 return packageCid.substring(0, idx); 11580 } 11581 11582 // Utility method used to create code paths based on package name and available index. 11583 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 11584 String idxStr = ""; 11585 int idx = 1; 11586 // Fall back to default value of idx=1 if prefix is not 11587 // part of oldCodePath 11588 if (oldCodePath != null) { 11589 String subStr = oldCodePath; 11590 // Drop the suffix right away 11591 if (suffix != null && subStr.endsWith(suffix)) { 11592 subStr = subStr.substring(0, subStr.length() - suffix.length()); 11593 } 11594 // If oldCodePath already contains prefix find out the 11595 // ending index to either increment or decrement. 11596 int sidx = subStr.lastIndexOf(prefix); 11597 if (sidx != -1) { 11598 subStr = subStr.substring(sidx + prefix.length()); 11599 if (subStr != null) { 11600 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 11601 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 11602 } 11603 try { 11604 idx = Integer.parseInt(subStr); 11605 if (idx <= 1) { 11606 idx++; 11607 } else { 11608 idx--; 11609 } 11610 } catch(NumberFormatException e) { 11611 } 11612 } 11613 } 11614 } 11615 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 11616 return prefix + idxStr; 11617 } 11618 11619 private File getNextCodePath(File targetDir, String packageName) { 11620 int suffix = 1; 11621 File result; 11622 do { 11623 result = new File(targetDir, packageName + "-" + suffix); 11624 suffix++; 11625 } while (result.exists()); 11626 return result; 11627 } 11628 11629 // Utility method that returns the relative package path with respect 11630 // to the installation directory. Like say for /data/data/com.test-1.apk 11631 // string com.test-1 is returned. 11632 static String deriveCodePathName(String codePath) { 11633 if (codePath == null) { 11634 return null; 11635 } 11636 final File codeFile = new File(codePath); 11637 final String name = codeFile.getName(); 11638 if (codeFile.isDirectory()) { 11639 return name; 11640 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 11641 final int lastDot = name.lastIndexOf('.'); 11642 return name.substring(0, lastDot); 11643 } else { 11644 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 11645 return null; 11646 } 11647 } 11648 11649 class PackageInstalledInfo { 11650 String name; 11651 int uid; 11652 // The set of users that originally had this package installed. 11653 int[] origUsers; 11654 // The set of users that now have this package installed. 11655 int[] newUsers; 11656 PackageParser.Package pkg; 11657 int returnCode; 11658 String returnMsg; 11659 PackageRemovedInfo removedInfo; 11660 11661 public void setError(int code, String msg) { 11662 returnCode = code; 11663 returnMsg = msg; 11664 Slog.w(TAG, msg); 11665 } 11666 11667 public void setError(String msg, PackageParserException e) { 11668 returnCode = e.error; 11669 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11670 Slog.w(TAG, msg, e); 11671 } 11672 11673 public void setError(String msg, PackageManagerException e) { 11674 returnCode = e.error; 11675 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11676 Slog.w(TAG, msg, e); 11677 } 11678 11679 // In some error cases we want to convey more info back to the observer 11680 String origPackage; 11681 String origPermission; 11682 } 11683 11684 /* 11685 * Install a non-existing package. 11686 */ 11687 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11688 UserHandle user, String installerPackageName, String volumeUuid, 11689 PackageInstalledInfo res) { 11690 // Remember this for later, in case we need to rollback this install 11691 String pkgName = pkg.packageName; 11692 11693 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 11694 final boolean dataDirExists = Environment 11695 .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists(); 11696 synchronized(mPackages) { 11697 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 11698 // A package with the same name is already installed, though 11699 // it has been renamed to an older name. The package we 11700 // are trying to install should be installed as an update to 11701 // the existing one, but that has not been requested, so bail. 11702 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11703 + " without first uninstalling package running as " 11704 + mSettings.mRenamedPackages.get(pkgName)); 11705 return; 11706 } 11707 if (mPackages.containsKey(pkgName)) { 11708 // Don't allow installation over an existing package with the same name. 11709 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11710 + " without first uninstalling."); 11711 return; 11712 } 11713 } 11714 11715 try { 11716 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 11717 System.currentTimeMillis(), user); 11718 11719 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 11720 // delete the partially installed application. the data directory will have to be 11721 // restored if it was already existing 11722 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11723 // remove package from internal structures. Note that we want deletePackageX to 11724 // delete the package data and cache directories that it created in 11725 // scanPackageLocked, unless those directories existed before we even tried to 11726 // install. 11727 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 11728 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 11729 res.removedInfo, true); 11730 } 11731 11732 } catch (PackageManagerException e) { 11733 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11734 } 11735 } 11736 11737 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 11738 // Can't rotate keys during boot or if sharedUser. 11739 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 11740 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 11741 return false; 11742 } 11743 // app is using upgradeKeySets; make sure all are valid 11744 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11745 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 11746 for (int i = 0; i < upgradeKeySets.length; i++) { 11747 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 11748 Slog.wtf(TAG, "Package " 11749 + (oldPs.name != null ? oldPs.name : "<null>") 11750 + " contains upgrade-key-set reference to unknown key-set: " 11751 + upgradeKeySets[i] 11752 + " reverting to signatures check."); 11753 return false; 11754 } 11755 } 11756 return true; 11757 } 11758 11759 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 11760 // Upgrade keysets are being used. Determine if new package has a superset of the 11761 // required keys. 11762 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 11763 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11764 for (int i = 0; i < upgradeKeySets.length; i++) { 11765 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 11766 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 11767 return true; 11768 } 11769 } 11770 return false; 11771 } 11772 11773 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11774 UserHandle user, String installerPackageName, String volumeUuid, 11775 PackageInstalledInfo res) { 11776 final PackageParser.Package oldPackage; 11777 final String pkgName = pkg.packageName; 11778 final int[] allUsers; 11779 final boolean[] perUserInstalled; 11780 11781 // First find the old package info and check signatures 11782 synchronized(mPackages) { 11783 oldPackage = mPackages.get(pkgName); 11784 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 11785 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11786 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 11787 if(!checkUpgradeKeySetLP(ps, pkg)) { 11788 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11789 "New package not signed by keys specified by upgrade-keysets: " 11790 + pkgName); 11791 return; 11792 } 11793 } else { 11794 // default to original signature matching 11795 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 11796 != PackageManager.SIGNATURE_MATCH) { 11797 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11798 "New package has a different signature: " + pkgName); 11799 return; 11800 } 11801 } 11802 11803 // In case of rollback, remember per-user/profile install state 11804 allUsers = sUserManager.getUserIds(); 11805 perUserInstalled = new boolean[allUsers.length]; 11806 for (int i = 0; i < allUsers.length; i++) { 11807 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11808 } 11809 } 11810 11811 boolean sysPkg = (isSystemApp(oldPackage)); 11812 if (sysPkg) { 11813 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11814 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11815 } else { 11816 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11817 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11818 } 11819 } 11820 11821 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 11822 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11823 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11824 String volumeUuid, PackageInstalledInfo res) { 11825 String pkgName = deletedPackage.packageName; 11826 boolean deletedPkg = true; 11827 boolean updatedSettings = false; 11828 11829 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 11830 + deletedPackage); 11831 long origUpdateTime; 11832 if (pkg.mExtras != null) { 11833 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 11834 } else { 11835 origUpdateTime = 0; 11836 } 11837 11838 // First delete the existing package while retaining the data directory 11839 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 11840 res.removedInfo, true)) { 11841 // If the existing package wasn't successfully deleted 11842 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 11843 deletedPkg = false; 11844 } else { 11845 // Successfully deleted the old package; proceed with replace. 11846 11847 // If deleted package lived in a container, give users a chance to 11848 // relinquish resources before killing. 11849 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 11850 if (DEBUG_INSTALL) { 11851 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 11852 } 11853 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 11854 final ArrayList<String> pkgList = new ArrayList<String>(1); 11855 pkgList.add(deletedPackage.applicationInfo.packageName); 11856 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 11857 } 11858 11859 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 11860 try { 11861 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 11862 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 11863 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11864 perUserInstalled, res, user); 11865 updatedSettings = true; 11866 } catch (PackageManagerException e) { 11867 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11868 } 11869 } 11870 11871 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11872 // remove package from internal structures. Note that we want deletePackageX to 11873 // delete the package data and cache directories that it created in 11874 // scanPackageLocked, unless those directories existed before we even tried to 11875 // install. 11876 if(updatedSettings) { 11877 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 11878 deletePackageLI( 11879 pkgName, null, true, allUsers, perUserInstalled, 11880 PackageManager.DELETE_KEEP_DATA, 11881 res.removedInfo, true); 11882 } 11883 // Since we failed to install the new package we need to restore the old 11884 // package that we deleted. 11885 if (deletedPkg) { 11886 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 11887 File restoreFile = new File(deletedPackage.codePath); 11888 // Parse old package 11889 boolean oldExternal = isExternal(deletedPackage); 11890 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 11891 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 11892 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11893 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 11894 try { 11895 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 11896 } catch (PackageManagerException e) { 11897 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 11898 + e.getMessage()); 11899 return; 11900 } 11901 // Restore of old package succeeded. Update permissions. 11902 // writer 11903 synchronized (mPackages) { 11904 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 11905 UPDATE_PERMISSIONS_ALL); 11906 // can downgrade to reader 11907 mSettings.writeLPr(); 11908 } 11909 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 11910 } 11911 } 11912 } 11913 11914 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 11915 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11916 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11917 String volumeUuid, PackageInstalledInfo res) { 11918 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 11919 + ", old=" + deletedPackage); 11920 boolean disabledSystem = false; 11921 boolean updatedSettings = false; 11922 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 11923 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 11924 != 0) { 11925 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11926 } 11927 String packageName = deletedPackage.packageName; 11928 if (packageName == null) { 11929 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11930 "Attempt to delete null packageName."); 11931 return; 11932 } 11933 PackageParser.Package oldPkg; 11934 PackageSetting oldPkgSetting; 11935 // reader 11936 synchronized (mPackages) { 11937 oldPkg = mPackages.get(packageName); 11938 oldPkgSetting = mSettings.mPackages.get(packageName); 11939 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 11940 (oldPkgSetting == null)) { 11941 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11942 "Couldn't find package:" + packageName + " information"); 11943 return; 11944 } 11945 } 11946 11947 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 11948 11949 res.removedInfo.uid = oldPkg.applicationInfo.uid; 11950 res.removedInfo.removedPackage = packageName; 11951 // Remove existing system package 11952 removePackageLI(oldPkgSetting, true); 11953 // writer 11954 synchronized (mPackages) { 11955 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 11956 if (!disabledSystem && deletedPackage != null) { 11957 // We didn't need to disable the .apk as a current system package, 11958 // which means we are replacing another update that is already 11959 // installed. We need to make sure to delete the older one's .apk. 11960 res.removedInfo.args = createInstallArgsForExisting(0, 11961 deletedPackage.applicationInfo.getCodePath(), 11962 deletedPackage.applicationInfo.getResourcePath(), 11963 getAppDexInstructionSets(deletedPackage.applicationInfo)); 11964 } else { 11965 res.removedInfo.args = null; 11966 } 11967 } 11968 11969 // Successfully disabled the old package. Now proceed with re-installation 11970 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 11971 11972 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11973 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 11974 11975 PackageParser.Package newPackage = null; 11976 try { 11977 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 11978 if (newPackage.mExtras != null) { 11979 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 11980 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 11981 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 11982 11983 // is the update attempting to change shared user? that isn't going to work... 11984 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 11985 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 11986 "Forbidding shared user change from " + oldPkgSetting.sharedUser 11987 + " to " + newPkgSetting.sharedUser); 11988 updatedSettings = true; 11989 } 11990 } 11991 11992 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11993 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11994 perUserInstalled, res, user); 11995 updatedSettings = true; 11996 } 11997 11998 } catch (PackageManagerException e) { 11999 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12000 } 12001 12002 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12003 // Re installation failed. Restore old information 12004 // Remove new pkg information 12005 if (newPackage != null) { 12006 removeInstalledPackageLI(newPackage, true); 12007 } 12008 // Add back the old system package 12009 try { 12010 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 12011 } catch (PackageManagerException e) { 12012 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 12013 } 12014 // Restore the old system information in Settings 12015 synchronized (mPackages) { 12016 if (disabledSystem) { 12017 mSettings.enableSystemPackageLPw(packageName); 12018 } 12019 if (updatedSettings) { 12020 mSettings.setInstallerPackageName(packageName, 12021 oldPkgSetting.installerPackageName); 12022 } 12023 mSettings.writeLPr(); 12024 } 12025 } 12026 } 12027 12028 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 12029 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 12030 UserHandle user) { 12031 String pkgName = newPackage.packageName; 12032 synchronized (mPackages) { 12033 //write settings. the installStatus will be incomplete at this stage. 12034 //note that the new package setting would have already been 12035 //added to mPackages. It hasn't been persisted yet. 12036 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 12037 mSettings.writeLPr(); 12038 } 12039 12040 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 12041 12042 synchronized (mPackages) { 12043 updatePermissionsLPw(newPackage.packageName, newPackage, 12044 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 12045 ? UPDATE_PERMISSIONS_ALL : 0)); 12046 // For system-bundled packages, we assume that installing an upgraded version 12047 // of the package implies that the user actually wants to run that new code, 12048 // so we enable the package. 12049 PackageSetting ps = mSettings.mPackages.get(pkgName); 12050 if (ps != null) { 12051 if (isSystemApp(newPackage)) { 12052 // NB: implicit assumption that system package upgrades apply to all users 12053 if (DEBUG_INSTALL) { 12054 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 12055 } 12056 if (res.origUsers != null) { 12057 for (int userHandle : res.origUsers) { 12058 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 12059 userHandle, installerPackageName); 12060 } 12061 } 12062 // Also convey the prior install/uninstall state 12063 if (allUsers != null && perUserInstalled != null) { 12064 for (int i = 0; i < allUsers.length; i++) { 12065 if (DEBUG_INSTALL) { 12066 Slog.d(TAG, " user " + allUsers[i] 12067 + " => " + perUserInstalled[i]); 12068 } 12069 ps.setInstalled(perUserInstalled[i], allUsers[i]); 12070 } 12071 // these install state changes will be persisted in the 12072 // upcoming call to mSettings.writeLPr(). 12073 } 12074 } 12075 // It's implied that when a user requests installation, they want the app to be 12076 // installed and enabled. 12077 int userId = user.getIdentifier(); 12078 if (userId != UserHandle.USER_ALL) { 12079 ps.setInstalled(true, userId); 12080 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 12081 } 12082 } 12083 res.name = pkgName; 12084 res.uid = newPackage.applicationInfo.uid; 12085 res.pkg = newPackage; 12086 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 12087 mSettings.setInstallerPackageName(pkgName, installerPackageName); 12088 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12089 //to update install status 12090 mSettings.writeLPr(); 12091 } 12092 } 12093 12094 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 12095 final int installFlags = args.installFlags; 12096 final String installerPackageName = args.installerPackageName; 12097 final String volumeUuid = args.volumeUuid; 12098 final File tmpPackageFile = new File(args.getCodePath()); 12099 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 12100 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 12101 || (args.volumeUuid != null)); 12102 boolean replace = false; 12103 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 12104 if (args.move != null) { 12105 // moving a complete application; perfom an initial scan on the new install location 12106 scanFlags |= SCAN_INITIAL; 12107 } 12108 // Result object to be returned 12109 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12110 12111 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 12112 // Retrieve PackageSettings and parse package 12113 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 12114 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 12115 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 12116 PackageParser pp = new PackageParser(); 12117 pp.setSeparateProcesses(mSeparateProcesses); 12118 pp.setDisplayMetrics(mMetrics); 12119 12120 final PackageParser.Package pkg; 12121 try { 12122 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 12123 } catch (PackageParserException e) { 12124 res.setError("Failed parse during installPackageLI", e); 12125 return; 12126 } 12127 12128 // Mark that we have an install time CPU ABI override. 12129 pkg.cpuAbiOverride = args.abiOverride; 12130 12131 String pkgName = res.name = pkg.packageName; 12132 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 12133 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 12134 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 12135 return; 12136 } 12137 } 12138 12139 try { 12140 pp.collectCertificates(pkg, parseFlags); 12141 pp.collectManifestDigest(pkg); 12142 } catch (PackageParserException e) { 12143 res.setError("Failed collect during installPackageLI", e); 12144 return; 12145 } 12146 12147 /* If the installer passed in a manifest digest, compare it now. */ 12148 if (args.manifestDigest != null) { 12149 if (DEBUG_INSTALL) { 12150 final String parsedManifest = pkg.manifestDigest == null ? "null" 12151 : pkg.manifestDigest.toString(); 12152 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 12153 + parsedManifest); 12154 } 12155 12156 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 12157 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 12158 return; 12159 } 12160 } else if (DEBUG_INSTALL) { 12161 final String parsedManifest = pkg.manifestDigest == null 12162 ? "null" : pkg.manifestDigest.toString(); 12163 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 12164 } 12165 12166 // Get rid of all references to package scan path via parser. 12167 pp = null; 12168 String oldCodePath = null; 12169 boolean systemApp = false; 12170 synchronized (mPackages) { 12171 // Check if installing already existing package 12172 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12173 String oldName = mSettings.mRenamedPackages.get(pkgName); 12174 if (pkg.mOriginalPackages != null 12175 && pkg.mOriginalPackages.contains(oldName) 12176 && mPackages.containsKey(oldName)) { 12177 // This package is derived from an original package, 12178 // and this device has been updating from that original 12179 // name. We must continue using the original name, so 12180 // rename the new package here. 12181 pkg.setPackageName(oldName); 12182 pkgName = pkg.packageName; 12183 replace = true; 12184 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 12185 + oldName + " pkgName=" + pkgName); 12186 } else if (mPackages.containsKey(pkgName)) { 12187 // This package, under its official name, already exists 12188 // on the device; we should replace it. 12189 replace = true; 12190 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 12191 } 12192 12193 // Prevent apps opting out from runtime permissions 12194 if (replace) { 12195 PackageParser.Package oldPackage = mPackages.get(pkgName); 12196 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 12197 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 12198 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 12199 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 12200 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 12201 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 12202 + " doesn't support runtime permissions but the old" 12203 + " target SDK " + oldTargetSdk + " does."); 12204 return; 12205 } 12206 } 12207 } 12208 12209 PackageSetting ps = mSettings.mPackages.get(pkgName); 12210 if (ps != null) { 12211 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 12212 12213 // Quick sanity check that we're signed correctly if updating; 12214 // we'll check this again later when scanning, but we want to 12215 // bail early here before tripping over redefined permissions. 12216 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12217 if (!checkUpgradeKeySetLP(ps, pkg)) { 12218 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 12219 + pkg.packageName + " upgrade keys do not match the " 12220 + "previously installed version"); 12221 return; 12222 } 12223 } else { 12224 try { 12225 verifySignaturesLP(ps, pkg); 12226 } catch (PackageManagerException e) { 12227 res.setError(e.error, e.getMessage()); 12228 return; 12229 } 12230 } 12231 12232 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 12233 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 12234 systemApp = (ps.pkg.applicationInfo.flags & 12235 ApplicationInfo.FLAG_SYSTEM) != 0; 12236 } 12237 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12238 } 12239 12240 // Check whether the newly-scanned package wants to define an already-defined perm 12241 int N = pkg.permissions.size(); 12242 for (int i = N-1; i >= 0; i--) { 12243 PackageParser.Permission perm = pkg.permissions.get(i); 12244 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 12245 if (bp != null) { 12246 // If the defining package is signed with our cert, it's okay. This 12247 // also includes the "updating the same package" case, of course. 12248 // "updating same package" could also involve key-rotation. 12249 final boolean sigsOk; 12250 if (bp.sourcePackage.equals(pkg.packageName) 12251 && (bp.packageSetting instanceof PackageSetting) 12252 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 12253 scanFlags))) { 12254 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 12255 } else { 12256 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 12257 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 12258 } 12259 if (!sigsOk) { 12260 // If the owning package is the system itself, we log but allow 12261 // install to proceed; we fail the install on all other permission 12262 // redefinitions. 12263 if (!bp.sourcePackage.equals("android")) { 12264 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 12265 + pkg.packageName + " attempting to redeclare permission " 12266 + perm.info.name + " already owned by " + bp.sourcePackage); 12267 res.origPermission = perm.info.name; 12268 res.origPackage = bp.sourcePackage; 12269 return; 12270 } else { 12271 Slog.w(TAG, "Package " + pkg.packageName 12272 + " attempting to redeclare system permission " 12273 + perm.info.name + "; ignoring new declaration"); 12274 pkg.permissions.remove(i); 12275 } 12276 } 12277 } 12278 } 12279 12280 } 12281 12282 if (systemApp && onExternal) { 12283 // Disable updates to system apps on sdcard 12284 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 12285 "Cannot install updates to system apps on sdcard"); 12286 return; 12287 } 12288 12289 if (args.move != null) { 12290 // We did an in-place move, so dex is ready to roll 12291 scanFlags |= SCAN_NO_DEX; 12292 scanFlags |= SCAN_MOVE; 12293 12294 synchronized (mPackages) { 12295 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12296 if (ps == null) { 12297 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 12298 "Missing settings for moved package " + pkgName); 12299 } 12300 12301 // We moved the entire application as-is, so bring over the 12302 // previously derived ABI information. 12303 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 12304 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 12305 } 12306 12307 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 12308 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 12309 scanFlags |= SCAN_NO_DEX; 12310 12311 try { 12312 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 12313 true /* extract libs */); 12314 } catch (PackageManagerException pme) { 12315 Slog.e(TAG, "Error deriving application ABI", pme); 12316 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 12317 return; 12318 } 12319 12320 // Run dexopt before old package gets removed, to minimize time when app is unavailable 12321 int result = mPackageDexOptimizer 12322 .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */, 12323 false /* defer */, false /* inclDependencies */); 12324 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 12325 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 12326 return; 12327 } 12328 } 12329 12330 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 12331 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 12332 return; 12333 } 12334 12335 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 12336 12337 if (replace) { 12338 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 12339 installerPackageName, volumeUuid, res); 12340 } else { 12341 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 12342 args.user, installerPackageName, volumeUuid, res); 12343 } 12344 synchronized (mPackages) { 12345 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12346 if (ps != null) { 12347 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12348 } 12349 } 12350 } 12351 12352 private void startIntentFilterVerifications(int userId, boolean replacing, 12353 PackageParser.Package pkg) { 12354 if (mIntentFilterVerifierComponent == null) { 12355 Slog.w(TAG, "No IntentFilter verification will not be done as " 12356 + "there is no IntentFilterVerifier available!"); 12357 return; 12358 } 12359 12360 final int verifierUid = getPackageUid( 12361 mIntentFilterVerifierComponent.getPackageName(), 12362 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 12363 12364 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 12365 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 12366 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 12367 mHandler.sendMessage(msg); 12368 } 12369 12370 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 12371 PackageParser.Package pkg) { 12372 int size = pkg.activities.size(); 12373 if (size == 0) { 12374 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12375 "No activity, so no need to verify any IntentFilter!"); 12376 return; 12377 } 12378 12379 final boolean hasDomainURLs = hasDomainURLs(pkg); 12380 if (!hasDomainURLs) { 12381 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12382 "No domain URLs, so no need to verify any IntentFilter!"); 12383 return; 12384 } 12385 12386 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 12387 + " if any IntentFilter from the " + size 12388 + " Activities needs verification ..."); 12389 12390 int count = 0; 12391 final String packageName = pkg.packageName; 12392 12393 synchronized (mPackages) { 12394 // If this is a new install and we see that we've already run verification for this 12395 // package, we have nothing to do: it means the state was restored from backup. 12396 if (!replacing) { 12397 IntentFilterVerificationInfo ivi = 12398 mSettings.getIntentFilterVerificationLPr(packageName); 12399 if (ivi != null) { 12400 if (DEBUG_DOMAIN_VERIFICATION) { 12401 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 12402 + ivi.getStatusString()); 12403 } 12404 return; 12405 } 12406 } 12407 12408 // If any filters need to be verified, then all need to be. 12409 boolean needToVerify = false; 12410 for (PackageParser.Activity a : pkg.activities) { 12411 for (ActivityIntentInfo filter : a.intents) { 12412 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 12413 if (DEBUG_DOMAIN_VERIFICATION) { 12414 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 12415 } 12416 needToVerify = true; 12417 break; 12418 } 12419 } 12420 } 12421 12422 if (needToVerify) { 12423 final int verificationId = mIntentFilterVerificationToken++; 12424 for (PackageParser.Activity a : pkg.activities) { 12425 for (ActivityIntentInfo filter : a.intents) { 12426 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 12427 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12428 "Verification needed for IntentFilter:" + filter.toString()); 12429 mIntentFilterVerifier.addOneIntentFilterVerification( 12430 verifierUid, userId, verificationId, filter, packageName); 12431 count++; 12432 } 12433 } 12434 } 12435 } 12436 } 12437 12438 if (count > 0) { 12439 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 12440 + " IntentFilter verification" + (count > 1 ? "s" : "") 12441 + " for userId:" + userId); 12442 mIntentFilterVerifier.startVerifications(userId); 12443 } else { 12444 if (DEBUG_DOMAIN_VERIFICATION) { 12445 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 12446 } 12447 } 12448 } 12449 12450 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 12451 final ComponentName cn = filter.activity.getComponentName(); 12452 final String packageName = cn.getPackageName(); 12453 12454 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 12455 packageName); 12456 if (ivi == null) { 12457 return true; 12458 } 12459 int status = ivi.getStatus(); 12460 switch (status) { 12461 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 12462 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 12463 return true; 12464 12465 default: 12466 // Nothing to do 12467 return false; 12468 } 12469 } 12470 12471 private static boolean isMultiArch(PackageSetting ps) { 12472 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12473 } 12474 12475 private static boolean isMultiArch(ApplicationInfo info) { 12476 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12477 } 12478 12479 private static boolean isExternal(PackageParser.Package pkg) { 12480 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12481 } 12482 12483 private static boolean isExternal(PackageSetting ps) { 12484 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12485 } 12486 12487 private static boolean isExternal(ApplicationInfo info) { 12488 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12489 } 12490 12491 private static boolean isSystemApp(PackageParser.Package pkg) { 12492 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 12493 } 12494 12495 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 12496 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 12497 } 12498 12499 private static boolean hasDomainURLs(PackageParser.Package pkg) { 12500 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 12501 } 12502 12503 private static boolean isSystemApp(PackageSetting ps) { 12504 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 12505 } 12506 12507 private static boolean isUpdatedSystemApp(PackageSetting ps) { 12508 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 12509 } 12510 12511 private int packageFlagsToInstallFlags(PackageSetting ps) { 12512 int installFlags = 0; 12513 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 12514 // This existing package was an external ASEC install when we have 12515 // the external flag without a UUID 12516 installFlags |= PackageManager.INSTALL_EXTERNAL; 12517 } 12518 if (ps.isForwardLocked()) { 12519 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12520 } 12521 return installFlags; 12522 } 12523 12524 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 12525 if (isExternal(pkg)) { 12526 if (TextUtils.isEmpty(pkg.volumeUuid)) { 12527 return mSettings.getExternalVersion(); 12528 } else { 12529 return mSettings.findOrCreateVersion(pkg.volumeUuid); 12530 } 12531 } else { 12532 return mSettings.getInternalVersion(); 12533 } 12534 } 12535 12536 private void deleteTempPackageFiles() { 12537 final FilenameFilter filter = new FilenameFilter() { 12538 public boolean accept(File dir, String name) { 12539 return name.startsWith("vmdl") && name.endsWith(".tmp"); 12540 } 12541 }; 12542 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 12543 file.delete(); 12544 } 12545 } 12546 12547 @Override 12548 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 12549 int flags) { 12550 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 12551 flags); 12552 } 12553 12554 @Override 12555 public void deletePackage(final String packageName, 12556 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 12557 mContext.enforceCallingOrSelfPermission( 12558 android.Manifest.permission.DELETE_PACKAGES, null); 12559 Preconditions.checkNotNull(packageName); 12560 Preconditions.checkNotNull(observer); 12561 final int uid = Binder.getCallingUid(); 12562 if (UserHandle.getUserId(uid) != userId) { 12563 mContext.enforceCallingPermission( 12564 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 12565 "deletePackage for user " + userId); 12566 } 12567 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 12568 try { 12569 observer.onPackageDeleted(packageName, 12570 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 12571 } catch (RemoteException re) { 12572 } 12573 return; 12574 } 12575 12576 boolean uninstallBlocked = false; 12577 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 12578 int[] users = sUserManager.getUserIds(); 12579 for (int i = 0; i < users.length; ++i) { 12580 if (getBlockUninstallForUser(packageName, users[i])) { 12581 uninstallBlocked = true; 12582 break; 12583 } 12584 } 12585 } else { 12586 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 12587 } 12588 if (uninstallBlocked) { 12589 try { 12590 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 12591 null); 12592 } catch (RemoteException re) { 12593 } 12594 return; 12595 } 12596 12597 if (DEBUG_REMOVE) { 12598 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 12599 } 12600 // Queue up an async operation since the package deletion may take a little while. 12601 mHandler.post(new Runnable() { 12602 public void run() { 12603 mHandler.removeCallbacks(this); 12604 final int returnCode = deletePackageX(packageName, userId, flags); 12605 if (observer != null) { 12606 try { 12607 observer.onPackageDeleted(packageName, returnCode, null); 12608 } catch (RemoteException e) { 12609 Log.i(TAG, "Observer no longer exists."); 12610 } //end catch 12611 } //end if 12612 } //end run 12613 }); 12614 } 12615 12616 private boolean isPackageDeviceAdmin(String packageName, int userId) { 12617 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 12618 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 12619 try { 12620 if (dpm != null) { 12621 if (dpm.isDeviceOwner(packageName)) { 12622 return true; 12623 } 12624 int[] users; 12625 if (userId == UserHandle.USER_ALL) { 12626 users = sUserManager.getUserIds(); 12627 } else { 12628 users = new int[]{userId}; 12629 } 12630 for (int i = 0; i < users.length; ++i) { 12631 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 12632 return true; 12633 } 12634 } 12635 } 12636 } catch (RemoteException e) { 12637 } 12638 return false; 12639 } 12640 12641 /** 12642 * This method is an internal method that could be get invoked either 12643 * to delete an installed package or to clean up a failed installation. 12644 * After deleting an installed package, a broadcast is sent to notify any 12645 * listeners that the package has been installed. For cleaning up a failed 12646 * installation, the broadcast is not necessary since the package's 12647 * installation wouldn't have sent the initial broadcast either 12648 * The key steps in deleting a package are 12649 * deleting the package information in internal structures like mPackages, 12650 * deleting the packages base directories through installd 12651 * updating mSettings to reflect current status 12652 * persisting settings for later use 12653 * sending a broadcast if necessary 12654 */ 12655 private int deletePackageX(String packageName, int userId, int flags) { 12656 final PackageRemovedInfo info = new PackageRemovedInfo(); 12657 final boolean res; 12658 12659 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 12660 ? UserHandle.ALL : new UserHandle(userId); 12661 12662 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 12663 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 12664 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 12665 } 12666 12667 boolean removedForAllUsers = false; 12668 boolean systemUpdate = false; 12669 12670 // for the uninstall-updates case and restricted profiles, remember the per- 12671 // userhandle installed state 12672 int[] allUsers; 12673 boolean[] perUserInstalled; 12674 synchronized (mPackages) { 12675 PackageSetting ps = mSettings.mPackages.get(packageName); 12676 allUsers = sUserManager.getUserIds(); 12677 perUserInstalled = new boolean[allUsers.length]; 12678 for (int i = 0; i < allUsers.length; i++) { 12679 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12680 } 12681 } 12682 12683 synchronized (mInstallLock) { 12684 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 12685 res = deletePackageLI(packageName, removeForUser, 12686 true, allUsers, perUserInstalled, 12687 flags | REMOVE_CHATTY, info, true); 12688 systemUpdate = info.isRemovedPackageSystemUpdate; 12689 if (res && !systemUpdate && mPackages.get(packageName) == null) { 12690 removedForAllUsers = true; 12691 } 12692 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 12693 + " removedForAllUsers=" + removedForAllUsers); 12694 } 12695 12696 if (res) { 12697 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 12698 12699 // If the removed package was a system update, the old system package 12700 // was re-enabled; we need to broadcast this information 12701 if (systemUpdate) { 12702 Bundle extras = new Bundle(1); 12703 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 12704 ? info.removedAppId : info.uid); 12705 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12706 12707 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 12708 extras, null, null, null); 12709 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 12710 extras, null, null, null); 12711 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 12712 null, packageName, null, null); 12713 } 12714 } 12715 // Force a gc here. 12716 Runtime.getRuntime().gc(); 12717 // Delete the resources here after sending the broadcast to let 12718 // other processes clean up before deleting resources. 12719 if (info.args != null) { 12720 synchronized (mInstallLock) { 12721 info.args.doPostDeleteLI(true); 12722 } 12723 } 12724 12725 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 12726 } 12727 12728 class PackageRemovedInfo { 12729 String removedPackage; 12730 int uid = -1; 12731 int removedAppId = -1; 12732 int[] removedUsers = null; 12733 boolean isRemovedPackageSystemUpdate = false; 12734 // Clean up resources deleted packages. 12735 InstallArgs args = null; 12736 12737 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 12738 Bundle extras = new Bundle(1); 12739 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 12740 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 12741 if (replacing) { 12742 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12743 } 12744 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 12745 if (removedPackage != null) { 12746 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 12747 extras, null, null, removedUsers); 12748 if (fullRemove && !replacing) { 12749 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 12750 extras, null, null, removedUsers); 12751 } 12752 } 12753 if (removedAppId >= 0) { 12754 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 12755 removedUsers); 12756 } 12757 } 12758 } 12759 12760 /* 12761 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 12762 * flag is not set, the data directory is removed as well. 12763 * make sure this flag is set for partially installed apps. If not its meaningless to 12764 * delete a partially installed application. 12765 */ 12766 private void removePackageDataLI(PackageSetting ps, 12767 int[] allUserHandles, boolean[] perUserInstalled, 12768 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 12769 String packageName = ps.name; 12770 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 12771 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 12772 // Retrieve object to delete permissions for shared user later on 12773 final PackageSetting deletedPs; 12774 // reader 12775 synchronized (mPackages) { 12776 deletedPs = mSettings.mPackages.get(packageName); 12777 if (outInfo != null) { 12778 outInfo.removedPackage = packageName; 12779 outInfo.removedUsers = deletedPs != null 12780 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 12781 : null; 12782 } 12783 } 12784 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12785 removeDataDirsLI(ps.volumeUuid, packageName); 12786 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 12787 } 12788 // writer 12789 synchronized (mPackages) { 12790 if (deletedPs != null) { 12791 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12792 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 12793 clearDefaultBrowserIfNeeded(packageName); 12794 if (outInfo != null) { 12795 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 12796 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 12797 } 12798 updatePermissionsLPw(deletedPs.name, null, 0); 12799 if (deletedPs.sharedUser != null) { 12800 // Remove permissions associated with package. Since runtime 12801 // permissions are per user we have to kill the removed package 12802 // or packages running under the shared user of the removed 12803 // package if revoking the permissions requested only by the removed 12804 // package is successful and this causes a change in gids. 12805 for (int userId : UserManagerService.getInstance().getUserIds()) { 12806 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 12807 userId); 12808 if (userIdToKill == UserHandle.USER_ALL 12809 || userIdToKill >= UserHandle.USER_OWNER) { 12810 // If gids changed for this user, kill all affected packages. 12811 mHandler.post(new Runnable() { 12812 @Override 12813 public void run() { 12814 // This has to happen with no lock held. 12815 killSettingPackagesForUser(deletedPs, userIdToKill, 12816 KILL_APP_REASON_GIDS_CHANGED); 12817 } 12818 }); 12819 break; 12820 } 12821 } 12822 } 12823 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 12824 } 12825 // make sure to preserve per-user disabled state if this removal was just 12826 // a downgrade of a system app to the factory package 12827 if (allUserHandles != null && perUserInstalled != null) { 12828 if (DEBUG_REMOVE) { 12829 Slog.d(TAG, "Propagating install state across downgrade"); 12830 } 12831 for (int i = 0; i < allUserHandles.length; i++) { 12832 if (DEBUG_REMOVE) { 12833 Slog.d(TAG, " user " + allUserHandles[i] 12834 + " => " + perUserInstalled[i]); 12835 } 12836 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12837 } 12838 } 12839 } 12840 // can downgrade to reader 12841 if (writeSettings) { 12842 // Save settings now 12843 mSettings.writeLPr(); 12844 } 12845 } 12846 if (outInfo != null) { 12847 // A user ID was deleted here. Go through all users and remove it 12848 // from KeyStore. 12849 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 12850 } 12851 } 12852 12853 static boolean locationIsPrivileged(File path) { 12854 try { 12855 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 12856 .getCanonicalPath(); 12857 return path.getCanonicalPath().startsWith(privilegedAppDir); 12858 } catch (IOException e) { 12859 Slog.e(TAG, "Unable to access code path " + path); 12860 } 12861 return false; 12862 } 12863 12864 /* 12865 * Tries to delete system package. 12866 */ 12867 private boolean deleteSystemPackageLI(PackageSetting newPs, 12868 int[] allUserHandles, boolean[] perUserInstalled, 12869 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 12870 final boolean applyUserRestrictions 12871 = (allUserHandles != null) && (perUserInstalled != null); 12872 PackageSetting disabledPs = null; 12873 // Confirm if the system package has been updated 12874 // An updated system app can be deleted. This will also have to restore 12875 // the system pkg from system partition 12876 // reader 12877 synchronized (mPackages) { 12878 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 12879 } 12880 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 12881 + " disabledPs=" + disabledPs); 12882 if (disabledPs == null) { 12883 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 12884 return false; 12885 } else if (DEBUG_REMOVE) { 12886 Slog.d(TAG, "Deleting system pkg from data partition"); 12887 } 12888 if (DEBUG_REMOVE) { 12889 if (applyUserRestrictions) { 12890 Slog.d(TAG, "Remembering install states:"); 12891 for (int i = 0; i < allUserHandles.length; i++) { 12892 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 12893 } 12894 } 12895 } 12896 // Delete the updated package 12897 outInfo.isRemovedPackageSystemUpdate = true; 12898 if (disabledPs.versionCode < newPs.versionCode) { 12899 // Delete data for downgrades 12900 flags &= ~PackageManager.DELETE_KEEP_DATA; 12901 } else { 12902 // Preserve data by setting flag 12903 flags |= PackageManager.DELETE_KEEP_DATA; 12904 } 12905 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 12906 allUserHandles, perUserInstalled, outInfo, writeSettings); 12907 if (!ret) { 12908 return false; 12909 } 12910 // writer 12911 synchronized (mPackages) { 12912 // Reinstate the old system package 12913 mSettings.enableSystemPackageLPw(newPs.name); 12914 // Remove any native libraries from the upgraded package. 12915 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 12916 } 12917 // Install the system package 12918 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 12919 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 12920 if (locationIsPrivileged(disabledPs.codePath)) { 12921 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12922 } 12923 12924 final PackageParser.Package newPkg; 12925 try { 12926 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 12927 } catch (PackageManagerException e) { 12928 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 12929 return false; 12930 } 12931 12932 // writer 12933 synchronized (mPackages) { 12934 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 12935 12936 updatePermissionsLPw(newPkg.packageName, newPkg, 12937 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 12938 12939 if (applyUserRestrictions) { 12940 if (DEBUG_REMOVE) { 12941 Slog.d(TAG, "Propagating install state across reinstall"); 12942 } 12943 for (int i = 0; i < allUserHandles.length; i++) { 12944 if (DEBUG_REMOVE) { 12945 Slog.d(TAG, " user " + allUserHandles[i] 12946 + " => " + perUserInstalled[i]); 12947 } 12948 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12949 12950 mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false); 12951 } 12952 // Regardless of writeSettings we need to ensure that this restriction 12953 // state propagation is persisted 12954 mSettings.writeAllUsersPackageRestrictionsLPr(); 12955 } 12956 // can downgrade to reader here 12957 if (writeSettings) { 12958 mSettings.writeLPr(); 12959 } 12960 } 12961 return true; 12962 } 12963 12964 private boolean deleteInstalledPackageLI(PackageSetting ps, 12965 boolean deleteCodeAndResources, int flags, 12966 int[] allUserHandles, boolean[] perUserInstalled, 12967 PackageRemovedInfo outInfo, boolean writeSettings) { 12968 if (outInfo != null) { 12969 outInfo.uid = ps.appId; 12970 } 12971 12972 // Delete package data from internal structures and also remove data if flag is set 12973 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 12974 12975 // Delete application code and resources 12976 if (deleteCodeAndResources && (outInfo != null)) { 12977 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 12978 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 12979 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 12980 } 12981 return true; 12982 } 12983 12984 @Override 12985 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 12986 int userId) { 12987 mContext.enforceCallingOrSelfPermission( 12988 android.Manifest.permission.DELETE_PACKAGES, null); 12989 synchronized (mPackages) { 12990 PackageSetting ps = mSettings.mPackages.get(packageName); 12991 if (ps == null) { 12992 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 12993 return false; 12994 } 12995 if (!ps.getInstalled(userId)) { 12996 // Can't block uninstall for an app that is not installed or enabled. 12997 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 12998 return false; 12999 } 13000 ps.setBlockUninstall(blockUninstall, userId); 13001 mSettings.writePackageRestrictionsLPr(userId); 13002 } 13003 return true; 13004 } 13005 13006 @Override 13007 public boolean getBlockUninstallForUser(String packageName, int userId) { 13008 synchronized (mPackages) { 13009 PackageSetting ps = mSettings.mPackages.get(packageName); 13010 if (ps == null) { 13011 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 13012 return false; 13013 } 13014 return ps.getBlockUninstall(userId); 13015 } 13016 } 13017 13018 /* 13019 * This method handles package deletion in general 13020 */ 13021 private boolean deletePackageLI(String packageName, UserHandle user, 13022 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 13023 int flags, PackageRemovedInfo outInfo, 13024 boolean writeSettings) { 13025 if (packageName == null) { 13026 Slog.w(TAG, "Attempt to delete null packageName."); 13027 return false; 13028 } 13029 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 13030 PackageSetting ps; 13031 boolean dataOnly = false; 13032 int removeUser = -1; 13033 int appId = -1; 13034 synchronized (mPackages) { 13035 ps = mSettings.mPackages.get(packageName); 13036 if (ps == null) { 13037 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13038 return false; 13039 } 13040 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 13041 && user.getIdentifier() != UserHandle.USER_ALL) { 13042 // The caller is asking that the package only be deleted for a single 13043 // user. To do this, we just mark its uninstalled state and delete 13044 // its data. If this is a system app, we only allow this to happen if 13045 // they have set the special DELETE_SYSTEM_APP which requests different 13046 // semantics than normal for uninstalling system apps. 13047 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 13048 ps.setUserState(user.getIdentifier(), 13049 COMPONENT_ENABLED_STATE_DEFAULT, 13050 false, //installed 13051 true, //stopped 13052 true, //notLaunched 13053 false, //hidden 13054 null, null, null, 13055 false, // blockUninstall 13056 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED, 0); 13057 if (!isSystemApp(ps)) { 13058 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 13059 // Other user still have this package installed, so all 13060 // we need to do is clear this user's data and save that 13061 // it is uninstalled. 13062 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 13063 removeUser = user.getIdentifier(); 13064 appId = ps.appId; 13065 scheduleWritePackageRestrictionsLocked(removeUser); 13066 } else { 13067 // We need to set it back to 'installed' so the uninstall 13068 // broadcasts will be sent correctly. 13069 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 13070 ps.setInstalled(true, user.getIdentifier()); 13071 } 13072 } else { 13073 // This is a system app, so we assume that the 13074 // other users still have this package installed, so all 13075 // we need to do is clear this user's data and save that 13076 // it is uninstalled. 13077 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 13078 removeUser = user.getIdentifier(); 13079 appId = ps.appId; 13080 scheduleWritePackageRestrictionsLocked(removeUser); 13081 } 13082 } 13083 } 13084 13085 if (removeUser >= 0) { 13086 // From above, we determined that we are deleting this only 13087 // for a single user. Continue the work here. 13088 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 13089 if (outInfo != null) { 13090 outInfo.removedPackage = packageName; 13091 outInfo.removedAppId = appId; 13092 outInfo.removedUsers = new int[] {removeUser}; 13093 } 13094 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 13095 removeKeystoreDataIfNeeded(removeUser, appId); 13096 schedulePackageCleaning(packageName, removeUser, false); 13097 synchronized (mPackages) { 13098 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 13099 scheduleWritePackageRestrictionsLocked(removeUser); 13100 } 13101 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser); 13102 } 13103 return true; 13104 } 13105 13106 if (dataOnly) { 13107 // Delete application data first 13108 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 13109 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 13110 return true; 13111 } 13112 13113 boolean ret = false; 13114 if (isSystemApp(ps)) { 13115 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 13116 // When an updated system application is deleted we delete the existing resources as well and 13117 // fall back to existing code in system partition 13118 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 13119 flags, outInfo, writeSettings); 13120 } else { 13121 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 13122 // Kill application pre-emptively especially for apps on sd. 13123 killApplication(packageName, ps.appId, "uninstall pkg"); 13124 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 13125 allUserHandles, perUserInstalled, 13126 outInfo, writeSettings); 13127 } 13128 13129 return ret; 13130 } 13131 13132 private final class ClearStorageConnection implements ServiceConnection { 13133 IMediaContainerService mContainerService; 13134 13135 @Override 13136 public void onServiceConnected(ComponentName name, IBinder service) { 13137 synchronized (this) { 13138 mContainerService = IMediaContainerService.Stub.asInterface(service); 13139 notifyAll(); 13140 } 13141 } 13142 13143 @Override 13144 public void onServiceDisconnected(ComponentName name) { 13145 } 13146 } 13147 13148 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 13149 final boolean mounted; 13150 if (Environment.isExternalStorageEmulated()) { 13151 mounted = true; 13152 } else { 13153 final String status = Environment.getExternalStorageState(); 13154 13155 mounted = status.equals(Environment.MEDIA_MOUNTED) 13156 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 13157 } 13158 13159 if (!mounted) { 13160 return; 13161 } 13162 13163 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 13164 int[] users; 13165 if (userId == UserHandle.USER_ALL) { 13166 users = sUserManager.getUserIds(); 13167 } else { 13168 users = new int[] { userId }; 13169 } 13170 final ClearStorageConnection conn = new ClearStorageConnection(); 13171 if (mContext.bindServiceAsUser( 13172 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 13173 try { 13174 for (int curUser : users) { 13175 long timeout = SystemClock.uptimeMillis() + 5000; 13176 synchronized (conn) { 13177 long now = SystemClock.uptimeMillis(); 13178 while (conn.mContainerService == null && now < timeout) { 13179 try { 13180 conn.wait(timeout - now); 13181 } catch (InterruptedException e) { 13182 } 13183 } 13184 } 13185 if (conn.mContainerService == null) { 13186 return; 13187 } 13188 13189 final UserEnvironment userEnv = new UserEnvironment(curUser); 13190 clearDirectory(conn.mContainerService, 13191 userEnv.buildExternalStorageAppCacheDirs(packageName)); 13192 if (allData) { 13193 clearDirectory(conn.mContainerService, 13194 userEnv.buildExternalStorageAppDataDirs(packageName)); 13195 clearDirectory(conn.mContainerService, 13196 userEnv.buildExternalStorageAppMediaDirs(packageName)); 13197 } 13198 } 13199 } finally { 13200 mContext.unbindService(conn); 13201 } 13202 } 13203 } 13204 13205 @Override 13206 public void clearApplicationUserData(final String packageName, 13207 final IPackageDataObserver observer, final int userId) { 13208 mContext.enforceCallingOrSelfPermission( 13209 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 13210 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 13211 // Queue up an async operation since the package deletion may take a little while. 13212 mHandler.post(new Runnable() { 13213 public void run() { 13214 mHandler.removeCallbacks(this); 13215 final boolean succeeded; 13216 synchronized (mInstallLock) { 13217 succeeded = clearApplicationUserDataLI(packageName, userId); 13218 } 13219 clearExternalStorageDataSync(packageName, userId, true); 13220 if (succeeded) { 13221 // invoke DeviceStorageMonitor's update method to clear any notifications 13222 DeviceStorageMonitorInternal 13223 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13224 if (dsm != null) { 13225 dsm.checkMemory(); 13226 } 13227 } 13228 if(observer != null) { 13229 try { 13230 observer.onRemoveCompleted(packageName, succeeded); 13231 } catch (RemoteException e) { 13232 Log.i(TAG, "Observer no longer exists."); 13233 } 13234 } //end if observer 13235 } //end run 13236 }); 13237 } 13238 13239 private boolean clearApplicationUserDataLI(String packageName, int userId) { 13240 if (packageName == null) { 13241 Slog.w(TAG, "Attempt to delete null packageName."); 13242 return false; 13243 } 13244 13245 // Try finding details about the requested package 13246 PackageParser.Package pkg; 13247 synchronized (mPackages) { 13248 pkg = mPackages.get(packageName); 13249 if (pkg == null) { 13250 final PackageSetting ps = mSettings.mPackages.get(packageName); 13251 if (ps != null) { 13252 pkg = ps.pkg; 13253 } 13254 } 13255 13256 if (pkg == null) { 13257 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13258 return false; 13259 } 13260 13261 PackageSetting ps = (PackageSetting) pkg.mExtras; 13262 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 13263 } 13264 13265 // Always delete data directories for package, even if we found no other 13266 // record of app. This helps users recover from UID mismatches without 13267 // resorting to a full data wipe. 13268 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 13269 if (retCode < 0) { 13270 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 13271 return false; 13272 } 13273 13274 final int appId = pkg.applicationInfo.uid; 13275 removeKeystoreDataIfNeeded(userId, appId); 13276 13277 // Create a native library symlink only if we have native libraries 13278 // and if the native libraries are 32 bit libraries. We do not provide 13279 // this symlink for 64 bit libraries. 13280 if (pkg.applicationInfo.primaryCpuAbi != null && 13281 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 13282 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 13283 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 13284 nativeLibPath, userId) < 0) { 13285 Slog.w(TAG, "Failed linking native library dir"); 13286 return false; 13287 } 13288 } 13289 13290 return true; 13291 } 13292 13293 /** 13294 * Reverts user permission state changes (permissions and flags) in 13295 * all packages for a given user. 13296 * 13297 * @param userId The device user for which to do a reset. 13298 */ 13299 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 13300 final int packageCount = mPackages.size(); 13301 for (int i = 0; i < packageCount; i++) { 13302 PackageParser.Package pkg = mPackages.valueAt(i); 13303 PackageSetting ps = (PackageSetting) pkg.mExtras; 13304 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 13305 } 13306 } 13307 13308 /** 13309 * Reverts user permission state changes (permissions and flags). 13310 * 13311 * @param ps The package for which to reset. 13312 * @param userId The device user for which to do a reset. 13313 */ 13314 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 13315 final PackageSetting ps, final int userId) { 13316 if (ps.pkg == null) { 13317 return; 13318 } 13319 13320 final int userSettableFlags = FLAG_PERMISSION_USER_SET 13321 | FLAG_PERMISSION_USER_FIXED 13322 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 13323 13324 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 13325 | FLAG_PERMISSION_POLICY_FIXED; 13326 13327 boolean writeInstallPermissions = false; 13328 boolean writeRuntimePermissions = false; 13329 13330 final int permissionCount = ps.pkg.requestedPermissions.size(); 13331 for (int i = 0; i < permissionCount; i++) { 13332 String permission = ps.pkg.requestedPermissions.get(i); 13333 13334 BasePermission bp = mSettings.mPermissions.get(permission); 13335 if (bp == null) { 13336 continue; 13337 } 13338 13339 // If shared user we just reset the state to which only this app contributed. 13340 if (ps.sharedUser != null) { 13341 boolean used = false; 13342 final int packageCount = ps.sharedUser.packages.size(); 13343 for (int j = 0; j < packageCount; j++) { 13344 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 13345 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 13346 && pkg.pkg.requestedPermissions.contains(permission)) { 13347 used = true; 13348 break; 13349 } 13350 } 13351 if (used) { 13352 continue; 13353 } 13354 } 13355 13356 PermissionsState permissionsState = ps.getPermissionsState(); 13357 13358 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 13359 13360 // Always clear the user settable flags. 13361 final boolean hasInstallState = permissionsState.getInstallPermissionState( 13362 bp.name) != null; 13363 if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) { 13364 if (hasInstallState) { 13365 writeInstallPermissions = true; 13366 } else { 13367 writeRuntimePermissions = true; 13368 } 13369 } 13370 13371 // Below is only runtime permission handling. 13372 if (!bp.isRuntime()) { 13373 continue; 13374 } 13375 13376 // Never clobber system or policy. 13377 if ((oldFlags & policyOrSystemFlags) != 0) { 13378 continue; 13379 } 13380 13381 // If this permission was granted by default, make sure it is. 13382 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 13383 if (permissionsState.grantRuntimePermission(bp, userId) 13384 != PERMISSION_OPERATION_FAILURE) { 13385 writeRuntimePermissions = true; 13386 } 13387 } else { 13388 // Otherwise, reset the permission. 13389 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 13390 switch (revokeResult) { 13391 case PERMISSION_OPERATION_SUCCESS: { 13392 writeRuntimePermissions = true; 13393 } break; 13394 13395 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 13396 writeRuntimePermissions = true; 13397 // If gids changed for this user, kill all affected packages. 13398 mHandler.post(new Runnable() { 13399 @Override 13400 public void run() { 13401 // This has to happen with no lock held. 13402 killSettingPackagesForUser(ps, userId, 13403 KILL_APP_REASON_GIDS_CHANGED); 13404 } 13405 }); 13406 } break; 13407 } 13408 } 13409 } 13410 13411 // Synchronously write as we are taking permissions away. 13412 if (writeRuntimePermissions) { 13413 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 13414 } 13415 13416 // Synchronously write as we are taking permissions away. 13417 if (writeInstallPermissions) { 13418 mSettings.writeLPr(); 13419 } 13420 } 13421 13422 /** 13423 * Remove entries from the keystore daemon. Will only remove it if the 13424 * {@code appId} is valid. 13425 */ 13426 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 13427 if (appId < 0) { 13428 return; 13429 } 13430 13431 final KeyStore keyStore = KeyStore.getInstance(); 13432 if (keyStore != null) { 13433 if (userId == UserHandle.USER_ALL) { 13434 for (final int individual : sUserManager.getUserIds()) { 13435 keyStore.clearUid(UserHandle.getUid(individual, appId)); 13436 } 13437 } else { 13438 keyStore.clearUid(UserHandle.getUid(userId, appId)); 13439 } 13440 } else { 13441 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 13442 } 13443 } 13444 13445 @Override 13446 public void deleteApplicationCacheFiles(final String packageName, 13447 final IPackageDataObserver observer) { 13448 mContext.enforceCallingOrSelfPermission( 13449 android.Manifest.permission.DELETE_CACHE_FILES, null); 13450 // Queue up an async operation since the package deletion may take a little while. 13451 final int userId = UserHandle.getCallingUserId(); 13452 mHandler.post(new Runnable() { 13453 public void run() { 13454 mHandler.removeCallbacks(this); 13455 final boolean succeded; 13456 synchronized (mInstallLock) { 13457 succeded = deleteApplicationCacheFilesLI(packageName, userId); 13458 } 13459 clearExternalStorageDataSync(packageName, userId, false); 13460 if (observer != null) { 13461 try { 13462 observer.onRemoveCompleted(packageName, succeded); 13463 } catch (RemoteException e) { 13464 Log.i(TAG, "Observer no longer exists."); 13465 } 13466 } //end if observer 13467 } //end run 13468 }); 13469 } 13470 13471 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 13472 if (packageName == null) { 13473 Slog.w(TAG, "Attempt to delete null packageName."); 13474 return false; 13475 } 13476 PackageParser.Package p; 13477 synchronized (mPackages) { 13478 p = mPackages.get(packageName); 13479 } 13480 if (p == null) { 13481 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13482 return false; 13483 } 13484 final ApplicationInfo applicationInfo = p.applicationInfo; 13485 if (applicationInfo == null) { 13486 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13487 return false; 13488 } 13489 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 13490 if (retCode < 0) { 13491 Slog.w(TAG, "Couldn't remove cache files for package: " 13492 + packageName + " u" + userId); 13493 return false; 13494 } 13495 return true; 13496 } 13497 13498 @Override 13499 public void getPackageSizeInfo(final String packageName, int userHandle, 13500 final IPackageStatsObserver observer) { 13501 mContext.enforceCallingOrSelfPermission( 13502 android.Manifest.permission.GET_PACKAGE_SIZE, null); 13503 if (packageName == null) { 13504 throw new IllegalArgumentException("Attempt to get size of null packageName"); 13505 } 13506 13507 PackageStats stats = new PackageStats(packageName, userHandle); 13508 13509 /* 13510 * Queue up an async operation since the package measurement may take a 13511 * little while. 13512 */ 13513 Message msg = mHandler.obtainMessage(INIT_COPY); 13514 msg.obj = new MeasureParams(stats, observer); 13515 mHandler.sendMessage(msg); 13516 } 13517 13518 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 13519 PackageStats pStats) { 13520 if (packageName == null) { 13521 Slog.w(TAG, "Attempt to get size of null packageName."); 13522 return false; 13523 } 13524 PackageParser.Package p; 13525 boolean dataOnly = false; 13526 String libDirRoot = null; 13527 String asecPath = null; 13528 PackageSetting ps = null; 13529 synchronized (mPackages) { 13530 p = mPackages.get(packageName); 13531 ps = mSettings.mPackages.get(packageName); 13532 if(p == null) { 13533 dataOnly = true; 13534 if((ps == null) || (ps.pkg == null)) { 13535 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13536 return false; 13537 } 13538 p = ps.pkg; 13539 } 13540 if (ps != null) { 13541 libDirRoot = ps.legacyNativeLibraryPathString; 13542 } 13543 if (p != null && (isExternal(p) || p.isForwardLocked())) { 13544 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 13545 if (secureContainerId != null) { 13546 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 13547 } 13548 } 13549 } 13550 String publicSrcDir = null; 13551 if(!dataOnly) { 13552 final ApplicationInfo applicationInfo = p.applicationInfo; 13553 if (applicationInfo == null) { 13554 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13555 return false; 13556 } 13557 if (p.isForwardLocked()) { 13558 publicSrcDir = applicationInfo.getBaseResourcePath(); 13559 } 13560 } 13561 // TODO: extend to measure size of split APKs 13562 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 13563 // not just the first level. 13564 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 13565 // just the primary. 13566 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 13567 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath, 13568 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 13569 if (res < 0) { 13570 return false; 13571 } 13572 13573 // Fix-up for forward-locked applications in ASEC containers. 13574 if (!isExternal(p)) { 13575 pStats.codeSize += pStats.externalCodeSize; 13576 pStats.externalCodeSize = 0L; 13577 } 13578 13579 return true; 13580 } 13581 13582 13583 @Override 13584 public void addPackageToPreferred(String packageName) { 13585 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 13586 } 13587 13588 @Override 13589 public void removePackageFromPreferred(String packageName) { 13590 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 13591 } 13592 13593 @Override 13594 public List<PackageInfo> getPreferredPackages(int flags) { 13595 return new ArrayList<PackageInfo>(); 13596 } 13597 13598 private int getUidTargetSdkVersionLockedLPr(int uid) { 13599 Object obj = mSettings.getUserIdLPr(uid); 13600 if (obj instanceof SharedUserSetting) { 13601 final SharedUserSetting sus = (SharedUserSetting) obj; 13602 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 13603 final Iterator<PackageSetting> it = sus.packages.iterator(); 13604 while (it.hasNext()) { 13605 final PackageSetting ps = it.next(); 13606 if (ps.pkg != null) { 13607 int v = ps.pkg.applicationInfo.targetSdkVersion; 13608 if (v < vers) vers = v; 13609 } 13610 } 13611 return vers; 13612 } else if (obj instanceof PackageSetting) { 13613 final PackageSetting ps = (PackageSetting) obj; 13614 if (ps.pkg != null) { 13615 return ps.pkg.applicationInfo.targetSdkVersion; 13616 } 13617 } 13618 return Build.VERSION_CODES.CUR_DEVELOPMENT; 13619 } 13620 13621 @Override 13622 public void addPreferredActivity(IntentFilter filter, int match, 13623 ComponentName[] set, ComponentName activity, int userId) { 13624 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13625 "Adding preferred"); 13626 } 13627 13628 private void addPreferredActivityInternal(IntentFilter filter, int match, 13629 ComponentName[] set, ComponentName activity, boolean always, int userId, 13630 String opname) { 13631 // writer 13632 int callingUid = Binder.getCallingUid(); 13633 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 13634 if (filter.countActions() == 0) { 13635 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13636 return; 13637 } 13638 synchronized (mPackages) { 13639 if (mContext.checkCallingOrSelfPermission( 13640 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13641 != PackageManager.PERMISSION_GRANTED) { 13642 if (getUidTargetSdkVersionLockedLPr(callingUid) 13643 < Build.VERSION_CODES.FROYO) { 13644 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 13645 + callingUid); 13646 return; 13647 } 13648 mContext.enforceCallingOrSelfPermission( 13649 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13650 } 13651 13652 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 13653 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 13654 + userId + ":"); 13655 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13656 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 13657 scheduleWritePackageRestrictionsLocked(userId); 13658 } 13659 } 13660 13661 @Override 13662 public void replacePreferredActivity(IntentFilter filter, int match, 13663 ComponentName[] set, ComponentName activity, int userId) { 13664 if (filter.countActions() != 1) { 13665 throw new IllegalArgumentException( 13666 "replacePreferredActivity expects filter to have only 1 action."); 13667 } 13668 if (filter.countDataAuthorities() != 0 13669 || filter.countDataPaths() != 0 13670 || filter.countDataSchemes() > 1 13671 || filter.countDataTypes() != 0) { 13672 throw new IllegalArgumentException( 13673 "replacePreferredActivity expects filter to have no data authorities, " + 13674 "paths, or types; and at most one scheme."); 13675 } 13676 13677 final int callingUid = Binder.getCallingUid(); 13678 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 13679 synchronized (mPackages) { 13680 if (mContext.checkCallingOrSelfPermission( 13681 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13682 != PackageManager.PERMISSION_GRANTED) { 13683 if (getUidTargetSdkVersionLockedLPr(callingUid) 13684 < Build.VERSION_CODES.FROYO) { 13685 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 13686 + Binder.getCallingUid()); 13687 return; 13688 } 13689 mContext.enforceCallingOrSelfPermission( 13690 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13691 } 13692 13693 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13694 if (pir != null) { 13695 // Get all of the existing entries that exactly match this filter. 13696 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 13697 if (existing != null && existing.size() == 1) { 13698 PreferredActivity cur = existing.get(0); 13699 if (DEBUG_PREFERRED) { 13700 Slog.i(TAG, "Checking replace of preferred:"); 13701 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13702 if (!cur.mPref.mAlways) { 13703 Slog.i(TAG, " -- CUR; not mAlways!"); 13704 } else { 13705 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 13706 Slog.i(TAG, " -- CUR: mSet=" 13707 + Arrays.toString(cur.mPref.mSetComponents)); 13708 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 13709 Slog.i(TAG, " -- NEW: mMatch=" 13710 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 13711 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 13712 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 13713 } 13714 } 13715 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 13716 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 13717 && cur.mPref.sameSet(set)) { 13718 // Setting the preferred activity to what it happens to be already 13719 if (DEBUG_PREFERRED) { 13720 Slog.i(TAG, "Replacing with same preferred activity " 13721 + cur.mPref.mShortComponent + " for user " 13722 + userId + ":"); 13723 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13724 } 13725 return; 13726 } 13727 } 13728 13729 if (existing != null) { 13730 if (DEBUG_PREFERRED) { 13731 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 13732 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13733 } 13734 for (int i = 0; i < existing.size(); i++) { 13735 PreferredActivity pa = existing.get(i); 13736 if (DEBUG_PREFERRED) { 13737 Slog.i(TAG, "Removing existing preferred activity " 13738 + pa.mPref.mComponent + ":"); 13739 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 13740 } 13741 pir.removeFilter(pa); 13742 } 13743 } 13744 } 13745 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13746 "Replacing preferred"); 13747 } 13748 } 13749 13750 @Override 13751 public void clearPackagePreferredActivities(String packageName) { 13752 final int uid = Binder.getCallingUid(); 13753 // writer 13754 synchronized (mPackages) { 13755 PackageParser.Package pkg = mPackages.get(packageName); 13756 if (pkg == null || pkg.applicationInfo.uid != uid) { 13757 if (mContext.checkCallingOrSelfPermission( 13758 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13759 != PackageManager.PERMISSION_GRANTED) { 13760 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 13761 < Build.VERSION_CODES.FROYO) { 13762 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 13763 + Binder.getCallingUid()); 13764 return; 13765 } 13766 mContext.enforceCallingOrSelfPermission( 13767 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13768 } 13769 } 13770 13771 int user = UserHandle.getCallingUserId(); 13772 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 13773 scheduleWritePackageRestrictionsLocked(user); 13774 } 13775 } 13776 } 13777 13778 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13779 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 13780 ArrayList<PreferredActivity> removed = null; 13781 boolean changed = false; 13782 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13783 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 13784 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13785 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 13786 continue; 13787 } 13788 Iterator<PreferredActivity> it = pir.filterIterator(); 13789 while (it.hasNext()) { 13790 PreferredActivity pa = it.next(); 13791 // Mark entry for removal only if it matches the package name 13792 // and the entry is of type "always". 13793 if (packageName == null || 13794 (pa.mPref.mComponent.getPackageName().equals(packageName) 13795 && pa.mPref.mAlways)) { 13796 if (removed == null) { 13797 removed = new ArrayList<PreferredActivity>(); 13798 } 13799 removed.add(pa); 13800 } 13801 } 13802 if (removed != null) { 13803 for (int j=0; j<removed.size(); j++) { 13804 PreferredActivity pa = removed.get(j); 13805 pir.removeFilter(pa); 13806 } 13807 changed = true; 13808 } 13809 } 13810 return changed; 13811 } 13812 13813 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13814 private void clearIntentFilterVerificationsLPw(int userId) { 13815 final int packageCount = mPackages.size(); 13816 for (int i = 0; i < packageCount; i++) { 13817 PackageParser.Package pkg = mPackages.valueAt(i); 13818 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 13819 } 13820 } 13821 13822 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13823 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 13824 if (userId == UserHandle.USER_ALL) { 13825 if (mSettings.removeIntentFilterVerificationLPw(packageName, 13826 sUserManager.getUserIds())) { 13827 for (int oneUserId : sUserManager.getUserIds()) { 13828 scheduleWritePackageRestrictionsLocked(oneUserId); 13829 } 13830 } 13831 } else { 13832 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 13833 scheduleWritePackageRestrictionsLocked(userId); 13834 } 13835 } 13836 } 13837 13838 void clearDefaultBrowserIfNeeded(String packageName) { 13839 for (int oneUserId : sUserManager.getUserIds()) { 13840 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 13841 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 13842 if (packageName.equals(defaultBrowserPackageName)) { 13843 setDefaultBrowserPackageName(null, oneUserId); 13844 } 13845 } 13846 } 13847 13848 @Override 13849 public void resetApplicationPreferences(int userId) { 13850 mContext.enforceCallingOrSelfPermission( 13851 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13852 // writer 13853 synchronized (mPackages) { 13854 final long identity = Binder.clearCallingIdentity(); 13855 try { 13856 clearPackagePreferredActivitiesLPw(null, userId); 13857 mSettings.applyDefaultPreferredAppsLPw(this, userId); 13858 // TODO: We have to reset the default SMS and Phone. This requires 13859 // significant refactoring to keep all default apps in the package 13860 // manager (cleaner but more work) or have the services provide 13861 // callbacks to the package manager to request a default app reset. 13862 applyFactoryDefaultBrowserLPw(userId); 13863 clearIntentFilterVerificationsLPw(userId); 13864 primeDomainVerificationsLPw(userId); 13865 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 13866 scheduleWritePackageRestrictionsLocked(userId); 13867 } finally { 13868 Binder.restoreCallingIdentity(identity); 13869 } 13870 } 13871 } 13872 13873 @Override 13874 public int getPreferredActivities(List<IntentFilter> outFilters, 13875 List<ComponentName> outActivities, String packageName) { 13876 13877 int num = 0; 13878 final int userId = UserHandle.getCallingUserId(); 13879 // reader 13880 synchronized (mPackages) { 13881 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13882 if (pir != null) { 13883 final Iterator<PreferredActivity> it = pir.filterIterator(); 13884 while (it.hasNext()) { 13885 final PreferredActivity pa = it.next(); 13886 if (packageName == null 13887 || (pa.mPref.mComponent.getPackageName().equals(packageName) 13888 && pa.mPref.mAlways)) { 13889 if (outFilters != null) { 13890 outFilters.add(new IntentFilter(pa)); 13891 } 13892 if (outActivities != null) { 13893 outActivities.add(pa.mPref.mComponent); 13894 } 13895 } 13896 } 13897 } 13898 } 13899 13900 return num; 13901 } 13902 13903 @Override 13904 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 13905 int userId) { 13906 int callingUid = Binder.getCallingUid(); 13907 if (callingUid != Process.SYSTEM_UID) { 13908 throw new SecurityException( 13909 "addPersistentPreferredActivity can only be run by the system"); 13910 } 13911 if (filter.countActions() == 0) { 13912 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13913 return; 13914 } 13915 synchronized (mPackages) { 13916 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 13917 " :"); 13918 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13919 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 13920 new PersistentPreferredActivity(filter, activity)); 13921 scheduleWritePackageRestrictionsLocked(userId); 13922 } 13923 } 13924 13925 @Override 13926 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 13927 int callingUid = Binder.getCallingUid(); 13928 if (callingUid != Process.SYSTEM_UID) { 13929 throw new SecurityException( 13930 "clearPackagePersistentPreferredActivities can only be run by the system"); 13931 } 13932 ArrayList<PersistentPreferredActivity> removed = null; 13933 boolean changed = false; 13934 synchronized (mPackages) { 13935 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 13936 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 13937 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 13938 .valueAt(i); 13939 if (userId != thisUserId) { 13940 continue; 13941 } 13942 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 13943 while (it.hasNext()) { 13944 PersistentPreferredActivity ppa = it.next(); 13945 // Mark entry for removal only if it matches the package name. 13946 if (ppa.mComponent.getPackageName().equals(packageName)) { 13947 if (removed == null) { 13948 removed = new ArrayList<PersistentPreferredActivity>(); 13949 } 13950 removed.add(ppa); 13951 } 13952 } 13953 if (removed != null) { 13954 for (int j=0; j<removed.size(); j++) { 13955 PersistentPreferredActivity ppa = removed.get(j); 13956 ppir.removeFilter(ppa); 13957 } 13958 changed = true; 13959 } 13960 } 13961 13962 if (changed) { 13963 scheduleWritePackageRestrictionsLocked(userId); 13964 } 13965 } 13966 } 13967 13968 /** 13969 * Common machinery for picking apart a restored XML blob and passing 13970 * it to a caller-supplied functor to be applied to the running system. 13971 */ 13972 private void restoreFromXml(XmlPullParser parser, int userId, 13973 String expectedStartTag, BlobXmlRestorer functor) 13974 throws IOException, XmlPullParserException { 13975 int type; 13976 while ((type = parser.next()) != XmlPullParser.START_TAG 13977 && type != XmlPullParser.END_DOCUMENT) { 13978 } 13979 if (type != XmlPullParser.START_TAG) { 13980 // oops didn't find a start tag?! 13981 if (DEBUG_BACKUP) { 13982 Slog.e(TAG, "Didn't find start tag during restore"); 13983 } 13984 return; 13985 } 13986 13987 // this is supposed to be TAG_PREFERRED_BACKUP 13988 if (!expectedStartTag.equals(parser.getName())) { 13989 if (DEBUG_BACKUP) { 13990 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 13991 } 13992 return; 13993 } 13994 13995 // skip interfering stuff, then we're aligned with the backing implementation 13996 while ((type = parser.next()) == XmlPullParser.TEXT) { } 13997 functor.apply(parser, userId); 13998 } 13999 14000 private interface BlobXmlRestorer { 14001 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 14002 } 14003 14004 /** 14005 * Non-Binder method, support for the backup/restore mechanism: write the 14006 * full set of preferred activities in its canonical XML format. Returns the 14007 * XML output as a byte array, or null if there is none. 14008 */ 14009 @Override 14010 public byte[] getPreferredActivityBackup(int userId) { 14011 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14012 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 14013 } 14014 14015 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14016 try { 14017 final XmlSerializer serializer = new FastXmlSerializer(); 14018 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14019 serializer.startDocument(null, true); 14020 serializer.startTag(null, TAG_PREFERRED_BACKUP); 14021 14022 synchronized (mPackages) { 14023 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 14024 } 14025 14026 serializer.endTag(null, TAG_PREFERRED_BACKUP); 14027 serializer.endDocument(); 14028 serializer.flush(); 14029 } catch (Exception e) { 14030 if (DEBUG_BACKUP) { 14031 Slog.e(TAG, "Unable to write preferred activities for backup", e); 14032 } 14033 return null; 14034 } 14035 14036 return dataStream.toByteArray(); 14037 } 14038 14039 @Override 14040 public void restorePreferredActivities(byte[] backup, int userId) { 14041 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14042 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14043 } 14044 14045 try { 14046 final XmlPullParser parser = Xml.newPullParser(); 14047 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14048 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 14049 new BlobXmlRestorer() { 14050 @Override 14051 public void apply(XmlPullParser parser, int userId) 14052 throws XmlPullParserException, IOException { 14053 synchronized (mPackages) { 14054 mSettings.readPreferredActivitiesLPw(parser, userId); 14055 } 14056 } 14057 } ); 14058 } catch (Exception e) { 14059 if (DEBUG_BACKUP) { 14060 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14061 } 14062 } 14063 } 14064 14065 /** 14066 * Non-Binder method, support for the backup/restore mechanism: write the 14067 * default browser (etc) settings in its canonical XML format. Returns the default 14068 * browser XML representation as a byte array, or null if there is none. 14069 */ 14070 @Override 14071 public byte[] getDefaultAppsBackup(int userId) { 14072 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14073 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 14074 } 14075 14076 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14077 try { 14078 final XmlSerializer serializer = new FastXmlSerializer(); 14079 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14080 serializer.startDocument(null, true); 14081 serializer.startTag(null, TAG_DEFAULT_APPS); 14082 14083 synchronized (mPackages) { 14084 mSettings.writeDefaultAppsLPr(serializer, userId); 14085 } 14086 14087 serializer.endTag(null, TAG_DEFAULT_APPS); 14088 serializer.endDocument(); 14089 serializer.flush(); 14090 } catch (Exception e) { 14091 if (DEBUG_BACKUP) { 14092 Slog.e(TAG, "Unable to write default apps for backup", e); 14093 } 14094 return null; 14095 } 14096 14097 return dataStream.toByteArray(); 14098 } 14099 14100 @Override 14101 public void restoreDefaultApps(byte[] backup, int userId) { 14102 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14103 throw new SecurityException("Only the system may call restoreDefaultApps()"); 14104 } 14105 14106 try { 14107 final XmlPullParser parser = Xml.newPullParser(); 14108 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14109 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 14110 new BlobXmlRestorer() { 14111 @Override 14112 public void apply(XmlPullParser parser, int userId) 14113 throws XmlPullParserException, IOException { 14114 synchronized (mPackages) { 14115 mSettings.readDefaultAppsLPw(parser, userId); 14116 } 14117 } 14118 } ); 14119 } catch (Exception e) { 14120 if (DEBUG_BACKUP) { 14121 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 14122 } 14123 } 14124 } 14125 14126 @Override 14127 public byte[] getIntentFilterVerificationBackup(int userId) { 14128 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14129 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 14130 } 14131 14132 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14133 try { 14134 final XmlSerializer serializer = new FastXmlSerializer(); 14135 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14136 serializer.startDocument(null, true); 14137 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 14138 14139 synchronized (mPackages) { 14140 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 14141 } 14142 14143 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 14144 serializer.endDocument(); 14145 serializer.flush(); 14146 } catch (Exception e) { 14147 if (DEBUG_BACKUP) { 14148 Slog.e(TAG, "Unable to write default apps for backup", e); 14149 } 14150 return null; 14151 } 14152 14153 return dataStream.toByteArray(); 14154 } 14155 14156 @Override 14157 public void restoreIntentFilterVerification(byte[] backup, int userId) { 14158 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14159 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14160 } 14161 14162 try { 14163 final XmlPullParser parser = Xml.newPullParser(); 14164 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14165 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 14166 new BlobXmlRestorer() { 14167 @Override 14168 public void apply(XmlPullParser parser, int userId) 14169 throws XmlPullParserException, IOException { 14170 synchronized (mPackages) { 14171 mSettings.readAllDomainVerificationsLPr(parser, userId); 14172 mSettings.writeLPr(); 14173 } 14174 } 14175 } ); 14176 } catch (Exception e) { 14177 if (DEBUG_BACKUP) { 14178 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14179 } 14180 } 14181 } 14182 14183 @Override 14184 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 14185 int sourceUserId, int targetUserId, int flags) { 14186 mContext.enforceCallingOrSelfPermission( 14187 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14188 int callingUid = Binder.getCallingUid(); 14189 enforceOwnerRights(ownerPackage, callingUid); 14190 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14191 if (intentFilter.countActions() == 0) { 14192 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 14193 return; 14194 } 14195 synchronized (mPackages) { 14196 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 14197 ownerPackage, targetUserId, flags); 14198 CrossProfileIntentResolver resolver = 14199 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14200 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 14201 // We have all those whose filter is equal. Now checking if the rest is equal as well. 14202 if (existing != null) { 14203 int size = existing.size(); 14204 for (int i = 0; i < size; i++) { 14205 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 14206 return; 14207 } 14208 } 14209 } 14210 resolver.addFilter(newFilter); 14211 scheduleWritePackageRestrictionsLocked(sourceUserId); 14212 } 14213 } 14214 14215 @Override 14216 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 14217 mContext.enforceCallingOrSelfPermission( 14218 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14219 int callingUid = Binder.getCallingUid(); 14220 enforceOwnerRights(ownerPackage, callingUid); 14221 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14222 synchronized (mPackages) { 14223 CrossProfileIntentResolver resolver = 14224 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14225 ArraySet<CrossProfileIntentFilter> set = 14226 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 14227 for (CrossProfileIntentFilter filter : set) { 14228 if (filter.getOwnerPackage().equals(ownerPackage)) { 14229 resolver.removeFilter(filter); 14230 } 14231 } 14232 scheduleWritePackageRestrictionsLocked(sourceUserId); 14233 } 14234 } 14235 14236 // Enforcing that callingUid is owning pkg on userId 14237 private void enforceOwnerRights(String pkg, int callingUid) { 14238 // The system owns everything. 14239 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 14240 return; 14241 } 14242 int callingUserId = UserHandle.getUserId(callingUid); 14243 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 14244 if (pi == null) { 14245 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 14246 + callingUserId); 14247 } 14248 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 14249 throw new SecurityException("Calling uid " + callingUid 14250 + " does not own package " + pkg); 14251 } 14252 } 14253 14254 @Override 14255 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 14256 Intent intent = new Intent(Intent.ACTION_MAIN); 14257 intent.addCategory(Intent.CATEGORY_HOME); 14258 14259 final int callingUserId = UserHandle.getCallingUserId(); 14260 List<ResolveInfo> list = queryIntentActivities(intent, null, 14261 PackageManager.GET_META_DATA, callingUserId); 14262 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 14263 true, false, false, callingUserId); 14264 14265 allHomeCandidates.clear(); 14266 if (list != null) { 14267 for (ResolveInfo ri : list) { 14268 allHomeCandidates.add(ri); 14269 } 14270 } 14271 return (preferred == null || preferred.activityInfo == null) 14272 ? null 14273 : new ComponentName(preferred.activityInfo.packageName, 14274 preferred.activityInfo.name); 14275 } 14276 14277 @Override 14278 public void setApplicationEnabledSetting(String appPackageName, 14279 int newState, int flags, int userId, String callingPackage) { 14280 if (!sUserManager.exists(userId)) return; 14281 if (callingPackage == null) { 14282 callingPackage = Integer.toString(Binder.getCallingUid()); 14283 } 14284 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 14285 } 14286 14287 @Override 14288 public void setComponentEnabledSetting(ComponentName componentName, 14289 int newState, int flags, int userId) { 14290 if (!sUserManager.exists(userId)) return; 14291 setEnabledSetting(componentName.getPackageName(), 14292 componentName.getClassName(), newState, flags, userId, null); 14293 } 14294 14295 private void setEnabledSetting(final String packageName, String className, int newState, 14296 final int flags, int userId, String callingPackage) { 14297 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 14298 || newState == COMPONENT_ENABLED_STATE_ENABLED 14299 || newState == COMPONENT_ENABLED_STATE_DISABLED 14300 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 14301 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 14302 throw new IllegalArgumentException("Invalid new component state: " 14303 + newState); 14304 } 14305 PackageSetting pkgSetting; 14306 final int uid = Binder.getCallingUid(); 14307 final int permission = mContext.checkCallingOrSelfPermission( 14308 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14309 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 14310 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14311 boolean sendNow = false; 14312 boolean isApp = (className == null); 14313 String componentName = isApp ? packageName : className; 14314 int packageUid = -1; 14315 ArrayList<String> components; 14316 14317 // writer 14318 synchronized (mPackages) { 14319 pkgSetting = mSettings.mPackages.get(packageName); 14320 if (pkgSetting == null) { 14321 if (className == null) { 14322 throw new IllegalArgumentException( 14323 "Unknown package: " + packageName); 14324 } 14325 throw new IllegalArgumentException( 14326 "Unknown component: " + packageName 14327 + "/" + className); 14328 } 14329 // Allow root and verify that userId is not being specified by a different user 14330 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 14331 throw new SecurityException( 14332 "Permission Denial: attempt to change component state from pid=" 14333 + Binder.getCallingPid() 14334 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 14335 } 14336 if (className == null) { 14337 // We're dealing with an application/package level state change 14338 if (pkgSetting.getEnabled(userId) == newState) { 14339 // Nothing to do 14340 return; 14341 } 14342 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 14343 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 14344 // Don't care about who enables an app. 14345 callingPackage = null; 14346 } 14347 pkgSetting.setEnabled(newState, userId, callingPackage); 14348 // pkgSetting.pkg.mSetEnabled = newState; 14349 } else { 14350 // We're dealing with a component level state change 14351 // First, verify that this is a valid class name. 14352 PackageParser.Package pkg = pkgSetting.pkg; 14353 if (pkg == null || !pkg.hasComponentClassName(className)) { 14354 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 14355 throw new IllegalArgumentException("Component class " + className 14356 + " does not exist in " + packageName); 14357 } else { 14358 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 14359 + className + " does not exist in " + packageName); 14360 } 14361 } 14362 switch (newState) { 14363 case COMPONENT_ENABLED_STATE_ENABLED: 14364 if (!pkgSetting.enableComponentLPw(className, userId)) { 14365 return; 14366 } 14367 break; 14368 case COMPONENT_ENABLED_STATE_DISABLED: 14369 if (!pkgSetting.disableComponentLPw(className, userId)) { 14370 return; 14371 } 14372 break; 14373 case COMPONENT_ENABLED_STATE_DEFAULT: 14374 if (!pkgSetting.restoreComponentLPw(className, userId)) { 14375 return; 14376 } 14377 break; 14378 default: 14379 Slog.e(TAG, "Invalid new component state: " + newState); 14380 return; 14381 } 14382 } 14383 scheduleWritePackageRestrictionsLocked(userId); 14384 components = mPendingBroadcasts.get(userId, packageName); 14385 final boolean newPackage = components == null; 14386 if (newPackage) { 14387 components = new ArrayList<String>(); 14388 } 14389 if (!components.contains(componentName)) { 14390 components.add(componentName); 14391 } 14392 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 14393 sendNow = true; 14394 // Purge entry from pending broadcast list if another one exists already 14395 // since we are sending one right away. 14396 mPendingBroadcasts.remove(userId, packageName); 14397 } else { 14398 if (newPackage) { 14399 mPendingBroadcasts.put(userId, packageName, components); 14400 } 14401 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 14402 // Schedule a message 14403 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 14404 } 14405 } 14406 } 14407 14408 long callingId = Binder.clearCallingIdentity(); 14409 try { 14410 if (sendNow) { 14411 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 14412 sendPackageChangedBroadcast(packageName, 14413 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 14414 } 14415 } finally { 14416 Binder.restoreCallingIdentity(callingId); 14417 } 14418 } 14419 14420 private void sendPackageChangedBroadcast(String packageName, 14421 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 14422 if (DEBUG_INSTALL) 14423 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 14424 + componentNames); 14425 Bundle extras = new Bundle(4); 14426 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 14427 String nameList[] = new String[componentNames.size()]; 14428 componentNames.toArray(nameList); 14429 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 14430 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 14431 extras.putInt(Intent.EXTRA_UID, packageUid); 14432 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 14433 new int[] {UserHandle.getUserId(packageUid)}); 14434 } 14435 14436 @Override 14437 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 14438 if (!sUserManager.exists(userId)) return; 14439 final int uid = Binder.getCallingUid(); 14440 final int permission = mContext.checkCallingOrSelfPermission( 14441 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14442 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14443 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 14444 // writer 14445 synchronized (mPackages) { 14446 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 14447 allowedByPermission, uid, userId)) { 14448 scheduleWritePackageRestrictionsLocked(userId); 14449 } 14450 } 14451 } 14452 14453 @Override 14454 public String getInstallerPackageName(String packageName) { 14455 // reader 14456 synchronized (mPackages) { 14457 return mSettings.getInstallerPackageNameLPr(packageName); 14458 } 14459 } 14460 14461 @Override 14462 public int getApplicationEnabledSetting(String packageName, int userId) { 14463 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14464 int uid = Binder.getCallingUid(); 14465 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 14466 // reader 14467 synchronized (mPackages) { 14468 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 14469 } 14470 } 14471 14472 @Override 14473 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 14474 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14475 int uid = Binder.getCallingUid(); 14476 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 14477 // reader 14478 synchronized (mPackages) { 14479 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 14480 } 14481 } 14482 14483 @Override 14484 public void enterSafeMode() { 14485 enforceSystemOrRoot("Only the system can request entering safe mode"); 14486 14487 if (!mSystemReady) { 14488 mSafeMode = true; 14489 } 14490 } 14491 14492 @Override 14493 public void systemReady() { 14494 mSystemReady = true; 14495 14496 // Read the compatibilty setting when the system is ready. 14497 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 14498 mContext.getContentResolver(), 14499 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 14500 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 14501 if (DEBUG_SETTINGS) { 14502 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 14503 } 14504 14505 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 14506 14507 synchronized (mPackages) { 14508 // Verify that all of the preferred activity components actually 14509 // exist. It is possible for applications to be updated and at 14510 // that point remove a previously declared activity component that 14511 // had been set as a preferred activity. We try to clean this up 14512 // the next time we encounter that preferred activity, but it is 14513 // possible for the user flow to never be able to return to that 14514 // situation so here we do a sanity check to make sure we haven't 14515 // left any junk around. 14516 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 14517 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14518 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14519 removed.clear(); 14520 for (PreferredActivity pa : pir.filterSet()) { 14521 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 14522 removed.add(pa); 14523 } 14524 } 14525 if (removed.size() > 0) { 14526 for (int r=0; r<removed.size(); r++) { 14527 PreferredActivity pa = removed.get(r); 14528 Slog.w(TAG, "Removing dangling preferred activity: " 14529 + pa.mPref.mComponent); 14530 pir.removeFilter(pa); 14531 } 14532 mSettings.writePackageRestrictionsLPr( 14533 mSettings.mPreferredActivities.keyAt(i)); 14534 } 14535 } 14536 14537 for (int userId : UserManagerService.getInstance().getUserIds()) { 14538 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 14539 grantPermissionsUserIds = ArrayUtils.appendInt( 14540 grantPermissionsUserIds, userId); 14541 } 14542 } 14543 } 14544 sUserManager.systemReady(); 14545 14546 // If we upgraded grant all default permissions before kicking off. 14547 for (int userId : grantPermissionsUserIds) { 14548 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 14549 } 14550 14551 // Kick off any messages waiting for system ready 14552 if (mPostSystemReadyMessages != null) { 14553 for (Message msg : mPostSystemReadyMessages) { 14554 msg.sendToTarget(); 14555 } 14556 mPostSystemReadyMessages = null; 14557 } 14558 14559 // Watch for external volumes that come and go over time 14560 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14561 storage.registerListener(mStorageListener); 14562 14563 mInstallerService.systemReady(); 14564 mPackageDexOptimizer.systemReady(); 14565 14566 MountServiceInternal mountServiceInternal = LocalServices.getService( 14567 MountServiceInternal.class); 14568 mountServiceInternal.addExternalStoragePolicy( 14569 new MountServiceInternal.ExternalStorageMountPolicy() { 14570 @Override 14571 public int getMountMode(int uid, String packageName) { 14572 if (Process.isIsolated(uid)) { 14573 return Zygote.MOUNT_EXTERNAL_NONE; 14574 } 14575 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 14576 return Zygote.MOUNT_EXTERNAL_DEFAULT; 14577 } 14578 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 14579 return Zygote.MOUNT_EXTERNAL_DEFAULT; 14580 } 14581 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 14582 return Zygote.MOUNT_EXTERNAL_READ; 14583 } 14584 return Zygote.MOUNT_EXTERNAL_WRITE; 14585 } 14586 14587 @Override 14588 public boolean hasExternalStorage(int uid, String packageName) { 14589 return true; 14590 } 14591 }); 14592 } 14593 14594 @Override 14595 public boolean isSafeMode() { 14596 return mSafeMode; 14597 } 14598 14599 @Override 14600 public boolean hasSystemUidErrors() { 14601 return mHasSystemUidErrors; 14602 } 14603 14604 static String arrayToString(int[] array) { 14605 StringBuffer buf = new StringBuffer(128); 14606 buf.append('['); 14607 if (array != null) { 14608 for (int i=0; i<array.length; i++) { 14609 if (i > 0) buf.append(", "); 14610 buf.append(array[i]); 14611 } 14612 } 14613 buf.append(']'); 14614 return buf.toString(); 14615 } 14616 14617 static class DumpState { 14618 public static final int DUMP_LIBS = 1 << 0; 14619 public static final int DUMP_FEATURES = 1 << 1; 14620 public static final int DUMP_RESOLVERS = 1 << 2; 14621 public static final int DUMP_PERMISSIONS = 1 << 3; 14622 public static final int DUMP_PACKAGES = 1 << 4; 14623 public static final int DUMP_SHARED_USERS = 1 << 5; 14624 public static final int DUMP_MESSAGES = 1 << 6; 14625 public static final int DUMP_PROVIDERS = 1 << 7; 14626 public static final int DUMP_VERIFIERS = 1 << 8; 14627 public static final int DUMP_PREFERRED = 1 << 9; 14628 public static final int DUMP_PREFERRED_XML = 1 << 10; 14629 public static final int DUMP_KEYSETS = 1 << 11; 14630 public static final int DUMP_VERSION = 1 << 12; 14631 public static final int DUMP_INSTALLS = 1 << 13; 14632 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 14633 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 14634 14635 public static final int OPTION_SHOW_FILTERS = 1 << 0; 14636 14637 private int mTypes; 14638 14639 private int mOptions; 14640 14641 private boolean mTitlePrinted; 14642 14643 private SharedUserSetting mSharedUser; 14644 14645 public boolean isDumping(int type) { 14646 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 14647 return true; 14648 } 14649 14650 return (mTypes & type) != 0; 14651 } 14652 14653 public void setDump(int type) { 14654 mTypes |= type; 14655 } 14656 14657 public boolean isOptionEnabled(int option) { 14658 return (mOptions & option) != 0; 14659 } 14660 14661 public void setOptionEnabled(int option) { 14662 mOptions |= option; 14663 } 14664 14665 public boolean onTitlePrinted() { 14666 final boolean printed = mTitlePrinted; 14667 mTitlePrinted = true; 14668 return printed; 14669 } 14670 14671 public boolean getTitlePrinted() { 14672 return mTitlePrinted; 14673 } 14674 14675 public void setTitlePrinted(boolean enabled) { 14676 mTitlePrinted = enabled; 14677 } 14678 14679 public SharedUserSetting getSharedUser() { 14680 return mSharedUser; 14681 } 14682 14683 public void setSharedUser(SharedUserSetting user) { 14684 mSharedUser = user; 14685 } 14686 } 14687 14688 @Override 14689 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 14690 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 14691 != PackageManager.PERMISSION_GRANTED) { 14692 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 14693 + Binder.getCallingPid() 14694 + ", uid=" + Binder.getCallingUid() 14695 + " without permission " 14696 + android.Manifest.permission.DUMP); 14697 return; 14698 } 14699 14700 DumpState dumpState = new DumpState(); 14701 boolean fullPreferred = false; 14702 boolean checkin = false; 14703 14704 String packageName = null; 14705 ArraySet<String> permissionNames = null; 14706 14707 int opti = 0; 14708 while (opti < args.length) { 14709 String opt = args[opti]; 14710 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 14711 break; 14712 } 14713 opti++; 14714 14715 if ("-a".equals(opt)) { 14716 // Right now we only know how to print all. 14717 } else if ("-h".equals(opt)) { 14718 pw.println("Package manager dump options:"); 14719 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 14720 pw.println(" --checkin: dump for a checkin"); 14721 pw.println(" -f: print details of intent filters"); 14722 pw.println(" -h: print this help"); 14723 pw.println(" cmd may be one of:"); 14724 pw.println(" l[ibraries]: list known shared libraries"); 14725 pw.println(" f[ibraries]: list device features"); 14726 pw.println(" k[eysets]: print known keysets"); 14727 pw.println(" r[esolvers]: dump intent resolvers"); 14728 pw.println(" perm[issions]: dump permissions"); 14729 pw.println(" permission [name ...]: dump declaration and use of given permission"); 14730 pw.println(" pref[erred]: print preferred package settings"); 14731 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 14732 pw.println(" prov[iders]: dump content providers"); 14733 pw.println(" p[ackages]: dump installed packages"); 14734 pw.println(" s[hared-users]: dump shared user IDs"); 14735 pw.println(" m[essages]: print collected runtime messages"); 14736 pw.println(" v[erifiers]: print package verifier info"); 14737 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 14738 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 14739 pw.println(" version: print database version info"); 14740 pw.println(" write: write current settings now"); 14741 pw.println(" installs: details about install sessions"); 14742 pw.println(" <package.name>: info about given package"); 14743 return; 14744 } else if ("--checkin".equals(opt)) { 14745 checkin = true; 14746 } else if ("-f".equals(opt)) { 14747 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14748 } else { 14749 pw.println("Unknown argument: " + opt + "; use -h for help"); 14750 } 14751 } 14752 14753 // Is the caller requesting to dump a particular piece of data? 14754 if (opti < args.length) { 14755 String cmd = args[opti]; 14756 opti++; 14757 // Is this a package name? 14758 if ("android".equals(cmd) || cmd.contains(".")) { 14759 packageName = cmd; 14760 // When dumping a single package, we always dump all of its 14761 // filter information since the amount of data will be reasonable. 14762 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14763 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 14764 dumpState.setDump(DumpState.DUMP_LIBS); 14765 } else if ("f".equals(cmd) || "features".equals(cmd)) { 14766 dumpState.setDump(DumpState.DUMP_FEATURES); 14767 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 14768 dumpState.setDump(DumpState.DUMP_RESOLVERS); 14769 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 14770 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 14771 } else if ("permission".equals(cmd)) { 14772 if (opti >= args.length) { 14773 pw.println("Error: permission requires permission name"); 14774 return; 14775 } 14776 permissionNames = new ArraySet<>(); 14777 while (opti < args.length) { 14778 permissionNames.add(args[opti]); 14779 opti++; 14780 } 14781 dumpState.setDump(DumpState.DUMP_PERMISSIONS 14782 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 14783 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 14784 dumpState.setDump(DumpState.DUMP_PREFERRED); 14785 } else if ("preferred-xml".equals(cmd)) { 14786 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 14787 if (opti < args.length && "--full".equals(args[opti])) { 14788 fullPreferred = true; 14789 opti++; 14790 } 14791 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 14792 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 14793 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 14794 dumpState.setDump(DumpState.DUMP_PACKAGES); 14795 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 14796 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 14797 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 14798 dumpState.setDump(DumpState.DUMP_PROVIDERS); 14799 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 14800 dumpState.setDump(DumpState.DUMP_MESSAGES); 14801 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 14802 dumpState.setDump(DumpState.DUMP_VERIFIERS); 14803 } else if ("i".equals(cmd) || "ifv".equals(cmd) 14804 || "intent-filter-verifiers".equals(cmd)) { 14805 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 14806 } else if ("version".equals(cmd)) { 14807 dumpState.setDump(DumpState.DUMP_VERSION); 14808 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 14809 dumpState.setDump(DumpState.DUMP_KEYSETS); 14810 } else if ("installs".equals(cmd)) { 14811 dumpState.setDump(DumpState.DUMP_INSTALLS); 14812 } else if ("write".equals(cmd)) { 14813 synchronized (mPackages) { 14814 mSettings.writeLPr(); 14815 pw.println("Settings written."); 14816 return; 14817 } 14818 } 14819 } 14820 14821 if (checkin) { 14822 pw.println("vers,1"); 14823 } 14824 14825 // reader 14826 synchronized (mPackages) { 14827 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 14828 if (!checkin) { 14829 if (dumpState.onTitlePrinted()) 14830 pw.println(); 14831 pw.println("Database versions:"); 14832 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 14833 } 14834 } 14835 14836 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 14837 if (!checkin) { 14838 if (dumpState.onTitlePrinted()) 14839 pw.println(); 14840 pw.println("Verifiers:"); 14841 pw.print(" Required: "); 14842 pw.print(mRequiredVerifierPackage); 14843 pw.print(" (uid="); 14844 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 14845 pw.println(")"); 14846 } else if (mRequiredVerifierPackage != null) { 14847 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 14848 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 14849 } 14850 } 14851 14852 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 14853 packageName == null) { 14854 if (mIntentFilterVerifierComponent != null) { 14855 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 14856 if (!checkin) { 14857 if (dumpState.onTitlePrinted()) 14858 pw.println(); 14859 pw.println("Intent Filter Verifier:"); 14860 pw.print(" Using: "); 14861 pw.print(verifierPackageName); 14862 pw.print(" (uid="); 14863 pw.print(getPackageUid(verifierPackageName, 0)); 14864 pw.println(")"); 14865 } else if (verifierPackageName != null) { 14866 pw.print("ifv,"); pw.print(verifierPackageName); 14867 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 14868 } 14869 } else { 14870 pw.println(); 14871 pw.println("No Intent Filter Verifier available!"); 14872 } 14873 } 14874 14875 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 14876 boolean printedHeader = false; 14877 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 14878 while (it.hasNext()) { 14879 String name = it.next(); 14880 SharedLibraryEntry ent = mSharedLibraries.get(name); 14881 if (!checkin) { 14882 if (!printedHeader) { 14883 if (dumpState.onTitlePrinted()) 14884 pw.println(); 14885 pw.println("Libraries:"); 14886 printedHeader = true; 14887 } 14888 pw.print(" "); 14889 } else { 14890 pw.print("lib,"); 14891 } 14892 pw.print(name); 14893 if (!checkin) { 14894 pw.print(" -> "); 14895 } 14896 if (ent.path != null) { 14897 if (!checkin) { 14898 pw.print("(jar) "); 14899 pw.print(ent.path); 14900 } else { 14901 pw.print(",jar,"); 14902 pw.print(ent.path); 14903 } 14904 } else { 14905 if (!checkin) { 14906 pw.print("(apk) "); 14907 pw.print(ent.apk); 14908 } else { 14909 pw.print(",apk,"); 14910 pw.print(ent.apk); 14911 } 14912 } 14913 pw.println(); 14914 } 14915 } 14916 14917 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 14918 if (dumpState.onTitlePrinted()) 14919 pw.println(); 14920 if (!checkin) { 14921 pw.println("Features:"); 14922 } 14923 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 14924 while (it.hasNext()) { 14925 String name = it.next(); 14926 if (!checkin) { 14927 pw.print(" "); 14928 } else { 14929 pw.print("feat,"); 14930 } 14931 pw.println(name); 14932 } 14933 } 14934 14935 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 14936 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 14937 : "Activity Resolver Table:", " ", packageName, 14938 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14939 dumpState.setTitlePrinted(true); 14940 } 14941 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 14942 : "Receiver Resolver Table:", " ", packageName, 14943 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14944 dumpState.setTitlePrinted(true); 14945 } 14946 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 14947 : "Service Resolver Table:", " ", packageName, 14948 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14949 dumpState.setTitlePrinted(true); 14950 } 14951 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 14952 : "Provider Resolver Table:", " ", packageName, 14953 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14954 dumpState.setTitlePrinted(true); 14955 } 14956 } 14957 14958 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 14959 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14960 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14961 int user = mSettings.mPreferredActivities.keyAt(i); 14962 if (pir.dump(pw, 14963 dumpState.getTitlePrinted() 14964 ? "\nPreferred Activities User " + user + ":" 14965 : "Preferred Activities User " + user + ":", " ", 14966 packageName, true, false)) { 14967 dumpState.setTitlePrinted(true); 14968 } 14969 } 14970 } 14971 14972 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 14973 pw.flush(); 14974 FileOutputStream fout = new FileOutputStream(fd); 14975 BufferedOutputStream str = new BufferedOutputStream(fout); 14976 XmlSerializer serializer = new FastXmlSerializer(); 14977 try { 14978 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 14979 serializer.startDocument(null, true); 14980 serializer.setFeature( 14981 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 14982 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 14983 serializer.endDocument(); 14984 serializer.flush(); 14985 } catch (IllegalArgumentException e) { 14986 pw.println("Failed writing: " + e); 14987 } catch (IllegalStateException e) { 14988 pw.println("Failed writing: " + e); 14989 } catch (IOException e) { 14990 pw.println("Failed writing: " + e); 14991 } 14992 } 14993 14994 if (!checkin 14995 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 14996 && packageName == null) { 14997 pw.println(); 14998 int count = mSettings.mPackages.size(); 14999 if (count == 0) { 15000 pw.println("No applications!"); 15001 pw.println(); 15002 } else { 15003 final String prefix = " "; 15004 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 15005 if (allPackageSettings.size() == 0) { 15006 pw.println("No domain preferred apps!"); 15007 pw.println(); 15008 } else { 15009 pw.println("App verification status:"); 15010 pw.println(); 15011 count = 0; 15012 for (PackageSetting ps : allPackageSettings) { 15013 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 15014 if (ivi == null || ivi.getPackageName() == null) continue; 15015 pw.println(prefix + "Package: " + ivi.getPackageName()); 15016 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 15017 pw.println(prefix + "Status: " + ivi.getStatusString()); 15018 pw.println(); 15019 count++; 15020 } 15021 if (count == 0) { 15022 pw.println(prefix + "No app verification established."); 15023 pw.println(); 15024 } 15025 for (int userId : sUserManager.getUserIds()) { 15026 pw.println("App linkages for user " + userId + ":"); 15027 pw.println(); 15028 count = 0; 15029 for (PackageSetting ps : allPackageSettings) { 15030 final long status = ps.getDomainVerificationStatusForUser(userId); 15031 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 15032 continue; 15033 } 15034 pw.println(prefix + "Package: " + ps.name); 15035 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 15036 String statusStr = IntentFilterVerificationInfo. 15037 getStatusStringFromValue(status); 15038 pw.println(prefix + "Status: " + statusStr); 15039 pw.println(); 15040 count++; 15041 } 15042 if (count == 0) { 15043 pw.println(prefix + "No configured app linkages."); 15044 pw.println(); 15045 } 15046 } 15047 } 15048 } 15049 } 15050 15051 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 15052 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 15053 if (packageName == null && permissionNames == null) { 15054 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 15055 if (iperm == 0) { 15056 if (dumpState.onTitlePrinted()) 15057 pw.println(); 15058 pw.println("AppOp Permissions:"); 15059 } 15060 pw.print(" AppOp Permission "); 15061 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 15062 pw.println(":"); 15063 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 15064 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 15065 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 15066 } 15067 } 15068 } 15069 } 15070 15071 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 15072 boolean printedSomething = false; 15073 for (PackageParser.Provider p : mProviders.mProviders.values()) { 15074 if (packageName != null && !packageName.equals(p.info.packageName)) { 15075 continue; 15076 } 15077 if (!printedSomething) { 15078 if (dumpState.onTitlePrinted()) 15079 pw.println(); 15080 pw.println("Registered ContentProviders:"); 15081 printedSomething = true; 15082 } 15083 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 15084 pw.print(" "); pw.println(p.toString()); 15085 } 15086 printedSomething = false; 15087 for (Map.Entry<String, PackageParser.Provider> entry : 15088 mProvidersByAuthority.entrySet()) { 15089 PackageParser.Provider p = entry.getValue(); 15090 if (packageName != null && !packageName.equals(p.info.packageName)) { 15091 continue; 15092 } 15093 if (!printedSomething) { 15094 if (dumpState.onTitlePrinted()) 15095 pw.println(); 15096 pw.println("ContentProvider Authorities:"); 15097 printedSomething = true; 15098 } 15099 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 15100 pw.print(" "); pw.println(p.toString()); 15101 if (p.info != null && p.info.applicationInfo != null) { 15102 final String appInfo = p.info.applicationInfo.toString(); 15103 pw.print(" applicationInfo="); pw.println(appInfo); 15104 } 15105 } 15106 } 15107 15108 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 15109 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 15110 } 15111 15112 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 15113 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 15114 } 15115 15116 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 15117 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 15118 } 15119 15120 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 15121 // XXX should handle packageName != null by dumping only install data that 15122 // the given package is involved with. 15123 if (dumpState.onTitlePrinted()) pw.println(); 15124 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 15125 } 15126 15127 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 15128 if (dumpState.onTitlePrinted()) pw.println(); 15129 mSettings.dumpReadMessagesLPr(pw, dumpState); 15130 15131 pw.println(); 15132 pw.println("Package warning messages:"); 15133 BufferedReader in = null; 15134 String line = null; 15135 try { 15136 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15137 while ((line = in.readLine()) != null) { 15138 if (line.contains("ignored: updated version")) continue; 15139 pw.println(line); 15140 } 15141 } catch (IOException ignored) { 15142 } finally { 15143 IoUtils.closeQuietly(in); 15144 } 15145 } 15146 15147 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 15148 BufferedReader in = null; 15149 String line = null; 15150 try { 15151 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15152 while ((line = in.readLine()) != null) { 15153 if (line.contains("ignored: updated version")) continue; 15154 pw.print("msg,"); 15155 pw.println(line); 15156 } 15157 } catch (IOException ignored) { 15158 } finally { 15159 IoUtils.closeQuietly(in); 15160 } 15161 } 15162 } 15163 } 15164 15165 private String dumpDomainString(String packageName) { 15166 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName); 15167 List<IntentFilter> filters = getAllIntentFilters(packageName); 15168 15169 ArraySet<String> result = new ArraySet<>(); 15170 if (iviList.size() > 0) { 15171 for (IntentFilterVerificationInfo ivi : iviList) { 15172 for (String host : ivi.getDomains()) { 15173 result.add(host); 15174 } 15175 } 15176 } 15177 if (filters != null && filters.size() > 0) { 15178 for (IntentFilter filter : filters) { 15179 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 15180 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 15181 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 15182 result.addAll(filter.getHostsList()); 15183 } 15184 } 15185 } 15186 15187 StringBuilder sb = new StringBuilder(result.size() * 16); 15188 for (String domain : result) { 15189 if (sb.length() > 0) sb.append(" "); 15190 sb.append(domain); 15191 } 15192 return sb.toString(); 15193 } 15194 15195 // ------- apps on sdcard specific code ------- 15196 static final boolean DEBUG_SD_INSTALL = false; 15197 15198 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 15199 15200 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 15201 15202 private boolean mMediaMounted = false; 15203 15204 static String getEncryptKey() { 15205 try { 15206 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 15207 SD_ENCRYPTION_KEYSTORE_NAME); 15208 if (sdEncKey == null) { 15209 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 15210 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 15211 if (sdEncKey == null) { 15212 Slog.e(TAG, "Failed to create encryption keys"); 15213 return null; 15214 } 15215 } 15216 return sdEncKey; 15217 } catch (NoSuchAlgorithmException nsae) { 15218 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 15219 return null; 15220 } catch (IOException ioe) { 15221 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 15222 return null; 15223 } 15224 } 15225 15226 /* 15227 * Update media status on PackageManager. 15228 */ 15229 @Override 15230 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 15231 int callingUid = Binder.getCallingUid(); 15232 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 15233 throw new SecurityException("Media status can only be updated by the system"); 15234 } 15235 // reader; this apparently protects mMediaMounted, but should probably 15236 // be a different lock in that case. 15237 synchronized (mPackages) { 15238 Log.i(TAG, "Updating external media status from " 15239 + (mMediaMounted ? "mounted" : "unmounted") + " to " 15240 + (mediaStatus ? "mounted" : "unmounted")); 15241 if (DEBUG_SD_INSTALL) 15242 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 15243 + ", mMediaMounted=" + mMediaMounted); 15244 if (mediaStatus == mMediaMounted) { 15245 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 15246 : 0, -1); 15247 mHandler.sendMessage(msg); 15248 return; 15249 } 15250 mMediaMounted = mediaStatus; 15251 } 15252 // Queue up an async operation since the package installation may take a 15253 // little while. 15254 mHandler.post(new Runnable() { 15255 public void run() { 15256 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 15257 } 15258 }); 15259 } 15260 15261 /** 15262 * Called by MountService when the initial ASECs to scan are available. 15263 * Should block until all the ASEC containers are finished being scanned. 15264 */ 15265 public void scanAvailableAsecs() { 15266 updateExternalMediaStatusInner(true, false, false); 15267 if (mShouldRestoreconData) { 15268 SELinuxMMAC.setRestoreconDone(); 15269 mShouldRestoreconData = false; 15270 } 15271 } 15272 15273 /* 15274 * Collect information of applications on external media, map them against 15275 * existing containers and update information based on current mount status. 15276 * Please note that we always have to report status if reportStatus has been 15277 * set to true especially when unloading packages. 15278 */ 15279 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 15280 boolean externalStorage) { 15281 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 15282 int[] uidArr = EmptyArray.INT; 15283 15284 final String[] list = PackageHelper.getSecureContainerList(); 15285 if (ArrayUtils.isEmpty(list)) { 15286 Log.i(TAG, "No secure containers found"); 15287 } else { 15288 // Process list of secure containers and categorize them 15289 // as active or stale based on their package internal state. 15290 15291 // reader 15292 synchronized (mPackages) { 15293 for (String cid : list) { 15294 // Leave stages untouched for now; installer service owns them 15295 if (PackageInstallerService.isStageName(cid)) continue; 15296 15297 if (DEBUG_SD_INSTALL) 15298 Log.i(TAG, "Processing container " + cid); 15299 String pkgName = getAsecPackageName(cid); 15300 if (pkgName == null) { 15301 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 15302 continue; 15303 } 15304 if (DEBUG_SD_INSTALL) 15305 Log.i(TAG, "Looking for pkg : " + pkgName); 15306 15307 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15308 if (ps == null) { 15309 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 15310 continue; 15311 } 15312 15313 /* 15314 * Skip packages that are not external if we're unmounting 15315 * external storage. 15316 */ 15317 if (externalStorage && !isMounted && !isExternal(ps)) { 15318 continue; 15319 } 15320 15321 final AsecInstallArgs args = new AsecInstallArgs(cid, 15322 getAppDexInstructionSets(ps), ps.isForwardLocked()); 15323 // The package status is changed only if the code path 15324 // matches between settings and the container id. 15325 if (ps.codePathString != null 15326 && ps.codePathString.startsWith(args.getCodePath())) { 15327 if (DEBUG_SD_INSTALL) { 15328 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 15329 + " at code path: " + ps.codePathString); 15330 } 15331 15332 // We do have a valid package installed on sdcard 15333 processCids.put(args, ps.codePathString); 15334 final int uid = ps.appId; 15335 if (uid != -1) { 15336 uidArr = ArrayUtils.appendInt(uidArr, uid); 15337 } 15338 } else { 15339 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 15340 + ps.codePathString); 15341 } 15342 } 15343 } 15344 15345 Arrays.sort(uidArr); 15346 } 15347 15348 // Process packages with valid entries. 15349 if (isMounted) { 15350 if (DEBUG_SD_INSTALL) 15351 Log.i(TAG, "Loading packages"); 15352 loadMediaPackages(processCids, uidArr); 15353 startCleaningPackages(); 15354 mInstallerService.onSecureContainersAvailable(); 15355 } else { 15356 if (DEBUG_SD_INSTALL) 15357 Log.i(TAG, "Unloading packages"); 15358 unloadMediaPackages(processCids, uidArr, reportStatus); 15359 } 15360 } 15361 15362 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15363 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 15364 final int size = infos.size(); 15365 final String[] packageNames = new String[size]; 15366 final int[] packageUids = new int[size]; 15367 for (int i = 0; i < size; i++) { 15368 final ApplicationInfo info = infos.get(i); 15369 packageNames[i] = info.packageName; 15370 packageUids[i] = info.uid; 15371 } 15372 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 15373 finishedReceiver); 15374 } 15375 15376 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15377 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15378 sendResourcesChangedBroadcast(mediaStatus, replacing, 15379 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 15380 } 15381 15382 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15383 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15384 int size = pkgList.length; 15385 if (size > 0) { 15386 // Send broadcasts here 15387 Bundle extras = new Bundle(); 15388 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 15389 if (uidArr != null) { 15390 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 15391 } 15392 if (replacing) { 15393 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 15394 } 15395 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 15396 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 15397 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 15398 } 15399 } 15400 15401 /* 15402 * Look at potentially valid container ids from processCids If package 15403 * information doesn't match the one on record or package scanning fails, 15404 * the cid is added to list of removeCids. We currently don't delete stale 15405 * containers. 15406 */ 15407 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 15408 ArrayList<String> pkgList = new ArrayList<String>(); 15409 Set<AsecInstallArgs> keys = processCids.keySet(); 15410 15411 for (AsecInstallArgs args : keys) { 15412 String codePath = processCids.get(args); 15413 if (DEBUG_SD_INSTALL) 15414 Log.i(TAG, "Loading container : " + args.cid); 15415 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15416 try { 15417 // Make sure there are no container errors first. 15418 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 15419 Slog.e(TAG, "Failed to mount cid : " + args.cid 15420 + " when installing from sdcard"); 15421 continue; 15422 } 15423 // Check code path here. 15424 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 15425 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 15426 + " does not match one in settings " + codePath); 15427 continue; 15428 } 15429 // Parse package 15430 int parseFlags = mDefParseFlags; 15431 if (args.isExternalAsec()) { 15432 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 15433 } 15434 if (args.isFwdLocked()) { 15435 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 15436 } 15437 15438 synchronized (mInstallLock) { 15439 PackageParser.Package pkg = null; 15440 try { 15441 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 15442 } catch (PackageManagerException e) { 15443 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 15444 } 15445 // Scan the package 15446 if (pkg != null) { 15447 /* 15448 * TODO why is the lock being held? doPostInstall is 15449 * called in other places without the lock. This needs 15450 * to be straightened out. 15451 */ 15452 // writer 15453 synchronized (mPackages) { 15454 retCode = PackageManager.INSTALL_SUCCEEDED; 15455 pkgList.add(pkg.packageName); 15456 // Post process args 15457 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 15458 pkg.applicationInfo.uid); 15459 } 15460 } else { 15461 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 15462 } 15463 } 15464 15465 } finally { 15466 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 15467 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 15468 } 15469 } 15470 } 15471 // writer 15472 synchronized (mPackages) { 15473 // If the platform SDK has changed since the last time we booted, 15474 // we need to re-grant app permission to catch any new ones that 15475 // appear. This is really a hack, and means that apps can in some 15476 // cases get permissions that the user didn't initially explicitly 15477 // allow... it would be nice to have some better way to handle 15478 // this situation. 15479 final VersionInfo ver = mSettings.getExternalVersion(); 15480 15481 int updateFlags = UPDATE_PERMISSIONS_ALL; 15482 if (ver.sdkVersion != mSdkVersion) { 15483 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 15484 + mSdkVersion + "; regranting permissions for external"); 15485 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 15486 } 15487 updatePermissionsLPw(null, null, updateFlags); 15488 15489 // Yay, everything is now upgraded 15490 ver.forceCurrent(); 15491 15492 // can downgrade to reader 15493 // Persist settings 15494 mSettings.writeLPr(); 15495 } 15496 // Send a broadcast to let everyone know we are done processing 15497 if (pkgList.size() > 0) { 15498 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 15499 } 15500 } 15501 15502 /* 15503 * Utility method to unload a list of specified containers 15504 */ 15505 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 15506 // Just unmount all valid containers. 15507 for (AsecInstallArgs arg : cidArgs) { 15508 synchronized (mInstallLock) { 15509 arg.doPostDeleteLI(false); 15510 } 15511 } 15512 } 15513 15514 /* 15515 * Unload packages mounted on external media. This involves deleting package 15516 * data from internal structures, sending broadcasts about diabled packages, 15517 * gc'ing to free up references, unmounting all secure containers 15518 * corresponding to packages on external media, and posting a 15519 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 15520 * that we always have to post this message if status has been requested no 15521 * matter what. 15522 */ 15523 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 15524 final boolean reportStatus) { 15525 if (DEBUG_SD_INSTALL) 15526 Log.i(TAG, "unloading media packages"); 15527 ArrayList<String> pkgList = new ArrayList<String>(); 15528 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 15529 final Set<AsecInstallArgs> keys = processCids.keySet(); 15530 for (AsecInstallArgs args : keys) { 15531 String pkgName = args.getPackageName(); 15532 if (DEBUG_SD_INSTALL) 15533 Log.i(TAG, "Trying to unload pkg : " + pkgName); 15534 // Delete package internally 15535 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15536 synchronized (mInstallLock) { 15537 boolean res = deletePackageLI(pkgName, null, false, null, null, 15538 PackageManager.DELETE_KEEP_DATA, outInfo, false); 15539 if (res) { 15540 pkgList.add(pkgName); 15541 } else { 15542 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 15543 failedList.add(args); 15544 } 15545 } 15546 } 15547 15548 // reader 15549 synchronized (mPackages) { 15550 // We didn't update the settings after removing each package; 15551 // write them now for all packages. 15552 mSettings.writeLPr(); 15553 } 15554 15555 // We have to absolutely send UPDATED_MEDIA_STATUS only 15556 // after confirming that all the receivers processed the ordered 15557 // broadcast when packages get disabled, force a gc to clean things up. 15558 // and unload all the containers. 15559 if (pkgList.size() > 0) { 15560 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 15561 new IIntentReceiver.Stub() { 15562 public void performReceive(Intent intent, int resultCode, String data, 15563 Bundle extras, boolean ordered, boolean sticky, 15564 int sendingUser) throws RemoteException { 15565 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 15566 reportStatus ? 1 : 0, 1, keys); 15567 mHandler.sendMessage(msg); 15568 } 15569 }); 15570 } else { 15571 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 15572 keys); 15573 mHandler.sendMessage(msg); 15574 } 15575 } 15576 15577 private void loadPrivatePackages(VolumeInfo vol) { 15578 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 15579 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 15580 synchronized (mInstallLock) { 15581 synchronized (mPackages) { 15582 final VersionInfo ver = mSettings.findOrCreateVersion(vol.fsUuid); 15583 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15584 for (PackageSetting ps : packages) { 15585 final PackageParser.Package pkg; 15586 try { 15587 pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null); 15588 loaded.add(pkg.applicationInfo); 15589 } catch (PackageManagerException e) { 15590 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 15591 } 15592 15593 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 15594 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 15595 } 15596 } 15597 15598 int updateFlags = UPDATE_PERMISSIONS_ALL; 15599 if (ver.sdkVersion != mSdkVersion) { 15600 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 15601 + mSdkVersion + "; regranting permissions for " + vol.fsUuid); 15602 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 15603 } 15604 updatePermissionsLPw(null, null, updateFlags); 15605 15606 // Yay, everything is now upgraded 15607 ver.forceCurrent(); 15608 15609 mSettings.writeLPr(); 15610 } 15611 } 15612 15613 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 15614 sendResourcesChangedBroadcast(true, false, loaded, null); 15615 } 15616 15617 private void unloadPrivatePackages(VolumeInfo vol) { 15618 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 15619 synchronized (mInstallLock) { 15620 synchronized (mPackages) { 15621 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15622 for (PackageSetting ps : packages) { 15623 if (ps.pkg == null) continue; 15624 15625 final ApplicationInfo info = ps.pkg.applicationInfo; 15626 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15627 if (deletePackageLI(ps.name, null, false, null, null, 15628 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 15629 unloaded.add(info); 15630 } else { 15631 Slog.w(TAG, "Failed to unload " + ps.codePath); 15632 } 15633 } 15634 15635 mSettings.writeLPr(); 15636 } 15637 } 15638 15639 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 15640 sendResourcesChangedBroadcast(false, false, unloaded, null); 15641 } 15642 15643 /** 15644 * Examine all users present on given mounted volume, and destroy data 15645 * belonging to users that are no longer valid, or whose user ID has been 15646 * recycled. 15647 */ 15648 private void reconcileUsers(String volumeUuid) { 15649 final File[] files = FileUtils 15650 .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid)); 15651 for (File file : files) { 15652 if (!file.isDirectory()) continue; 15653 15654 final int userId; 15655 final UserInfo info; 15656 try { 15657 userId = Integer.parseInt(file.getName()); 15658 info = sUserManager.getUserInfo(userId); 15659 } catch (NumberFormatException e) { 15660 Slog.w(TAG, "Invalid user directory " + file); 15661 continue; 15662 } 15663 15664 boolean destroyUser = false; 15665 if (info == null) { 15666 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15667 + " because no matching user was found"); 15668 destroyUser = true; 15669 } else { 15670 try { 15671 UserManagerService.enforceSerialNumber(file, info.serialNumber); 15672 } catch (IOException e) { 15673 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15674 + " because we failed to enforce serial number: " + e); 15675 destroyUser = true; 15676 } 15677 } 15678 15679 if (destroyUser) { 15680 synchronized (mInstallLock) { 15681 mInstaller.removeUserDataDirs(volumeUuid, userId); 15682 } 15683 } 15684 } 15685 15686 final UserManager um = mContext.getSystemService(UserManager.class); 15687 for (UserInfo user : um.getUsers()) { 15688 final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id); 15689 if (userDir.exists()) continue; 15690 15691 try { 15692 UserManagerService.prepareUserDirectory(userDir); 15693 UserManagerService.enforceSerialNumber(userDir, user.serialNumber); 15694 } catch (IOException e) { 15695 Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e); 15696 } 15697 } 15698 } 15699 15700 /** 15701 * Examine all apps present on given mounted volume, and destroy apps that 15702 * aren't expected, either due to uninstallation or reinstallation on 15703 * another volume. 15704 */ 15705 private void reconcileApps(String volumeUuid) { 15706 final File[] files = FileUtils 15707 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 15708 for (File file : files) { 15709 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 15710 && !PackageInstallerService.isStageName(file.getName()); 15711 if (!isPackage) { 15712 // Ignore entries which are not packages 15713 continue; 15714 } 15715 15716 boolean destroyApp = false; 15717 String packageName = null; 15718 try { 15719 final PackageLite pkg = PackageParser.parsePackageLite(file, 15720 PackageParser.PARSE_MUST_BE_APK); 15721 packageName = pkg.packageName; 15722 15723 synchronized (mPackages) { 15724 final PackageSetting ps = mSettings.mPackages.get(packageName); 15725 if (ps == null) { 15726 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + " 15727 + volumeUuid + " because we found no install record"); 15728 destroyApp = true; 15729 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 15730 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on " 15731 + volumeUuid + " because we expected it on " + ps.volumeUuid); 15732 destroyApp = true; 15733 } 15734 } 15735 15736 } catch (PackageParserException e) { 15737 logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e); 15738 destroyApp = true; 15739 } 15740 15741 if (destroyApp) { 15742 synchronized (mInstallLock) { 15743 if (packageName != null) { 15744 removeDataDirsLI(volumeUuid, packageName); 15745 } 15746 if (file.isDirectory()) { 15747 mInstaller.rmPackageDir(file.getAbsolutePath()); 15748 } else { 15749 file.delete(); 15750 } 15751 } 15752 } 15753 } 15754 } 15755 15756 private void unfreezePackage(String packageName) { 15757 synchronized (mPackages) { 15758 final PackageSetting ps = mSettings.mPackages.get(packageName); 15759 if (ps != null) { 15760 ps.frozen = false; 15761 } 15762 } 15763 } 15764 15765 @Override 15766 public int movePackage(final String packageName, final String volumeUuid) { 15767 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15768 15769 final int moveId = mNextMoveId.getAndIncrement(); 15770 try { 15771 movePackageInternal(packageName, volumeUuid, moveId); 15772 } catch (PackageManagerException e) { 15773 Slog.w(TAG, "Failed to move " + packageName, e); 15774 mMoveCallbacks.notifyStatusChanged(moveId, 15775 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15776 } 15777 return moveId; 15778 } 15779 15780 private void movePackageInternal(final String packageName, final String volumeUuid, 15781 final int moveId) throws PackageManagerException { 15782 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 15783 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15784 final PackageManager pm = mContext.getPackageManager(); 15785 15786 final boolean currentAsec; 15787 final String currentVolumeUuid; 15788 final File codeFile; 15789 final String installerPackageName; 15790 final String packageAbiOverride; 15791 final int appId; 15792 final String seinfo; 15793 final String label; 15794 15795 // reader 15796 synchronized (mPackages) { 15797 final PackageParser.Package pkg = mPackages.get(packageName); 15798 final PackageSetting ps = mSettings.mPackages.get(packageName); 15799 if (pkg == null || ps == null) { 15800 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 15801 } 15802 15803 if (pkg.applicationInfo.isSystemApp()) { 15804 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 15805 "Cannot move system application"); 15806 } 15807 15808 if (Objects.equals(ps.volumeUuid, volumeUuid)) { 15809 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15810 "Package already moved to " + volumeUuid); 15811 } 15812 15813 final File probe = new File(pkg.codePath); 15814 final File probeOat = new File(probe, "oat"); 15815 if (!probe.isDirectory() || !probeOat.isDirectory()) { 15816 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15817 "Move only supported for modern cluster style installs"); 15818 } 15819 15820 if (ps.frozen) { 15821 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 15822 "Failed to move already frozen package"); 15823 } 15824 ps.frozen = true; 15825 15826 currentAsec = pkg.applicationInfo.isForwardLocked() 15827 || pkg.applicationInfo.isExternalAsec(); 15828 currentVolumeUuid = ps.volumeUuid; 15829 codeFile = new File(pkg.codePath); 15830 installerPackageName = ps.installerPackageName; 15831 packageAbiOverride = ps.cpuAbiOverrideString; 15832 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 15833 seinfo = pkg.applicationInfo.seinfo; 15834 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 15835 } 15836 15837 // Now that we're guarded by frozen state, kill app during move 15838 final long token = Binder.clearCallingIdentity(); 15839 try { 15840 killApplication(packageName, appId, "move pkg"); 15841 } finally { 15842 Binder.restoreCallingIdentity(token); 15843 } 15844 15845 final Bundle extras = new Bundle(); 15846 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 15847 extras.putString(Intent.EXTRA_TITLE, label); 15848 mMoveCallbacks.notifyCreated(moveId, extras); 15849 15850 int installFlags; 15851 final boolean moveCompleteApp; 15852 final File measurePath; 15853 15854 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 15855 installFlags = INSTALL_INTERNAL; 15856 moveCompleteApp = !currentAsec; 15857 measurePath = Environment.getDataAppDirectory(volumeUuid); 15858 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 15859 installFlags = INSTALL_EXTERNAL; 15860 moveCompleteApp = false; 15861 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 15862 } else { 15863 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 15864 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 15865 || !volume.isMountedWritable()) { 15866 unfreezePackage(packageName); 15867 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15868 "Move location not mounted private volume"); 15869 } 15870 15871 Preconditions.checkState(!currentAsec); 15872 15873 installFlags = INSTALL_INTERNAL; 15874 moveCompleteApp = true; 15875 measurePath = Environment.getDataAppDirectory(volumeUuid); 15876 } 15877 15878 final PackageStats stats = new PackageStats(null, -1); 15879 synchronized (mInstaller) { 15880 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 15881 unfreezePackage(packageName); 15882 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15883 "Failed to measure package size"); 15884 } 15885 } 15886 15887 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 15888 + stats.dataSize); 15889 15890 final long startFreeBytes = measurePath.getFreeSpace(); 15891 final long sizeBytes; 15892 if (moveCompleteApp) { 15893 sizeBytes = stats.codeSize + stats.dataSize; 15894 } else { 15895 sizeBytes = stats.codeSize; 15896 } 15897 15898 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 15899 unfreezePackage(packageName); 15900 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15901 "Not enough free space to move"); 15902 } 15903 15904 mMoveCallbacks.notifyStatusChanged(moveId, 10); 15905 15906 final CountDownLatch installedLatch = new CountDownLatch(1); 15907 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 15908 @Override 15909 public void onUserActionRequired(Intent intent) throws RemoteException { 15910 throw new IllegalStateException(); 15911 } 15912 15913 @Override 15914 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 15915 Bundle extras) throws RemoteException { 15916 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 15917 + PackageManager.installStatusToString(returnCode, msg)); 15918 15919 installedLatch.countDown(); 15920 15921 // Regardless of success or failure of the move operation, 15922 // always unfreeze the package 15923 unfreezePackage(packageName); 15924 15925 final int status = PackageManager.installStatusToPublicStatus(returnCode); 15926 switch (status) { 15927 case PackageInstaller.STATUS_SUCCESS: 15928 mMoveCallbacks.notifyStatusChanged(moveId, 15929 PackageManager.MOVE_SUCCEEDED); 15930 break; 15931 case PackageInstaller.STATUS_FAILURE_STORAGE: 15932 mMoveCallbacks.notifyStatusChanged(moveId, 15933 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 15934 break; 15935 default: 15936 mMoveCallbacks.notifyStatusChanged(moveId, 15937 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15938 break; 15939 } 15940 } 15941 }; 15942 15943 final MoveInfo move; 15944 if (moveCompleteApp) { 15945 // Kick off a thread to report progress estimates 15946 new Thread() { 15947 @Override 15948 public void run() { 15949 while (true) { 15950 try { 15951 if (installedLatch.await(1, TimeUnit.SECONDS)) { 15952 break; 15953 } 15954 } catch (InterruptedException ignored) { 15955 } 15956 15957 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 15958 final int progress = 10 + (int) MathUtils.constrain( 15959 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 15960 mMoveCallbacks.notifyStatusChanged(moveId, progress); 15961 } 15962 } 15963 }.start(); 15964 15965 final String dataAppName = codeFile.getName(); 15966 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 15967 dataAppName, appId, seinfo); 15968 } else { 15969 move = null; 15970 } 15971 15972 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 15973 15974 final Message msg = mHandler.obtainMessage(INIT_COPY); 15975 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 15976 msg.obj = new InstallParams(origin, move, installObserver, installFlags, 15977 installerPackageName, volumeUuid, null, user, packageAbiOverride, null); 15978 mHandler.sendMessage(msg); 15979 } 15980 15981 @Override 15982 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 15983 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15984 15985 final int realMoveId = mNextMoveId.getAndIncrement(); 15986 final Bundle extras = new Bundle(); 15987 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 15988 mMoveCallbacks.notifyCreated(realMoveId, extras); 15989 15990 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 15991 @Override 15992 public void onCreated(int moveId, Bundle extras) { 15993 // Ignored 15994 } 15995 15996 @Override 15997 public void onStatusChanged(int moveId, int status, long estMillis) { 15998 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 15999 } 16000 }; 16001 16002 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16003 storage.setPrimaryStorageUuid(volumeUuid, callback); 16004 return realMoveId; 16005 } 16006 16007 @Override 16008 public int getMoveStatus(int moveId) { 16009 mContext.enforceCallingOrSelfPermission( 16010 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16011 return mMoveCallbacks.mLastStatus.get(moveId); 16012 } 16013 16014 @Override 16015 public void registerMoveCallback(IPackageMoveObserver callback) { 16016 mContext.enforceCallingOrSelfPermission( 16017 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16018 mMoveCallbacks.register(callback); 16019 } 16020 16021 @Override 16022 public void unregisterMoveCallback(IPackageMoveObserver callback) { 16023 mContext.enforceCallingOrSelfPermission( 16024 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16025 mMoveCallbacks.unregister(callback); 16026 } 16027 16028 @Override 16029 public boolean setInstallLocation(int loc) { 16030 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 16031 null); 16032 if (getInstallLocation() == loc) { 16033 return true; 16034 } 16035 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 16036 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 16037 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 16038 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 16039 return true; 16040 } 16041 return false; 16042 } 16043 16044 @Override 16045 public int getInstallLocation() { 16046 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 16047 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 16048 PackageHelper.APP_INSTALL_AUTO); 16049 } 16050 16051 /** Called by UserManagerService */ 16052 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 16053 mDirtyUsers.remove(userHandle); 16054 mSettings.removeUserLPw(userHandle); 16055 mPendingBroadcasts.remove(userHandle); 16056 if (mInstaller != null) { 16057 // Technically, we shouldn't be doing this with the package lock 16058 // held. However, this is very rare, and there is already so much 16059 // other disk I/O going on, that we'll let it slide for now. 16060 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16061 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 16062 final String volumeUuid = vol.getFsUuid(); 16063 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 16064 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 16065 } 16066 } 16067 mUserNeedsBadging.delete(userHandle); 16068 removeUnusedPackagesLILPw(userManager, userHandle); 16069 } 16070 16071 /** 16072 * We're removing userHandle and would like to remove any downloaded packages 16073 * that are no longer in use by any other user. 16074 * @param userHandle the user being removed 16075 */ 16076 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 16077 final boolean DEBUG_CLEAN_APKS = false; 16078 int [] users = userManager.getUserIdsLPr(); 16079 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 16080 while (psit.hasNext()) { 16081 PackageSetting ps = psit.next(); 16082 if (ps.pkg == null) { 16083 continue; 16084 } 16085 final String packageName = ps.pkg.packageName; 16086 // Skip over if system app 16087 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 16088 continue; 16089 } 16090 if (DEBUG_CLEAN_APKS) { 16091 Slog.i(TAG, "Checking package " + packageName); 16092 } 16093 boolean keep = false; 16094 for (int i = 0; i < users.length; i++) { 16095 if (users[i] != userHandle && ps.getInstalled(users[i])) { 16096 keep = true; 16097 if (DEBUG_CLEAN_APKS) { 16098 Slog.i(TAG, " Keeping package " + packageName + " for user " 16099 + users[i]); 16100 } 16101 break; 16102 } 16103 } 16104 if (!keep) { 16105 if (DEBUG_CLEAN_APKS) { 16106 Slog.i(TAG, " Removing package " + packageName); 16107 } 16108 mHandler.post(new Runnable() { 16109 public void run() { 16110 deletePackageX(packageName, userHandle, 0); 16111 } //end run 16112 }); 16113 } 16114 } 16115 } 16116 16117 /** Called by UserManagerService */ 16118 void createNewUserLILPw(int userHandle) { 16119 if (mInstaller != null) { 16120 mInstaller.createUserConfig(userHandle); 16121 mSettings.createNewUserLILPw(this, mInstaller, userHandle); 16122 applyFactoryDefaultBrowserLPw(userHandle); 16123 primeDomainVerificationsLPw(userHandle); 16124 } 16125 } 16126 16127 void newUserCreated(final int userHandle) { 16128 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 16129 } 16130 16131 @Override 16132 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 16133 mContext.enforceCallingOrSelfPermission( 16134 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 16135 "Only package verification agents can read the verifier device identity"); 16136 16137 synchronized (mPackages) { 16138 return mSettings.getVerifierDeviceIdentityLPw(); 16139 } 16140 } 16141 16142 @Override 16143 public void setPermissionEnforced(String permission, boolean enforced) { 16144 // TODO: Now that we no longer change GID for storage, this should to away. 16145 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 16146 "setPermissionEnforced"); 16147 if (READ_EXTERNAL_STORAGE.equals(permission)) { 16148 synchronized (mPackages) { 16149 if (mSettings.mReadExternalStorageEnforced == null 16150 || mSettings.mReadExternalStorageEnforced != enforced) { 16151 mSettings.mReadExternalStorageEnforced = enforced; 16152 mSettings.writeLPr(); 16153 } 16154 } 16155 // kill any non-foreground processes so we restart them and 16156 // grant/revoke the GID. 16157 final IActivityManager am = ActivityManagerNative.getDefault(); 16158 if (am != null) { 16159 final long token = Binder.clearCallingIdentity(); 16160 try { 16161 am.killProcessesBelowForeground("setPermissionEnforcement"); 16162 } catch (RemoteException e) { 16163 } finally { 16164 Binder.restoreCallingIdentity(token); 16165 } 16166 } 16167 } else { 16168 throw new IllegalArgumentException("No selective enforcement for " + permission); 16169 } 16170 } 16171 16172 @Override 16173 @Deprecated 16174 public boolean isPermissionEnforced(String permission) { 16175 return true; 16176 } 16177 16178 @Override 16179 public boolean isStorageLow() { 16180 final long token = Binder.clearCallingIdentity(); 16181 try { 16182 final DeviceStorageMonitorInternal 16183 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 16184 if (dsm != null) { 16185 return dsm.isMemoryLow(); 16186 } else { 16187 return false; 16188 } 16189 } finally { 16190 Binder.restoreCallingIdentity(token); 16191 } 16192 } 16193 16194 @Override 16195 public IPackageInstaller getPackageInstaller() { 16196 return mInstallerService; 16197 } 16198 16199 private boolean userNeedsBadging(int userId) { 16200 int index = mUserNeedsBadging.indexOfKey(userId); 16201 if (index < 0) { 16202 final UserInfo userInfo; 16203 final long token = Binder.clearCallingIdentity(); 16204 try { 16205 userInfo = sUserManager.getUserInfo(userId); 16206 } finally { 16207 Binder.restoreCallingIdentity(token); 16208 } 16209 final boolean b; 16210 if (userInfo != null && userInfo.isManagedProfile()) { 16211 b = true; 16212 } else { 16213 b = false; 16214 } 16215 mUserNeedsBadging.put(userId, b); 16216 return b; 16217 } 16218 return mUserNeedsBadging.valueAt(index); 16219 } 16220 16221 @Override 16222 public KeySet getKeySetByAlias(String packageName, String alias) { 16223 if (packageName == null || alias == null) { 16224 return null; 16225 } 16226 synchronized(mPackages) { 16227 final PackageParser.Package pkg = mPackages.get(packageName); 16228 if (pkg == null) { 16229 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16230 throw new IllegalArgumentException("Unknown package: " + packageName); 16231 } 16232 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16233 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 16234 } 16235 } 16236 16237 @Override 16238 public KeySet getSigningKeySet(String packageName) { 16239 if (packageName == null) { 16240 return null; 16241 } 16242 synchronized(mPackages) { 16243 final PackageParser.Package pkg = mPackages.get(packageName); 16244 if (pkg == null) { 16245 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16246 throw new IllegalArgumentException("Unknown package: " + packageName); 16247 } 16248 if (pkg.applicationInfo.uid != Binder.getCallingUid() 16249 && Process.SYSTEM_UID != Binder.getCallingUid()) { 16250 throw new SecurityException("May not access signing KeySet of other apps."); 16251 } 16252 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16253 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 16254 } 16255 } 16256 16257 @Override 16258 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 16259 if (packageName == null || ks == null) { 16260 return false; 16261 } 16262 synchronized(mPackages) { 16263 final PackageParser.Package pkg = mPackages.get(packageName); 16264 if (pkg == null) { 16265 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16266 throw new IllegalArgumentException("Unknown package: " + packageName); 16267 } 16268 IBinder ksh = ks.getToken(); 16269 if (ksh instanceof KeySetHandle) { 16270 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16271 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 16272 } 16273 return false; 16274 } 16275 } 16276 16277 @Override 16278 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 16279 if (packageName == null || ks == null) { 16280 return false; 16281 } 16282 synchronized(mPackages) { 16283 final PackageParser.Package pkg = mPackages.get(packageName); 16284 if (pkg == null) { 16285 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16286 throw new IllegalArgumentException("Unknown package: " + packageName); 16287 } 16288 IBinder ksh = ks.getToken(); 16289 if (ksh instanceof KeySetHandle) { 16290 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16291 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 16292 } 16293 return false; 16294 } 16295 } 16296 16297 public void getUsageStatsIfNoPackageUsageInfo() { 16298 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 16299 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 16300 if (usm == null) { 16301 throw new IllegalStateException("UsageStatsManager must be initialized"); 16302 } 16303 long now = System.currentTimeMillis(); 16304 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 16305 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 16306 String packageName = entry.getKey(); 16307 PackageParser.Package pkg = mPackages.get(packageName); 16308 if (pkg == null) { 16309 continue; 16310 } 16311 UsageStats usage = entry.getValue(); 16312 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 16313 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 16314 } 16315 } 16316 } 16317 16318 /** 16319 * Check and throw if the given before/after packages would be considered a 16320 * downgrade. 16321 */ 16322 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 16323 throws PackageManagerException { 16324 if (after.versionCode < before.mVersionCode) { 16325 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16326 "Update version code " + after.versionCode + " is older than current " 16327 + before.mVersionCode); 16328 } else if (after.versionCode == before.mVersionCode) { 16329 if (after.baseRevisionCode < before.baseRevisionCode) { 16330 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16331 "Update base revision code " + after.baseRevisionCode 16332 + " is older than current " + before.baseRevisionCode); 16333 } 16334 16335 if (!ArrayUtils.isEmpty(after.splitNames)) { 16336 for (int i = 0; i < after.splitNames.length; i++) { 16337 final String splitName = after.splitNames[i]; 16338 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 16339 if (j != -1) { 16340 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 16341 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16342 "Update split " + splitName + " revision code " 16343 + after.splitRevisionCodes[i] + " is older than current " 16344 + before.splitRevisionCodes[j]); 16345 } 16346 } 16347 } 16348 } 16349 } 16350 } 16351 16352 private static class MoveCallbacks extends Handler { 16353 private static final int MSG_CREATED = 1; 16354 private static final int MSG_STATUS_CHANGED = 2; 16355 16356 private final RemoteCallbackList<IPackageMoveObserver> 16357 mCallbacks = new RemoteCallbackList<>(); 16358 16359 private final SparseIntArray mLastStatus = new SparseIntArray(); 16360 16361 public MoveCallbacks(Looper looper) { 16362 super(looper); 16363 } 16364 16365 public void register(IPackageMoveObserver callback) { 16366 mCallbacks.register(callback); 16367 } 16368 16369 public void unregister(IPackageMoveObserver callback) { 16370 mCallbacks.unregister(callback); 16371 } 16372 16373 @Override 16374 public void handleMessage(Message msg) { 16375 final SomeArgs args = (SomeArgs) msg.obj; 16376 final int n = mCallbacks.beginBroadcast(); 16377 for (int i = 0; i < n; i++) { 16378 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 16379 try { 16380 invokeCallback(callback, msg.what, args); 16381 } catch (RemoteException ignored) { 16382 } 16383 } 16384 mCallbacks.finishBroadcast(); 16385 args.recycle(); 16386 } 16387 16388 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 16389 throws RemoteException { 16390 switch (what) { 16391 case MSG_CREATED: { 16392 callback.onCreated(args.argi1, (Bundle) args.arg2); 16393 break; 16394 } 16395 case MSG_STATUS_CHANGED: { 16396 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 16397 break; 16398 } 16399 } 16400 } 16401 16402 private void notifyCreated(int moveId, Bundle extras) { 16403 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 16404 16405 final SomeArgs args = SomeArgs.obtain(); 16406 args.argi1 = moveId; 16407 args.arg2 = extras; 16408 obtainMessage(MSG_CREATED, args).sendToTarget(); 16409 } 16410 16411 private void notifyStatusChanged(int moveId, int status) { 16412 notifyStatusChanged(moveId, status, -1); 16413 } 16414 16415 private void notifyStatusChanged(int moveId, int status, long estMillis) { 16416 Slog.v(TAG, "Move " + moveId + " status " + status); 16417 16418 final SomeArgs args = SomeArgs.obtain(); 16419 args.argi1 = moveId; 16420 args.argi2 = status; 16421 args.arg3 = estMillis; 16422 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 16423 16424 synchronized (mLastStatus) { 16425 mLastStatus.put(moveId, status); 16426 } 16427 } 16428 } 16429 16430 private final class OnPermissionChangeListeners extends Handler { 16431 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 16432 16433 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 16434 new RemoteCallbackList<>(); 16435 16436 public OnPermissionChangeListeners(Looper looper) { 16437 super(looper); 16438 } 16439 16440 @Override 16441 public void handleMessage(Message msg) { 16442 switch (msg.what) { 16443 case MSG_ON_PERMISSIONS_CHANGED: { 16444 final int uid = msg.arg1; 16445 handleOnPermissionsChanged(uid); 16446 } break; 16447 } 16448 } 16449 16450 public void addListenerLocked(IOnPermissionsChangeListener listener) { 16451 mPermissionListeners.register(listener); 16452 16453 } 16454 16455 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 16456 mPermissionListeners.unregister(listener); 16457 } 16458 16459 public void onPermissionsChanged(int uid) { 16460 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 16461 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 16462 } 16463 } 16464 16465 private void handleOnPermissionsChanged(int uid) { 16466 final int count = mPermissionListeners.beginBroadcast(); 16467 try { 16468 for (int i = 0; i < count; i++) { 16469 IOnPermissionsChangeListener callback = mPermissionListeners 16470 .getBroadcastItem(i); 16471 try { 16472 callback.onPermissionsChanged(uid); 16473 } catch (RemoteException e) { 16474 Log.e(TAG, "Permission listener is dead", e); 16475 } 16476 } 16477 } finally { 16478 mPermissionListeners.finishBroadcast(); 16479 } 16480 } 16481 } 16482 16483 private class PackageManagerInternalImpl extends PackageManagerInternal { 16484 @Override 16485 public void setLocationPackagesProvider(PackagesProvider provider) { 16486 synchronized (mPackages) { 16487 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 16488 } 16489 } 16490 16491 @Override 16492 public void setImePackagesProvider(PackagesProvider provider) { 16493 synchronized (mPackages) { 16494 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 16495 } 16496 } 16497 16498 @Override 16499 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 16500 synchronized (mPackages) { 16501 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 16502 } 16503 } 16504 16505 @Override 16506 public void setSmsAppPackagesProvider(PackagesProvider provider) { 16507 synchronized (mPackages) { 16508 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 16509 } 16510 } 16511 16512 @Override 16513 public void setDialerAppPackagesProvider(PackagesProvider provider) { 16514 synchronized (mPackages) { 16515 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 16516 } 16517 } 16518 16519 @Override 16520 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 16521 synchronized (mPackages) { 16522 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 16523 } 16524 } 16525 16526 @Override 16527 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 16528 synchronized (mPackages) { 16529 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 16530 packageName, userId); 16531 } 16532 } 16533 16534 @Override 16535 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 16536 synchronized (mPackages) { 16537 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 16538 packageName, userId); 16539 } 16540 } 16541 } 16542 16543 @Override 16544 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 16545 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 16546 synchronized (mPackages) { 16547 final long identity = Binder.clearCallingIdentity(); 16548 try { 16549 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 16550 packageNames, userId); 16551 } finally { 16552 Binder.restoreCallingIdentity(identity); 16553 } 16554 } 16555 } 16556 16557 private static void enforceSystemOrPhoneCaller(String tag) { 16558 int callingUid = Binder.getCallingUid(); 16559 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 16560 throw new SecurityException( 16561 "Cannot call " + tag + " from UID " + callingUid); 16562 } 16563 } 16564} 16565