PackageManagerService.java revision 5c269121d8ea0bf3f530f2314695e189ffdb3165
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.storage.DeviceStorageMonitorInternal; 228 229import org.xmlpull.v1.XmlPullParser; 230import org.xmlpull.v1.XmlPullParserException; 231import org.xmlpull.v1.XmlSerializer; 232 233import java.io.BufferedInputStream; 234import java.io.BufferedOutputStream; 235import java.io.BufferedReader; 236import java.io.ByteArrayInputStream; 237import java.io.ByteArrayOutputStream; 238import java.io.File; 239import java.io.FileDescriptor; 240import java.io.FileNotFoundException; 241import java.io.FileOutputStream; 242import java.io.FileReader; 243import java.io.FilenameFilter; 244import java.io.IOException; 245import java.io.InputStream; 246import java.io.PrintWriter; 247import java.nio.charset.StandardCharsets; 248import java.security.NoSuchAlgorithmException; 249import java.security.PublicKey; 250import java.security.cert.CertificateEncodingException; 251import java.security.cert.CertificateException; 252import java.text.SimpleDateFormat; 253import java.util.ArrayList; 254import java.util.Arrays; 255import java.util.Collection; 256import java.util.Collections; 257import java.util.Comparator; 258import java.util.Date; 259import java.util.Iterator; 260import java.util.List; 261import java.util.Map; 262import java.util.Objects; 263import java.util.Set; 264import java.util.concurrent.CountDownLatch; 265import java.util.concurrent.TimeUnit; 266import java.util.concurrent.atomic.AtomicBoolean; 267import java.util.concurrent.atomic.AtomicInteger; 268import java.util.concurrent.atomic.AtomicLong; 269 270/** 271 * Keep track of all those .apks everywhere. 272 * 273 * This is very central to the platform's security; please run the unit 274 * tests whenever making modifications here: 275 * 276mmm frameworks/base/tests/AndroidTests 277adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 278adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 279 * 280 * {@hide} 281 */ 282public class PackageManagerService extends IPackageManager.Stub { 283 static final String TAG = "PackageManager"; 284 static final boolean DEBUG_SETTINGS = false; 285 static final boolean DEBUG_PREFERRED = false; 286 static final boolean DEBUG_UPGRADE = false; 287 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 288 private static final boolean DEBUG_BACKUP = false; 289 private static final boolean DEBUG_INSTALL = false; 290 private static final boolean DEBUG_REMOVE = false; 291 private static final boolean DEBUG_BROADCASTS = false; 292 private static final boolean DEBUG_SHOW_INFO = false; 293 private static final boolean DEBUG_PACKAGE_INFO = false; 294 private static final boolean DEBUG_INTENT_MATCHING = false; 295 private static final boolean DEBUG_PACKAGE_SCANNING = false; 296 private static final boolean DEBUG_VERIFY = false; 297 private static final boolean DEBUG_DEXOPT = false; 298 private static final boolean DEBUG_ABI_SELECTION = false; 299 300 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = Build.IS_DEBUGGABLE; 301 302 private static final int RADIO_UID = Process.PHONE_UID; 303 private static final int LOG_UID = Process.LOG_UID; 304 private static final int NFC_UID = Process.NFC_UID; 305 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 306 private static final int SHELL_UID = Process.SHELL_UID; 307 308 // Cap the size of permission trees that 3rd party apps can define 309 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 310 311 // Suffix used during package installation when copying/moving 312 // package apks to install directory. 313 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 314 315 static final int SCAN_NO_DEX = 1<<1; 316 static final int SCAN_FORCE_DEX = 1<<2; 317 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 318 static final int SCAN_NEW_INSTALL = 1<<4; 319 static final int SCAN_NO_PATHS = 1<<5; 320 static final int SCAN_UPDATE_TIME = 1<<6; 321 static final int SCAN_DEFER_DEX = 1<<7; 322 static final int SCAN_BOOTING = 1<<8; 323 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 324 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 325 static final int SCAN_REQUIRE_KNOWN = 1<<12; 326 static final int SCAN_MOVE = 1<<13; 327 static final int SCAN_INITIAL = 1<<14; 328 329 static final int REMOVE_CHATTY = 1<<16; 330 331 private static final int[] EMPTY_INT_ARRAY = new int[0]; 332 333 /** 334 * Timeout (in milliseconds) after which the watchdog should declare that 335 * our handler thread is wedged. The usual default for such things is one 336 * minute but we sometimes do very lengthy I/O operations on this thread, 337 * such as installing multi-gigabyte applications, so ours needs to be longer. 338 */ 339 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 340 341 /** 342 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 343 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 344 * settings entry if available, otherwise we use the hardcoded default. If it's been 345 * more than this long since the last fstrim, we force one during the boot sequence. 346 * 347 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 348 * one gets run at the next available charging+idle time. This final mandatory 349 * no-fstrim check kicks in only of the other scheduling criteria is never met. 350 */ 351 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 352 353 /** 354 * Whether verification is enabled by default. 355 */ 356 private static final boolean DEFAULT_VERIFY_ENABLE = true; 357 358 /** 359 * The default maximum time to wait for the verification agent to return in 360 * milliseconds. 361 */ 362 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 363 364 /** 365 * The default response for package verification timeout. 366 * 367 * This can be either PackageManager.VERIFICATION_ALLOW or 368 * PackageManager.VERIFICATION_REJECT. 369 */ 370 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 371 372 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 373 374 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 375 DEFAULT_CONTAINER_PACKAGE, 376 "com.android.defcontainer.DefaultContainerService"); 377 378 private static final String KILL_APP_REASON_GIDS_CHANGED = 379 "permission grant or revoke changed gids"; 380 381 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 382 "permissions revoked"; 383 384 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 385 386 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 387 388 /** Permission grant: not grant the permission. */ 389 private static final int GRANT_DENIED = 1; 390 391 /** Permission grant: grant the permission as an install permission. */ 392 private static final int GRANT_INSTALL = 2; 393 394 /** Permission grant: grant the permission as an install permission for a legacy app. */ 395 private static final int GRANT_INSTALL_LEGACY = 3; 396 397 /** Permission grant: grant the permission as a runtime one. */ 398 private static final int GRANT_RUNTIME = 4; 399 400 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 401 private static final int GRANT_UPGRADE = 5; 402 403 /** Canonical intent used to identify what counts as a "web browser" app */ 404 private static final Intent sBrowserIntent; 405 static { 406 sBrowserIntent = new Intent(); 407 sBrowserIntent.setAction(Intent.ACTION_VIEW); 408 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 409 sBrowserIntent.setData(Uri.parse("http:")); 410 } 411 412 final ServiceThread mHandlerThread; 413 414 final PackageHandler mHandler; 415 416 /** 417 * Messages for {@link #mHandler} that need to wait for system ready before 418 * being dispatched. 419 */ 420 private ArrayList<Message> mPostSystemReadyMessages; 421 422 final int mSdkVersion = Build.VERSION.SDK_INT; 423 424 final Context mContext; 425 final boolean mFactoryTest; 426 final boolean mOnlyCore; 427 final boolean mLazyDexOpt; 428 final long mDexOptLRUThresholdInMills; 429 final DisplayMetrics mMetrics; 430 final int mDefParseFlags; 431 final String[] mSeparateProcesses; 432 final boolean mIsUpgrade; 433 434 // This is where all application persistent data goes. 435 final File mAppDataDir; 436 437 // This is where all application persistent data goes for secondary users. 438 final File mUserAppDataDir; 439 440 /** The location for ASEC container files on internal storage. */ 441 final String mAsecInternalPath; 442 443 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 444 // LOCK HELD. Can be called with mInstallLock held. 445 @GuardedBy("mInstallLock") 446 final Installer mInstaller; 447 448 /** Directory where installed third-party apps stored */ 449 final File mAppInstallDir; 450 451 /** 452 * Directory to which applications installed internally have their 453 * 32 bit native libraries copied. 454 */ 455 private File mAppLib32InstallDir; 456 457 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 458 // apps. 459 final File mDrmAppPrivateInstallDir; 460 461 // ---------------------------------------------------------------- 462 463 // Lock for state used when installing and doing other long running 464 // operations. Methods that must be called with this lock held have 465 // the suffix "LI". 466 final Object mInstallLock = new Object(); 467 468 // ---------------------------------------------------------------- 469 470 // Keys are String (package name), values are Package. This also serves 471 // as the lock for the global state. Methods that must be called with 472 // this lock held have the prefix "LP". 473 @GuardedBy("mPackages") 474 final ArrayMap<String, PackageParser.Package> mPackages = 475 new ArrayMap<String, PackageParser.Package>(); 476 477 // Tracks available target package names -> overlay package paths. 478 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 479 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 480 481 /** 482 * Tracks new system packages [receiving in an OTA] that we expect to 483 * find updated user-installed versions. Keys are package name, values 484 * are package location. 485 */ 486 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 487 488 final Settings mSettings; 489 boolean mRestoredSettings; 490 491 // System configuration read by SystemConfig. 492 final int[] mGlobalGids; 493 final SparseArray<ArraySet<String>> mSystemPermissions; 494 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 495 496 // If mac_permissions.xml was found for seinfo labeling. 497 boolean mFoundPolicyFile; 498 499 // If a recursive restorecon of /data/data/<pkg> is needed. 500 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 501 502 public static final class SharedLibraryEntry { 503 public final String path; 504 public final String apk; 505 506 SharedLibraryEntry(String _path, String _apk) { 507 path = _path; 508 apk = _apk; 509 } 510 } 511 512 // Currently known shared libraries. 513 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 514 new ArrayMap<String, SharedLibraryEntry>(); 515 516 // All available activities, for your resolving pleasure. 517 final ActivityIntentResolver mActivities = 518 new ActivityIntentResolver(); 519 520 // All available receivers, for your resolving pleasure. 521 final ActivityIntentResolver mReceivers = 522 new ActivityIntentResolver(); 523 524 // All available services, for your resolving pleasure. 525 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 526 527 // All available providers, for your resolving pleasure. 528 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 529 530 // Mapping from provider base names (first directory in content URI codePath) 531 // to the provider information. 532 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 533 new ArrayMap<String, PackageParser.Provider>(); 534 535 // Mapping from instrumentation class names to info about them. 536 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 537 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 538 539 // Mapping from permission names to info about them. 540 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 541 new ArrayMap<String, PackageParser.PermissionGroup>(); 542 543 // Packages whose data we have transfered into another package, thus 544 // should no longer exist. 545 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 546 547 // Broadcast actions that are only available to the system. 548 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 549 550 /** List of packages waiting for verification. */ 551 final SparseArray<PackageVerificationState> mPendingVerification 552 = new SparseArray<PackageVerificationState>(); 553 554 /** Set of packages associated with each app op permission. */ 555 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 556 557 final PackageInstallerService mInstallerService; 558 559 private final PackageDexOptimizer mPackageDexOptimizer; 560 561 private AtomicInteger mNextMoveId = new AtomicInteger(); 562 private final MoveCallbacks mMoveCallbacks; 563 564 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 565 566 // Cache of users who need badging. 567 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 568 569 /** Token for keys in mPendingVerification. */ 570 private int mPendingVerificationToken = 0; 571 572 volatile boolean mSystemReady; 573 volatile boolean mSafeMode; 574 volatile boolean mHasSystemUidErrors; 575 576 ApplicationInfo mAndroidApplication; 577 final ActivityInfo mResolveActivity = new ActivityInfo(); 578 final ResolveInfo mResolveInfo = new ResolveInfo(); 579 ComponentName mResolveComponentName; 580 PackageParser.Package mPlatformPackage; 581 ComponentName mCustomResolverComponentName; 582 583 boolean mResolverReplaced = false; 584 585 private final ComponentName mIntentFilterVerifierComponent; 586 private int mIntentFilterVerificationToken = 0; 587 588 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 589 = new SparseArray<IntentFilterVerificationState>(); 590 591 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 592 new DefaultPermissionGrantPolicy(this); 593 594 private static class IFVerificationParams { 595 PackageParser.Package pkg; 596 boolean replacing; 597 int userId; 598 int verifierUid; 599 600 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 601 int _userId, int _verifierUid) { 602 pkg = _pkg; 603 replacing = _replacing; 604 userId = _userId; 605 replacing = _replacing; 606 verifierUid = _verifierUid; 607 } 608 } 609 610 private interface IntentFilterVerifier<T extends IntentFilter> { 611 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 612 T filter, String packageName); 613 void startVerifications(int userId); 614 void receiveVerificationResponse(int verificationId); 615 } 616 617 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 618 private Context mContext; 619 private ComponentName mIntentFilterVerifierComponent; 620 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 621 622 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 623 mContext = context; 624 mIntentFilterVerifierComponent = verifierComponent; 625 } 626 627 private String getDefaultScheme() { 628 return IntentFilter.SCHEME_HTTPS; 629 } 630 631 @Override 632 public void startVerifications(int userId) { 633 // Launch verifications requests 634 int count = mCurrentIntentFilterVerifications.size(); 635 for (int n=0; n<count; n++) { 636 int verificationId = mCurrentIntentFilterVerifications.get(n); 637 final IntentFilterVerificationState ivs = 638 mIntentFilterVerificationStates.get(verificationId); 639 640 String packageName = ivs.getPackageName(); 641 642 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 643 final int filterCount = filters.size(); 644 ArraySet<String> domainsSet = new ArraySet<>(); 645 for (int m=0; m<filterCount; m++) { 646 PackageParser.ActivityIntentInfo filter = filters.get(m); 647 domainsSet.addAll(filter.getHostsList()); 648 } 649 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 650 synchronized (mPackages) { 651 if (mSettings.createIntentFilterVerificationIfNeededLPw( 652 packageName, domainsList) != null) { 653 scheduleWriteSettingsLocked(); 654 } 655 } 656 sendVerificationRequest(userId, verificationId, ivs); 657 } 658 mCurrentIntentFilterVerifications.clear(); 659 } 660 661 private void sendVerificationRequest(int userId, int verificationId, 662 IntentFilterVerificationState ivs) { 663 664 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 665 verificationIntent.putExtra( 666 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 667 verificationId); 668 verificationIntent.putExtra( 669 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 670 getDefaultScheme()); 671 verificationIntent.putExtra( 672 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 673 ivs.getHostsString()); 674 verificationIntent.putExtra( 675 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 676 ivs.getPackageName()); 677 verificationIntent.setComponent(mIntentFilterVerifierComponent); 678 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 679 680 UserHandle user = new UserHandle(userId); 681 mContext.sendBroadcastAsUser(verificationIntent, user); 682 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 683 "Sending IntentFilter verification broadcast"); 684 } 685 686 public void receiveVerificationResponse(int verificationId) { 687 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 688 689 final boolean verified = ivs.isVerified(); 690 691 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 692 final int count = filters.size(); 693 if (DEBUG_DOMAIN_VERIFICATION) { 694 Slog.i(TAG, "Received verification response " + verificationId 695 + " for " + count + " filters, verified=" + verified); 696 } 697 for (int n=0; n<count; n++) { 698 PackageParser.ActivityIntentInfo filter = filters.get(n); 699 filter.setVerified(verified); 700 701 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 702 + " verified with result:" + verified + " and hosts:" 703 + ivs.getHostsString()); 704 } 705 706 mIntentFilterVerificationStates.remove(verificationId); 707 708 final String packageName = ivs.getPackageName(); 709 IntentFilterVerificationInfo ivi = null; 710 711 synchronized (mPackages) { 712 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 713 } 714 if (ivi == null) { 715 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 716 + verificationId + " packageName:" + packageName); 717 return; 718 } 719 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 720 "Updating IntentFilterVerificationInfo for package " + packageName 721 +" verificationId:" + verificationId); 722 723 synchronized (mPackages) { 724 if (verified) { 725 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 726 } else { 727 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 728 } 729 scheduleWriteSettingsLocked(); 730 731 final int userId = ivs.getUserId(); 732 if (userId != UserHandle.USER_ALL) { 733 final int userStatus = 734 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 735 736 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 737 boolean needUpdate = false; 738 739 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 740 // already been set by the User thru the Disambiguation dialog 741 switch (userStatus) { 742 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 743 if (verified) { 744 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 745 } else { 746 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 747 } 748 needUpdate = true; 749 break; 750 751 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 752 if (verified) { 753 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 754 needUpdate = true; 755 } 756 break; 757 758 default: 759 // Nothing to do 760 } 761 762 if (needUpdate) { 763 mSettings.updateIntentFilterVerificationStatusLPw( 764 packageName, updatedStatus, userId); 765 scheduleWritePackageRestrictionsLocked(userId); 766 } 767 } 768 } 769 } 770 771 @Override 772 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 773 ActivityIntentInfo filter, String packageName) { 774 if (!hasValidDomains(filter)) { 775 return false; 776 } 777 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 778 if (ivs == null) { 779 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 780 packageName); 781 } 782 if (DEBUG_DOMAIN_VERIFICATION) { 783 Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter); 784 } 785 ivs.addFilter(filter); 786 return true; 787 } 788 789 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 790 int userId, int verificationId, String packageName) { 791 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 792 verifierUid, userId, packageName); 793 ivs.setPendingState(); 794 synchronized (mPackages) { 795 mIntentFilterVerificationStates.append(verificationId, ivs); 796 mCurrentIntentFilterVerifications.add(verificationId); 797 } 798 return ivs; 799 } 800 } 801 802 private static boolean hasValidDomains(ActivityIntentInfo filter) { 803 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 804 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 805 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 806 } 807 808 private IntentFilterVerifier mIntentFilterVerifier; 809 810 // Set of pending broadcasts for aggregating enable/disable of components. 811 static class PendingPackageBroadcasts { 812 // for each user id, a map of <package name -> components within that package> 813 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 814 815 public PendingPackageBroadcasts() { 816 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 817 } 818 819 public ArrayList<String> get(int userId, String packageName) { 820 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 821 return packages.get(packageName); 822 } 823 824 public void put(int userId, String packageName, ArrayList<String> components) { 825 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 826 packages.put(packageName, components); 827 } 828 829 public void remove(int userId, String packageName) { 830 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 831 if (packages != null) { 832 packages.remove(packageName); 833 } 834 } 835 836 public void remove(int userId) { 837 mUidMap.remove(userId); 838 } 839 840 public int userIdCount() { 841 return mUidMap.size(); 842 } 843 844 public int userIdAt(int n) { 845 return mUidMap.keyAt(n); 846 } 847 848 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 849 return mUidMap.get(userId); 850 } 851 852 public int size() { 853 // total number of pending broadcast entries across all userIds 854 int num = 0; 855 for (int i = 0; i< mUidMap.size(); i++) { 856 num += mUidMap.valueAt(i).size(); 857 } 858 return num; 859 } 860 861 public void clear() { 862 mUidMap.clear(); 863 } 864 865 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 866 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 867 if (map == null) { 868 map = new ArrayMap<String, ArrayList<String>>(); 869 mUidMap.put(userId, map); 870 } 871 return map; 872 } 873 } 874 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 875 876 // Service Connection to remote media container service to copy 877 // package uri's from external media onto secure containers 878 // or internal storage. 879 private IMediaContainerService mContainerService = null; 880 881 static final int SEND_PENDING_BROADCAST = 1; 882 static final int MCS_BOUND = 3; 883 static final int END_COPY = 4; 884 static final int INIT_COPY = 5; 885 static final int MCS_UNBIND = 6; 886 static final int START_CLEANING_PACKAGE = 7; 887 static final int FIND_INSTALL_LOC = 8; 888 static final int POST_INSTALL = 9; 889 static final int MCS_RECONNECT = 10; 890 static final int MCS_GIVE_UP = 11; 891 static final int UPDATED_MEDIA_STATUS = 12; 892 static final int WRITE_SETTINGS = 13; 893 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 894 static final int PACKAGE_VERIFIED = 15; 895 static final int CHECK_PENDING_VERIFICATION = 16; 896 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 897 static final int INTENT_FILTER_VERIFIED = 18; 898 899 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 900 901 // Delay time in millisecs 902 static final int BROADCAST_DELAY = 10 * 1000; 903 904 static UserManagerService sUserManager; 905 906 // Stores a list of users whose package restrictions file needs to be updated 907 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 908 909 final private DefaultContainerConnection mDefContainerConn = 910 new DefaultContainerConnection(); 911 class DefaultContainerConnection implements ServiceConnection { 912 public void onServiceConnected(ComponentName name, IBinder service) { 913 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 914 IMediaContainerService imcs = 915 IMediaContainerService.Stub.asInterface(service); 916 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 917 } 918 919 public void onServiceDisconnected(ComponentName name) { 920 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 921 } 922 } 923 924 // Recordkeeping of restore-after-install operations that are currently in flight 925 // between the Package Manager and the Backup Manager 926 class PostInstallData { 927 public InstallArgs args; 928 public PackageInstalledInfo res; 929 930 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 931 args = _a; 932 res = _r; 933 } 934 } 935 936 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 937 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 938 939 // XML tags for backup/restore of various bits of state 940 private static final String TAG_PREFERRED_BACKUP = "pa"; 941 private static final String TAG_DEFAULT_APPS = "da"; 942 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 943 944 final String mRequiredVerifierPackage; 945 final String mRequiredInstallerPackage; 946 947 private final PackageUsage mPackageUsage = new PackageUsage(); 948 949 private class PackageUsage { 950 private static final int WRITE_INTERVAL 951 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 952 953 private final Object mFileLock = new Object(); 954 private final AtomicLong mLastWritten = new AtomicLong(0); 955 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 956 957 private boolean mIsHistoricalPackageUsageAvailable = true; 958 959 boolean isHistoricalPackageUsageAvailable() { 960 return mIsHistoricalPackageUsageAvailable; 961 } 962 963 void write(boolean force) { 964 if (force) { 965 writeInternal(); 966 return; 967 } 968 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 969 && !DEBUG_DEXOPT) { 970 return; 971 } 972 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 973 new Thread("PackageUsage_DiskWriter") { 974 @Override 975 public void run() { 976 try { 977 writeInternal(); 978 } finally { 979 mBackgroundWriteRunning.set(false); 980 } 981 } 982 }.start(); 983 } 984 } 985 986 private void writeInternal() { 987 synchronized (mPackages) { 988 synchronized (mFileLock) { 989 AtomicFile file = getFile(); 990 FileOutputStream f = null; 991 try { 992 f = file.startWrite(); 993 BufferedOutputStream out = new BufferedOutputStream(f); 994 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 995 StringBuilder sb = new StringBuilder(); 996 for (PackageParser.Package pkg : mPackages.values()) { 997 if (pkg.mLastPackageUsageTimeInMills == 0) { 998 continue; 999 } 1000 sb.setLength(0); 1001 sb.append(pkg.packageName); 1002 sb.append(' '); 1003 sb.append((long)pkg.mLastPackageUsageTimeInMills); 1004 sb.append('\n'); 1005 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1006 } 1007 out.flush(); 1008 file.finishWrite(f); 1009 } catch (IOException e) { 1010 if (f != null) { 1011 file.failWrite(f); 1012 } 1013 Log.e(TAG, "Failed to write package usage times", e); 1014 } 1015 } 1016 } 1017 mLastWritten.set(SystemClock.elapsedRealtime()); 1018 } 1019 1020 void readLP() { 1021 synchronized (mFileLock) { 1022 AtomicFile file = getFile(); 1023 BufferedInputStream in = null; 1024 try { 1025 in = new BufferedInputStream(file.openRead()); 1026 StringBuffer sb = new StringBuffer(); 1027 while (true) { 1028 String packageName = readToken(in, sb, ' '); 1029 if (packageName == null) { 1030 break; 1031 } 1032 String timeInMillisString = readToken(in, sb, '\n'); 1033 if (timeInMillisString == null) { 1034 throw new IOException("Failed to find last usage time for package " 1035 + packageName); 1036 } 1037 PackageParser.Package pkg = mPackages.get(packageName); 1038 if (pkg == null) { 1039 continue; 1040 } 1041 long timeInMillis; 1042 try { 1043 timeInMillis = Long.parseLong(timeInMillisString.toString()); 1044 } catch (NumberFormatException e) { 1045 throw new IOException("Failed to parse " + timeInMillisString 1046 + " as a long.", e); 1047 } 1048 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1049 } 1050 } catch (FileNotFoundException expected) { 1051 mIsHistoricalPackageUsageAvailable = false; 1052 } catch (IOException e) { 1053 Log.w(TAG, "Failed to read package usage times", e); 1054 } finally { 1055 IoUtils.closeQuietly(in); 1056 } 1057 } 1058 mLastWritten.set(SystemClock.elapsedRealtime()); 1059 } 1060 1061 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1062 throws IOException { 1063 sb.setLength(0); 1064 while (true) { 1065 int ch = in.read(); 1066 if (ch == -1) { 1067 if (sb.length() == 0) { 1068 return null; 1069 } 1070 throw new IOException("Unexpected EOF"); 1071 } 1072 if (ch == endOfToken) { 1073 return sb.toString(); 1074 } 1075 sb.append((char)ch); 1076 } 1077 } 1078 1079 private AtomicFile getFile() { 1080 File dataDir = Environment.getDataDirectory(); 1081 File systemDir = new File(dataDir, "system"); 1082 File fname = new File(systemDir, "package-usage.list"); 1083 return new AtomicFile(fname); 1084 } 1085 } 1086 1087 class PackageHandler extends Handler { 1088 private boolean mBound = false; 1089 final ArrayList<HandlerParams> mPendingInstalls = 1090 new ArrayList<HandlerParams>(); 1091 1092 private boolean connectToService() { 1093 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1094 " DefaultContainerService"); 1095 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1096 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1097 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1098 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 1099 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1100 mBound = true; 1101 return true; 1102 } 1103 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1104 return false; 1105 } 1106 1107 private void disconnectService() { 1108 mContainerService = null; 1109 mBound = false; 1110 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1111 mContext.unbindService(mDefContainerConn); 1112 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1113 } 1114 1115 PackageHandler(Looper looper) { 1116 super(looper); 1117 } 1118 1119 public void handleMessage(Message msg) { 1120 try { 1121 doHandleMessage(msg); 1122 } finally { 1123 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1124 } 1125 } 1126 1127 void doHandleMessage(Message msg) { 1128 switch (msg.what) { 1129 case INIT_COPY: { 1130 HandlerParams params = (HandlerParams) msg.obj; 1131 int idx = mPendingInstalls.size(); 1132 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1133 // If a bind was already initiated we dont really 1134 // need to do anything. The pending install 1135 // will be processed later on. 1136 if (!mBound) { 1137 // If this is the only one pending we might 1138 // have to bind to the service again. 1139 if (!connectToService()) { 1140 Slog.e(TAG, "Failed to bind to media container service"); 1141 params.serviceError(); 1142 return; 1143 } else { 1144 // Once we bind to the service, the first 1145 // pending request will be processed. 1146 mPendingInstalls.add(idx, params); 1147 } 1148 } else { 1149 mPendingInstalls.add(idx, params); 1150 // Already bound to the service. Just make 1151 // sure we trigger off processing the first request. 1152 if (idx == 0) { 1153 mHandler.sendEmptyMessage(MCS_BOUND); 1154 } 1155 } 1156 break; 1157 } 1158 case MCS_BOUND: { 1159 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1160 if (msg.obj != null) { 1161 mContainerService = (IMediaContainerService) msg.obj; 1162 } 1163 if (mContainerService == null) { 1164 if (!mBound) { 1165 // Something seriously wrong since we are not bound and we are not 1166 // waiting for connection. Bail out. 1167 Slog.e(TAG, "Cannot bind to media container service"); 1168 for (HandlerParams params : mPendingInstalls) { 1169 // Indicate service bind error 1170 params.serviceError(); 1171 } 1172 mPendingInstalls.clear(); 1173 } else { 1174 Slog.w(TAG, "Waiting to connect to media container service"); 1175 } 1176 } else if (mPendingInstalls.size() > 0) { 1177 HandlerParams params = mPendingInstalls.get(0); 1178 if (params != null) { 1179 if (params.startCopy()) { 1180 // We are done... look for more work or to 1181 // go idle. 1182 if (DEBUG_SD_INSTALL) Log.i(TAG, 1183 "Checking for more work or unbind..."); 1184 // Delete pending install 1185 if (mPendingInstalls.size() > 0) { 1186 mPendingInstalls.remove(0); 1187 } 1188 if (mPendingInstalls.size() == 0) { 1189 if (mBound) { 1190 if (DEBUG_SD_INSTALL) Log.i(TAG, 1191 "Posting delayed MCS_UNBIND"); 1192 removeMessages(MCS_UNBIND); 1193 Message ubmsg = obtainMessage(MCS_UNBIND); 1194 // Unbind after a little delay, to avoid 1195 // continual thrashing. 1196 sendMessageDelayed(ubmsg, 10000); 1197 } 1198 } else { 1199 // There are more pending requests in queue. 1200 // Just post MCS_BOUND message to trigger processing 1201 // of next pending install. 1202 if (DEBUG_SD_INSTALL) Log.i(TAG, 1203 "Posting MCS_BOUND for next work"); 1204 mHandler.sendEmptyMessage(MCS_BOUND); 1205 } 1206 } 1207 } 1208 } else { 1209 // Should never happen ideally. 1210 Slog.w(TAG, "Empty queue"); 1211 } 1212 break; 1213 } 1214 case MCS_RECONNECT: { 1215 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1216 if (mPendingInstalls.size() > 0) { 1217 if (mBound) { 1218 disconnectService(); 1219 } 1220 if (!connectToService()) { 1221 Slog.e(TAG, "Failed to bind to media container service"); 1222 for (HandlerParams params : mPendingInstalls) { 1223 // Indicate service bind error 1224 params.serviceError(); 1225 } 1226 mPendingInstalls.clear(); 1227 } 1228 } 1229 break; 1230 } 1231 case MCS_UNBIND: { 1232 // If there is no actual work left, then time to unbind. 1233 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1234 1235 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1236 if (mBound) { 1237 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1238 1239 disconnectService(); 1240 } 1241 } else if (mPendingInstalls.size() > 0) { 1242 // There are more pending requests in queue. 1243 // Just post MCS_BOUND message to trigger processing 1244 // of next pending install. 1245 mHandler.sendEmptyMessage(MCS_BOUND); 1246 } 1247 1248 break; 1249 } 1250 case MCS_GIVE_UP: { 1251 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1252 mPendingInstalls.remove(0); 1253 break; 1254 } 1255 case SEND_PENDING_BROADCAST: { 1256 String packages[]; 1257 ArrayList<String> components[]; 1258 int size = 0; 1259 int uids[]; 1260 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1261 synchronized (mPackages) { 1262 if (mPendingBroadcasts == null) { 1263 return; 1264 } 1265 size = mPendingBroadcasts.size(); 1266 if (size <= 0) { 1267 // Nothing to be done. Just return 1268 return; 1269 } 1270 packages = new String[size]; 1271 components = new ArrayList[size]; 1272 uids = new int[size]; 1273 int i = 0; // filling out the above arrays 1274 1275 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1276 int packageUserId = mPendingBroadcasts.userIdAt(n); 1277 Iterator<Map.Entry<String, ArrayList<String>>> it 1278 = mPendingBroadcasts.packagesForUserId(packageUserId) 1279 .entrySet().iterator(); 1280 while (it.hasNext() && i < size) { 1281 Map.Entry<String, ArrayList<String>> ent = it.next(); 1282 packages[i] = ent.getKey(); 1283 components[i] = ent.getValue(); 1284 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1285 uids[i] = (ps != null) 1286 ? UserHandle.getUid(packageUserId, ps.appId) 1287 : -1; 1288 i++; 1289 } 1290 } 1291 size = i; 1292 mPendingBroadcasts.clear(); 1293 } 1294 // Send broadcasts 1295 for (int i = 0; i < size; i++) { 1296 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1297 } 1298 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1299 break; 1300 } 1301 case START_CLEANING_PACKAGE: { 1302 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1303 final String packageName = (String)msg.obj; 1304 final int userId = msg.arg1; 1305 final boolean andCode = msg.arg2 != 0; 1306 synchronized (mPackages) { 1307 if (userId == UserHandle.USER_ALL) { 1308 int[] users = sUserManager.getUserIds(); 1309 for (int user : users) { 1310 mSettings.addPackageToCleanLPw( 1311 new PackageCleanItem(user, packageName, andCode)); 1312 } 1313 } else { 1314 mSettings.addPackageToCleanLPw( 1315 new PackageCleanItem(userId, packageName, andCode)); 1316 } 1317 } 1318 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1319 startCleaningPackages(); 1320 } break; 1321 case POST_INSTALL: { 1322 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1323 PostInstallData data = mRunningInstalls.get(msg.arg1); 1324 mRunningInstalls.delete(msg.arg1); 1325 boolean deleteOld = false; 1326 1327 if (data != null) { 1328 InstallArgs args = data.args; 1329 PackageInstalledInfo res = data.res; 1330 1331 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1332 final String packageName = res.pkg.applicationInfo.packageName; 1333 res.removedInfo.sendBroadcast(false, true, false); 1334 Bundle extras = new Bundle(1); 1335 extras.putInt(Intent.EXTRA_UID, res.uid); 1336 1337 // Now that we successfully installed the package, grant runtime 1338 // permissions if requested before broadcasting the install. 1339 if ((args.installFlags 1340 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1341 grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(), 1342 args.installGrantPermissions); 1343 } 1344 1345 // Determine the set of users who are adding this 1346 // package for the first time vs. those who are seeing 1347 // an update. 1348 int[] firstUsers; 1349 int[] updateUsers = new int[0]; 1350 if (res.origUsers == null || res.origUsers.length == 0) { 1351 firstUsers = res.newUsers; 1352 } else { 1353 firstUsers = new int[0]; 1354 for (int i=0; i<res.newUsers.length; i++) { 1355 int user = res.newUsers[i]; 1356 boolean isNew = true; 1357 for (int j=0; j<res.origUsers.length; j++) { 1358 if (res.origUsers[j] == user) { 1359 isNew = false; 1360 break; 1361 } 1362 } 1363 if (isNew) { 1364 int[] newFirst = new int[firstUsers.length+1]; 1365 System.arraycopy(firstUsers, 0, newFirst, 0, 1366 firstUsers.length); 1367 newFirst[firstUsers.length] = user; 1368 firstUsers = newFirst; 1369 } else { 1370 int[] newUpdate = new int[updateUsers.length+1]; 1371 System.arraycopy(updateUsers, 0, newUpdate, 0, 1372 updateUsers.length); 1373 newUpdate[updateUsers.length] = user; 1374 updateUsers = newUpdate; 1375 } 1376 } 1377 } 1378 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1379 packageName, extras, null, null, firstUsers); 1380 final boolean update = res.removedInfo.removedPackage != null; 1381 if (update) { 1382 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1383 } 1384 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1385 packageName, extras, null, null, updateUsers); 1386 if (update) { 1387 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1388 packageName, extras, null, null, updateUsers); 1389 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1390 null, null, packageName, null, updateUsers); 1391 1392 // treat asec-hosted packages like removable media on upgrade 1393 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1394 if (DEBUG_INSTALL) { 1395 Slog.i(TAG, "upgrading pkg " + res.pkg 1396 + " is ASEC-hosted -> AVAILABLE"); 1397 } 1398 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1399 ArrayList<String> pkgList = new ArrayList<String>(1); 1400 pkgList.add(packageName); 1401 sendResourcesChangedBroadcast(true, true, 1402 pkgList,uidArray, null); 1403 } 1404 } 1405 if (res.removedInfo.args != null) { 1406 // Remove the replaced package's older resources safely now 1407 deleteOld = true; 1408 } 1409 1410 // If this app is a browser and it's newly-installed for some 1411 // users, clear any default-browser state in those users 1412 if (firstUsers.length > 0) { 1413 // the app's nature doesn't depend on the user, so we can just 1414 // check its browser nature in any user and generalize. 1415 if (packageIsBrowser(packageName, firstUsers[0])) { 1416 synchronized (mPackages) { 1417 for (int userId : firstUsers) { 1418 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1419 } 1420 } 1421 } 1422 } 1423 // Log current value of "unknown sources" setting 1424 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1425 getUnknownSourcesSettings()); 1426 } 1427 // Force a gc to clear up things 1428 Runtime.getRuntime().gc(); 1429 // We delete after a gc for applications on sdcard. 1430 if (deleteOld) { 1431 synchronized (mInstallLock) { 1432 res.removedInfo.args.doPostDeleteLI(true); 1433 } 1434 } 1435 if (args.observer != null) { 1436 try { 1437 Bundle extras = extrasForInstallResult(res); 1438 args.observer.onPackageInstalled(res.name, res.returnCode, 1439 res.returnMsg, extras); 1440 } catch (RemoteException e) { 1441 Slog.i(TAG, "Observer no longer exists."); 1442 } 1443 } 1444 } else { 1445 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1446 } 1447 } break; 1448 case UPDATED_MEDIA_STATUS: { 1449 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1450 boolean reportStatus = msg.arg1 == 1; 1451 boolean doGc = msg.arg2 == 1; 1452 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1453 if (doGc) { 1454 // Force a gc to clear up stale containers. 1455 Runtime.getRuntime().gc(); 1456 } 1457 if (msg.obj != null) { 1458 @SuppressWarnings("unchecked") 1459 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1460 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1461 // Unload containers 1462 unloadAllContainers(args); 1463 } 1464 if (reportStatus) { 1465 try { 1466 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1467 PackageHelper.getMountService().finishMediaUpdate(); 1468 } catch (RemoteException e) { 1469 Log.e(TAG, "MountService not running?"); 1470 } 1471 } 1472 } break; 1473 case WRITE_SETTINGS: { 1474 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1475 synchronized (mPackages) { 1476 removeMessages(WRITE_SETTINGS); 1477 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1478 mSettings.writeLPr(); 1479 mDirtyUsers.clear(); 1480 } 1481 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1482 } break; 1483 case WRITE_PACKAGE_RESTRICTIONS: { 1484 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1485 synchronized (mPackages) { 1486 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1487 for (int userId : mDirtyUsers) { 1488 mSettings.writePackageRestrictionsLPr(userId); 1489 } 1490 mDirtyUsers.clear(); 1491 } 1492 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1493 } break; 1494 case CHECK_PENDING_VERIFICATION: { 1495 final int verificationId = msg.arg1; 1496 final PackageVerificationState state = mPendingVerification.get(verificationId); 1497 1498 if ((state != null) && !state.timeoutExtended()) { 1499 final InstallArgs args = state.getInstallArgs(); 1500 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1501 1502 Slog.i(TAG, "Verification timed out for " + originUri); 1503 mPendingVerification.remove(verificationId); 1504 1505 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1506 1507 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1508 Slog.i(TAG, "Continuing with installation of " + originUri); 1509 state.setVerifierResponse(Binder.getCallingUid(), 1510 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1511 broadcastPackageVerified(verificationId, originUri, 1512 PackageManager.VERIFICATION_ALLOW, 1513 state.getInstallArgs().getUser()); 1514 try { 1515 ret = args.copyApk(mContainerService, true); 1516 } catch (RemoteException e) { 1517 Slog.e(TAG, "Could not contact the ContainerService"); 1518 } 1519 } else { 1520 broadcastPackageVerified(verificationId, originUri, 1521 PackageManager.VERIFICATION_REJECT, 1522 state.getInstallArgs().getUser()); 1523 } 1524 1525 processPendingInstall(args, ret); 1526 mHandler.sendEmptyMessage(MCS_UNBIND); 1527 } 1528 break; 1529 } 1530 case PACKAGE_VERIFIED: { 1531 final int verificationId = msg.arg1; 1532 1533 final PackageVerificationState state = mPendingVerification.get(verificationId); 1534 if (state == null) { 1535 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1536 break; 1537 } 1538 1539 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1540 1541 state.setVerifierResponse(response.callerUid, response.code); 1542 1543 if (state.isVerificationComplete()) { 1544 mPendingVerification.remove(verificationId); 1545 1546 final InstallArgs args = state.getInstallArgs(); 1547 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1548 1549 int ret; 1550 if (state.isInstallAllowed()) { 1551 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1552 broadcastPackageVerified(verificationId, originUri, 1553 response.code, state.getInstallArgs().getUser()); 1554 try { 1555 ret = args.copyApk(mContainerService, true); 1556 } catch (RemoteException e) { 1557 Slog.e(TAG, "Could not contact the ContainerService"); 1558 } 1559 } else { 1560 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1561 } 1562 1563 processPendingInstall(args, ret); 1564 1565 mHandler.sendEmptyMessage(MCS_UNBIND); 1566 } 1567 1568 break; 1569 } 1570 case START_INTENT_FILTER_VERIFICATIONS: { 1571 IFVerificationParams params = (IFVerificationParams) msg.obj; 1572 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1573 params.replacing, params.pkg); 1574 break; 1575 } 1576 case INTENT_FILTER_VERIFIED: { 1577 final int verificationId = msg.arg1; 1578 1579 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1580 verificationId); 1581 if (state == null) { 1582 Slog.w(TAG, "Invalid IntentFilter verification token " 1583 + verificationId + " received"); 1584 break; 1585 } 1586 1587 final int userId = state.getUserId(); 1588 1589 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1590 "Processing IntentFilter verification with token:" 1591 + verificationId + " and userId:" + userId); 1592 1593 final IntentFilterVerificationResponse response = 1594 (IntentFilterVerificationResponse) msg.obj; 1595 1596 state.setVerifierResponse(response.callerUid, response.code); 1597 1598 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1599 "IntentFilter verification with token:" + verificationId 1600 + " and userId:" + userId 1601 + " is settings verifier response with response code:" 1602 + response.code); 1603 1604 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1605 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1606 + response.getFailedDomainsString()); 1607 } 1608 1609 if (state.isVerificationComplete()) { 1610 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1611 } else { 1612 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1613 "IntentFilter verification with token:" + verificationId 1614 + " was not said to be complete"); 1615 } 1616 1617 break; 1618 } 1619 } 1620 } 1621 } 1622 1623 private StorageEventListener mStorageListener = new StorageEventListener() { 1624 @Override 1625 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1626 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1627 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1628 final String volumeUuid = vol.getFsUuid(); 1629 1630 // Clean up any users or apps that were removed or recreated 1631 // while this volume was missing 1632 reconcileUsers(volumeUuid); 1633 reconcileApps(volumeUuid); 1634 1635 // Clean up any install sessions that expired or were 1636 // cancelled while this volume was missing 1637 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1638 1639 loadPrivatePackages(vol); 1640 1641 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1642 unloadPrivatePackages(vol); 1643 } 1644 } 1645 1646 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1647 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1648 updateExternalMediaStatus(true, false); 1649 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1650 updateExternalMediaStatus(false, false); 1651 } 1652 } 1653 } 1654 1655 @Override 1656 public void onVolumeForgotten(String fsUuid) { 1657 // Remove any apps installed on the forgotten volume 1658 synchronized (mPackages) { 1659 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1660 for (PackageSetting ps : packages) { 1661 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1662 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1663 UserHandle.USER_OWNER, PackageManager.DELETE_ALL_USERS); 1664 } 1665 1666 mSettings.writeLPr(); 1667 } 1668 } 1669 }; 1670 1671 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId, 1672 String[] grantedPermissions) { 1673 if (userId >= UserHandle.USER_OWNER) { 1674 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1675 } else if (userId == UserHandle.USER_ALL) { 1676 final int[] userIds; 1677 synchronized (mPackages) { 1678 userIds = UserManagerService.getInstance().getUserIds(); 1679 } 1680 for (int someUserId : userIds) { 1681 grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions); 1682 } 1683 } 1684 1685 // We could have touched GID membership, so flush out packages.list 1686 synchronized (mPackages) { 1687 mSettings.writePackageListLPr(); 1688 } 1689 } 1690 1691 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1692 String[] grantedPermissions) { 1693 SettingBase sb = (SettingBase) pkg.mExtras; 1694 if (sb == null) { 1695 return; 1696 } 1697 1698 PermissionsState permissionsState = sb.getPermissionsState(); 1699 1700 for (String permission : pkg.requestedPermissions) { 1701 BasePermission bp = mSettings.mPermissions.get(permission); 1702 if (bp != null && bp.isRuntime() && (grantedPermissions == null 1703 || ArrayUtils.contains(grantedPermissions, permission))) { 1704 permissionsState.grantRuntimePermission(bp, userId); 1705 } 1706 } 1707 } 1708 1709 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1710 Bundle extras = null; 1711 switch (res.returnCode) { 1712 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1713 extras = new Bundle(); 1714 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1715 res.origPermission); 1716 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1717 res.origPackage); 1718 break; 1719 } 1720 case PackageManager.INSTALL_SUCCEEDED: { 1721 extras = new Bundle(); 1722 extras.putBoolean(Intent.EXTRA_REPLACING, 1723 res.removedInfo != null && res.removedInfo.removedPackage != null); 1724 break; 1725 } 1726 } 1727 return extras; 1728 } 1729 1730 void scheduleWriteSettingsLocked() { 1731 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1732 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1733 } 1734 } 1735 1736 void scheduleWritePackageRestrictionsLocked(int userId) { 1737 if (!sUserManager.exists(userId)) return; 1738 mDirtyUsers.add(userId); 1739 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1740 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1741 } 1742 } 1743 1744 public static PackageManagerService main(Context context, Installer installer, 1745 boolean factoryTest, boolean onlyCore) { 1746 PackageManagerService m = new PackageManagerService(context, installer, 1747 factoryTest, onlyCore); 1748 ServiceManager.addService("package", m); 1749 return m; 1750 } 1751 1752 static String[] splitString(String str, char sep) { 1753 int count = 1; 1754 int i = 0; 1755 while ((i=str.indexOf(sep, i)) >= 0) { 1756 count++; 1757 i++; 1758 } 1759 1760 String[] res = new String[count]; 1761 i=0; 1762 count = 0; 1763 int lastI=0; 1764 while ((i=str.indexOf(sep, i)) >= 0) { 1765 res[count] = str.substring(lastI, i); 1766 count++; 1767 i++; 1768 lastI = i; 1769 } 1770 res[count] = str.substring(lastI, str.length()); 1771 return res; 1772 } 1773 1774 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1775 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1776 Context.DISPLAY_SERVICE); 1777 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1778 } 1779 1780 public PackageManagerService(Context context, Installer installer, 1781 boolean factoryTest, boolean onlyCore) { 1782 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1783 SystemClock.uptimeMillis()); 1784 1785 if (mSdkVersion <= 0) { 1786 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1787 } 1788 1789 mContext = context; 1790 mFactoryTest = factoryTest; 1791 mOnlyCore = onlyCore; 1792 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1793 mMetrics = new DisplayMetrics(); 1794 mSettings = new Settings(mPackages); 1795 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1796 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1797 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1798 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1799 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1800 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1801 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1802 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1803 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1804 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1805 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1806 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1807 1808 // TODO: add a property to control this? 1809 long dexOptLRUThresholdInMinutes; 1810 if (mLazyDexOpt) { 1811 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1812 } else { 1813 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1814 } 1815 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1816 1817 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1818 if (separateProcesses != null && separateProcesses.length() > 0) { 1819 if ("*".equals(separateProcesses)) { 1820 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1821 mSeparateProcesses = null; 1822 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1823 } else { 1824 mDefParseFlags = 0; 1825 mSeparateProcesses = separateProcesses.split(","); 1826 Slog.w(TAG, "Running with debug.separate_processes: " 1827 + separateProcesses); 1828 } 1829 } else { 1830 mDefParseFlags = 0; 1831 mSeparateProcesses = null; 1832 } 1833 1834 mInstaller = installer; 1835 mPackageDexOptimizer = new PackageDexOptimizer(this); 1836 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1837 1838 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 1839 FgThread.get().getLooper()); 1840 1841 getDefaultDisplayMetrics(context, mMetrics); 1842 1843 SystemConfig systemConfig = SystemConfig.getInstance(); 1844 mGlobalGids = systemConfig.getGlobalGids(); 1845 mSystemPermissions = systemConfig.getSystemPermissions(); 1846 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1847 1848 synchronized (mInstallLock) { 1849 // writer 1850 synchronized (mPackages) { 1851 mHandlerThread = new ServiceThread(TAG, 1852 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1853 mHandlerThread.start(); 1854 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1855 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1856 1857 File dataDir = Environment.getDataDirectory(); 1858 mAppDataDir = new File(dataDir, "data"); 1859 mAppInstallDir = new File(dataDir, "app"); 1860 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1861 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1862 mUserAppDataDir = new File(dataDir, "user"); 1863 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1864 1865 sUserManager = new UserManagerService(context, this, 1866 mInstallLock, mPackages); 1867 1868 // Propagate permission configuration in to package manager. 1869 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1870 = systemConfig.getPermissions(); 1871 for (int i=0; i<permConfig.size(); i++) { 1872 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1873 BasePermission bp = mSettings.mPermissions.get(perm.name); 1874 if (bp == null) { 1875 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1876 mSettings.mPermissions.put(perm.name, bp); 1877 } 1878 if (perm.gids != null) { 1879 bp.setGids(perm.gids, perm.perUser); 1880 } 1881 } 1882 1883 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1884 for (int i=0; i<libConfig.size(); i++) { 1885 mSharedLibraries.put(libConfig.keyAt(i), 1886 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1887 } 1888 1889 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1890 1891 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1892 mSdkVersion, mOnlyCore); 1893 1894 String customResolverActivity = Resources.getSystem().getString( 1895 R.string.config_customResolverActivity); 1896 if (TextUtils.isEmpty(customResolverActivity)) { 1897 customResolverActivity = null; 1898 } else { 1899 mCustomResolverComponentName = ComponentName.unflattenFromString( 1900 customResolverActivity); 1901 } 1902 1903 long startTime = SystemClock.uptimeMillis(); 1904 1905 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1906 startTime); 1907 1908 // Set flag to monitor and not change apk file paths when 1909 // scanning install directories. 1910 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 1911 1912 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1913 1914 /** 1915 * Add everything in the in the boot class path to the 1916 * list of process files because dexopt will have been run 1917 * if necessary during zygote startup. 1918 */ 1919 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1920 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1921 1922 if (bootClassPath != null) { 1923 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1924 for (String element : bootClassPathElements) { 1925 alreadyDexOpted.add(element); 1926 } 1927 } else { 1928 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1929 } 1930 1931 if (systemServerClassPath != null) { 1932 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1933 for (String element : systemServerClassPathElements) { 1934 alreadyDexOpted.add(element); 1935 } 1936 } else { 1937 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1938 } 1939 1940 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1941 final String[] dexCodeInstructionSets = 1942 getDexCodeInstructionSets( 1943 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1944 1945 /** 1946 * Ensure all external libraries have had dexopt run on them. 1947 */ 1948 if (mSharedLibraries.size() > 0) { 1949 // NOTE: For now, we're compiling these system "shared libraries" 1950 // (and framework jars) into all available architectures. It's possible 1951 // to compile them only when we come across an app that uses them (there's 1952 // already logic for that in scanPackageLI) but that adds some complexity. 1953 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1954 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1955 final String lib = libEntry.path; 1956 if (lib == null) { 1957 continue; 1958 } 1959 1960 try { 1961 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 1962 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1963 alreadyDexOpted.add(lib); 1964 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1965 } 1966 } catch (FileNotFoundException e) { 1967 Slog.w(TAG, "Library not found: " + lib); 1968 } catch (IOException e) { 1969 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1970 + e.getMessage()); 1971 } 1972 } 1973 } 1974 } 1975 1976 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1977 1978 // Gross hack for now: we know this file doesn't contain any 1979 // code, so don't dexopt it to avoid the resulting log spew. 1980 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1981 1982 // Gross hack for now: we know this file is only part of 1983 // the boot class path for art, so don't dexopt it to 1984 // avoid the resulting log spew. 1985 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1986 1987 /** 1988 * There are a number of commands implemented in Java, which 1989 * we currently need to do the dexopt on so that they can be 1990 * run from a non-root shell. 1991 */ 1992 String[] frameworkFiles = frameworkDir.list(); 1993 if (frameworkFiles != null) { 1994 // TODO: We could compile these only for the most preferred ABI. We should 1995 // first double check that the dex files for these commands are not referenced 1996 // by other system apps. 1997 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1998 for (int i=0; i<frameworkFiles.length; i++) { 1999 File libPath = new File(frameworkDir, frameworkFiles[i]); 2000 String path = libPath.getPath(); 2001 // Skip the file if we already did it. 2002 if (alreadyDexOpted.contains(path)) { 2003 continue; 2004 } 2005 // Skip the file if it is not a type we want to dexopt. 2006 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 2007 continue; 2008 } 2009 try { 2010 int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false); 2011 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2012 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 2013 } 2014 } catch (FileNotFoundException e) { 2015 Slog.w(TAG, "Jar not found: " + path); 2016 } catch (IOException e) { 2017 Slog.w(TAG, "Exception reading jar: " + path, e); 2018 } 2019 } 2020 } 2021 } 2022 2023 // Collect vendor overlay packages. 2024 // (Do this before scanning any apps.) 2025 // For security and version matching reason, only consider 2026 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2027 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2028 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2029 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2030 2031 // Find base frameworks (resource packages without code). 2032 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2033 | PackageParser.PARSE_IS_SYSTEM_DIR 2034 | PackageParser.PARSE_IS_PRIVILEGED, 2035 scanFlags | SCAN_NO_DEX, 0); 2036 2037 // Collected privileged system packages. 2038 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2039 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2040 | PackageParser.PARSE_IS_SYSTEM_DIR 2041 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2042 2043 // Collect ordinary system packages. 2044 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2045 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2046 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2047 2048 // Collect all vendor packages. 2049 File vendorAppDir = new File("/vendor/app"); 2050 try { 2051 vendorAppDir = vendorAppDir.getCanonicalFile(); 2052 } catch (IOException e) { 2053 // failed to look up canonical path, continue with original one 2054 } 2055 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2056 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2057 2058 // Collect all OEM packages. 2059 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2060 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2061 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2062 2063 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 2064 mInstaller.moveFiles(); 2065 2066 // Prune any system packages that no longer exist. 2067 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2068 if (!mOnlyCore) { 2069 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2070 while (psit.hasNext()) { 2071 PackageSetting ps = psit.next(); 2072 2073 /* 2074 * If this is not a system app, it can't be a 2075 * disable system app. 2076 */ 2077 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2078 continue; 2079 } 2080 2081 /* 2082 * If the package is scanned, it's not erased. 2083 */ 2084 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2085 if (scannedPkg != null) { 2086 /* 2087 * If the system app is both scanned and in the 2088 * disabled packages list, then it must have been 2089 * added via OTA. Remove it from the currently 2090 * scanned package so the previously user-installed 2091 * application can be scanned. 2092 */ 2093 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2094 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2095 + ps.name + "; removing system app. Last known codePath=" 2096 + ps.codePathString + ", installStatus=" + ps.installStatus 2097 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2098 + scannedPkg.mVersionCode); 2099 removePackageLI(ps, true); 2100 mExpectingBetter.put(ps.name, ps.codePath); 2101 } 2102 2103 continue; 2104 } 2105 2106 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2107 psit.remove(); 2108 logCriticalInfo(Log.WARN, "System package " + ps.name 2109 + " no longer exists; wiping its data"); 2110 removeDataDirsLI(null, ps.name); 2111 } else { 2112 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2113 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2114 possiblyDeletedUpdatedSystemApps.add(ps.name); 2115 } 2116 } 2117 } 2118 } 2119 2120 //look for any incomplete package installations 2121 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2122 //clean up list 2123 for(int i = 0; i < deletePkgsList.size(); i++) { 2124 //clean up here 2125 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2126 } 2127 //delete tmp files 2128 deleteTempPackageFiles(); 2129 2130 // Remove any shared userIDs that have no associated packages 2131 mSettings.pruneSharedUsersLPw(); 2132 2133 if (!mOnlyCore) { 2134 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2135 SystemClock.uptimeMillis()); 2136 scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2137 2138 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2139 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2140 2141 /** 2142 * Remove disable package settings for any updated system 2143 * apps that were removed via an OTA. If they're not a 2144 * previously-updated app, remove them completely. 2145 * Otherwise, just revoke their system-level permissions. 2146 */ 2147 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2148 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2149 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2150 2151 String msg; 2152 if (deletedPkg == null) { 2153 msg = "Updated system package " + deletedAppName 2154 + " no longer exists; wiping its data"; 2155 removeDataDirsLI(null, deletedAppName); 2156 } else { 2157 msg = "Updated system app + " + deletedAppName 2158 + " no longer present; removing system privileges for " 2159 + deletedAppName; 2160 2161 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2162 2163 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2164 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2165 } 2166 logCriticalInfo(Log.WARN, msg); 2167 } 2168 2169 /** 2170 * Make sure all system apps that we expected to appear on 2171 * the userdata partition actually showed up. If they never 2172 * appeared, crawl back and revive the system version. 2173 */ 2174 for (int i = 0; i < mExpectingBetter.size(); i++) { 2175 final String packageName = mExpectingBetter.keyAt(i); 2176 if (!mPackages.containsKey(packageName)) { 2177 final File scanFile = mExpectingBetter.valueAt(i); 2178 2179 logCriticalInfo(Log.WARN, "Expected better " + packageName 2180 + " but never showed up; reverting to system"); 2181 2182 final int reparseFlags; 2183 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2184 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2185 | PackageParser.PARSE_IS_SYSTEM_DIR 2186 | PackageParser.PARSE_IS_PRIVILEGED; 2187 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2188 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2189 | PackageParser.PARSE_IS_SYSTEM_DIR; 2190 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2191 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2192 | PackageParser.PARSE_IS_SYSTEM_DIR; 2193 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2194 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2195 | PackageParser.PARSE_IS_SYSTEM_DIR; 2196 } else { 2197 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2198 continue; 2199 } 2200 2201 mSettings.enableSystemPackageLPw(packageName); 2202 2203 try { 2204 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 2205 } catch (PackageManagerException e) { 2206 Slog.e(TAG, "Failed to parse original system package: " 2207 + e.getMessage()); 2208 } 2209 } 2210 } 2211 } 2212 mExpectingBetter.clear(); 2213 2214 // Now that we know all of the shared libraries, update all clients to have 2215 // the correct library paths. 2216 updateAllSharedLibrariesLPw(); 2217 2218 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2219 // NOTE: We ignore potential failures here during a system scan (like 2220 // the rest of the commands above) because there's precious little we 2221 // can do about it. A settings error is reported, though. 2222 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2223 false /* force dexopt */, false /* defer dexopt */); 2224 } 2225 2226 // Now that we know all the packages we are keeping, 2227 // read and update their last usage times. 2228 mPackageUsage.readLP(); 2229 2230 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2231 SystemClock.uptimeMillis()); 2232 Slog.i(TAG, "Time to scan packages: " 2233 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2234 + " seconds"); 2235 2236 // If the platform SDK has changed since the last time we booted, 2237 // we need to re-grant app permission to catch any new ones that 2238 // appear. This is really a hack, and means that apps can in some 2239 // cases get permissions that the user didn't initially explicitly 2240 // allow... it would be nice to have some better way to handle 2241 // this situation. 2242 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 2243 != mSdkVersion; 2244 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 2245 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 2246 + "; regranting permissions for internal storage"); 2247 mSettings.mInternalSdkPlatform = mSdkVersion; 2248 2249 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 2250 | (regrantPermissions 2251 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 2252 : 0)); 2253 2254 // If this is the first boot, and it is a normal boot, then 2255 // we need to initialize the default preferred apps. 2256 if (!mRestoredSettings && !onlyCore) { 2257 mSettings.applyDefaultPreferredAppsLPw(this, UserHandle.USER_OWNER); 2258 applyFactoryDefaultBrowserLPw(UserHandle.USER_OWNER); 2259 primeDomainVerificationsLPw(UserHandle.USER_OWNER); 2260 } 2261 2262 // If this is first boot after an OTA, and a normal boot, then 2263 // we need to clear code cache directories. 2264 mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint); 2265 if (mIsUpgrade && !onlyCore) { 2266 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2267 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2268 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2269 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2270 } 2271 mSettings.mFingerprint = Build.FINGERPRINT; 2272 } 2273 2274 checkDefaultBrowser(); 2275 2276 // All the changes are done during package scanning. 2277 mSettings.updateInternalDatabaseVersion(); 2278 2279 // can downgrade to reader 2280 mSettings.writeLPr(); 2281 2282 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2283 SystemClock.uptimeMillis()); 2284 2285 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2286 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2287 2288 mInstallerService = new PackageInstallerService(context, this); 2289 2290 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2291 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2292 mIntentFilterVerifierComponent); 2293 2294 } // synchronized (mPackages) 2295 } // synchronized (mInstallLock) 2296 2297 // Now after opening every single application zip, make sure they 2298 // are all flushed. Not really needed, but keeps things nice and 2299 // tidy. 2300 Runtime.getRuntime().gc(); 2301 2302 // Expose private service for system components to use. 2303 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2304 } 2305 2306 @Override 2307 public boolean isFirstBoot() { 2308 return !mRestoredSettings; 2309 } 2310 2311 @Override 2312 public boolean isOnlyCoreApps() { 2313 return mOnlyCore; 2314 } 2315 2316 @Override 2317 public boolean isUpgrade() { 2318 return mIsUpgrade; 2319 } 2320 2321 private String getRequiredVerifierLPr() { 2322 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2323 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2324 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 2325 2326 String requiredVerifier = null; 2327 2328 final int N = receivers.size(); 2329 for (int i = 0; i < N; i++) { 2330 final ResolveInfo info = receivers.get(i); 2331 2332 if (info.activityInfo == null) { 2333 continue; 2334 } 2335 2336 final String packageName = info.activityInfo.packageName; 2337 2338 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2339 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2340 continue; 2341 } 2342 2343 if (requiredVerifier != null) { 2344 throw new RuntimeException("There can be only one required verifier"); 2345 } 2346 2347 requiredVerifier = packageName; 2348 } 2349 2350 return requiredVerifier; 2351 } 2352 2353 private String getRequiredInstallerLPr() { 2354 Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2355 installerIntent.addCategory(Intent.CATEGORY_DEFAULT); 2356 installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2357 2358 final List<ResolveInfo> installers = queryIntentActivities(installerIntent, 2359 PACKAGE_MIME_TYPE, 0, 0); 2360 2361 String requiredInstaller = null; 2362 2363 final int N = installers.size(); 2364 for (int i = 0; i < N; i++) { 2365 final ResolveInfo info = installers.get(i); 2366 final String packageName = info.activityInfo.packageName; 2367 2368 if (!info.activityInfo.applicationInfo.isSystemApp()) { 2369 continue; 2370 } 2371 2372 if (requiredInstaller != null) { 2373 throw new RuntimeException("There must be one required installer"); 2374 } 2375 2376 requiredInstaller = packageName; 2377 } 2378 2379 if (requiredInstaller == null) { 2380 throw new RuntimeException("There must be one required installer"); 2381 } 2382 2383 return requiredInstaller; 2384 } 2385 2386 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2387 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2388 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2389 PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */); 2390 2391 ComponentName verifierComponentName = null; 2392 2393 int priority = -1000; 2394 final int N = receivers.size(); 2395 for (int i = 0; i < N; i++) { 2396 final ResolveInfo info = receivers.get(i); 2397 2398 if (info.activityInfo == null) { 2399 continue; 2400 } 2401 2402 final String packageName = info.activityInfo.packageName; 2403 2404 final PackageSetting ps = mSettings.mPackages.get(packageName); 2405 if (ps == null) { 2406 continue; 2407 } 2408 2409 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2410 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2411 continue; 2412 } 2413 2414 // Select the IntentFilterVerifier with the highest priority 2415 if (priority < info.priority) { 2416 priority = info.priority; 2417 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2418 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: " 2419 + verifierComponentName + " with priority: " + info.priority); 2420 } 2421 } 2422 2423 return verifierComponentName; 2424 } 2425 2426 private void primeDomainVerificationsLPw(int userId) { 2427 if (DEBUG_DOMAIN_VERIFICATION) { 2428 Slog.d(TAG, "Priming domain verifications in user " + userId); 2429 } 2430 2431 SystemConfig systemConfig = SystemConfig.getInstance(); 2432 ArraySet<String> packages = systemConfig.getLinkedApps(); 2433 ArraySet<String> domains = new ArraySet<String>(); 2434 2435 for (String packageName : packages) { 2436 PackageParser.Package pkg = mPackages.get(packageName); 2437 if (pkg != null) { 2438 if (!pkg.isSystemApp()) { 2439 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2440 continue; 2441 } 2442 2443 domains.clear(); 2444 for (PackageParser.Activity a : pkg.activities) { 2445 for (ActivityIntentInfo filter : a.intents) { 2446 if (hasValidDomains(filter)) { 2447 domains.addAll(filter.getHostsList()); 2448 } 2449 } 2450 } 2451 2452 if (domains.size() > 0) { 2453 if (DEBUG_DOMAIN_VERIFICATION) { 2454 Slog.v(TAG, " + " + packageName); 2455 } 2456 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2457 // state w.r.t. the formal app-linkage "no verification attempted" state; 2458 // and then 'always' in the per-user state actually used for intent resolution. 2459 final IntentFilterVerificationInfo ivi; 2460 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2461 new ArrayList<String>(domains)); 2462 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2463 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2464 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2465 } else { 2466 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2467 + "' does not handle web links"); 2468 } 2469 } else { 2470 Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>"); 2471 } 2472 } 2473 2474 scheduleWritePackageRestrictionsLocked(userId); 2475 scheduleWriteSettingsLocked(); 2476 } 2477 2478 private void applyFactoryDefaultBrowserLPw(int userId) { 2479 // The default browser app's package name is stored in a string resource, 2480 // with a product-specific overlay used for vendor customization. 2481 String browserPkg = mContext.getResources().getString( 2482 com.android.internal.R.string.default_browser); 2483 if (!TextUtils.isEmpty(browserPkg)) { 2484 // non-empty string => required to be a known package 2485 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2486 if (ps == null) { 2487 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2488 browserPkg = null; 2489 } else { 2490 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2491 } 2492 } 2493 2494 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2495 // default. If there's more than one, just leave everything alone. 2496 if (browserPkg == null) { 2497 calculateDefaultBrowserLPw(userId); 2498 } 2499 } 2500 2501 private void calculateDefaultBrowserLPw(int userId) { 2502 List<String> allBrowsers = resolveAllBrowserApps(userId); 2503 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2504 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2505 } 2506 2507 private List<String> resolveAllBrowserApps(int userId) { 2508 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2509 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2510 PackageManager.MATCH_ALL, userId); 2511 2512 final int count = list.size(); 2513 List<String> result = new ArrayList<String>(count); 2514 for (int i=0; i<count; i++) { 2515 ResolveInfo info = list.get(i); 2516 if (info.activityInfo == null 2517 || !info.handleAllWebDataURI 2518 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2519 || result.contains(info.activityInfo.packageName)) { 2520 continue; 2521 } 2522 result.add(info.activityInfo.packageName); 2523 } 2524 2525 return result; 2526 } 2527 2528 private boolean packageIsBrowser(String packageName, int userId) { 2529 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2530 PackageManager.MATCH_ALL, userId); 2531 final int N = list.size(); 2532 for (int i = 0; i < N; i++) { 2533 ResolveInfo info = list.get(i); 2534 if (packageName.equals(info.activityInfo.packageName)) { 2535 return true; 2536 } 2537 } 2538 return false; 2539 } 2540 2541 private void checkDefaultBrowser() { 2542 final int myUserId = UserHandle.myUserId(); 2543 final String packageName = getDefaultBrowserPackageName(myUserId); 2544 if (packageName != null) { 2545 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2546 if (info == null) { 2547 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2548 synchronized (mPackages) { 2549 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2550 } 2551 } 2552 } 2553 } 2554 2555 @Override 2556 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2557 throws RemoteException { 2558 try { 2559 return super.onTransact(code, data, reply, flags); 2560 } catch (RuntimeException e) { 2561 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2562 Slog.wtf(TAG, "Package Manager Crash", e); 2563 } 2564 throw e; 2565 } 2566 } 2567 2568 void cleanupInstallFailedPackage(PackageSetting ps) { 2569 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2570 2571 removeDataDirsLI(ps.volumeUuid, ps.name); 2572 if (ps.codePath != null) { 2573 if (ps.codePath.isDirectory()) { 2574 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2575 } else { 2576 ps.codePath.delete(); 2577 } 2578 } 2579 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2580 if (ps.resourcePath.isDirectory()) { 2581 FileUtils.deleteContents(ps.resourcePath); 2582 } 2583 ps.resourcePath.delete(); 2584 } 2585 mSettings.removePackageLPw(ps.name); 2586 } 2587 2588 static int[] appendInts(int[] cur, int[] add) { 2589 if (add == null) return cur; 2590 if (cur == null) return add; 2591 final int N = add.length; 2592 for (int i=0; i<N; i++) { 2593 cur = appendInt(cur, add[i]); 2594 } 2595 return cur; 2596 } 2597 2598 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2599 if (!sUserManager.exists(userId)) return null; 2600 final PackageSetting ps = (PackageSetting) p.mExtras; 2601 if (ps == null) { 2602 return null; 2603 } 2604 2605 final PermissionsState permissionsState = ps.getPermissionsState(); 2606 2607 final int[] gids = permissionsState.computeGids(userId); 2608 final Set<String> permissions = permissionsState.getPermissions(userId); 2609 final PackageUserState state = ps.readUserState(userId); 2610 2611 return PackageParser.generatePackageInfo(p, gids, flags, 2612 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2613 } 2614 2615 @Override 2616 public boolean isPackageFrozen(String packageName) { 2617 synchronized (mPackages) { 2618 final PackageSetting ps = mSettings.mPackages.get(packageName); 2619 if (ps != null) { 2620 return ps.frozen; 2621 } 2622 } 2623 Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen"); 2624 return true; 2625 } 2626 2627 @Override 2628 public boolean isPackageAvailable(String packageName, int userId) { 2629 if (!sUserManager.exists(userId)) return false; 2630 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2631 synchronized (mPackages) { 2632 PackageParser.Package p = mPackages.get(packageName); 2633 if (p != null) { 2634 final PackageSetting ps = (PackageSetting) p.mExtras; 2635 if (ps != null) { 2636 final PackageUserState state = ps.readUserState(userId); 2637 if (state != null) { 2638 return PackageParser.isAvailable(state); 2639 } 2640 } 2641 } 2642 } 2643 return false; 2644 } 2645 2646 @Override 2647 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2648 if (!sUserManager.exists(userId)) return null; 2649 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2650 // reader 2651 synchronized (mPackages) { 2652 PackageParser.Package p = mPackages.get(packageName); 2653 if (DEBUG_PACKAGE_INFO) 2654 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2655 if (p != null) { 2656 return generatePackageInfo(p, flags, userId); 2657 } 2658 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2659 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2660 } 2661 } 2662 return null; 2663 } 2664 2665 @Override 2666 public String[] currentToCanonicalPackageNames(String[] names) { 2667 String[] out = new String[names.length]; 2668 // reader 2669 synchronized (mPackages) { 2670 for (int i=names.length-1; i>=0; i--) { 2671 PackageSetting ps = mSettings.mPackages.get(names[i]); 2672 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2673 } 2674 } 2675 return out; 2676 } 2677 2678 @Override 2679 public String[] canonicalToCurrentPackageNames(String[] names) { 2680 String[] out = new String[names.length]; 2681 // reader 2682 synchronized (mPackages) { 2683 for (int i=names.length-1; i>=0; i--) { 2684 String cur = mSettings.mRenamedPackages.get(names[i]); 2685 out[i] = cur != null ? cur : names[i]; 2686 } 2687 } 2688 return out; 2689 } 2690 2691 @Override 2692 public int getPackageUid(String packageName, int userId) { 2693 if (!sUserManager.exists(userId)) return -1; 2694 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2695 2696 // reader 2697 synchronized (mPackages) { 2698 PackageParser.Package p = mPackages.get(packageName); 2699 if(p != null) { 2700 return UserHandle.getUid(userId, p.applicationInfo.uid); 2701 } 2702 PackageSetting ps = mSettings.mPackages.get(packageName); 2703 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2704 return -1; 2705 } 2706 p = ps.pkg; 2707 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2708 } 2709 } 2710 2711 @Override 2712 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2713 if (!sUserManager.exists(userId)) { 2714 return null; 2715 } 2716 2717 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2718 "getPackageGids"); 2719 2720 // reader 2721 synchronized (mPackages) { 2722 PackageParser.Package p = mPackages.get(packageName); 2723 if (DEBUG_PACKAGE_INFO) { 2724 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2725 } 2726 if (p != null) { 2727 PackageSetting ps = (PackageSetting) p.mExtras; 2728 return ps.getPermissionsState().computeGids(userId); 2729 } 2730 } 2731 2732 return null; 2733 } 2734 2735 static PermissionInfo generatePermissionInfo( 2736 BasePermission bp, int flags) { 2737 if (bp.perm != null) { 2738 return PackageParser.generatePermissionInfo(bp.perm, flags); 2739 } 2740 PermissionInfo pi = new PermissionInfo(); 2741 pi.name = bp.name; 2742 pi.packageName = bp.sourcePackage; 2743 pi.nonLocalizedLabel = bp.name; 2744 pi.protectionLevel = bp.protectionLevel; 2745 return pi; 2746 } 2747 2748 @Override 2749 public PermissionInfo getPermissionInfo(String name, int flags) { 2750 // reader 2751 synchronized (mPackages) { 2752 final BasePermission p = mSettings.mPermissions.get(name); 2753 if (p != null) { 2754 return generatePermissionInfo(p, flags); 2755 } 2756 return null; 2757 } 2758 } 2759 2760 @Override 2761 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2762 // reader 2763 synchronized (mPackages) { 2764 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2765 for (BasePermission p : mSettings.mPermissions.values()) { 2766 if (group == null) { 2767 if (p.perm == null || p.perm.info.group == null) { 2768 out.add(generatePermissionInfo(p, flags)); 2769 } 2770 } else { 2771 if (p.perm != null && group.equals(p.perm.info.group)) { 2772 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2773 } 2774 } 2775 } 2776 2777 if (out.size() > 0) { 2778 return out; 2779 } 2780 return mPermissionGroups.containsKey(group) ? out : null; 2781 } 2782 } 2783 2784 @Override 2785 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2786 // reader 2787 synchronized (mPackages) { 2788 return PackageParser.generatePermissionGroupInfo( 2789 mPermissionGroups.get(name), flags); 2790 } 2791 } 2792 2793 @Override 2794 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2795 // reader 2796 synchronized (mPackages) { 2797 final int N = mPermissionGroups.size(); 2798 ArrayList<PermissionGroupInfo> out 2799 = new ArrayList<PermissionGroupInfo>(N); 2800 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2801 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2802 } 2803 return out; 2804 } 2805 } 2806 2807 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2808 int userId) { 2809 if (!sUserManager.exists(userId)) return null; 2810 PackageSetting ps = mSettings.mPackages.get(packageName); 2811 if (ps != null) { 2812 if (ps.pkg == null) { 2813 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2814 flags, userId); 2815 if (pInfo != null) { 2816 return pInfo.applicationInfo; 2817 } 2818 return null; 2819 } 2820 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2821 ps.readUserState(userId), userId); 2822 } 2823 return null; 2824 } 2825 2826 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2827 int userId) { 2828 if (!sUserManager.exists(userId)) return null; 2829 PackageSetting ps = mSettings.mPackages.get(packageName); 2830 if (ps != null) { 2831 PackageParser.Package pkg = ps.pkg; 2832 if (pkg == null) { 2833 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2834 return null; 2835 } 2836 // Only data remains, so we aren't worried about code paths 2837 pkg = new PackageParser.Package(packageName); 2838 pkg.applicationInfo.packageName = packageName; 2839 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2840 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2841 pkg.applicationInfo.dataDir = Environment 2842 .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName) 2843 .getAbsolutePath(); 2844 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2845 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2846 } 2847 return generatePackageInfo(pkg, flags, userId); 2848 } 2849 return null; 2850 } 2851 2852 @Override 2853 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2854 if (!sUserManager.exists(userId)) return null; 2855 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2856 // writer 2857 synchronized (mPackages) { 2858 PackageParser.Package p = mPackages.get(packageName); 2859 if (DEBUG_PACKAGE_INFO) Log.v( 2860 TAG, "getApplicationInfo " + packageName 2861 + ": " + p); 2862 if (p != null) { 2863 PackageSetting ps = mSettings.mPackages.get(packageName); 2864 if (ps == null) return null; 2865 // Note: isEnabledLP() does not apply here - always return info 2866 return PackageParser.generateApplicationInfo( 2867 p, flags, ps.readUserState(userId), userId); 2868 } 2869 if ("android".equals(packageName)||"system".equals(packageName)) { 2870 return mAndroidApplication; 2871 } 2872 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2873 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2874 } 2875 } 2876 return null; 2877 } 2878 2879 @Override 2880 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2881 final IPackageDataObserver observer) { 2882 mContext.enforceCallingOrSelfPermission( 2883 android.Manifest.permission.CLEAR_APP_CACHE, null); 2884 // Queue up an async operation since clearing cache may take a little while. 2885 mHandler.post(new Runnable() { 2886 public void run() { 2887 mHandler.removeCallbacks(this); 2888 int retCode = -1; 2889 synchronized (mInstallLock) { 2890 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2891 if (retCode < 0) { 2892 Slog.w(TAG, "Couldn't clear application caches"); 2893 } 2894 } 2895 if (observer != null) { 2896 try { 2897 observer.onRemoveCompleted(null, (retCode >= 0)); 2898 } catch (RemoteException e) { 2899 Slog.w(TAG, "RemoveException when invoking call back"); 2900 } 2901 } 2902 } 2903 }); 2904 } 2905 2906 @Override 2907 public void freeStorage(final String volumeUuid, final long freeStorageSize, 2908 final IntentSender pi) { 2909 mContext.enforceCallingOrSelfPermission( 2910 android.Manifest.permission.CLEAR_APP_CACHE, null); 2911 // Queue up an async operation since clearing cache may take a little while. 2912 mHandler.post(new Runnable() { 2913 public void run() { 2914 mHandler.removeCallbacks(this); 2915 int retCode = -1; 2916 synchronized (mInstallLock) { 2917 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2918 if (retCode < 0) { 2919 Slog.w(TAG, "Couldn't clear application caches"); 2920 } 2921 } 2922 if(pi != null) { 2923 try { 2924 // Callback via pending intent 2925 int code = (retCode >= 0) ? 1 : 0; 2926 pi.sendIntent(null, code, null, 2927 null, null); 2928 } catch (SendIntentException e1) { 2929 Slog.i(TAG, "Failed to send pending intent"); 2930 } 2931 } 2932 } 2933 }); 2934 } 2935 2936 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 2937 synchronized (mInstallLock) { 2938 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 2939 throw new IOException("Failed to free enough space"); 2940 } 2941 } 2942 } 2943 2944 @Override 2945 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2946 if (!sUserManager.exists(userId)) return null; 2947 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2948 synchronized (mPackages) { 2949 PackageParser.Activity a = mActivities.mActivities.get(component); 2950 2951 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2952 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2953 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2954 if (ps == null) return null; 2955 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2956 userId); 2957 } 2958 if (mResolveComponentName.equals(component)) { 2959 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2960 new PackageUserState(), userId); 2961 } 2962 } 2963 return null; 2964 } 2965 2966 @Override 2967 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2968 String resolvedType) { 2969 synchronized (mPackages) { 2970 if (component.equals(mResolveComponentName)) { 2971 // The resolver supports EVERYTHING! 2972 return true; 2973 } 2974 PackageParser.Activity a = mActivities.mActivities.get(component); 2975 if (a == null) { 2976 return false; 2977 } 2978 for (int i=0; i<a.intents.size(); i++) { 2979 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2980 intent.getData(), intent.getCategories(), TAG) >= 0) { 2981 return true; 2982 } 2983 } 2984 return false; 2985 } 2986 } 2987 2988 @Override 2989 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2990 if (!sUserManager.exists(userId)) return null; 2991 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 2992 synchronized (mPackages) { 2993 PackageParser.Activity a = mReceivers.mActivities.get(component); 2994 if (DEBUG_PACKAGE_INFO) Log.v( 2995 TAG, "getReceiverInfo " + component + ": " + a); 2996 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2997 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2998 if (ps == null) return null; 2999 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3000 userId); 3001 } 3002 } 3003 return null; 3004 } 3005 3006 @Override 3007 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3008 if (!sUserManager.exists(userId)) return null; 3009 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 3010 synchronized (mPackages) { 3011 PackageParser.Service s = mServices.mServices.get(component); 3012 if (DEBUG_PACKAGE_INFO) Log.v( 3013 TAG, "getServiceInfo " + component + ": " + s); 3014 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 3015 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3016 if (ps == null) return null; 3017 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3018 userId); 3019 } 3020 } 3021 return null; 3022 } 3023 3024 @Override 3025 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3026 if (!sUserManager.exists(userId)) return null; 3027 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 3028 synchronized (mPackages) { 3029 PackageParser.Provider p = mProviders.mProviders.get(component); 3030 if (DEBUG_PACKAGE_INFO) Log.v( 3031 TAG, "getProviderInfo " + component + ": " + p); 3032 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 3033 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3034 if (ps == null) return null; 3035 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3036 userId); 3037 } 3038 } 3039 return null; 3040 } 3041 3042 @Override 3043 public String[] getSystemSharedLibraryNames() { 3044 Set<String> libSet; 3045 synchronized (mPackages) { 3046 libSet = mSharedLibraries.keySet(); 3047 int size = libSet.size(); 3048 if (size > 0) { 3049 String[] libs = new String[size]; 3050 libSet.toArray(libs); 3051 return libs; 3052 } 3053 } 3054 return null; 3055 } 3056 3057 /** 3058 * @hide 3059 */ 3060 PackageParser.Package findSharedNonSystemLibrary(String libName) { 3061 synchronized (mPackages) { 3062 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 3063 if (lib != null && lib.apk != null) { 3064 return mPackages.get(lib.apk); 3065 } 3066 } 3067 return null; 3068 } 3069 3070 @Override 3071 public FeatureInfo[] getSystemAvailableFeatures() { 3072 Collection<FeatureInfo> featSet; 3073 synchronized (mPackages) { 3074 featSet = mAvailableFeatures.values(); 3075 int size = featSet.size(); 3076 if (size > 0) { 3077 FeatureInfo[] features = new FeatureInfo[size+1]; 3078 featSet.toArray(features); 3079 FeatureInfo fi = new FeatureInfo(); 3080 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3081 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3082 features[size] = fi; 3083 return features; 3084 } 3085 } 3086 return null; 3087 } 3088 3089 @Override 3090 public boolean hasSystemFeature(String name) { 3091 synchronized (mPackages) { 3092 return mAvailableFeatures.containsKey(name); 3093 } 3094 } 3095 3096 private void checkValidCaller(int uid, int userId) { 3097 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 3098 return; 3099 3100 throw new SecurityException("Caller uid=" + uid 3101 + " is not privileged to communicate with user=" + userId); 3102 } 3103 3104 @Override 3105 public int checkPermission(String permName, String pkgName, int userId) { 3106 if (!sUserManager.exists(userId)) { 3107 return PackageManager.PERMISSION_DENIED; 3108 } 3109 3110 synchronized (mPackages) { 3111 final PackageParser.Package p = mPackages.get(pkgName); 3112 if (p != null && p.mExtras != null) { 3113 final PackageSetting ps = (PackageSetting) p.mExtras; 3114 if (ps.getPermissionsState().hasPermission(permName, userId)) { 3115 return PackageManager.PERMISSION_GRANTED; 3116 } 3117 } 3118 } 3119 3120 return PackageManager.PERMISSION_DENIED; 3121 } 3122 3123 @Override 3124 public int checkUidPermission(String permName, int uid) { 3125 final int userId = UserHandle.getUserId(uid); 3126 3127 if (!sUserManager.exists(userId)) { 3128 return PackageManager.PERMISSION_DENIED; 3129 } 3130 3131 synchronized (mPackages) { 3132 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3133 if (obj != null) { 3134 final SettingBase ps = (SettingBase) obj; 3135 if (ps.getPermissionsState().hasPermission(permName, userId)) { 3136 return PackageManager.PERMISSION_GRANTED; 3137 } 3138 } else { 3139 ArraySet<String> perms = mSystemPermissions.get(uid); 3140 if (perms != null && perms.contains(permName)) { 3141 return PackageManager.PERMISSION_GRANTED; 3142 } 3143 } 3144 } 3145 3146 return PackageManager.PERMISSION_DENIED; 3147 } 3148 3149 @Override 3150 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3151 if (UserHandle.getCallingUserId() != userId) { 3152 mContext.enforceCallingPermission( 3153 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3154 "isPermissionRevokedByPolicy for user " + userId); 3155 } 3156 3157 if (checkPermission(permission, packageName, userId) 3158 == PackageManager.PERMISSION_GRANTED) { 3159 return false; 3160 } 3161 3162 final long identity = Binder.clearCallingIdentity(); 3163 try { 3164 final int flags = getPermissionFlags(permission, packageName, userId); 3165 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3166 } finally { 3167 Binder.restoreCallingIdentity(identity); 3168 } 3169 } 3170 3171 /** 3172 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3173 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3174 * @param checkShell TODO(yamasani): 3175 * @param message the message to log on security exception 3176 */ 3177 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3178 boolean checkShell, String message) { 3179 if (userId < 0) { 3180 throw new IllegalArgumentException("Invalid userId " + userId); 3181 } 3182 if (checkShell) { 3183 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3184 } 3185 if (userId == UserHandle.getUserId(callingUid)) return; 3186 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3187 if (requireFullPermission) { 3188 mContext.enforceCallingOrSelfPermission( 3189 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3190 } else { 3191 try { 3192 mContext.enforceCallingOrSelfPermission( 3193 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3194 } catch (SecurityException se) { 3195 mContext.enforceCallingOrSelfPermission( 3196 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3197 } 3198 } 3199 } 3200 } 3201 3202 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3203 if (callingUid == Process.SHELL_UID) { 3204 if (userHandle >= 0 3205 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3206 throw new SecurityException("Shell does not have permission to access user " 3207 + userHandle); 3208 } else if (userHandle < 0) { 3209 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3210 + Debug.getCallers(3)); 3211 } 3212 } 3213 } 3214 3215 private BasePermission findPermissionTreeLP(String permName) { 3216 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3217 if (permName.startsWith(bp.name) && 3218 permName.length() > bp.name.length() && 3219 permName.charAt(bp.name.length()) == '.') { 3220 return bp; 3221 } 3222 } 3223 return null; 3224 } 3225 3226 private BasePermission checkPermissionTreeLP(String permName) { 3227 if (permName != null) { 3228 BasePermission bp = findPermissionTreeLP(permName); 3229 if (bp != null) { 3230 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3231 return bp; 3232 } 3233 throw new SecurityException("Calling uid " 3234 + Binder.getCallingUid() 3235 + " is not allowed to add to permission tree " 3236 + bp.name + " owned by uid " + bp.uid); 3237 } 3238 } 3239 throw new SecurityException("No permission tree found for " + permName); 3240 } 3241 3242 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3243 if (s1 == null) { 3244 return s2 == null; 3245 } 3246 if (s2 == null) { 3247 return false; 3248 } 3249 if (s1.getClass() != s2.getClass()) { 3250 return false; 3251 } 3252 return s1.equals(s2); 3253 } 3254 3255 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3256 if (pi1.icon != pi2.icon) return false; 3257 if (pi1.logo != pi2.logo) return false; 3258 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3259 if (!compareStrings(pi1.name, pi2.name)) return false; 3260 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3261 // We'll take care of setting this one. 3262 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3263 // These are not currently stored in settings. 3264 //if (!compareStrings(pi1.group, pi2.group)) return false; 3265 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3266 //if (pi1.labelRes != pi2.labelRes) return false; 3267 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3268 return true; 3269 } 3270 3271 int permissionInfoFootprint(PermissionInfo info) { 3272 int size = info.name.length(); 3273 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3274 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3275 return size; 3276 } 3277 3278 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3279 int size = 0; 3280 for (BasePermission perm : mSettings.mPermissions.values()) { 3281 if (perm.uid == tree.uid) { 3282 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3283 } 3284 } 3285 return size; 3286 } 3287 3288 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3289 // We calculate the max size of permissions defined by this uid and throw 3290 // if that plus the size of 'info' would exceed our stated maximum. 3291 if (tree.uid != Process.SYSTEM_UID) { 3292 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3293 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3294 throw new SecurityException("Permission tree size cap exceeded"); 3295 } 3296 } 3297 } 3298 3299 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3300 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3301 throw new SecurityException("Label must be specified in permission"); 3302 } 3303 BasePermission tree = checkPermissionTreeLP(info.name); 3304 BasePermission bp = mSettings.mPermissions.get(info.name); 3305 boolean added = bp == null; 3306 boolean changed = true; 3307 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3308 if (added) { 3309 enforcePermissionCapLocked(info, tree); 3310 bp = new BasePermission(info.name, tree.sourcePackage, 3311 BasePermission.TYPE_DYNAMIC); 3312 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3313 throw new SecurityException( 3314 "Not allowed to modify non-dynamic permission " 3315 + info.name); 3316 } else { 3317 if (bp.protectionLevel == fixedLevel 3318 && bp.perm.owner.equals(tree.perm.owner) 3319 && bp.uid == tree.uid 3320 && comparePermissionInfos(bp.perm.info, info)) { 3321 changed = false; 3322 } 3323 } 3324 bp.protectionLevel = fixedLevel; 3325 info = new PermissionInfo(info); 3326 info.protectionLevel = fixedLevel; 3327 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3328 bp.perm.info.packageName = tree.perm.info.packageName; 3329 bp.uid = tree.uid; 3330 if (added) { 3331 mSettings.mPermissions.put(info.name, bp); 3332 } 3333 if (changed) { 3334 if (!async) { 3335 mSettings.writeLPr(); 3336 } else { 3337 scheduleWriteSettingsLocked(); 3338 } 3339 } 3340 return added; 3341 } 3342 3343 @Override 3344 public boolean addPermission(PermissionInfo info) { 3345 synchronized (mPackages) { 3346 return addPermissionLocked(info, false); 3347 } 3348 } 3349 3350 @Override 3351 public boolean addPermissionAsync(PermissionInfo info) { 3352 synchronized (mPackages) { 3353 return addPermissionLocked(info, true); 3354 } 3355 } 3356 3357 @Override 3358 public void removePermission(String name) { 3359 synchronized (mPackages) { 3360 checkPermissionTreeLP(name); 3361 BasePermission bp = mSettings.mPermissions.get(name); 3362 if (bp != null) { 3363 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3364 throw new SecurityException( 3365 "Not allowed to modify non-dynamic permission " 3366 + name); 3367 } 3368 mSettings.mPermissions.remove(name); 3369 mSettings.writeLPr(); 3370 } 3371 } 3372 } 3373 3374 private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg, 3375 BasePermission bp) { 3376 int index = pkg.requestedPermissions.indexOf(bp.name); 3377 if (index == -1) { 3378 throw new SecurityException("Package " + pkg.packageName 3379 + " has not requested permission " + bp.name); 3380 } 3381 if (!bp.isRuntime()) { 3382 throw new SecurityException("Permission " + bp.name 3383 + " is not a changeable permission type"); 3384 } 3385 } 3386 3387 @Override 3388 public void grantRuntimePermission(String packageName, String name, final int userId) { 3389 if (!sUserManager.exists(userId)) { 3390 Log.e(TAG, "No such user:" + userId); 3391 return; 3392 } 3393 3394 mContext.enforceCallingOrSelfPermission( 3395 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3396 "grantRuntimePermission"); 3397 3398 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3399 "grantRuntimePermission"); 3400 3401 final int uid; 3402 final SettingBase sb; 3403 3404 synchronized (mPackages) { 3405 final PackageParser.Package pkg = mPackages.get(packageName); 3406 if (pkg == null) { 3407 throw new IllegalArgumentException("Unknown package: " + packageName); 3408 } 3409 3410 final BasePermission bp = mSettings.mPermissions.get(name); 3411 if (bp == null) { 3412 throw new IllegalArgumentException("Unknown permission: " + name); 3413 } 3414 3415 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3416 3417 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3418 sb = (SettingBase) pkg.mExtras; 3419 if (sb == null) { 3420 throw new IllegalArgumentException("Unknown package: " + packageName); 3421 } 3422 3423 final PermissionsState permissionsState = sb.getPermissionsState(); 3424 3425 final int flags = permissionsState.getPermissionFlags(name, userId); 3426 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3427 throw new SecurityException("Cannot grant system fixed permission: " 3428 + name + " for package: " + packageName); 3429 } 3430 3431 final int result = permissionsState.grantRuntimePermission(bp, userId); 3432 switch (result) { 3433 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3434 return; 3435 } 3436 3437 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3438 mHandler.post(new Runnable() { 3439 @Override 3440 public void run() { 3441 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED); 3442 } 3443 }); 3444 } break; 3445 } 3446 3447 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3448 3449 // Not critical if that is lost - app has to request again. 3450 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3451 } 3452 3453 // Only need to do this if user is initialized. Otherwise it's a new user 3454 // and there are no processes running as the user yet and there's no need 3455 // to make an expensive call to remount processes for the changed permissions. 3456 if (READ_EXTERNAL_STORAGE.equals(name) 3457 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3458 final long token = Binder.clearCallingIdentity(); 3459 try { 3460 if (sUserManager.isInitialized(userId)) { 3461 MountServiceInternal mountServiceInternal = LocalServices.getService( 3462 MountServiceInternal.class); 3463 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 3464 } 3465 } finally { 3466 Binder.restoreCallingIdentity(token); 3467 } 3468 } 3469 } 3470 3471 @Override 3472 public void revokeRuntimePermission(String packageName, String name, int userId) { 3473 if (!sUserManager.exists(userId)) { 3474 Log.e(TAG, "No such user:" + userId); 3475 return; 3476 } 3477 3478 mContext.enforceCallingOrSelfPermission( 3479 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3480 "revokeRuntimePermission"); 3481 3482 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3483 "revokeRuntimePermission"); 3484 3485 final SettingBase sb; 3486 3487 synchronized (mPackages) { 3488 final PackageParser.Package pkg = mPackages.get(packageName); 3489 if (pkg == null) { 3490 throw new IllegalArgumentException("Unknown package: " + packageName); 3491 } 3492 3493 final BasePermission bp = mSettings.mPermissions.get(name); 3494 if (bp == null) { 3495 throw new IllegalArgumentException("Unknown permission: " + name); 3496 } 3497 3498 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3499 3500 sb = (SettingBase) pkg.mExtras; 3501 if (sb == null) { 3502 throw new IllegalArgumentException("Unknown package: " + packageName); 3503 } 3504 3505 final PermissionsState permissionsState = sb.getPermissionsState(); 3506 3507 final int flags = permissionsState.getPermissionFlags(name, userId); 3508 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3509 throw new SecurityException("Cannot revoke system fixed permission: " 3510 + name + " for package: " + packageName); 3511 } 3512 3513 if (permissionsState.revokeRuntimePermission(bp, userId) == 3514 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3515 return; 3516 } 3517 3518 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3519 3520 // Critical, after this call app should never have the permission. 3521 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3522 } 3523 3524 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3525 } 3526 3527 @Override 3528 public void resetRuntimePermissions() { 3529 mContext.enforceCallingOrSelfPermission( 3530 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3531 "revokeRuntimePermission"); 3532 3533 int callingUid = Binder.getCallingUid(); 3534 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3535 mContext.enforceCallingOrSelfPermission( 3536 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3537 "resetRuntimePermissions"); 3538 } 3539 3540 synchronized (mPackages) { 3541 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 3542 for (int userId : UserManagerService.getInstance().getUserIds()) { 3543 final int packageCount = mPackages.size(); 3544 for (int i = 0; i < packageCount; i++) { 3545 PackageParser.Package pkg = mPackages.valueAt(i); 3546 if (!(pkg.mExtras instanceof PackageSetting)) { 3547 continue; 3548 } 3549 PackageSetting ps = (PackageSetting) pkg.mExtras; 3550 resetUserChangesToRuntimePermissionsAndFlagsLocked(ps, userId); 3551 } 3552 } 3553 } 3554 } 3555 3556 @Override 3557 public int getPermissionFlags(String name, String packageName, int userId) { 3558 if (!sUserManager.exists(userId)) { 3559 return 0; 3560 } 3561 3562 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 3563 3564 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3565 "getPermissionFlags"); 3566 3567 synchronized (mPackages) { 3568 final PackageParser.Package pkg = mPackages.get(packageName); 3569 if (pkg == null) { 3570 throw new IllegalArgumentException("Unknown package: " + packageName); 3571 } 3572 3573 final BasePermission bp = mSettings.mPermissions.get(name); 3574 if (bp == null) { 3575 throw new IllegalArgumentException("Unknown permission: " + name); 3576 } 3577 3578 SettingBase sb = (SettingBase) pkg.mExtras; 3579 if (sb == null) { 3580 throw new IllegalArgumentException("Unknown package: " + packageName); 3581 } 3582 3583 PermissionsState permissionsState = sb.getPermissionsState(); 3584 return permissionsState.getPermissionFlags(name, userId); 3585 } 3586 } 3587 3588 @Override 3589 public void updatePermissionFlags(String name, String packageName, int flagMask, 3590 int flagValues, int userId) { 3591 if (!sUserManager.exists(userId)) { 3592 return; 3593 } 3594 3595 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 3596 3597 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3598 "updatePermissionFlags"); 3599 3600 // Only the system can change system fixed flags. 3601 if (getCallingUid() != Process.SYSTEM_UID) { 3602 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3603 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3604 } 3605 3606 synchronized (mPackages) { 3607 final PackageParser.Package pkg = mPackages.get(packageName); 3608 if (pkg == null) { 3609 throw new IllegalArgumentException("Unknown package: " + packageName); 3610 } 3611 3612 final BasePermission bp = mSettings.mPermissions.get(name); 3613 if (bp == null) { 3614 throw new IllegalArgumentException("Unknown permission: " + name); 3615 } 3616 3617 SettingBase sb = (SettingBase) pkg.mExtras; 3618 if (sb == null) { 3619 throw new IllegalArgumentException("Unknown package: " + packageName); 3620 } 3621 3622 PermissionsState permissionsState = sb.getPermissionsState(); 3623 3624 // Only the package manager can change flags for system component permissions. 3625 final int flags = permissionsState.getPermissionFlags(bp.name, userId); 3626 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3627 return; 3628 } 3629 3630 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 3631 3632 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3633 // Install and runtime permissions are stored in different places, 3634 // so figure out what permission changed and persist the change. 3635 if (permissionsState.getInstallPermissionState(name) != null) { 3636 scheduleWriteSettingsLocked(); 3637 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 3638 || hadState) { 3639 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3640 } 3641 } 3642 } 3643 } 3644 3645 /** 3646 * Update the permission flags for all packages and runtime permissions of a user in order 3647 * to allow device or profile owner to remove POLICY_FIXED. 3648 */ 3649 @Override 3650 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 3651 if (!sUserManager.exists(userId)) { 3652 return; 3653 } 3654 3655 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 3656 3657 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3658 "updatePermissionFlagsForAllApps"); 3659 3660 // Only the system can change system fixed flags. 3661 if (getCallingUid() != Process.SYSTEM_UID) { 3662 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3663 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3664 } 3665 3666 synchronized (mPackages) { 3667 boolean changed = false; 3668 final int packageCount = mPackages.size(); 3669 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 3670 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 3671 SettingBase sb = (SettingBase) pkg.mExtras; 3672 if (sb == null) { 3673 continue; 3674 } 3675 PermissionsState permissionsState = sb.getPermissionsState(); 3676 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 3677 userId, flagMask, flagValues); 3678 } 3679 if (changed) { 3680 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3681 } 3682 } 3683 } 3684 3685 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 3686 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 3687 != PackageManager.PERMISSION_GRANTED 3688 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 3689 != PackageManager.PERMISSION_GRANTED) { 3690 throw new SecurityException(message + " requires " 3691 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 3692 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 3693 } 3694 } 3695 3696 @Override 3697 public boolean shouldShowRequestPermissionRationale(String permissionName, 3698 String packageName, int userId) { 3699 if (UserHandle.getCallingUserId() != userId) { 3700 mContext.enforceCallingPermission( 3701 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3702 "canShowRequestPermissionRationale for user " + userId); 3703 } 3704 3705 final int uid = getPackageUid(packageName, userId); 3706 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 3707 return false; 3708 } 3709 3710 if (checkPermission(permissionName, packageName, userId) 3711 == PackageManager.PERMISSION_GRANTED) { 3712 return false; 3713 } 3714 3715 final int flags; 3716 3717 final long identity = Binder.clearCallingIdentity(); 3718 try { 3719 flags = getPermissionFlags(permissionName, 3720 packageName, userId); 3721 } finally { 3722 Binder.restoreCallingIdentity(identity); 3723 } 3724 3725 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 3726 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 3727 | PackageManager.FLAG_PERMISSION_USER_FIXED; 3728 3729 if ((flags & fixedFlags) != 0) { 3730 return false; 3731 } 3732 3733 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 3734 } 3735 3736 void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) { 3737 BasePermission bp = mSettings.mPermissions.get(permission); 3738 if (bp == null) { 3739 throw new SecurityException("Missing " + permission + " permission"); 3740 } 3741 3742 SettingBase sb = (SettingBase) pkg.mExtras; 3743 PermissionsState permissionsState = sb.getPermissionsState(); 3744 3745 if (permissionsState.grantInstallPermission(bp) != 3746 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3747 scheduleWriteSettingsLocked(); 3748 } 3749 } 3750 3751 @Override 3752 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3753 mContext.enforceCallingOrSelfPermission( 3754 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 3755 "addOnPermissionsChangeListener"); 3756 3757 synchronized (mPackages) { 3758 mOnPermissionChangeListeners.addListenerLocked(listener); 3759 } 3760 } 3761 3762 @Override 3763 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3764 synchronized (mPackages) { 3765 mOnPermissionChangeListeners.removeListenerLocked(listener); 3766 } 3767 } 3768 3769 @Override 3770 public boolean isProtectedBroadcast(String actionName) { 3771 synchronized (mPackages) { 3772 return mProtectedBroadcasts.contains(actionName); 3773 } 3774 } 3775 3776 @Override 3777 public int checkSignatures(String pkg1, String pkg2) { 3778 synchronized (mPackages) { 3779 final PackageParser.Package p1 = mPackages.get(pkg1); 3780 final PackageParser.Package p2 = mPackages.get(pkg2); 3781 if (p1 == null || p1.mExtras == null 3782 || p2 == null || p2.mExtras == null) { 3783 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3784 } 3785 return compareSignatures(p1.mSignatures, p2.mSignatures); 3786 } 3787 } 3788 3789 @Override 3790 public int checkUidSignatures(int uid1, int uid2) { 3791 // Map to base uids. 3792 uid1 = UserHandle.getAppId(uid1); 3793 uid2 = UserHandle.getAppId(uid2); 3794 // reader 3795 synchronized (mPackages) { 3796 Signature[] s1; 3797 Signature[] s2; 3798 Object obj = mSettings.getUserIdLPr(uid1); 3799 if (obj != null) { 3800 if (obj instanceof SharedUserSetting) { 3801 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3802 } else if (obj instanceof PackageSetting) { 3803 s1 = ((PackageSetting)obj).signatures.mSignatures; 3804 } else { 3805 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3806 } 3807 } else { 3808 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3809 } 3810 obj = mSettings.getUserIdLPr(uid2); 3811 if (obj != null) { 3812 if (obj instanceof SharedUserSetting) { 3813 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3814 } else if (obj instanceof PackageSetting) { 3815 s2 = ((PackageSetting)obj).signatures.mSignatures; 3816 } else { 3817 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3818 } 3819 } else { 3820 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3821 } 3822 return compareSignatures(s1, s2); 3823 } 3824 } 3825 3826 private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) { 3827 final long identity = Binder.clearCallingIdentity(); 3828 try { 3829 if (sb instanceof SharedUserSetting) { 3830 SharedUserSetting sus = (SharedUserSetting) sb; 3831 final int packageCount = sus.packages.size(); 3832 for (int i = 0; i < packageCount; i++) { 3833 PackageSetting susPs = sus.packages.valueAt(i); 3834 if (userId == UserHandle.USER_ALL) { 3835 killApplication(susPs.pkg.packageName, susPs.appId, reason); 3836 } else { 3837 final int uid = UserHandle.getUid(userId, susPs.appId); 3838 killUid(uid, reason); 3839 } 3840 } 3841 } else if (sb instanceof PackageSetting) { 3842 PackageSetting ps = (PackageSetting) sb; 3843 if (userId == UserHandle.USER_ALL) { 3844 killApplication(ps.pkg.packageName, ps.appId, reason); 3845 } else { 3846 final int uid = UserHandle.getUid(userId, ps.appId); 3847 killUid(uid, reason); 3848 } 3849 } 3850 } finally { 3851 Binder.restoreCallingIdentity(identity); 3852 } 3853 } 3854 3855 private static void killUid(int uid, String reason) { 3856 IActivityManager am = ActivityManagerNative.getDefault(); 3857 if (am != null) { 3858 try { 3859 am.killUid(uid, reason); 3860 } catch (RemoteException e) { 3861 /* ignore - same process */ 3862 } 3863 } 3864 } 3865 3866 /** 3867 * Compares two sets of signatures. Returns: 3868 * <br /> 3869 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3870 * <br /> 3871 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3872 * <br /> 3873 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3874 * <br /> 3875 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3876 * <br /> 3877 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3878 */ 3879 static int compareSignatures(Signature[] s1, Signature[] s2) { 3880 if (s1 == null) { 3881 return s2 == null 3882 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3883 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3884 } 3885 3886 if (s2 == null) { 3887 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3888 } 3889 3890 if (s1.length != s2.length) { 3891 return PackageManager.SIGNATURE_NO_MATCH; 3892 } 3893 3894 // Since both signature sets are of size 1, we can compare without HashSets. 3895 if (s1.length == 1) { 3896 return s1[0].equals(s2[0]) ? 3897 PackageManager.SIGNATURE_MATCH : 3898 PackageManager.SIGNATURE_NO_MATCH; 3899 } 3900 3901 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3902 for (Signature sig : s1) { 3903 set1.add(sig); 3904 } 3905 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3906 for (Signature sig : s2) { 3907 set2.add(sig); 3908 } 3909 // Make sure s2 contains all signatures in s1. 3910 if (set1.equals(set2)) { 3911 return PackageManager.SIGNATURE_MATCH; 3912 } 3913 return PackageManager.SIGNATURE_NO_MATCH; 3914 } 3915 3916 /** 3917 * If the database version for this type of package (internal storage or 3918 * external storage) is less than the version where package signatures 3919 * were updated, return true. 3920 */ 3921 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3922 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 3923 DatabaseVersion.SIGNATURE_END_ENTITY)) 3924 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 3925 DatabaseVersion.SIGNATURE_END_ENTITY)); 3926 } 3927 3928 /** 3929 * Used for backward compatibility to make sure any packages with 3930 * certificate chains get upgraded to the new style. {@code existingSigs} 3931 * will be in the old format (since they were stored on disk from before the 3932 * system upgrade) and {@code scannedSigs} will be in the newer format. 3933 */ 3934 private int compareSignaturesCompat(PackageSignatures existingSigs, 3935 PackageParser.Package scannedPkg) { 3936 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 3937 return PackageManager.SIGNATURE_NO_MATCH; 3938 } 3939 3940 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 3941 for (Signature sig : existingSigs.mSignatures) { 3942 existingSet.add(sig); 3943 } 3944 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 3945 for (Signature sig : scannedPkg.mSignatures) { 3946 try { 3947 Signature[] chainSignatures = sig.getChainSignatures(); 3948 for (Signature chainSig : chainSignatures) { 3949 scannedCompatSet.add(chainSig); 3950 } 3951 } catch (CertificateEncodingException e) { 3952 scannedCompatSet.add(sig); 3953 } 3954 } 3955 /* 3956 * Make sure the expanded scanned set contains all signatures in the 3957 * existing one. 3958 */ 3959 if (scannedCompatSet.equals(existingSet)) { 3960 // Migrate the old signatures to the new scheme. 3961 existingSigs.assignSignatures(scannedPkg.mSignatures); 3962 // The new KeySets will be re-added later in the scanning process. 3963 synchronized (mPackages) { 3964 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 3965 } 3966 return PackageManager.SIGNATURE_MATCH; 3967 } 3968 return PackageManager.SIGNATURE_NO_MATCH; 3969 } 3970 3971 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3972 if (isExternal(scannedPkg)) { 3973 return mSettings.isExternalDatabaseVersionOlderThan( 3974 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3975 } else { 3976 return mSettings.isInternalDatabaseVersionOlderThan( 3977 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3978 } 3979 } 3980 3981 private int compareSignaturesRecover(PackageSignatures existingSigs, 3982 PackageParser.Package scannedPkg) { 3983 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 3984 return PackageManager.SIGNATURE_NO_MATCH; 3985 } 3986 3987 String msg = null; 3988 try { 3989 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 3990 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 3991 + scannedPkg.packageName); 3992 return PackageManager.SIGNATURE_MATCH; 3993 } 3994 } catch (CertificateException e) { 3995 msg = e.getMessage(); 3996 } 3997 3998 logCriticalInfo(Log.INFO, 3999 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4000 return PackageManager.SIGNATURE_NO_MATCH; 4001 } 4002 4003 @Override 4004 public String[] getPackagesForUid(int uid) { 4005 uid = UserHandle.getAppId(uid); 4006 // reader 4007 synchronized (mPackages) { 4008 Object obj = mSettings.getUserIdLPr(uid); 4009 if (obj instanceof SharedUserSetting) { 4010 final SharedUserSetting sus = (SharedUserSetting) obj; 4011 final int N = sus.packages.size(); 4012 final String[] res = new String[N]; 4013 final Iterator<PackageSetting> it = sus.packages.iterator(); 4014 int i = 0; 4015 while (it.hasNext()) { 4016 res[i++] = it.next().name; 4017 } 4018 return res; 4019 } else if (obj instanceof PackageSetting) { 4020 final PackageSetting ps = (PackageSetting) obj; 4021 return new String[] { ps.name }; 4022 } 4023 } 4024 return null; 4025 } 4026 4027 @Override 4028 public String getNameForUid(int uid) { 4029 // reader 4030 synchronized (mPackages) { 4031 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4032 if (obj instanceof SharedUserSetting) { 4033 final SharedUserSetting sus = (SharedUserSetting) obj; 4034 return sus.name + ":" + sus.userId; 4035 } else if (obj instanceof PackageSetting) { 4036 final PackageSetting ps = (PackageSetting) obj; 4037 return ps.name; 4038 } 4039 } 4040 return null; 4041 } 4042 4043 @Override 4044 public int getUidForSharedUser(String sharedUserName) { 4045 if(sharedUserName == null) { 4046 return -1; 4047 } 4048 // reader 4049 synchronized (mPackages) { 4050 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4051 if (suid == null) { 4052 return -1; 4053 } 4054 return suid.userId; 4055 } 4056 } 4057 4058 @Override 4059 public int getFlagsForUid(int uid) { 4060 synchronized (mPackages) { 4061 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4062 if (obj instanceof SharedUserSetting) { 4063 final SharedUserSetting sus = (SharedUserSetting) obj; 4064 return sus.pkgFlags; 4065 } else if (obj instanceof PackageSetting) { 4066 final PackageSetting ps = (PackageSetting) obj; 4067 return ps.pkgFlags; 4068 } 4069 } 4070 return 0; 4071 } 4072 4073 @Override 4074 public int getPrivateFlagsForUid(int uid) { 4075 synchronized (mPackages) { 4076 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4077 if (obj instanceof SharedUserSetting) { 4078 final SharedUserSetting sus = (SharedUserSetting) obj; 4079 return sus.pkgPrivateFlags; 4080 } else if (obj instanceof PackageSetting) { 4081 final PackageSetting ps = (PackageSetting) obj; 4082 return ps.pkgPrivateFlags; 4083 } 4084 } 4085 return 0; 4086 } 4087 4088 @Override 4089 public boolean isUidPrivileged(int uid) { 4090 uid = UserHandle.getAppId(uid); 4091 // reader 4092 synchronized (mPackages) { 4093 Object obj = mSettings.getUserIdLPr(uid); 4094 if (obj instanceof SharedUserSetting) { 4095 final SharedUserSetting sus = (SharedUserSetting) obj; 4096 final Iterator<PackageSetting> it = sus.packages.iterator(); 4097 while (it.hasNext()) { 4098 if (it.next().isPrivileged()) { 4099 return true; 4100 } 4101 } 4102 } else if (obj instanceof PackageSetting) { 4103 final PackageSetting ps = (PackageSetting) obj; 4104 return ps.isPrivileged(); 4105 } 4106 } 4107 return false; 4108 } 4109 4110 @Override 4111 public String[] getAppOpPermissionPackages(String permissionName) { 4112 synchronized (mPackages) { 4113 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4114 if (pkgs == null) { 4115 return null; 4116 } 4117 return pkgs.toArray(new String[pkgs.size()]); 4118 } 4119 } 4120 4121 @Override 4122 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4123 int flags, int userId) { 4124 if (!sUserManager.exists(userId)) return null; 4125 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 4126 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4127 return chooseBestActivity(intent, resolvedType, flags, query, userId); 4128 } 4129 4130 @Override 4131 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4132 IntentFilter filter, int match, ComponentName activity) { 4133 final int userId = UserHandle.getCallingUserId(); 4134 if (DEBUG_PREFERRED) { 4135 Log.v(TAG, "setLastChosenActivity intent=" + intent 4136 + " resolvedType=" + resolvedType 4137 + " flags=" + flags 4138 + " filter=" + filter 4139 + " match=" + match 4140 + " activity=" + activity); 4141 filter.dump(new PrintStreamPrinter(System.out), " "); 4142 } 4143 intent.setComponent(null); 4144 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4145 // Find any earlier preferred or last chosen entries and nuke them 4146 findPreferredActivity(intent, resolvedType, 4147 flags, query, 0, false, true, false, userId); 4148 // Add the new activity as the last chosen for this filter 4149 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4150 "Setting last chosen"); 4151 } 4152 4153 @Override 4154 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4155 final int userId = UserHandle.getCallingUserId(); 4156 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4157 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4158 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4159 false, false, false, userId); 4160 } 4161 4162 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4163 int flags, List<ResolveInfo> query, int userId) { 4164 if (query != null) { 4165 final int N = query.size(); 4166 if (N == 1) { 4167 return query.get(0); 4168 } else if (N > 1) { 4169 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4170 // If there is more than one activity with the same priority, 4171 // then let the user decide between them. 4172 ResolveInfo r0 = query.get(0); 4173 ResolveInfo r1 = query.get(1); 4174 if (DEBUG_INTENT_MATCHING || debug) { 4175 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4176 + r1.activityInfo.name + "=" + r1.priority); 4177 } 4178 // If the first activity has a higher priority, or a different 4179 // default, then it is always desireable to pick it. 4180 if (r0.priority != r1.priority 4181 || r0.preferredOrder != r1.preferredOrder 4182 || r0.isDefault != r1.isDefault) { 4183 return query.get(0); 4184 } 4185 // If we have saved a preference for a preferred activity for 4186 // this Intent, use that. 4187 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4188 flags, query, r0.priority, true, false, debug, userId); 4189 if (ri != null) { 4190 return ri; 4191 } 4192 if (userId != 0) { 4193 ri = new ResolveInfo(mResolveInfo); 4194 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4195 ri.activityInfo.applicationInfo = new ApplicationInfo( 4196 ri.activityInfo.applicationInfo); 4197 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4198 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4199 return ri; 4200 } 4201 return mResolveInfo; 4202 } 4203 } 4204 return null; 4205 } 4206 4207 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4208 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4209 final int N = query.size(); 4210 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4211 .get(userId); 4212 // Get the list of persistent preferred activities that handle the intent 4213 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4214 List<PersistentPreferredActivity> pprefs = ppir != null 4215 ? ppir.queryIntent(intent, resolvedType, 4216 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4217 : null; 4218 if (pprefs != null && pprefs.size() > 0) { 4219 final int M = pprefs.size(); 4220 for (int i=0; i<M; i++) { 4221 final PersistentPreferredActivity ppa = pprefs.get(i); 4222 if (DEBUG_PREFERRED || debug) { 4223 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4224 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4225 + "\n component=" + ppa.mComponent); 4226 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4227 } 4228 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4229 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4230 if (DEBUG_PREFERRED || debug) { 4231 Slog.v(TAG, "Found persistent preferred activity:"); 4232 if (ai != null) { 4233 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4234 } else { 4235 Slog.v(TAG, " null"); 4236 } 4237 } 4238 if (ai == null) { 4239 // This previously registered persistent preferred activity 4240 // component is no longer known. Ignore it and do NOT remove it. 4241 continue; 4242 } 4243 for (int j=0; j<N; j++) { 4244 final ResolveInfo ri = query.get(j); 4245 if (!ri.activityInfo.applicationInfo.packageName 4246 .equals(ai.applicationInfo.packageName)) { 4247 continue; 4248 } 4249 if (!ri.activityInfo.name.equals(ai.name)) { 4250 continue; 4251 } 4252 // Found a persistent preference that can handle the intent. 4253 if (DEBUG_PREFERRED || debug) { 4254 Slog.v(TAG, "Returning persistent preferred activity: " + 4255 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4256 } 4257 return ri; 4258 } 4259 } 4260 } 4261 return null; 4262 } 4263 4264 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4265 List<ResolveInfo> query, int priority, boolean always, 4266 boolean removeMatches, boolean debug, int userId) { 4267 if (!sUserManager.exists(userId)) return null; 4268 // writer 4269 synchronized (mPackages) { 4270 if (intent.getSelector() != null) { 4271 intent = intent.getSelector(); 4272 } 4273 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4274 4275 // Try to find a matching persistent preferred activity. 4276 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4277 debug, userId); 4278 4279 // If a persistent preferred activity matched, use it. 4280 if (pri != null) { 4281 return pri; 4282 } 4283 4284 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4285 // Get the list of preferred activities that handle the intent 4286 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4287 List<PreferredActivity> prefs = pir != null 4288 ? pir.queryIntent(intent, resolvedType, 4289 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4290 : null; 4291 if (prefs != null && prefs.size() > 0) { 4292 boolean changed = false; 4293 try { 4294 // First figure out how good the original match set is. 4295 // We will only allow preferred activities that came 4296 // from the same match quality. 4297 int match = 0; 4298 4299 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4300 4301 final int N = query.size(); 4302 for (int j=0; j<N; j++) { 4303 final ResolveInfo ri = query.get(j); 4304 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4305 + ": 0x" + Integer.toHexString(match)); 4306 if (ri.match > match) { 4307 match = ri.match; 4308 } 4309 } 4310 4311 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4312 + Integer.toHexString(match)); 4313 4314 match &= IntentFilter.MATCH_CATEGORY_MASK; 4315 final int M = prefs.size(); 4316 for (int i=0; i<M; i++) { 4317 final PreferredActivity pa = prefs.get(i); 4318 if (DEBUG_PREFERRED || debug) { 4319 Slog.v(TAG, "Checking PreferredActivity ds=" 4320 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4321 + "\n component=" + pa.mPref.mComponent); 4322 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4323 } 4324 if (pa.mPref.mMatch != match) { 4325 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4326 + Integer.toHexString(pa.mPref.mMatch)); 4327 continue; 4328 } 4329 // If it's not an "always" type preferred activity and that's what we're 4330 // looking for, skip it. 4331 if (always && !pa.mPref.mAlways) { 4332 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4333 continue; 4334 } 4335 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4336 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4337 if (DEBUG_PREFERRED || debug) { 4338 Slog.v(TAG, "Found preferred activity:"); 4339 if (ai != null) { 4340 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4341 } else { 4342 Slog.v(TAG, " null"); 4343 } 4344 } 4345 if (ai == null) { 4346 // This previously registered preferred activity 4347 // component is no longer known. Most likely an update 4348 // to the app was installed and in the new version this 4349 // component no longer exists. Clean it up by removing 4350 // it from the preferred activities list, and skip it. 4351 Slog.w(TAG, "Removing dangling preferred activity: " 4352 + pa.mPref.mComponent); 4353 pir.removeFilter(pa); 4354 changed = true; 4355 continue; 4356 } 4357 for (int j=0; j<N; j++) { 4358 final ResolveInfo ri = query.get(j); 4359 if (!ri.activityInfo.applicationInfo.packageName 4360 .equals(ai.applicationInfo.packageName)) { 4361 continue; 4362 } 4363 if (!ri.activityInfo.name.equals(ai.name)) { 4364 continue; 4365 } 4366 4367 if (removeMatches) { 4368 pir.removeFilter(pa); 4369 changed = true; 4370 if (DEBUG_PREFERRED) { 4371 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4372 } 4373 break; 4374 } 4375 4376 // Okay we found a previously set preferred or last chosen app. 4377 // If the result set is different from when this 4378 // was created, we need to clear it and re-ask the 4379 // user their preference, if we're looking for an "always" type entry. 4380 if (always && !pa.mPref.sameSet(query)) { 4381 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4382 + intent + " type " + resolvedType); 4383 if (DEBUG_PREFERRED) { 4384 Slog.v(TAG, "Removing preferred activity since set changed " 4385 + pa.mPref.mComponent); 4386 } 4387 pir.removeFilter(pa); 4388 // Re-add the filter as a "last chosen" entry (!always) 4389 PreferredActivity lastChosen = new PreferredActivity( 4390 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4391 pir.addFilter(lastChosen); 4392 changed = true; 4393 return null; 4394 } 4395 4396 // Yay! Either the set matched or we're looking for the last chosen 4397 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4398 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4399 return ri; 4400 } 4401 } 4402 } finally { 4403 if (changed) { 4404 if (DEBUG_PREFERRED) { 4405 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4406 } 4407 scheduleWritePackageRestrictionsLocked(userId); 4408 } 4409 } 4410 } 4411 } 4412 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4413 return null; 4414 } 4415 4416 /* 4417 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4418 */ 4419 @Override 4420 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4421 int targetUserId) { 4422 mContext.enforceCallingOrSelfPermission( 4423 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4424 List<CrossProfileIntentFilter> matches = 4425 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4426 if (matches != null) { 4427 int size = matches.size(); 4428 for (int i = 0; i < size; i++) { 4429 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4430 } 4431 } 4432 if (hasWebURI(intent)) { 4433 // cross-profile app linking works only towards the parent. 4434 final UserInfo parent = getProfileParent(sourceUserId); 4435 synchronized(mPackages) { 4436 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 4437 intent, resolvedType, 0, sourceUserId, parent.id); 4438 return xpDomainInfo != null; 4439 } 4440 } 4441 return false; 4442 } 4443 4444 private UserInfo getProfileParent(int userId) { 4445 final long identity = Binder.clearCallingIdentity(); 4446 try { 4447 return sUserManager.getProfileParent(userId); 4448 } finally { 4449 Binder.restoreCallingIdentity(identity); 4450 } 4451 } 4452 4453 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4454 String resolvedType, int userId) { 4455 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4456 if (resolver != null) { 4457 return resolver.queryIntent(intent, resolvedType, false, userId); 4458 } 4459 return null; 4460 } 4461 4462 @Override 4463 public List<ResolveInfo> queryIntentActivities(Intent intent, 4464 String resolvedType, int flags, int userId) { 4465 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4466 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4467 ComponentName comp = intent.getComponent(); 4468 if (comp == null) { 4469 if (intent.getSelector() != null) { 4470 intent = intent.getSelector(); 4471 comp = intent.getComponent(); 4472 } 4473 } 4474 4475 if (comp != null) { 4476 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4477 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4478 if (ai != null) { 4479 final ResolveInfo ri = new ResolveInfo(); 4480 ri.activityInfo = ai; 4481 list.add(ri); 4482 } 4483 return list; 4484 } 4485 4486 // reader 4487 synchronized (mPackages) { 4488 final String pkgName = intent.getPackage(); 4489 if (pkgName == null) { 4490 List<CrossProfileIntentFilter> matchingFilters = 4491 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4492 // Check for results that need to skip the current profile. 4493 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4494 resolvedType, flags, userId); 4495 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4496 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4497 result.add(xpResolveInfo); 4498 return filterIfNotPrimaryUser(result, userId); 4499 } 4500 4501 // Check for results in the current profile. 4502 List<ResolveInfo> result = mActivities.queryIntent( 4503 intent, resolvedType, flags, userId); 4504 4505 // Check for cross profile results. 4506 xpResolveInfo = queryCrossProfileIntents( 4507 matchingFilters, intent, resolvedType, flags, userId); 4508 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4509 result.add(xpResolveInfo); 4510 Collections.sort(result, mResolvePrioritySorter); 4511 } 4512 result = filterIfNotPrimaryUser(result, userId); 4513 if (hasWebURI(intent)) { 4514 CrossProfileDomainInfo xpDomainInfo = null; 4515 final UserInfo parent = getProfileParent(userId); 4516 if (parent != null) { 4517 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 4518 flags, userId, parent.id); 4519 } 4520 if (xpDomainInfo != null) { 4521 if (xpResolveInfo != null) { 4522 // If we didn't remove it, the cross-profile ResolveInfo would be twice 4523 // in the result. 4524 result.remove(xpResolveInfo); 4525 } 4526 if (result.size() == 0) { 4527 result.add(xpDomainInfo.resolveInfo); 4528 return result; 4529 } 4530 } else if (result.size() <= 1) { 4531 return result; 4532 } 4533 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 4534 xpDomainInfo, userId); 4535 Collections.sort(result, mResolvePrioritySorter); 4536 } 4537 return result; 4538 } 4539 final PackageParser.Package pkg = mPackages.get(pkgName); 4540 if (pkg != null) { 4541 return filterIfNotPrimaryUser( 4542 mActivities.queryIntentForPackage( 4543 intent, resolvedType, flags, pkg.activities, userId), 4544 userId); 4545 } 4546 return new ArrayList<ResolveInfo>(); 4547 } 4548 } 4549 4550 private static class CrossProfileDomainInfo { 4551 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 4552 ResolveInfo resolveInfo; 4553 /* Best domain verification status of the activities found in the other profile */ 4554 int bestDomainVerificationStatus; 4555 } 4556 4557 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 4558 String resolvedType, int flags, int sourceUserId, int parentUserId) { 4559 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 4560 sourceUserId)) { 4561 return null; 4562 } 4563 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4564 resolvedType, flags, parentUserId); 4565 4566 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 4567 return null; 4568 } 4569 CrossProfileDomainInfo result = null; 4570 int size = resultTargetUser.size(); 4571 for (int i = 0; i < size; i++) { 4572 ResolveInfo riTargetUser = resultTargetUser.get(i); 4573 // Intent filter verification is only for filters that specify a host. So don't return 4574 // those that handle all web uris. 4575 if (riTargetUser.handleAllWebDataURI) { 4576 continue; 4577 } 4578 String packageName = riTargetUser.activityInfo.packageName; 4579 PackageSetting ps = mSettings.mPackages.get(packageName); 4580 if (ps == null) { 4581 continue; 4582 } 4583 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 4584 int status = (int)(verificationState >> 32); 4585 if (result == null) { 4586 result = new CrossProfileDomainInfo(); 4587 result.resolveInfo = 4588 createForwardingResolveInfo(null, sourceUserId, parentUserId); 4589 result.bestDomainVerificationStatus = status; 4590 } else { 4591 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 4592 result.bestDomainVerificationStatus); 4593 } 4594 } 4595 // Don't consider matches with status NEVER across profiles. 4596 if (result != null && result.bestDomainVerificationStatus 4597 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4598 return null; 4599 } 4600 return result; 4601 } 4602 4603 /** 4604 * Verification statuses are ordered from the worse to the best, except for 4605 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 4606 */ 4607 private int bestDomainVerificationStatus(int status1, int status2) { 4608 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4609 return status2; 4610 } 4611 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4612 return status1; 4613 } 4614 return (int) MathUtils.max(status1, status2); 4615 } 4616 4617 private boolean isUserEnabled(int userId) { 4618 long callingId = Binder.clearCallingIdentity(); 4619 try { 4620 UserInfo userInfo = sUserManager.getUserInfo(userId); 4621 return userInfo != null && userInfo.isEnabled(); 4622 } finally { 4623 Binder.restoreCallingIdentity(callingId); 4624 } 4625 } 4626 4627 /** 4628 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 4629 * 4630 * @return filtered list 4631 */ 4632 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 4633 if (userId == UserHandle.USER_OWNER) { 4634 return resolveInfos; 4635 } 4636 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 4637 ResolveInfo info = resolveInfos.get(i); 4638 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 4639 resolveInfos.remove(i); 4640 } 4641 } 4642 return resolveInfos; 4643 } 4644 4645 private static boolean hasWebURI(Intent intent) { 4646 if (intent.getData() == null) { 4647 return false; 4648 } 4649 final String scheme = intent.getScheme(); 4650 if (TextUtils.isEmpty(scheme)) { 4651 return false; 4652 } 4653 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4654 } 4655 4656 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 4657 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 4658 int userId) { 4659 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 4660 4661 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4662 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 4663 candidates.size()); 4664 } 4665 4666 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4667 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 4668 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4669 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4670 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4671 4672 synchronized (mPackages) { 4673 final int count = candidates.size(); 4674 // First, try to use linked apps. Partition the candidates into four lists: 4675 // one for the final results, one for the "do not use ever", one for "undefined status" 4676 // and finally one for "browser app type". 4677 for (int n=0; n<count; n++) { 4678 ResolveInfo info = candidates.get(n); 4679 String packageName = info.activityInfo.packageName; 4680 PackageSetting ps = mSettings.mPackages.get(packageName); 4681 if (ps != null) { 4682 // Add to the special match all list (Browser use case) 4683 if (info.handleAllWebDataURI) { 4684 matchAllList.add(info); 4685 continue; 4686 } 4687 // Try to get the status from User settings first 4688 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4689 int status = (int)(packedStatus >> 32); 4690 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 4691 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4692 if (DEBUG_DOMAIN_VERIFICATION) { 4693 Slog.i(TAG, " + always: " + info.activityInfo.packageName 4694 + " : linkgen=" + linkGeneration); 4695 } 4696 // Use link-enabled generation as preferredOrder, i.e. 4697 // prefer newly-enabled over earlier-enabled. 4698 info.preferredOrder = linkGeneration; 4699 alwaysList.add(info); 4700 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4701 if (DEBUG_DOMAIN_VERIFICATION) { 4702 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 4703 } 4704 neverList.add(info); 4705 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 4706 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 4707 if (DEBUG_DOMAIN_VERIFICATION) { 4708 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 4709 } 4710 undefinedList.add(info); 4711 } 4712 } 4713 } 4714 // First try to add the "always" resolution(s) for the current user, if any 4715 if (alwaysList.size() > 0) { 4716 result.addAll(alwaysList); 4717 // if there is an "always" for the parent user, add it. 4718 } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus 4719 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4720 result.add(xpDomainInfo.resolveInfo); 4721 } else { 4722 // Add all undefined Apps as we want them to appear in the Disambiguation dialog. 4723 result.addAll(undefinedList); 4724 if (xpDomainInfo != null && ( 4725 xpDomainInfo.bestDomainVerificationStatus 4726 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 4727 || xpDomainInfo.bestDomainVerificationStatus 4728 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) { 4729 result.add(xpDomainInfo.resolveInfo); 4730 } 4731 // Also add Browsers (all of them or only the default one) 4732 if ((matchFlags & MATCH_ALL) != 0) { 4733 result.addAll(matchAllList); 4734 } else { 4735 // Browser/generic handling case. If there's a default browser, go straight 4736 // to that (but only if there is no other higher-priority match). 4737 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 4738 int maxMatchPrio = 0; 4739 ResolveInfo defaultBrowserMatch = null; 4740 final int numCandidates = matchAllList.size(); 4741 for (int n = 0; n < numCandidates; n++) { 4742 ResolveInfo info = matchAllList.get(n); 4743 // track the highest overall match priority... 4744 if (info.priority > maxMatchPrio) { 4745 maxMatchPrio = info.priority; 4746 } 4747 // ...and the highest-priority default browser match 4748 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4749 if (defaultBrowserMatch == null 4750 || (defaultBrowserMatch.priority < info.priority)) { 4751 if (debug) { 4752 Slog.v(TAG, "Considering default browser match " + info); 4753 } 4754 defaultBrowserMatch = info; 4755 } 4756 } 4757 } 4758 if (defaultBrowserMatch != null 4759 && defaultBrowserMatch.priority >= maxMatchPrio 4760 && !TextUtils.isEmpty(defaultBrowserPackageName)) 4761 { 4762 if (debug) { 4763 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 4764 } 4765 result.add(defaultBrowserMatch); 4766 } else { 4767 result.addAll(matchAllList); 4768 } 4769 } 4770 4771 // If there is nothing selected, add all candidates and remove the ones that the user 4772 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 4773 if (result.size() == 0) { 4774 result.addAll(candidates); 4775 result.removeAll(neverList); 4776 } 4777 } 4778 } 4779 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4780 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 4781 result.size()); 4782 for (ResolveInfo info : result) { 4783 Slog.v(TAG, " + " + info.activityInfo); 4784 } 4785 } 4786 return result; 4787 } 4788 4789 // Returns a packed value as a long: 4790 // 4791 // high 'int'-sized word: link status: undefined/ask/never/always. 4792 // low 'int'-sized word: relative priority among 'always' results. 4793 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4794 long result = ps.getDomainVerificationStatusForUser(userId); 4795 // if none available, get the master status 4796 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4797 if (ps.getIntentFilterVerificationInfo() != null) { 4798 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 4799 } 4800 } 4801 return result; 4802 } 4803 4804 private ResolveInfo querySkipCurrentProfileIntents( 4805 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4806 int flags, int sourceUserId) { 4807 if (matchingFilters != null) { 4808 int size = matchingFilters.size(); 4809 for (int i = 0; i < size; i ++) { 4810 CrossProfileIntentFilter filter = matchingFilters.get(i); 4811 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4812 // Checking if there are activities in the target user that can handle the 4813 // intent. 4814 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4815 flags, sourceUserId); 4816 if (resolveInfo != null) { 4817 return resolveInfo; 4818 } 4819 } 4820 } 4821 } 4822 return null; 4823 } 4824 4825 // Return matching ResolveInfo if any for skip current profile intent filters. 4826 private ResolveInfo queryCrossProfileIntents( 4827 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4828 int flags, int sourceUserId) { 4829 if (matchingFilters != null) { 4830 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4831 // match the same intent. For performance reasons, it is better not to 4832 // run queryIntent twice for the same userId 4833 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4834 int size = matchingFilters.size(); 4835 for (int i = 0; i < size; i++) { 4836 CrossProfileIntentFilter filter = matchingFilters.get(i); 4837 int targetUserId = filter.getTargetUserId(); 4838 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4839 && !alreadyTriedUserIds.get(targetUserId)) { 4840 // Checking if there are activities in the target user that can handle the 4841 // intent. 4842 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4843 flags, sourceUserId); 4844 if (resolveInfo != null) return resolveInfo; 4845 alreadyTriedUserIds.put(targetUserId, true); 4846 } 4847 } 4848 } 4849 return null; 4850 } 4851 4852 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 4853 String resolvedType, int flags, int sourceUserId) { 4854 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4855 resolvedType, flags, filter.getTargetUserId()); 4856 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4857 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4858 } 4859 return null; 4860 } 4861 4862 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4863 int sourceUserId, int targetUserId) { 4864 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4865 String className; 4866 if (targetUserId == UserHandle.USER_OWNER) { 4867 className = FORWARD_INTENT_TO_USER_OWNER; 4868 } else { 4869 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4870 } 4871 ComponentName forwardingActivityComponentName = new ComponentName( 4872 mAndroidApplication.packageName, className); 4873 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4874 sourceUserId); 4875 if (targetUserId == UserHandle.USER_OWNER) { 4876 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 4877 forwardingResolveInfo.noResourceId = true; 4878 } 4879 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4880 forwardingResolveInfo.priority = 0; 4881 forwardingResolveInfo.preferredOrder = 0; 4882 forwardingResolveInfo.match = 0; 4883 forwardingResolveInfo.isDefault = true; 4884 forwardingResolveInfo.filter = filter; 4885 forwardingResolveInfo.targetUserId = targetUserId; 4886 return forwardingResolveInfo; 4887 } 4888 4889 @Override 4890 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4891 Intent[] specifics, String[] specificTypes, Intent intent, 4892 String resolvedType, int flags, int userId) { 4893 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4894 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4895 false, "query intent activity options"); 4896 final String resultsAction = intent.getAction(); 4897 4898 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4899 | PackageManager.GET_RESOLVED_FILTER, userId); 4900 4901 if (DEBUG_INTENT_MATCHING) { 4902 Log.v(TAG, "Query " + intent + ": " + results); 4903 } 4904 4905 int specificsPos = 0; 4906 int N; 4907 4908 // todo: note that the algorithm used here is O(N^2). This 4909 // isn't a problem in our current environment, but if we start running 4910 // into situations where we have more than 5 or 10 matches then this 4911 // should probably be changed to something smarter... 4912 4913 // First we go through and resolve each of the specific items 4914 // that were supplied, taking care of removing any corresponding 4915 // duplicate items in the generic resolve list. 4916 if (specifics != null) { 4917 for (int i=0; i<specifics.length; i++) { 4918 final Intent sintent = specifics[i]; 4919 if (sintent == null) { 4920 continue; 4921 } 4922 4923 if (DEBUG_INTENT_MATCHING) { 4924 Log.v(TAG, "Specific #" + i + ": " + sintent); 4925 } 4926 4927 String action = sintent.getAction(); 4928 if (resultsAction != null && resultsAction.equals(action)) { 4929 // If this action was explicitly requested, then don't 4930 // remove things that have it. 4931 action = null; 4932 } 4933 4934 ResolveInfo ri = null; 4935 ActivityInfo ai = null; 4936 4937 ComponentName comp = sintent.getComponent(); 4938 if (comp == null) { 4939 ri = resolveIntent( 4940 sintent, 4941 specificTypes != null ? specificTypes[i] : null, 4942 flags, userId); 4943 if (ri == null) { 4944 continue; 4945 } 4946 if (ri == mResolveInfo) { 4947 // ACK! Must do something better with this. 4948 } 4949 ai = ri.activityInfo; 4950 comp = new ComponentName(ai.applicationInfo.packageName, 4951 ai.name); 4952 } else { 4953 ai = getActivityInfo(comp, flags, userId); 4954 if (ai == null) { 4955 continue; 4956 } 4957 } 4958 4959 // Look for any generic query activities that are duplicates 4960 // of this specific one, and remove them from the results. 4961 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 4962 N = results.size(); 4963 int j; 4964 for (j=specificsPos; j<N; j++) { 4965 ResolveInfo sri = results.get(j); 4966 if ((sri.activityInfo.name.equals(comp.getClassName()) 4967 && sri.activityInfo.applicationInfo.packageName.equals( 4968 comp.getPackageName())) 4969 || (action != null && sri.filter.matchAction(action))) { 4970 results.remove(j); 4971 if (DEBUG_INTENT_MATCHING) Log.v( 4972 TAG, "Removing duplicate item from " + j 4973 + " due to specific " + specificsPos); 4974 if (ri == null) { 4975 ri = sri; 4976 } 4977 j--; 4978 N--; 4979 } 4980 } 4981 4982 // Add this specific item to its proper place. 4983 if (ri == null) { 4984 ri = new ResolveInfo(); 4985 ri.activityInfo = ai; 4986 } 4987 results.add(specificsPos, ri); 4988 ri.specificIndex = i; 4989 specificsPos++; 4990 } 4991 } 4992 4993 // Now we go through the remaining generic results and remove any 4994 // duplicate actions that are found here. 4995 N = results.size(); 4996 for (int i=specificsPos; i<N-1; i++) { 4997 final ResolveInfo rii = results.get(i); 4998 if (rii.filter == null) { 4999 continue; 5000 } 5001 5002 // Iterate over all of the actions of this result's intent 5003 // filter... typically this should be just one. 5004 final Iterator<String> it = rii.filter.actionsIterator(); 5005 if (it == null) { 5006 continue; 5007 } 5008 while (it.hasNext()) { 5009 final String action = it.next(); 5010 if (resultsAction != null && resultsAction.equals(action)) { 5011 // If this action was explicitly requested, then don't 5012 // remove things that have it. 5013 continue; 5014 } 5015 for (int j=i+1; j<N; j++) { 5016 final ResolveInfo rij = results.get(j); 5017 if (rij.filter != null && rij.filter.hasAction(action)) { 5018 results.remove(j); 5019 if (DEBUG_INTENT_MATCHING) Log.v( 5020 TAG, "Removing duplicate item from " + j 5021 + " due to action " + action + " at " + i); 5022 j--; 5023 N--; 5024 } 5025 } 5026 } 5027 5028 // If the caller didn't request filter information, drop it now 5029 // so we don't have to marshall/unmarshall it. 5030 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5031 rii.filter = null; 5032 } 5033 } 5034 5035 // Filter out the caller activity if so requested. 5036 if (caller != null) { 5037 N = results.size(); 5038 for (int i=0; i<N; i++) { 5039 ActivityInfo ainfo = results.get(i).activityInfo; 5040 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5041 && caller.getClassName().equals(ainfo.name)) { 5042 results.remove(i); 5043 break; 5044 } 5045 } 5046 } 5047 5048 // If the caller didn't request filter information, 5049 // drop them now so we don't have to 5050 // marshall/unmarshall it. 5051 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5052 N = results.size(); 5053 for (int i=0; i<N; i++) { 5054 results.get(i).filter = null; 5055 } 5056 } 5057 5058 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5059 return results; 5060 } 5061 5062 @Override 5063 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 5064 int userId) { 5065 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5066 ComponentName comp = intent.getComponent(); 5067 if (comp == null) { 5068 if (intent.getSelector() != null) { 5069 intent = intent.getSelector(); 5070 comp = intent.getComponent(); 5071 } 5072 } 5073 if (comp != null) { 5074 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5075 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5076 if (ai != null) { 5077 ResolveInfo ri = new ResolveInfo(); 5078 ri.activityInfo = ai; 5079 list.add(ri); 5080 } 5081 return list; 5082 } 5083 5084 // reader 5085 synchronized (mPackages) { 5086 String pkgName = intent.getPackage(); 5087 if (pkgName == null) { 5088 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5089 } 5090 final PackageParser.Package pkg = mPackages.get(pkgName); 5091 if (pkg != null) { 5092 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5093 userId); 5094 } 5095 return null; 5096 } 5097 } 5098 5099 @Override 5100 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5101 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 5102 if (!sUserManager.exists(userId)) return null; 5103 if (query != null) { 5104 if (query.size() >= 1) { 5105 // If there is more than one service with the same priority, 5106 // just arbitrarily pick the first one. 5107 return query.get(0); 5108 } 5109 } 5110 return null; 5111 } 5112 5113 @Override 5114 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 5115 int userId) { 5116 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5117 ComponentName comp = intent.getComponent(); 5118 if (comp == null) { 5119 if (intent.getSelector() != null) { 5120 intent = intent.getSelector(); 5121 comp = intent.getComponent(); 5122 } 5123 } 5124 if (comp != null) { 5125 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5126 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5127 if (si != null) { 5128 final ResolveInfo ri = new ResolveInfo(); 5129 ri.serviceInfo = si; 5130 list.add(ri); 5131 } 5132 return list; 5133 } 5134 5135 // reader 5136 synchronized (mPackages) { 5137 String pkgName = intent.getPackage(); 5138 if (pkgName == null) { 5139 return mServices.queryIntent(intent, resolvedType, flags, userId); 5140 } 5141 final PackageParser.Package pkg = mPackages.get(pkgName); 5142 if (pkg != null) { 5143 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5144 userId); 5145 } 5146 return null; 5147 } 5148 } 5149 5150 @Override 5151 public List<ResolveInfo> queryIntentContentProviders( 5152 Intent intent, String resolvedType, int flags, int userId) { 5153 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5154 ComponentName comp = intent.getComponent(); 5155 if (comp == null) { 5156 if (intent.getSelector() != null) { 5157 intent = intent.getSelector(); 5158 comp = intent.getComponent(); 5159 } 5160 } 5161 if (comp != null) { 5162 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5163 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5164 if (pi != null) { 5165 final ResolveInfo ri = new ResolveInfo(); 5166 ri.providerInfo = pi; 5167 list.add(ri); 5168 } 5169 return list; 5170 } 5171 5172 // reader 5173 synchronized (mPackages) { 5174 String pkgName = intent.getPackage(); 5175 if (pkgName == null) { 5176 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5177 } 5178 final PackageParser.Package pkg = mPackages.get(pkgName); 5179 if (pkg != null) { 5180 return mProviders.queryIntentForPackage( 5181 intent, resolvedType, flags, pkg.providers, userId); 5182 } 5183 return null; 5184 } 5185 } 5186 5187 @Override 5188 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5189 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5190 5191 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 5192 5193 // writer 5194 synchronized (mPackages) { 5195 ArrayList<PackageInfo> list; 5196 if (listUninstalled) { 5197 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5198 for (PackageSetting ps : mSettings.mPackages.values()) { 5199 PackageInfo pi; 5200 if (ps.pkg != null) { 5201 pi = generatePackageInfo(ps.pkg, flags, userId); 5202 } else { 5203 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5204 } 5205 if (pi != null) { 5206 list.add(pi); 5207 } 5208 } 5209 } else { 5210 list = new ArrayList<PackageInfo>(mPackages.size()); 5211 for (PackageParser.Package p : mPackages.values()) { 5212 PackageInfo pi = generatePackageInfo(p, flags, userId); 5213 if (pi != null) { 5214 list.add(pi); 5215 } 5216 } 5217 } 5218 5219 return new ParceledListSlice<PackageInfo>(list); 5220 } 5221 } 5222 5223 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5224 String[] permissions, boolean[] tmp, int flags, int userId) { 5225 int numMatch = 0; 5226 final PermissionsState permissionsState = ps.getPermissionsState(); 5227 for (int i=0; i<permissions.length; i++) { 5228 final String permission = permissions[i]; 5229 if (permissionsState.hasPermission(permission, userId)) { 5230 tmp[i] = true; 5231 numMatch++; 5232 } else { 5233 tmp[i] = false; 5234 } 5235 } 5236 if (numMatch == 0) { 5237 return; 5238 } 5239 PackageInfo pi; 5240 if (ps.pkg != null) { 5241 pi = generatePackageInfo(ps.pkg, flags, userId); 5242 } else { 5243 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5244 } 5245 // The above might return null in cases of uninstalled apps or install-state 5246 // skew across users/profiles. 5247 if (pi != null) { 5248 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5249 if (numMatch == permissions.length) { 5250 pi.requestedPermissions = permissions; 5251 } else { 5252 pi.requestedPermissions = new String[numMatch]; 5253 numMatch = 0; 5254 for (int i=0; i<permissions.length; i++) { 5255 if (tmp[i]) { 5256 pi.requestedPermissions[numMatch] = permissions[i]; 5257 numMatch++; 5258 } 5259 } 5260 } 5261 } 5262 list.add(pi); 5263 } 5264 } 5265 5266 @Override 5267 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5268 String[] permissions, int flags, int userId) { 5269 if (!sUserManager.exists(userId)) return null; 5270 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5271 5272 // writer 5273 synchronized (mPackages) { 5274 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5275 boolean[] tmpBools = new boolean[permissions.length]; 5276 if (listUninstalled) { 5277 for (PackageSetting ps : mSettings.mPackages.values()) { 5278 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5279 } 5280 } else { 5281 for (PackageParser.Package pkg : mPackages.values()) { 5282 PackageSetting ps = (PackageSetting)pkg.mExtras; 5283 if (ps != null) { 5284 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5285 userId); 5286 } 5287 } 5288 } 5289 5290 return new ParceledListSlice<PackageInfo>(list); 5291 } 5292 } 5293 5294 @Override 5295 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5296 if (!sUserManager.exists(userId)) return null; 5297 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5298 5299 // writer 5300 synchronized (mPackages) { 5301 ArrayList<ApplicationInfo> list; 5302 if (listUninstalled) { 5303 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5304 for (PackageSetting ps : mSettings.mPackages.values()) { 5305 ApplicationInfo ai; 5306 if (ps.pkg != null) { 5307 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5308 ps.readUserState(userId), userId); 5309 } else { 5310 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5311 } 5312 if (ai != null) { 5313 list.add(ai); 5314 } 5315 } 5316 } else { 5317 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5318 for (PackageParser.Package p : mPackages.values()) { 5319 if (p.mExtras != null) { 5320 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5321 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5322 if (ai != null) { 5323 list.add(ai); 5324 } 5325 } 5326 } 5327 } 5328 5329 return new ParceledListSlice<ApplicationInfo>(list); 5330 } 5331 } 5332 5333 public List<ApplicationInfo> getPersistentApplications(int flags) { 5334 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 5335 5336 // reader 5337 synchronized (mPackages) { 5338 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 5339 final int userId = UserHandle.getCallingUserId(); 5340 while (i.hasNext()) { 5341 final PackageParser.Package p = i.next(); 5342 if (p.applicationInfo != null 5343 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 5344 && (!mSafeMode || isSystemApp(p))) { 5345 PackageSetting ps = mSettings.mPackages.get(p.packageName); 5346 if (ps != null) { 5347 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5348 ps.readUserState(userId), userId); 5349 if (ai != null) { 5350 finalList.add(ai); 5351 } 5352 } 5353 } 5354 } 5355 } 5356 5357 return finalList; 5358 } 5359 5360 @Override 5361 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 5362 if (!sUserManager.exists(userId)) return null; 5363 // reader 5364 synchronized (mPackages) { 5365 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 5366 PackageSetting ps = provider != null 5367 ? mSettings.mPackages.get(provider.owner.packageName) 5368 : null; 5369 return ps != null 5370 && mSettings.isEnabledLPr(provider.info, flags, userId) 5371 && (!mSafeMode || (provider.info.applicationInfo.flags 5372 &ApplicationInfo.FLAG_SYSTEM) != 0) 5373 ? PackageParser.generateProviderInfo(provider, flags, 5374 ps.readUserState(userId), userId) 5375 : null; 5376 } 5377 } 5378 5379 /** 5380 * @deprecated 5381 */ 5382 @Deprecated 5383 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 5384 // reader 5385 synchronized (mPackages) { 5386 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 5387 .entrySet().iterator(); 5388 final int userId = UserHandle.getCallingUserId(); 5389 while (i.hasNext()) { 5390 Map.Entry<String, PackageParser.Provider> entry = i.next(); 5391 PackageParser.Provider p = entry.getValue(); 5392 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5393 5394 if (ps != null && p.syncable 5395 && (!mSafeMode || (p.info.applicationInfo.flags 5396 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 5397 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 5398 ps.readUserState(userId), userId); 5399 if (info != null) { 5400 outNames.add(entry.getKey()); 5401 outInfo.add(info); 5402 } 5403 } 5404 } 5405 } 5406 } 5407 5408 @Override 5409 public List<ProviderInfo> queryContentProviders(String processName, 5410 int uid, int flags) { 5411 ArrayList<ProviderInfo> finalList = null; 5412 // reader 5413 synchronized (mPackages) { 5414 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 5415 final int userId = processName != null ? 5416 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 5417 while (i.hasNext()) { 5418 final PackageParser.Provider p = i.next(); 5419 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5420 if (ps != null && p.info.authority != null 5421 && (processName == null 5422 || (p.info.processName.equals(processName) 5423 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 5424 && mSettings.isEnabledLPr(p.info, flags, userId) 5425 && (!mSafeMode 5426 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 5427 if (finalList == null) { 5428 finalList = new ArrayList<ProviderInfo>(3); 5429 } 5430 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 5431 ps.readUserState(userId), userId); 5432 if (info != null) { 5433 finalList.add(info); 5434 } 5435 } 5436 } 5437 } 5438 5439 if (finalList != null) { 5440 Collections.sort(finalList, mProviderInitOrderSorter); 5441 } 5442 5443 return finalList; 5444 } 5445 5446 @Override 5447 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 5448 int flags) { 5449 // reader 5450 synchronized (mPackages) { 5451 final PackageParser.Instrumentation i = mInstrumentation.get(name); 5452 return PackageParser.generateInstrumentationInfo(i, flags); 5453 } 5454 } 5455 5456 @Override 5457 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 5458 int flags) { 5459 ArrayList<InstrumentationInfo> finalList = 5460 new ArrayList<InstrumentationInfo>(); 5461 5462 // reader 5463 synchronized (mPackages) { 5464 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 5465 while (i.hasNext()) { 5466 final PackageParser.Instrumentation p = i.next(); 5467 if (targetPackage == null 5468 || targetPackage.equals(p.info.targetPackage)) { 5469 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 5470 flags); 5471 if (ii != null) { 5472 finalList.add(ii); 5473 } 5474 } 5475 } 5476 } 5477 5478 return finalList; 5479 } 5480 5481 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 5482 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 5483 if (overlays == null) { 5484 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 5485 return; 5486 } 5487 for (PackageParser.Package opkg : overlays.values()) { 5488 // Not much to do if idmap fails: we already logged the error 5489 // and we certainly don't want to abort installation of pkg simply 5490 // because an overlay didn't fit properly. For these reasons, 5491 // ignore the return value of createIdmapForPackagePairLI. 5492 createIdmapForPackagePairLI(pkg, opkg); 5493 } 5494 } 5495 5496 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 5497 PackageParser.Package opkg) { 5498 if (!opkg.mTrustedOverlay) { 5499 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 5500 opkg.baseCodePath + ": overlay not trusted"); 5501 return false; 5502 } 5503 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 5504 if (overlaySet == null) { 5505 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 5506 opkg.baseCodePath + " but target package has no known overlays"); 5507 return false; 5508 } 5509 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 5510 // TODO: generate idmap for split APKs 5511 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 5512 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 5513 + opkg.baseCodePath); 5514 return false; 5515 } 5516 PackageParser.Package[] overlayArray = 5517 overlaySet.values().toArray(new PackageParser.Package[0]); 5518 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 5519 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 5520 return p1.mOverlayPriority - p2.mOverlayPriority; 5521 } 5522 }; 5523 Arrays.sort(overlayArray, cmp); 5524 5525 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 5526 int i = 0; 5527 for (PackageParser.Package p : overlayArray) { 5528 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 5529 } 5530 return true; 5531 } 5532 5533 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5534 final File[] files = dir.listFiles(); 5535 if (ArrayUtils.isEmpty(files)) { 5536 Log.d(TAG, "No files in app dir " + dir); 5537 return; 5538 } 5539 5540 if (DEBUG_PACKAGE_SCANNING) { 5541 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 5542 + " flags=0x" + Integer.toHexString(parseFlags)); 5543 } 5544 5545 for (File file : files) { 5546 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 5547 && !PackageInstallerService.isStageName(file.getName()); 5548 if (!isPackage) { 5549 // Ignore entries which are not packages 5550 continue; 5551 } 5552 try { 5553 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 5554 scanFlags, currentTime, null); 5555 } catch (PackageManagerException e) { 5556 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 5557 5558 // Delete invalid userdata apps 5559 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 5560 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 5561 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 5562 if (file.isDirectory()) { 5563 mInstaller.rmPackageDir(file.getAbsolutePath()); 5564 } else { 5565 file.delete(); 5566 } 5567 } 5568 } 5569 } 5570 } 5571 5572 private static File getSettingsProblemFile() { 5573 File dataDir = Environment.getDataDirectory(); 5574 File systemDir = new File(dataDir, "system"); 5575 File fname = new File(systemDir, "uiderrors.txt"); 5576 return fname; 5577 } 5578 5579 static void reportSettingsProblem(int priority, String msg) { 5580 logCriticalInfo(priority, msg); 5581 } 5582 5583 static void logCriticalInfo(int priority, String msg) { 5584 Slog.println(priority, TAG, msg); 5585 EventLogTags.writePmCriticalInfo(msg); 5586 try { 5587 File fname = getSettingsProblemFile(); 5588 FileOutputStream out = new FileOutputStream(fname, true); 5589 PrintWriter pw = new FastPrintWriter(out); 5590 SimpleDateFormat formatter = new SimpleDateFormat(); 5591 String dateString = formatter.format(new Date(System.currentTimeMillis())); 5592 pw.println(dateString + ": " + msg); 5593 pw.close(); 5594 FileUtils.setPermissions( 5595 fname.toString(), 5596 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 5597 -1, -1); 5598 } catch (java.io.IOException e) { 5599 } 5600 } 5601 5602 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 5603 PackageParser.Package pkg, File srcFile, int parseFlags) 5604 throws PackageManagerException { 5605 if (ps != null 5606 && ps.codePath.equals(srcFile) 5607 && ps.timeStamp == srcFile.lastModified() 5608 && !isCompatSignatureUpdateNeeded(pkg) 5609 && !isRecoverSignatureUpdateNeeded(pkg)) { 5610 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 5611 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5612 ArraySet<PublicKey> signingKs; 5613 synchronized (mPackages) { 5614 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 5615 } 5616 if (ps.signatures.mSignatures != null 5617 && ps.signatures.mSignatures.length != 0 5618 && signingKs != null) { 5619 // Optimization: reuse the existing cached certificates 5620 // if the package appears to be unchanged. 5621 pkg.mSignatures = ps.signatures.mSignatures; 5622 pkg.mSigningKeys = signingKs; 5623 return; 5624 } 5625 5626 Slog.w(TAG, "PackageSetting for " + ps.name 5627 + " is missing signatures. Collecting certs again to recover them."); 5628 } else { 5629 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 5630 } 5631 5632 try { 5633 pp.collectCertificates(pkg, parseFlags); 5634 pp.collectManifestDigest(pkg); 5635 } catch (PackageParserException e) { 5636 throw PackageManagerException.from(e); 5637 } 5638 } 5639 5640 /* 5641 * Scan a package and return the newly parsed package. 5642 * Returns null in case of errors and the error code is stored in mLastScanError 5643 */ 5644 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 5645 long currentTime, UserHandle user) throws PackageManagerException { 5646 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 5647 parseFlags |= mDefParseFlags; 5648 PackageParser pp = new PackageParser(); 5649 pp.setSeparateProcesses(mSeparateProcesses); 5650 pp.setOnlyCoreApps(mOnlyCore); 5651 pp.setDisplayMetrics(mMetrics); 5652 5653 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 5654 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 5655 } 5656 5657 final PackageParser.Package pkg; 5658 try { 5659 pkg = pp.parsePackage(scanFile, parseFlags); 5660 } catch (PackageParserException e) { 5661 throw PackageManagerException.from(e); 5662 } 5663 5664 PackageSetting ps = null; 5665 PackageSetting updatedPkg; 5666 // reader 5667 synchronized (mPackages) { 5668 // Look to see if we already know about this package. 5669 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 5670 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 5671 // This package has been renamed to its original name. Let's 5672 // use that. 5673 ps = mSettings.peekPackageLPr(oldName); 5674 } 5675 // If there was no original package, see one for the real package name. 5676 if (ps == null) { 5677 ps = mSettings.peekPackageLPr(pkg.packageName); 5678 } 5679 // Check to see if this package could be hiding/updating a system 5680 // package. Must look for it either under the original or real 5681 // package name depending on our state. 5682 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 5683 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 5684 } 5685 boolean updatedPkgBetter = false; 5686 // First check if this is a system package that may involve an update 5687 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5688 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5689 // it needs to drop FLAG_PRIVILEGED. 5690 if (locationIsPrivileged(scanFile)) { 5691 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5692 } else { 5693 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5694 } 5695 5696 if (ps != null && !ps.codePath.equals(scanFile)) { 5697 // The path has changed from what was last scanned... check the 5698 // version of the new path against what we have stored to determine 5699 // what to do. 5700 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5701 if (pkg.mVersionCode <= ps.versionCode) { 5702 // The system package has been updated and the code path does not match 5703 // Ignore entry. Skip it. 5704 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5705 + " ignored: updated version " + ps.versionCode 5706 + " better than this " + pkg.mVersionCode); 5707 if (!updatedPkg.codePath.equals(scanFile)) { 5708 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5709 + ps.name + " changing from " + updatedPkg.codePathString 5710 + " to " + scanFile); 5711 updatedPkg.codePath = scanFile; 5712 updatedPkg.codePathString = scanFile.toString(); 5713 updatedPkg.resourcePath = scanFile; 5714 updatedPkg.resourcePathString = scanFile.toString(); 5715 } 5716 updatedPkg.pkg = pkg; 5717 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5718 "Package " + ps.name + " at " + scanFile 5719 + " ignored: updated version " + ps.versionCode 5720 + " better than this " + pkg.mVersionCode); 5721 } else { 5722 // The current app on the system partition is better than 5723 // what we have updated to on the data partition; switch 5724 // back to the system partition version. 5725 // At this point, its safely assumed that package installation for 5726 // apps in system partition will go through. If not there won't be a working 5727 // version of the app 5728 // writer 5729 synchronized (mPackages) { 5730 // Just remove the loaded entries from package lists. 5731 mPackages.remove(ps.name); 5732 } 5733 5734 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5735 + " reverting from " + ps.codePathString 5736 + ": new version " + pkg.mVersionCode 5737 + " better than installed " + ps.versionCode); 5738 5739 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5740 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5741 synchronized (mInstallLock) { 5742 args.cleanUpResourcesLI(); 5743 } 5744 synchronized (mPackages) { 5745 mSettings.enableSystemPackageLPw(ps.name); 5746 } 5747 updatedPkgBetter = true; 5748 } 5749 } 5750 } 5751 5752 if (updatedPkg != null) { 5753 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5754 // initially 5755 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5756 5757 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5758 // flag set initially 5759 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5760 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5761 } 5762 } 5763 5764 // Verify certificates against what was last scanned 5765 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5766 5767 /* 5768 * A new system app appeared, but we already had a non-system one of the 5769 * same name installed earlier. 5770 */ 5771 boolean shouldHideSystemApp = false; 5772 if (updatedPkg == null && ps != null 5773 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5774 /* 5775 * Check to make sure the signatures match first. If they don't, 5776 * wipe the installed application and its data. 5777 */ 5778 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5779 != PackageManager.SIGNATURE_MATCH) { 5780 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5781 + " signatures don't match existing userdata copy; removing"); 5782 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5783 ps = null; 5784 } else { 5785 /* 5786 * If the newly-added system app is an older version than the 5787 * already installed version, hide it. It will be scanned later 5788 * and re-added like an update. 5789 */ 5790 if (pkg.mVersionCode <= ps.versionCode) { 5791 shouldHideSystemApp = true; 5792 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5793 + " but new version " + pkg.mVersionCode + " better than installed " 5794 + ps.versionCode + "; hiding system"); 5795 } else { 5796 /* 5797 * The newly found system app is a newer version that the 5798 * one previously installed. Simply remove the 5799 * already-installed application and replace it with our own 5800 * while keeping the application data. 5801 */ 5802 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5803 + " reverting from " + ps.codePathString + ": new version " 5804 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5805 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5806 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5807 synchronized (mInstallLock) { 5808 args.cleanUpResourcesLI(); 5809 } 5810 } 5811 } 5812 } 5813 5814 // The apk is forward locked (not public) if its code and resources 5815 // are kept in different files. (except for app in either system or 5816 // vendor path). 5817 // TODO grab this value from PackageSettings 5818 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5819 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5820 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5821 } 5822 } 5823 5824 // TODO: extend to support forward-locked splits 5825 String resourcePath = null; 5826 String baseResourcePath = null; 5827 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5828 if (ps != null && ps.resourcePathString != null) { 5829 resourcePath = ps.resourcePathString; 5830 baseResourcePath = ps.resourcePathString; 5831 } else { 5832 // Should not happen at all. Just log an error. 5833 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5834 } 5835 } else { 5836 resourcePath = pkg.codePath; 5837 baseResourcePath = pkg.baseCodePath; 5838 } 5839 5840 // Set application objects path explicitly. 5841 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5842 pkg.applicationInfo.setCodePath(pkg.codePath); 5843 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5844 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5845 pkg.applicationInfo.setResourcePath(resourcePath); 5846 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5847 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5848 5849 // Note that we invoke the following method only if we are about to unpack an application 5850 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5851 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5852 5853 /* 5854 * If the system app should be overridden by a previously installed 5855 * data, hide the system app now and let the /data/app scan pick it up 5856 * again. 5857 */ 5858 if (shouldHideSystemApp) { 5859 synchronized (mPackages) { 5860 /* 5861 * We have to grant systems permissions before we hide, because 5862 * grantPermissions will assume the package update is trying to 5863 * expand its permissions. 5864 */ 5865 grantPermissionsLPw(pkg, true, pkg.packageName); 5866 mSettings.disableSystemPackageLPw(pkg.packageName); 5867 } 5868 } 5869 5870 return scannedPkg; 5871 } 5872 5873 private static String fixProcessName(String defProcessName, 5874 String processName, int uid) { 5875 if (processName == null) { 5876 return defProcessName; 5877 } 5878 return processName; 5879 } 5880 5881 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 5882 throws PackageManagerException { 5883 if (pkgSetting.signatures.mSignatures != null) { 5884 // Already existing package. Make sure signatures match 5885 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 5886 == PackageManager.SIGNATURE_MATCH; 5887 if (!match) { 5888 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 5889 == PackageManager.SIGNATURE_MATCH; 5890 } 5891 if (!match) { 5892 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 5893 == PackageManager.SIGNATURE_MATCH; 5894 } 5895 if (!match) { 5896 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5897 + pkg.packageName + " signatures do not match the " 5898 + "previously installed version; ignoring!"); 5899 } 5900 } 5901 5902 // Check for shared user signatures 5903 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 5904 // Already existing package. Make sure signatures match 5905 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5906 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 5907 if (!match) { 5908 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 5909 == PackageManager.SIGNATURE_MATCH; 5910 } 5911 if (!match) { 5912 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 5913 == PackageManager.SIGNATURE_MATCH; 5914 } 5915 if (!match) { 5916 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 5917 "Package " + pkg.packageName 5918 + " has no signatures that match those in shared user " 5919 + pkgSetting.sharedUser.name + "; ignoring!"); 5920 } 5921 } 5922 } 5923 5924 /** 5925 * Enforces that only the system UID or root's UID can call a method exposed 5926 * via Binder. 5927 * 5928 * @param message used as message if SecurityException is thrown 5929 * @throws SecurityException if the caller is not system or root 5930 */ 5931 private static final void enforceSystemOrRoot(String message) { 5932 final int uid = Binder.getCallingUid(); 5933 if (uid != Process.SYSTEM_UID && uid != 0) { 5934 throw new SecurityException(message); 5935 } 5936 } 5937 5938 @Override 5939 public void performBootDexOpt() { 5940 enforceSystemOrRoot("Only the system can request dexopt be performed"); 5941 5942 // Before everything else, see whether we need to fstrim. 5943 try { 5944 IMountService ms = PackageHelper.getMountService(); 5945 if (ms != null) { 5946 final boolean isUpgrade = isUpgrade(); 5947 boolean doTrim = isUpgrade; 5948 if (doTrim) { 5949 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 5950 } else { 5951 final long interval = android.provider.Settings.Global.getLong( 5952 mContext.getContentResolver(), 5953 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 5954 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 5955 if (interval > 0) { 5956 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 5957 if (timeSinceLast > interval) { 5958 doTrim = true; 5959 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 5960 + "; running immediately"); 5961 } 5962 } 5963 } 5964 if (doTrim) { 5965 if (!isFirstBoot()) { 5966 try { 5967 ActivityManagerNative.getDefault().showBootMessage( 5968 mContext.getResources().getString( 5969 R.string.android_upgrading_fstrim), true); 5970 } catch (RemoteException e) { 5971 } 5972 } 5973 ms.runMaintenance(); 5974 } 5975 } else { 5976 Slog.e(TAG, "Mount service unavailable!"); 5977 } 5978 } catch (RemoteException e) { 5979 // Can't happen; MountService is local 5980 } 5981 5982 final ArraySet<PackageParser.Package> pkgs; 5983 synchronized (mPackages) { 5984 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 5985 } 5986 5987 if (pkgs != null) { 5988 // Sort apps by importance for dexopt ordering. Important apps are given more priority 5989 // in case the device runs out of space. 5990 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 5991 // Give priority to core apps. 5992 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5993 PackageParser.Package pkg = it.next(); 5994 if (pkg.coreApp) { 5995 if (DEBUG_DEXOPT) { 5996 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 5997 } 5998 sortedPkgs.add(pkg); 5999 it.remove(); 6000 } 6001 } 6002 // Give priority to system apps that listen for pre boot complete. 6003 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 6004 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 6005 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6006 PackageParser.Package pkg = it.next(); 6007 if (pkgNames.contains(pkg.packageName)) { 6008 if (DEBUG_DEXOPT) { 6009 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 6010 } 6011 sortedPkgs.add(pkg); 6012 it.remove(); 6013 } 6014 } 6015 // Give priority to system apps. 6016 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6017 PackageParser.Package pkg = it.next(); 6018 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 6019 if (DEBUG_DEXOPT) { 6020 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 6021 } 6022 sortedPkgs.add(pkg); 6023 it.remove(); 6024 } 6025 } 6026 // Give priority to updated system apps. 6027 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6028 PackageParser.Package pkg = it.next(); 6029 if (pkg.isUpdatedSystemApp()) { 6030 if (DEBUG_DEXOPT) { 6031 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 6032 } 6033 sortedPkgs.add(pkg); 6034 it.remove(); 6035 } 6036 } 6037 // Give priority to apps that listen for boot complete. 6038 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 6039 pkgNames = getPackageNamesForIntent(intent); 6040 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6041 PackageParser.Package pkg = it.next(); 6042 if (pkgNames.contains(pkg.packageName)) { 6043 if (DEBUG_DEXOPT) { 6044 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 6045 } 6046 sortedPkgs.add(pkg); 6047 it.remove(); 6048 } 6049 } 6050 // Filter out packages that aren't recently used. 6051 filterRecentlyUsedApps(pkgs); 6052 // Add all remaining apps. 6053 for (PackageParser.Package pkg : pkgs) { 6054 if (DEBUG_DEXOPT) { 6055 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 6056 } 6057 sortedPkgs.add(pkg); 6058 } 6059 6060 // If we want to be lazy, filter everything that wasn't recently used. 6061 if (mLazyDexOpt) { 6062 filterRecentlyUsedApps(sortedPkgs); 6063 } 6064 6065 int i = 0; 6066 int total = sortedPkgs.size(); 6067 File dataDir = Environment.getDataDirectory(); 6068 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 6069 if (lowThreshold == 0) { 6070 throw new IllegalStateException("Invalid low memory threshold"); 6071 } 6072 for (PackageParser.Package pkg : sortedPkgs) { 6073 long usableSpace = dataDir.getUsableSpace(); 6074 if (usableSpace < lowThreshold) { 6075 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 6076 break; 6077 } 6078 performBootDexOpt(pkg, ++i, total); 6079 } 6080 } 6081 } 6082 6083 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 6084 // Filter out packages that aren't recently used. 6085 // 6086 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 6087 // should do a full dexopt. 6088 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 6089 int total = pkgs.size(); 6090 int skipped = 0; 6091 long now = System.currentTimeMillis(); 6092 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 6093 PackageParser.Package pkg = i.next(); 6094 long then = pkg.mLastPackageUsageTimeInMills; 6095 if (then + mDexOptLRUThresholdInMills < now) { 6096 if (DEBUG_DEXOPT) { 6097 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 6098 ((then == 0) ? "never" : new Date(then))); 6099 } 6100 i.remove(); 6101 skipped++; 6102 } 6103 } 6104 if (DEBUG_DEXOPT) { 6105 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 6106 } 6107 } 6108 } 6109 6110 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 6111 List<ResolveInfo> ris = null; 6112 try { 6113 ris = AppGlobals.getPackageManager().queryIntentReceivers( 6114 intent, null, 0, UserHandle.USER_OWNER); 6115 } catch (RemoteException e) { 6116 } 6117 ArraySet<String> pkgNames = new ArraySet<String>(); 6118 if (ris != null) { 6119 for (ResolveInfo ri : ris) { 6120 pkgNames.add(ri.activityInfo.packageName); 6121 } 6122 } 6123 return pkgNames; 6124 } 6125 6126 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 6127 if (DEBUG_DEXOPT) { 6128 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 6129 } 6130 if (!isFirstBoot()) { 6131 try { 6132 ActivityManagerNative.getDefault().showBootMessage( 6133 mContext.getResources().getString(R.string.android_upgrading_apk, 6134 curr, total), true); 6135 } catch (RemoteException e) { 6136 } 6137 } 6138 PackageParser.Package p = pkg; 6139 synchronized (mInstallLock) { 6140 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 6141 false /* force dex */, false /* defer */, true /* include dependencies */); 6142 } 6143 } 6144 6145 @Override 6146 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6147 return performDexOpt(packageName, instructionSet, false); 6148 } 6149 6150 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 6151 boolean dexopt = mLazyDexOpt || backgroundDexopt; 6152 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 6153 if (!dexopt && !updateUsage) { 6154 // We aren't going to dexopt or update usage, so bail early. 6155 return false; 6156 } 6157 PackageParser.Package p; 6158 final String targetInstructionSet; 6159 synchronized (mPackages) { 6160 p = mPackages.get(packageName); 6161 if (p == null) { 6162 return false; 6163 } 6164 if (updateUsage) { 6165 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6166 } 6167 mPackageUsage.write(false); 6168 if (!dexopt) { 6169 // We aren't going to dexopt, so bail early. 6170 return false; 6171 } 6172 6173 targetInstructionSet = instructionSet != null ? instructionSet : 6174 getPrimaryInstructionSet(p.applicationInfo); 6175 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 6176 return false; 6177 } 6178 } 6179 long callingId = Binder.clearCallingIdentity(); 6180 try { 6181 synchronized (mInstallLock) { 6182 final String[] instructionSets = new String[] { targetInstructionSet }; 6183 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 6184 false /* forceDex */, false /* defer */, true /* inclDependencies */); 6185 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6186 } 6187 } finally { 6188 Binder.restoreCallingIdentity(callingId); 6189 } 6190 } 6191 6192 public ArraySet<String> getPackagesThatNeedDexOpt() { 6193 ArraySet<String> pkgs = null; 6194 synchronized (mPackages) { 6195 for (PackageParser.Package p : mPackages.values()) { 6196 if (DEBUG_DEXOPT) { 6197 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 6198 } 6199 if (!p.mDexOptPerformed.isEmpty()) { 6200 continue; 6201 } 6202 if (pkgs == null) { 6203 pkgs = new ArraySet<String>(); 6204 } 6205 pkgs.add(p.packageName); 6206 } 6207 } 6208 return pkgs; 6209 } 6210 6211 public void shutdown() { 6212 mPackageUsage.write(true); 6213 } 6214 6215 @Override 6216 public void forceDexOpt(String packageName) { 6217 enforceSystemOrRoot("forceDexOpt"); 6218 6219 PackageParser.Package pkg; 6220 synchronized (mPackages) { 6221 pkg = mPackages.get(packageName); 6222 if (pkg == null) { 6223 throw new IllegalArgumentException("Missing package: " + packageName); 6224 } 6225 } 6226 6227 synchronized (mInstallLock) { 6228 final String[] instructionSets = new String[] { 6229 getPrimaryInstructionSet(pkg.applicationInfo) }; 6230 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 6231 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 6232 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 6233 throw new IllegalStateException("Failed to dexopt: " + res); 6234 } 6235 } 6236 } 6237 6238 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 6239 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 6240 Slog.w(TAG, "Unable to update from " + oldPkg.name 6241 + " to " + newPkg.packageName 6242 + ": old package not in system partition"); 6243 return false; 6244 } else if (mPackages.get(oldPkg.name) != null) { 6245 Slog.w(TAG, "Unable to update from " + oldPkg.name 6246 + " to " + newPkg.packageName 6247 + ": old package still exists"); 6248 return false; 6249 } 6250 return true; 6251 } 6252 6253 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 6254 int[] users = sUserManager.getUserIds(); 6255 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 6256 if (res < 0) { 6257 return res; 6258 } 6259 for (int user : users) { 6260 if (user != 0) { 6261 res = mInstaller.createUserData(volumeUuid, packageName, 6262 UserHandle.getUid(user, uid), user, seinfo); 6263 if (res < 0) { 6264 return res; 6265 } 6266 } 6267 } 6268 return res; 6269 } 6270 6271 private int removeDataDirsLI(String volumeUuid, String packageName) { 6272 int[] users = sUserManager.getUserIds(); 6273 int res = 0; 6274 for (int user : users) { 6275 int resInner = mInstaller.remove(volumeUuid, packageName, user); 6276 if (resInner < 0) { 6277 res = resInner; 6278 } 6279 } 6280 6281 return res; 6282 } 6283 6284 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 6285 int[] users = sUserManager.getUserIds(); 6286 int res = 0; 6287 for (int user : users) { 6288 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 6289 if (resInner < 0) { 6290 res = resInner; 6291 } 6292 } 6293 return res; 6294 } 6295 6296 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 6297 PackageParser.Package changingLib) { 6298 if (file.path != null) { 6299 usesLibraryFiles.add(file.path); 6300 return; 6301 } 6302 PackageParser.Package p = mPackages.get(file.apk); 6303 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 6304 // If we are doing this while in the middle of updating a library apk, 6305 // then we need to make sure to use that new apk for determining the 6306 // dependencies here. (We haven't yet finished committing the new apk 6307 // to the package manager state.) 6308 if (p == null || p.packageName.equals(changingLib.packageName)) { 6309 p = changingLib; 6310 } 6311 } 6312 if (p != null) { 6313 usesLibraryFiles.addAll(p.getAllCodePaths()); 6314 } 6315 } 6316 6317 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 6318 PackageParser.Package changingLib) throws PackageManagerException { 6319 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 6320 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 6321 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 6322 for (int i=0; i<N; i++) { 6323 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 6324 if (file == null) { 6325 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 6326 "Package " + pkg.packageName + " requires unavailable shared library " 6327 + pkg.usesLibraries.get(i) + "; failing!"); 6328 } 6329 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6330 } 6331 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 6332 for (int i=0; i<N; i++) { 6333 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 6334 if (file == null) { 6335 Slog.w(TAG, "Package " + pkg.packageName 6336 + " desires unavailable shared library " 6337 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 6338 } else { 6339 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6340 } 6341 } 6342 N = usesLibraryFiles.size(); 6343 if (N > 0) { 6344 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 6345 } else { 6346 pkg.usesLibraryFiles = null; 6347 } 6348 } 6349 } 6350 6351 private static boolean hasString(List<String> list, List<String> which) { 6352 if (list == null) { 6353 return false; 6354 } 6355 for (int i=list.size()-1; i>=0; i--) { 6356 for (int j=which.size()-1; j>=0; j--) { 6357 if (which.get(j).equals(list.get(i))) { 6358 return true; 6359 } 6360 } 6361 } 6362 return false; 6363 } 6364 6365 private void updateAllSharedLibrariesLPw() { 6366 for (PackageParser.Package pkg : mPackages.values()) { 6367 try { 6368 updateSharedLibrariesLPw(pkg, null); 6369 } catch (PackageManagerException e) { 6370 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6371 } 6372 } 6373 } 6374 6375 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 6376 PackageParser.Package changingPkg) { 6377 ArrayList<PackageParser.Package> res = null; 6378 for (PackageParser.Package pkg : mPackages.values()) { 6379 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 6380 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 6381 if (res == null) { 6382 res = new ArrayList<PackageParser.Package>(); 6383 } 6384 res.add(pkg); 6385 try { 6386 updateSharedLibrariesLPw(pkg, changingPkg); 6387 } catch (PackageManagerException e) { 6388 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6389 } 6390 } 6391 } 6392 return res; 6393 } 6394 6395 /** 6396 * Derive the value of the {@code cpuAbiOverride} based on the provided 6397 * value and an optional stored value from the package settings. 6398 */ 6399 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 6400 String cpuAbiOverride = null; 6401 6402 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 6403 cpuAbiOverride = null; 6404 } else if (abiOverride != null) { 6405 cpuAbiOverride = abiOverride; 6406 } else if (settings != null) { 6407 cpuAbiOverride = settings.cpuAbiOverrideString; 6408 } 6409 6410 return cpuAbiOverride; 6411 } 6412 6413 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 6414 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6415 boolean success = false; 6416 try { 6417 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 6418 currentTime, user); 6419 success = true; 6420 return res; 6421 } finally { 6422 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 6423 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 6424 } 6425 } 6426 } 6427 6428 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 6429 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6430 final File scanFile = new File(pkg.codePath); 6431 if (pkg.applicationInfo.getCodePath() == null || 6432 pkg.applicationInfo.getResourcePath() == null) { 6433 // Bail out. The resource and code paths haven't been set. 6434 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 6435 "Code and resource paths haven't been set correctly"); 6436 } 6437 6438 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 6439 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 6440 } else { 6441 // Only allow system apps to be flagged as core apps. 6442 pkg.coreApp = false; 6443 } 6444 6445 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 6446 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6447 } 6448 6449 if (mCustomResolverComponentName != null && 6450 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 6451 setUpCustomResolverActivity(pkg); 6452 } 6453 6454 if (pkg.packageName.equals("android")) { 6455 synchronized (mPackages) { 6456 if (mAndroidApplication != null) { 6457 Slog.w(TAG, "*************************************************"); 6458 Slog.w(TAG, "Core android package being redefined. Skipping."); 6459 Slog.w(TAG, " file=" + scanFile); 6460 Slog.w(TAG, "*************************************************"); 6461 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6462 "Core android package being redefined. Skipping."); 6463 } 6464 6465 // Set up information for our fall-back user intent resolution activity. 6466 mPlatformPackage = pkg; 6467 pkg.mVersionCode = mSdkVersion; 6468 mAndroidApplication = pkg.applicationInfo; 6469 6470 if (!mResolverReplaced) { 6471 mResolveActivity.applicationInfo = mAndroidApplication; 6472 mResolveActivity.name = ResolverActivity.class.getName(); 6473 mResolveActivity.packageName = mAndroidApplication.packageName; 6474 mResolveActivity.processName = "system:ui"; 6475 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6476 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 6477 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 6478 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 6479 mResolveActivity.exported = true; 6480 mResolveActivity.enabled = true; 6481 mResolveInfo.activityInfo = mResolveActivity; 6482 mResolveInfo.priority = 0; 6483 mResolveInfo.preferredOrder = 0; 6484 mResolveInfo.match = 0; 6485 mResolveComponentName = new ComponentName( 6486 mAndroidApplication.packageName, mResolveActivity.name); 6487 } 6488 } 6489 } 6490 6491 if (DEBUG_PACKAGE_SCANNING) { 6492 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6493 Log.d(TAG, "Scanning package " + pkg.packageName); 6494 } 6495 6496 if (mPackages.containsKey(pkg.packageName) 6497 || mSharedLibraries.containsKey(pkg.packageName)) { 6498 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6499 "Application package " + pkg.packageName 6500 + " already installed. Skipping duplicate."); 6501 } 6502 6503 // If we're only installing presumed-existing packages, require that the 6504 // scanned APK is both already known and at the path previously established 6505 // for it. Previously unknown packages we pick up normally, but if we have an 6506 // a priori expectation about this package's install presence, enforce it. 6507 // With a singular exception for new system packages. When an OTA contains 6508 // a new system package, we allow the codepath to change from a system location 6509 // to the user-installed location. If we don't allow this change, any newer, 6510 // user-installed version of the application will be ignored. 6511 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 6512 if (mExpectingBetter.containsKey(pkg.packageName)) { 6513 logCriticalInfo(Log.WARN, 6514 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 6515 } else { 6516 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 6517 if (known != null) { 6518 if (DEBUG_PACKAGE_SCANNING) { 6519 Log.d(TAG, "Examining " + pkg.codePath 6520 + " and requiring known paths " + known.codePathString 6521 + " & " + known.resourcePathString); 6522 } 6523 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6524 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6525 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6526 "Application package " + pkg.packageName 6527 + " found at " + pkg.applicationInfo.getCodePath() 6528 + " but expected at " + known.codePathString + "; ignoring."); 6529 } 6530 } 6531 } 6532 } 6533 6534 // Initialize package source and resource directories 6535 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6536 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6537 6538 SharedUserSetting suid = null; 6539 PackageSetting pkgSetting = null; 6540 6541 if (!isSystemApp(pkg)) { 6542 // Only system apps can use these features. 6543 pkg.mOriginalPackages = null; 6544 pkg.mRealPackage = null; 6545 pkg.mAdoptPermissions = null; 6546 } 6547 6548 // writer 6549 synchronized (mPackages) { 6550 if (pkg.mSharedUserId != null) { 6551 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 6552 if (suid == null) { 6553 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6554 "Creating application package " + pkg.packageName 6555 + " for shared user failed"); 6556 } 6557 if (DEBUG_PACKAGE_SCANNING) { 6558 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6559 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 6560 + "): packages=" + suid.packages); 6561 } 6562 } 6563 6564 // Check if we are renaming from an original package name. 6565 PackageSetting origPackage = null; 6566 String realName = null; 6567 if (pkg.mOriginalPackages != null) { 6568 // This package may need to be renamed to a previously 6569 // installed name. Let's check on that... 6570 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 6571 if (pkg.mOriginalPackages.contains(renamed)) { 6572 // This package had originally been installed as the 6573 // original name, and we have already taken care of 6574 // transitioning to the new one. Just update the new 6575 // one to continue using the old name. 6576 realName = pkg.mRealPackage; 6577 if (!pkg.packageName.equals(renamed)) { 6578 // Callers into this function may have already taken 6579 // care of renaming the package; only do it here if 6580 // it is not already done. 6581 pkg.setPackageName(renamed); 6582 } 6583 6584 } else { 6585 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 6586 if ((origPackage = mSettings.peekPackageLPr( 6587 pkg.mOriginalPackages.get(i))) != null) { 6588 // We do have the package already installed under its 6589 // original name... should we use it? 6590 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 6591 // New package is not compatible with original. 6592 origPackage = null; 6593 continue; 6594 } else if (origPackage.sharedUser != null) { 6595 // Make sure uid is compatible between packages. 6596 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 6597 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 6598 + " to " + pkg.packageName + ": old uid " 6599 + origPackage.sharedUser.name 6600 + " differs from " + pkg.mSharedUserId); 6601 origPackage = null; 6602 continue; 6603 } 6604 } else { 6605 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6606 + pkg.packageName + " to old name " + origPackage.name); 6607 } 6608 break; 6609 } 6610 } 6611 } 6612 } 6613 6614 if (mTransferedPackages.contains(pkg.packageName)) { 6615 Slog.w(TAG, "Package " + pkg.packageName 6616 + " was transferred to another, but its .apk remains"); 6617 } 6618 6619 // Just create the setting, don't add it yet. For already existing packages 6620 // the PkgSetting exists already and doesn't have to be created. 6621 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6622 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6623 pkg.applicationInfo.primaryCpuAbi, 6624 pkg.applicationInfo.secondaryCpuAbi, 6625 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6626 user, false); 6627 if (pkgSetting == null) { 6628 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6629 "Creating application package " + pkg.packageName + " failed"); 6630 } 6631 6632 if (pkgSetting.origPackage != null) { 6633 // If we are first transitioning from an original package, 6634 // fix up the new package's name now. We need to do this after 6635 // looking up the package under its new name, so getPackageLP 6636 // can take care of fiddling things correctly. 6637 pkg.setPackageName(origPackage.name); 6638 6639 // File a report about this. 6640 String msg = "New package " + pkgSetting.realName 6641 + " renamed to replace old package " + pkgSetting.name; 6642 reportSettingsProblem(Log.WARN, msg); 6643 6644 // Make a note of it. 6645 mTransferedPackages.add(origPackage.name); 6646 6647 // No longer need to retain this. 6648 pkgSetting.origPackage = null; 6649 } 6650 6651 if (realName != null) { 6652 // Make a note of it. 6653 mTransferedPackages.add(pkg.packageName); 6654 } 6655 6656 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6657 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6658 } 6659 6660 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6661 // Check all shared libraries and map to their actual file path. 6662 // We only do this here for apps not on a system dir, because those 6663 // are the only ones that can fail an install due to this. We 6664 // will take care of the system apps by updating all of their 6665 // library paths after the scan is done. 6666 updateSharedLibrariesLPw(pkg, null); 6667 } 6668 6669 if (mFoundPolicyFile) { 6670 SELinuxMMAC.assignSeinfoValue(pkg); 6671 } 6672 6673 pkg.applicationInfo.uid = pkgSetting.appId; 6674 pkg.mExtras = pkgSetting; 6675 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 6676 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 6677 // We just determined the app is signed correctly, so bring 6678 // over the latest parsed certs. 6679 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6680 } else { 6681 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6682 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6683 "Package " + pkg.packageName + " upgrade keys do not match the " 6684 + "previously installed version"); 6685 } else { 6686 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6687 String msg = "System package " + pkg.packageName 6688 + " signature changed; retaining data."; 6689 reportSettingsProblem(Log.WARN, msg); 6690 } 6691 } 6692 } else { 6693 try { 6694 verifySignaturesLP(pkgSetting, pkg); 6695 // We just determined the app is signed correctly, so bring 6696 // over the latest parsed certs. 6697 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6698 } catch (PackageManagerException e) { 6699 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6700 throw e; 6701 } 6702 // The signature has changed, but this package is in the system 6703 // image... let's recover! 6704 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6705 // However... if this package is part of a shared user, but it 6706 // doesn't match the signature of the shared user, let's fail. 6707 // What this means is that you can't change the signatures 6708 // associated with an overall shared user, which doesn't seem all 6709 // that unreasonable. 6710 if (pkgSetting.sharedUser != null) { 6711 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6712 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 6713 throw new PackageManagerException( 6714 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6715 "Signature mismatch for shared user : " 6716 + pkgSetting.sharedUser); 6717 } 6718 } 6719 // File a report about this. 6720 String msg = "System package " + pkg.packageName 6721 + " signature changed; retaining data."; 6722 reportSettingsProblem(Log.WARN, msg); 6723 } 6724 } 6725 // Verify that this new package doesn't have any content providers 6726 // that conflict with existing packages. Only do this if the 6727 // package isn't already installed, since we don't want to break 6728 // things that are installed. 6729 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6730 final int N = pkg.providers.size(); 6731 int i; 6732 for (i=0; i<N; i++) { 6733 PackageParser.Provider p = pkg.providers.get(i); 6734 if (p.info.authority != null) { 6735 String names[] = p.info.authority.split(";"); 6736 for (int j = 0; j < names.length; j++) { 6737 if (mProvidersByAuthority.containsKey(names[j])) { 6738 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6739 final String otherPackageName = 6740 ((other != null && other.getComponentName() != null) ? 6741 other.getComponentName().getPackageName() : "?"); 6742 throw new PackageManagerException( 6743 INSTALL_FAILED_CONFLICTING_PROVIDER, 6744 "Can't install because provider name " + names[j] 6745 + " (in package " + pkg.applicationInfo.packageName 6746 + ") is already used by " + otherPackageName); 6747 } 6748 } 6749 } 6750 } 6751 } 6752 6753 if (pkg.mAdoptPermissions != null) { 6754 // This package wants to adopt ownership of permissions from 6755 // another package. 6756 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6757 final String origName = pkg.mAdoptPermissions.get(i); 6758 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6759 if (orig != null) { 6760 if (verifyPackageUpdateLPr(orig, pkg)) { 6761 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6762 + pkg.packageName); 6763 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6764 } 6765 } 6766 } 6767 } 6768 } 6769 6770 final String pkgName = pkg.packageName; 6771 6772 final long scanFileTime = scanFile.lastModified(); 6773 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6774 pkg.applicationInfo.processName = fixProcessName( 6775 pkg.applicationInfo.packageName, 6776 pkg.applicationInfo.processName, 6777 pkg.applicationInfo.uid); 6778 6779 File dataPath; 6780 if (mPlatformPackage == pkg) { 6781 // The system package is special. 6782 dataPath = new File(Environment.getDataDirectory(), "system"); 6783 6784 pkg.applicationInfo.dataDir = dataPath.getPath(); 6785 6786 } else { 6787 // This is a normal package, need to make its data directory. 6788 dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid, 6789 UserHandle.USER_OWNER, pkg.packageName); 6790 6791 boolean uidError = false; 6792 if (dataPath.exists()) { 6793 int currentUid = 0; 6794 try { 6795 StructStat stat = Os.stat(dataPath.getPath()); 6796 currentUid = stat.st_uid; 6797 } catch (ErrnoException e) { 6798 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6799 } 6800 6801 // If we have mismatched owners for the data path, we have a problem. 6802 if (currentUid != pkg.applicationInfo.uid) { 6803 boolean recovered = false; 6804 if (currentUid == 0) { 6805 // The directory somehow became owned by root. Wow. 6806 // This is probably because the system was stopped while 6807 // installd was in the middle of messing with its libs 6808 // directory. Ask installd to fix that. 6809 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6810 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6811 if (ret >= 0) { 6812 recovered = true; 6813 String msg = "Package " + pkg.packageName 6814 + " unexpectedly changed to uid 0; recovered to " + 6815 + pkg.applicationInfo.uid; 6816 reportSettingsProblem(Log.WARN, msg); 6817 } 6818 } 6819 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6820 || (scanFlags&SCAN_BOOTING) != 0)) { 6821 // If this is a system app, we can at least delete its 6822 // current data so the application will still work. 6823 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6824 if (ret >= 0) { 6825 // TODO: Kill the processes first 6826 // Old data gone! 6827 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6828 ? "System package " : "Third party package "; 6829 String msg = prefix + pkg.packageName 6830 + " has changed from uid: " 6831 + currentUid + " to " 6832 + pkg.applicationInfo.uid + "; old data erased"; 6833 reportSettingsProblem(Log.WARN, msg); 6834 recovered = true; 6835 6836 // And now re-install the app. 6837 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6838 pkg.applicationInfo.seinfo); 6839 if (ret == -1) { 6840 // Ack should not happen! 6841 msg = prefix + pkg.packageName 6842 + " could not have data directory re-created after delete."; 6843 reportSettingsProblem(Log.WARN, msg); 6844 throw new PackageManagerException( 6845 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6846 } 6847 } 6848 if (!recovered) { 6849 mHasSystemUidErrors = true; 6850 } 6851 } else if (!recovered) { 6852 // If we allow this install to proceed, we will be broken. 6853 // Abort, abort! 6854 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6855 "scanPackageLI"); 6856 } 6857 if (!recovered) { 6858 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6859 + pkg.applicationInfo.uid + "/fs_" 6860 + currentUid; 6861 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6862 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6863 String msg = "Package " + pkg.packageName 6864 + " has mismatched uid: " 6865 + currentUid + " on disk, " 6866 + pkg.applicationInfo.uid + " in settings"; 6867 // writer 6868 synchronized (mPackages) { 6869 mSettings.mReadMessages.append(msg); 6870 mSettings.mReadMessages.append('\n'); 6871 uidError = true; 6872 if (!pkgSetting.uidError) { 6873 reportSettingsProblem(Log.ERROR, msg); 6874 } 6875 } 6876 } 6877 } 6878 pkg.applicationInfo.dataDir = dataPath.getPath(); 6879 if (mShouldRestoreconData) { 6880 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6881 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 6882 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 6883 } 6884 } else { 6885 if (DEBUG_PACKAGE_SCANNING) { 6886 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6887 Log.v(TAG, "Want this data dir: " + dataPath); 6888 } 6889 //invoke installer to do the actual installation 6890 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6891 pkg.applicationInfo.seinfo); 6892 if (ret < 0) { 6893 // Error from installer 6894 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6895 "Unable to create data dirs [errorCode=" + ret + "]"); 6896 } 6897 6898 if (dataPath.exists()) { 6899 pkg.applicationInfo.dataDir = dataPath.getPath(); 6900 } else { 6901 Slog.w(TAG, "Unable to create data directory: " + dataPath); 6902 pkg.applicationInfo.dataDir = null; 6903 } 6904 } 6905 6906 pkgSetting.uidError = uidError; 6907 } 6908 6909 final String path = scanFile.getPath(); 6910 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6911 6912 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 6913 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 6914 6915 // Some system apps still use directory structure for native libraries 6916 // in which case we might end up not detecting abi solely based on apk 6917 // structure. Try to detect abi based on directory structure. 6918 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 6919 pkg.applicationInfo.primaryCpuAbi == null) { 6920 setBundledAppAbisAndRoots(pkg, pkgSetting); 6921 setNativeLibraryPaths(pkg); 6922 } 6923 6924 } else { 6925 if ((scanFlags & SCAN_MOVE) != 0) { 6926 // We haven't run dex-opt for this move (since we've moved the compiled output too) 6927 // but we already have this packages package info in the PackageSetting. We just 6928 // use that and derive the native library path based on the new codepath. 6929 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 6930 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 6931 } 6932 6933 // Set native library paths again. For moves, the path will be updated based on the 6934 // ABIs we've determined above. For non-moves, the path will be updated based on the 6935 // ABIs we determined during compilation, but the path will depend on the final 6936 // package path (after the rename away from the stage path). 6937 setNativeLibraryPaths(pkg); 6938 } 6939 6940 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 6941 final int[] userIds = sUserManager.getUserIds(); 6942 synchronized (mInstallLock) { 6943 // Make sure all user data directories are ready to roll; we're okay 6944 // if they already exist 6945 if (!TextUtils.isEmpty(pkg.volumeUuid)) { 6946 for (int userId : userIds) { 6947 if (userId != 0) { 6948 mInstaller.createUserData(pkg.volumeUuid, pkg.packageName, 6949 UserHandle.getUid(userId, pkg.applicationInfo.uid), userId, 6950 pkg.applicationInfo.seinfo); 6951 } 6952 } 6953 } 6954 6955 // Create a native library symlink only if we have native libraries 6956 // and if the native libraries are 32 bit libraries. We do not provide 6957 // this symlink for 64 bit libraries. 6958 if (pkg.applicationInfo.primaryCpuAbi != null && 6959 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 6960 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 6961 for (int userId : userIds) { 6962 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 6963 nativeLibPath, userId) < 0) { 6964 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6965 "Failed linking native library dir (user=" + userId + ")"); 6966 } 6967 } 6968 } 6969 } 6970 6971 // This is a special case for the "system" package, where the ABI is 6972 // dictated by the zygote configuration (and init.rc). We should keep track 6973 // of this ABI so that we can deal with "normal" applications that run under 6974 // the same UID correctly. 6975 if (mPlatformPackage == pkg) { 6976 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 6977 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 6978 } 6979 6980 // If there's a mismatch between the abi-override in the package setting 6981 // and the abiOverride specified for the install. Warn about this because we 6982 // would've already compiled the app without taking the package setting into 6983 // account. 6984 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 6985 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 6986 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 6987 " for package: " + pkg.packageName); 6988 } 6989 } 6990 6991 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6992 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6993 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 6994 6995 // Copy the derived override back to the parsed package, so that we can 6996 // update the package settings accordingly. 6997 pkg.cpuAbiOverride = cpuAbiOverride; 6998 6999 if (DEBUG_ABI_SELECTION) { 7000 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 7001 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 7002 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 7003 } 7004 7005 // Push the derived path down into PackageSettings so we know what to 7006 // clean up at uninstall time. 7007 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 7008 7009 if (DEBUG_ABI_SELECTION) { 7010 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 7011 " primary=" + pkg.applicationInfo.primaryCpuAbi + 7012 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 7013 } 7014 7015 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 7016 // We don't do this here during boot because we can do it all 7017 // at once after scanning all existing packages. 7018 // 7019 // We also do this *before* we perform dexopt on this package, so that 7020 // we can avoid redundant dexopts, and also to make sure we've got the 7021 // code and package path correct. 7022 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 7023 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 7024 } 7025 7026 if ((scanFlags & SCAN_NO_DEX) == 0) { 7027 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 7028 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 7029 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7030 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 7031 } 7032 } 7033 if (mFactoryTest && pkg.requestedPermissions.contains( 7034 android.Manifest.permission.FACTORY_TEST)) { 7035 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 7036 } 7037 7038 ArrayList<PackageParser.Package> clientLibPkgs = null; 7039 7040 // writer 7041 synchronized (mPackages) { 7042 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7043 // Only system apps can add new shared libraries. 7044 if (pkg.libraryNames != null) { 7045 for (int i=0; i<pkg.libraryNames.size(); i++) { 7046 String name = pkg.libraryNames.get(i); 7047 boolean allowed = false; 7048 if (pkg.isUpdatedSystemApp()) { 7049 // New library entries can only be added through the 7050 // system image. This is important to get rid of a lot 7051 // of nasty edge cases: for example if we allowed a non- 7052 // system update of the app to add a library, then uninstalling 7053 // the update would make the library go away, and assumptions 7054 // we made such as through app install filtering would now 7055 // have allowed apps on the device which aren't compatible 7056 // with it. Better to just have the restriction here, be 7057 // conservative, and create many fewer cases that can negatively 7058 // impact the user experience. 7059 final PackageSetting sysPs = mSettings 7060 .getDisabledSystemPkgLPr(pkg.packageName); 7061 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 7062 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 7063 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 7064 allowed = true; 7065 allowed = true; 7066 break; 7067 } 7068 } 7069 } 7070 } else { 7071 allowed = true; 7072 } 7073 if (allowed) { 7074 if (!mSharedLibraries.containsKey(name)) { 7075 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 7076 } else if (!name.equals(pkg.packageName)) { 7077 Slog.w(TAG, "Package " + pkg.packageName + " library " 7078 + name + " already exists; skipping"); 7079 } 7080 } else { 7081 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 7082 + name + " that is not declared on system image; skipping"); 7083 } 7084 } 7085 if ((scanFlags&SCAN_BOOTING) == 0) { 7086 // If we are not booting, we need to update any applications 7087 // that are clients of our shared library. If we are booting, 7088 // this will all be done once the scan is complete. 7089 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 7090 } 7091 } 7092 } 7093 } 7094 7095 // We also need to dexopt any apps that are dependent on this library. Note that 7096 // if these fail, we should abort the install since installing the library will 7097 // result in some apps being broken. 7098 if (clientLibPkgs != null) { 7099 if ((scanFlags & SCAN_NO_DEX) == 0) { 7100 for (int i = 0; i < clientLibPkgs.size(); i++) { 7101 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7102 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 7103 null /* instruction sets */, forceDex, 7104 (scanFlags & SCAN_DEFER_DEX) != 0, false); 7105 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7106 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 7107 "scanPackageLI failed to dexopt clientLibPkgs"); 7108 } 7109 } 7110 } 7111 } 7112 7113 // Also need to kill any apps that are dependent on the library. 7114 if (clientLibPkgs != null) { 7115 for (int i=0; i<clientLibPkgs.size(); i++) { 7116 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7117 killApplication(clientPkg.applicationInfo.packageName, 7118 clientPkg.applicationInfo.uid, "update lib"); 7119 } 7120 } 7121 7122 // Make sure we're not adding any bogus keyset info 7123 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7124 ksms.assertScannedPackageValid(pkg); 7125 7126 // writer 7127 synchronized (mPackages) { 7128 // We don't expect installation to fail beyond this point 7129 7130 // Add the new setting to mSettings 7131 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 7132 // Add the new setting to mPackages 7133 mPackages.put(pkg.applicationInfo.packageName, pkg); 7134 // Make sure we don't accidentally delete its data. 7135 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 7136 while (iter.hasNext()) { 7137 PackageCleanItem item = iter.next(); 7138 if (pkgName.equals(item.packageName)) { 7139 iter.remove(); 7140 } 7141 } 7142 7143 // Take care of first install / last update times. 7144 if (currentTime != 0) { 7145 if (pkgSetting.firstInstallTime == 0) { 7146 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7147 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7148 pkgSetting.lastUpdateTime = currentTime; 7149 } 7150 } else if (pkgSetting.firstInstallTime == 0) { 7151 // We need *something*. Take time time stamp of the file. 7152 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7153 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7154 if (scanFileTime != pkgSetting.timeStamp) { 7155 // A package on the system image has changed; consider this 7156 // to be an update. 7157 pkgSetting.lastUpdateTime = scanFileTime; 7158 } 7159 } 7160 7161 // Add the package's KeySets to the global KeySetManagerService 7162 ksms.addScannedPackageLPw(pkg); 7163 7164 int N = pkg.providers.size(); 7165 StringBuilder r = null; 7166 int i; 7167 for (i=0; i<N; i++) { 7168 PackageParser.Provider p = pkg.providers.get(i); 7169 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7170 p.info.processName, pkg.applicationInfo.uid); 7171 mProviders.addProvider(p); 7172 p.syncable = p.info.isSyncable; 7173 if (p.info.authority != null) { 7174 String names[] = p.info.authority.split(";"); 7175 p.info.authority = null; 7176 for (int j = 0; j < names.length; j++) { 7177 if (j == 1 && p.syncable) { 7178 // We only want the first authority for a provider to possibly be 7179 // syncable, so if we already added this provider using a different 7180 // authority clear the syncable flag. We copy the provider before 7181 // changing it because the mProviders object contains a reference 7182 // to a provider that we don't want to change. 7183 // Only do this for the second authority since the resulting provider 7184 // object can be the same for all future authorities for this provider. 7185 p = new PackageParser.Provider(p); 7186 p.syncable = false; 7187 } 7188 if (!mProvidersByAuthority.containsKey(names[j])) { 7189 mProvidersByAuthority.put(names[j], p); 7190 if (p.info.authority == null) { 7191 p.info.authority = names[j]; 7192 } else { 7193 p.info.authority = p.info.authority + ";" + names[j]; 7194 } 7195 if (DEBUG_PACKAGE_SCANNING) { 7196 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7197 Log.d(TAG, "Registered content provider: " + names[j] 7198 + ", className = " + p.info.name + ", isSyncable = " 7199 + p.info.isSyncable); 7200 } 7201 } else { 7202 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7203 Slog.w(TAG, "Skipping provider name " + names[j] + 7204 " (in package " + pkg.applicationInfo.packageName + 7205 "): name already used by " 7206 + ((other != null && other.getComponentName() != null) 7207 ? other.getComponentName().getPackageName() : "?")); 7208 } 7209 } 7210 } 7211 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7212 if (r == null) { 7213 r = new StringBuilder(256); 7214 } else { 7215 r.append(' '); 7216 } 7217 r.append(p.info.name); 7218 } 7219 } 7220 if (r != null) { 7221 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7222 } 7223 7224 N = pkg.services.size(); 7225 r = null; 7226 for (i=0; i<N; i++) { 7227 PackageParser.Service s = pkg.services.get(i); 7228 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 7229 s.info.processName, pkg.applicationInfo.uid); 7230 mServices.addService(s); 7231 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7232 if (r == null) { 7233 r = new StringBuilder(256); 7234 } else { 7235 r.append(' '); 7236 } 7237 r.append(s.info.name); 7238 } 7239 } 7240 if (r != null) { 7241 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 7242 } 7243 7244 N = pkg.receivers.size(); 7245 r = null; 7246 for (i=0; i<N; i++) { 7247 PackageParser.Activity a = pkg.receivers.get(i); 7248 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7249 a.info.processName, pkg.applicationInfo.uid); 7250 mReceivers.addActivity(a, "receiver"); 7251 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7252 if (r == null) { 7253 r = new StringBuilder(256); 7254 } else { 7255 r.append(' '); 7256 } 7257 r.append(a.info.name); 7258 } 7259 } 7260 if (r != null) { 7261 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 7262 } 7263 7264 N = pkg.activities.size(); 7265 r = null; 7266 for (i=0; i<N; i++) { 7267 PackageParser.Activity a = pkg.activities.get(i); 7268 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7269 a.info.processName, pkg.applicationInfo.uid); 7270 mActivities.addActivity(a, "activity"); 7271 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7272 if (r == null) { 7273 r = new StringBuilder(256); 7274 } else { 7275 r.append(' '); 7276 } 7277 r.append(a.info.name); 7278 } 7279 } 7280 if (r != null) { 7281 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 7282 } 7283 7284 N = pkg.permissionGroups.size(); 7285 r = null; 7286 for (i=0; i<N; i++) { 7287 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 7288 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 7289 if (cur == null) { 7290 mPermissionGroups.put(pg.info.name, pg); 7291 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7292 if (r == null) { 7293 r = new StringBuilder(256); 7294 } else { 7295 r.append(' '); 7296 } 7297 r.append(pg.info.name); 7298 } 7299 } else { 7300 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 7301 + pg.info.packageName + " ignored: original from " 7302 + cur.info.packageName); 7303 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7304 if (r == null) { 7305 r = new StringBuilder(256); 7306 } else { 7307 r.append(' '); 7308 } 7309 r.append("DUP:"); 7310 r.append(pg.info.name); 7311 } 7312 } 7313 } 7314 if (r != null) { 7315 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 7316 } 7317 7318 N = pkg.permissions.size(); 7319 r = null; 7320 for (i=0; i<N; i++) { 7321 PackageParser.Permission p = pkg.permissions.get(i); 7322 7323 // Now that permission groups have a special meaning, we ignore permission 7324 // groups for legacy apps to prevent unexpected behavior. In particular, 7325 // permissions for one app being granted to someone just becuase they happen 7326 // to be in a group defined by another app (before this had no implications). 7327 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 7328 p.group = mPermissionGroups.get(p.info.group); 7329 // Warn for a permission in an unknown group. 7330 if (p.info.group != null && p.group == null) { 7331 Slog.w(TAG, "Permission " + p.info.name + " from package " 7332 + p.info.packageName + " in an unknown group " + p.info.group); 7333 } 7334 } 7335 7336 ArrayMap<String, BasePermission> permissionMap = 7337 p.tree ? mSettings.mPermissionTrees 7338 : mSettings.mPermissions; 7339 BasePermission bp = permissionMap.get(p.info.name); 7340 7341 // Allow system apps to redefine non-system permissions 7342 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 7343 final boolean currentOwnerIsSystem = (bp.perm != null 7344 && isSystemApp(bp.perm.owner)); 7345 if (isSystemApp(p.owner)) { 7346 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 7347 // It's a built-in permission and no owner, take ownership now 7348 bp.packageSetting = pkgSetting; 7349 bp.perm = p; 7350 bp.uid = pkg.applicationInfo.uid; 7351 bp.sourcePackage = p.info.packageName; 7352 } else if (!currentOwnerIsSystem) { 7353 String msg = "New decl " + p.owner + " of permission " 7354 + p.info.name + " is system; overriding " + bp.sourcePackage; 7355 reportSettingsProblem(Log.WARN, msg); 7356 bp = null; 7357 } 7358 } 7359 } 7360 7361 if (bp == null) { 7362 bp = new BasePermission(p.info.name, p.info.packageName, 7363 BasePermission.TYPE_NORMAL); 7364 permissionMap.put(p.info.name, bp); 7365 } 7366 7367 if (bp.perm == null) { 7368 if (bp.sourcePackage == null 7369 || bp.sourcePackage.equals(p.info.packageName)) { 7370 BasePermission tree = findPermissionTreeLP(p.info.name); 7371 if (tree == null 7372 || tree.sourcePackage.equals(p.info.packageName)) { 7373 bp.packageSetting = pkgSetting; 7374 bp.perm = p; 7375 bp.uid = pkg.applicationInfo.uid; 7376 bp.sourcePackage = p.info.packageName; 7377 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7378 if (r == null) { 7379 r = new StringBuilder(256); 7380 } else { 7381 r.append(' '); 7382 } 7383 r.append(p.info.name); 7384 } 7385 } else { 7386 Slog.w(TAG, "Permission " + p.info.name + " from package " 7387 + p.info.packageName + " ignored: base tree " 7388 + tree.name + " is from package " 7389 + tree.sourcePackage); 7390 } 7391 } else { 7392 Slog.w(TAG, "Permission " + p.info.name + " from package " 7393 + p.info.packageName + " ignored: original from " 7394 + bp.sourcePackage); 7395 } 7396 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7397 if (r == null) { 7398 r = new StringBuilder(256); 7399 } else { 7400 r.append(' '); 7401 } 7402 r.append("DUP:"); 7403 r.append(p.info.name); 7404 } 7405 if (bp.perm == p) { 7406 bp.protectionLevel = p.info.protectionLevel; 7407 } 7408 } 7409 7410 if (r != null) { 7411 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 7412 } 7413 7414 N = pkg.instrumentation.size(); 7415 r = null; 7416 for (i=0; i<N; i++) { 7417 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7418 a.info.packageName = pkg.applicationInfo.packageName; 7419 a.info.sourceDir = pkg.applicationInfo.sourceDir; 7420 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 7421 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 7422 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 7423 a.info.dataDir = pkg.applicationInfo.dataDir; 7424 7425 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 7426 // need other information about the application, like the ABI and what not ? 7427 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 7428 mInstrumentation.put(a.getComponentName(), a); 7429 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7430 if (r == null) { 7431 r = new StringBuilder(256); 7432 } else { 7433 r.append(' '); 7434 } 7435 r.append(a.info.name); 7436 } 7437 } 7438 if (r != null) { 7439 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 7440 } 7441 7442 if (pkg.protectedBroadcasts != null) { 7443 N = pkg.protectedBroadcasts.size(); 7444 for (i=0; i<N; i++) { 7445 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 7446 } 7447 } 7448 7449 pkgSetting.setTimeStamp(scanFileTime); 7450 7451 // Create idmap files for pairs of (packages, overlay packages). 7452 // Note: "android", ie framework-res.apk, is handled by native layers. 7453 if (pkg.mOverlayTarget != null) { 7454 // This is an overlay package. 7455 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 7456 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 7457 mOverlays.put(pkg.mOverlayTarget, 7458 new ArrayMap<String, PackageParser.Package>()); 7459 } 7460 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 7461 map.put(pkg.packageName, pkg); 7462 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 7463 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 7464 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7465 "scanPackageLI failed to createIdmap"); 7466 } 7467 } 7468 } else if (mOverlays.containsKey(pkg.packageName) && 7469 !pkg.packageName.equals("android")) { 7470 // This is a regular package, with one or more known overlay packages. 7471 createIdmapsForPackageLI(pkg); 7472 } 7473 } 7474 7475 return pkg; 7476 } 7477 7478 /** 7479 * Derive the ABI of a non-system package located at {@code scanFile}. This information 7480 * is derived purely on the basis of the contents of {@code scanFile} and 7481 * {@code cpuAbiOverride}. 7482 * 7483 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 7484 */ 7485 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 7486 String cpuAbiOverride, boolean extractLibs) 7487 throws PackageManagerException { 7488 // TODO: We can probably be smarter about this stuff. For installed apps, 7489 // we can calculate this information at install time once and for all. For 7490 // system apps, we can probably assume that this information doesn't change 7491 // after the first boot scan. As things stand, we do lots of unnecessary work. 7492 7493 // Give ourselves some initial paths; we'll come back for another 7494 // pass once we've determined ABI below. 7495 setNativeLibraryPaths(pkg); 7496 7497 // We would never need to extract libs for forward-locked and external packages, 7498 // since the container service will do it for us. We shouldn't attempt to 7499 // extract libs from system app when it was not updated. 7500 if (pkg.isForwardLocked() || isExternal(pkg) || 7501 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) { 7502 extractLibs = false; 7503 } 7504 7505 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7506 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7507 7508 NativeLibraryHelper.Handle handle = null; 7509 try { 7510 handle = NativeLibraryHelper.Handle.create(scanFile); 7511 // TODO(multiArch): This can be null for apps that didn't go through the 7512 // usual installation process. We can calculate it again, like we 7513 // do during install time. 7514 // 7515 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7516 // unnecessary. 7517 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7518 7519 // Null out the abis so that they can be recalculated. 7520 pkg.applicationInfo.primaryCpuAbi = null; 7521 pkg.applicationInfo.secondaryCpuAbi = null; 7522 if (isMultiArch(pkg.applicationInfo)) { 7523 // Warn if we've set an abiOverride for multi-lib packages.. 7524 // By definition, we need to copy both 32 and 64 bit libraries for 7525 // such packages. 7526 if (pkg.cpuAbiOverride != null 7527 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7528 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7529 } 7530 7531 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7532 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7533 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7534 if (extractLibs) { 7535 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7536 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7537 useIsaSpecificSubdirs); 7538 } else { 7539 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7540 } 7541 } 7542 7543 maybeThrowExceptionForMultiArchCopy( 7544 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7545 7546 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7547 if (extractLibs) { 7548 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7549 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7550 useIsaSpecificSubdirs); 7551 } else { 7552 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7553 } 7554 } 7555 7556 maybeThrowExceptionForMultiArchCopy( 7557 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7558 7559 if (abi64 >= 0) { 7560 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7561 } 7562 7563 if (abi32 >= 0) { 7564 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7565 if (abi64 >= 0) { 7566 pkg.applicationInfo.secondaryCpuAbi = abi; 7567 } else { 7568 pkg.applicationInfo.primaryCpuAbi = abi; 7569 } 7570 } 7571 } else { 7572 String[] abiList = (cpuAbiOverride != null) ? 7573 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7574 7575 // Enable gross and lame hacks for apps that are built with old 7576 // SDK tools. We must scan their APKs for renderscript bitcode and 7577 // not launch them if it's present. Don't bother checking on devices 7578 // that don't have 64 bit support. 7579 boolean needsRenderScriptOverride = false; 7580 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7581 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7582 abiList = Build.SUPPORTED_32_BIT_ABIS; 7583 needsRenderScriptOverride = true; 7584 } 7585 7586 final int copyRet; 7587 if (extractLibs) { 7588 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7589 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7590 } else { 7591 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7592 } 7593 7594 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7595 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7596 "Error unpackaging native libs for app, errorCode=" + copyRet); 7597 } 7598 7599 if (copyRet >= 0) { 7600 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7601 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7602 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7603 } else if (needsRenderScriptOverride) { 7604 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7605 } 7606 } 7607 } catch (IOException ioe) { 7608 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7609 } finally { 7610 IoUtils.closeQuietly(handle); 7611 } 7612 7613 // Now that we've calculated the ABIs and determined if it's an internal app, 7614 // we will go ahead and populate the nativeLibraryPath. 7615 setNativeLibraryPaths(pkg); 7616 } 7617 7618 /** 7619 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7620 * i.e, so that all packages can be run inside a single process if required. 7621 * 7622 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7623 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7624 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7625 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7626 * updating a package that belongs to a shared user. 7627 * 7628 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7629 * adds unnecessary complexity. 7630 */ 7631 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7632 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 7633 String requiredInstructionSet = null; 7634 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7635 requiredInstructionSet = VMRuntime.getInstructionSet( 7636 scannedPackage.applicationInfo.primaryCpuAbi); 7637 } 7638 7639 PackageSetting requirer = null; 7640 for (PackageSetting ps : packagesForUser) { 7641 // If packagesForUser contains scannedPackage, we skip it. This will happen 7642 // when scannedPackage is an update of an existing package. Without this check, 7643 // we will never be able to change the ABI of any package belonging to a shared 7644 // user, even if it's compatible with other packages. 7645 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7646 if (ps.primaryCpuAbiString == null) { 7647 continue; 7648 } 7649 7650 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7651 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7652 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7653 // this but there's not much we can do. 7654 String errorMessage = "Instruction set mismatch, " 7655 + ((requirer == null) ? "[caller]" : requirer) 7656 + " requires " + requiredInstructionSet + " whereas " + ps 7657 + " requires " + instructionSet; 7658 Slog.w(TAG, errorMessage); 7659 } 7660 7661 if (requiredInstructionSet == null) { 7662 requiredInstructionSet = instructionSet; 7663 requirer = ps; 7664 } 7665 } 7666 } 7667 7668 if (requiredInstructionSet != null) { 7669 String adjustedAbi; 7670 if (requirer != null) { 7671 // requirer != null implies that either scannedPackage was null or that scannedPackage 7672 // did not require an ABI, in which case we have to adjust scannedPackage to match 7673 // the ABI of the set (which is the same as requirer's ABI) 7674 adjustedAbi = requirer.primaryCpuAbiString; 7675 if (scannedPackage != null) { 7676 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7677 } 7678 } else { 7679 // requirer == null implies that we're updating all ABIs in the set to 7680 // match scannedPackage. 7681 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7682 } 7683 7684 for (PackageSetting ps : packagesForUser) { 7685 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7686 if (ps.primaryCpuAbiString != null) { 7687 continue; 7688 } 7689 7690 ps.primaryCpuAbiString = adjustedAbi; 7691 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7692 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7693 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7694 7695 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 7696 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 7697 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7698 ps.primaryCpuAbiString = null; 7699 ps.pkg.applicationInfo.primaryCpuAbi = null; 7700 return; 7701 } else { 7702 mInstaller.rmdex(ps.codePathString, 7703 getDexCodeInstructionSet(getPreferredInstructionSet())); 7704 } 7705 } 7706 } 7707 } 7708 } 7709 } 7710 7711 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7712 synchronized (mPackages) { 7713 mResolverReplaced = true; 7714 // Set up information for custom user intent resolution activity. 7715 mResolveActivity.applicationInfo = pkg.applicationInfo; 7716 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7717 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7718 mResolveActivity.processName = pkg.applicationInfo.packageName; 7719 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7720 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7721 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7722 mResolveActivity.theme = 0; 7723 mResolveActivity.exported = true; 7724 mResolveActivity.enabled = true; 7725 mResolveInfo.activityInfo = mResolveActivity; 7726 mResolveInfo.priority = 0; 7727 mResolveInfo.preferredOrder = 0; 7728 mResolveInfo.match = 0; 7729 mResolveComponentName = mCustomResolverComponentName; 7730 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7731 mResolveComponentName); 7732 } 7733 } 7734 7735 private static String calculateBundledApkRoot(final String codePathString) { 7736 final File codePath = new File(codePathString); 7737 final File codeRoot; 7738 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 7739 codeRoot = Environment.getRootDirectory(); 7740 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7741 codeRoot = Environment.getOemDirectory(); 7742 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7743 codeRoot = Environment.getVendorDirectory(); 7744 } else { 7745 // Unrecognized code path; take its top real segment as the apk root: 7746 // e.g. /something/app/blah.apk => /something 7747 try { 7748 File f = codePath.getCanonicalFile(); 7749 File parent = f.getParentFile(); // non-null because codePath is a file 7750 File tmp; 7751 while ((tmp = parent.getParentFile()) != null) { 7752 f = parent; 7753 parent = tmp; 7754 } 7755 codeRoot = f; 7756 Slog.w(TAG, "Unrecognized code path " 7757 + codePath + " - using " + codeRoot); 7758 } catch (IOException e) { 7759 // Can't canonicalize the code path -- shenanigans? 7760 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7761 return Environment.getRootDirectory().getPath(); 7762 } 7763 } 7764 return codeRoot.getPath(); 7765 } 7766 7767 /** 7768 * Derive and set the location of native libraries for the given package, 7769 * which varies depending on where and how the package was installed. 7770 */ 7771 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7772 final ApplicationInfo info = pkg.applicationInfo; 7773 final String codePath = pkg.codePath; 7774 final File codeFile = new File(codePath); 7775 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7776 final boolean asecApp = info.isForwardLocked() || isExternal(info); 7777 7778 info.nativeLibraryRootDir = null; 7779 info.nativeLibraryRootRequiresIsa = false; 7780 info.nativeLibraryDir = null; 7781 info.secondaryNativeLibraryDir = null; 7782 7783 if (isApkFile(codeFile)) { 7784 // Monolithic install 7785 if (bundledApp) { 7786 // If "/system/lib64/apkname" exists, assume that is the per-package 7787 // native library directory to use; otherwise use "/system/lib/apkname". 7788 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7789 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7790 getPrimaryInstructionSet(info)); 7791 7792 // This is a bundled system app so choose the path based on the ABI. 7793 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7794 // is just the default path. 7795 final String apkName = deriveCodePathName(codePath); 7796 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7797 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7798 apkName).getAbsolutePath(); 7799 7800 if (info.secondaryCpuAbi != null) { 7801 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7802 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7803 secondaryLibDir, apkName).getAbsolutePath(); 7804 } 7805 } else if (asecApp) { 7806 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 7807 .getAbsolutePath(); 7808 } else { 7809 final String apkName = deriveCodePathName(codePath); 7810 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 7811 .getAbsolutePath(); 7812 } 7813 7814 info.nativeLibraryRootRequiresIsa = false; 7815 info.nativeLibraryDir = info.nativeLibraryRootDir; 7816 } else { 7817 // Cluster install 7818 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 7819 info.nativeLibraryRootRequiresIsa = true; 7820 7821 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 7822 getPrimaryInstructionSet(info)).getAbsolutePath(); 7823 7824 if (info.secondaryCpuAbi != null) { 7825 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 7826 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 7827 } 7828 } 7829 } 7830 7831 /** 7832 * Calculate the abis and roots for a bundled app. These can uniquely 7833 * be determined from the contents of the system partition, i.e whether 7834 * it contains 64 or 32 bit shared libraries etc. We do not validate any 7835 * of this information, and instead assume that the system was built 7836 * sensibly. 7837 */ 7838 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 7839 PackageSetting pkgSetting) { 7840 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 7841 7842 // If "/system/lib64/apkname" exists, assume that is the per-package 7843 // native library directory to use; otherwise use "/system/lib/apkname". 7844 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 7845 setBundledAppAbi(pkg, apkRoot, apkName); 7846 // pkgSetting might be null during rescan following uninstall of updates 7847 // to a bundled app, so accommodate that possibility. The settings in 7848 // that case will be established later from the parsed package. 7849 // 7850 // If the settings aren't null, sync them up with what we've just derived. 7851 // note that apkRoot isn't stored in the package settings. 7852 if (pkgSetting != null) { 7853 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7854 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7855 } 7856 } 7857 7858 /** 7859 * Deduces the ABI of a bundled app and sets the relevant fields on the 7860 * parsed pkg object. 7861 * 7862 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 7863 * under which system libraries are installed. 7864 * @param apkName the name of the installed package. 7865 */ 7866 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 7867 final File codeFile = new File(pkg.codePath); 7868 7869 final boolean has64BitLibs; 7870 final boolean has32BitLibs; 7871 if (isApkFile(codeFile)) { 7872 // Monolithic install 7873 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 7874 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7875 } else { 7876 // Cluster install 7877 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7878 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7879 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7880 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7881 has64BitLibs = (new File(rootDir, isa)).exists(); 7882 } else { 7883 has64BitLibs = false; 7884 } 7885 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7886 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 7887 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 7888 has32BitLibs = (new File(rootDir, isa)).exists(); 7889 } else { 7890 has32BitLibs = false; 7891 } 7892 } 7893 7894 if (has64BitLibs && !has32BitLibs) { 7895 // The package has 64 bit libs, but not 32 bit libs. Its primary 7896 // ABI should be 64 bit. We can safely assume here that the bundled 7897 // native libraries correspond to the most preferred ABI in the list. 7898 7899 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7900 pkg.applicationInfo.secondaryCpuAbi = null; 7901 } else if (has32BitLibs && !has64BitLibs) { 7902 // The package has 32 bit libs but not 64 bit libs. Its primary 7903 // ABI should be 32 bit. 7904 7905 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7906 pkg.applicationInfo.secondaryCpuAbi = null; 7907 } else if (has32BitLibs && has64BitLibs) { 7908 // The application has both 64 and 32 bit bundled libraries. We check 7909 // here that the app declares multiArch support, and warn if it doesn't. 7910 // 7911 // We will be lenient here and record both ABIs. The primary will be the 7912 // ABI that's higher on the list, i.e, a device that's configured to prefer 7913 // 64 bit apps will see a 64 bit primary ABI, 7914 7915 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 7916 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 7917 } 7918 7919 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 7920 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7921 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7922 } else { 7923 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7924 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7925 } 7926 } else { 7927 pkg.applicationInfo.primaryCpuAbi = null; 7928 pkg.applicationInfo.secondaryCpuAbi = null; 7929 } 7930 } 7931 7932 private void killApplication(String pkgName, int appId, String reason) { 7933 // Request the ActivityManager to kill the process(only for existing packages) 7934 // so that we do not end up in a confused state while the user is still using the older 7935 // version of the application while the new one gets installed. 7936 IActivityManager am = ActivityManagerNative.getDefault(); 7937 if (am != null) { 7938 try { 7939 am.killApplicationWithAppId(pkgName, appId, reason); 7940 } catch (RemoteException e) { 7941 } 7942 } 7943 } 7944 7945 void removePackageLI(PackageSetting ps, boolean chatty) { 7946 if (DEBUG_INSTALL) { 7947 if (chatty) 7948 Log.d(TAG, "Removing package " + ps.name); 7949 } 7950 7951 // writer 7952 synchronized (mPackages) { 7953 mPackages.remove(ps.name); 7954 final PackageParser.Package pkg = ps.pkg; 7955 if (pkg != null) { 7956 cleanPackageDataStructuresLILPw(pkg, chatty); 7957 } 7958 } 7959 } 7960 7961 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 7962 if (DEBUG_INSTALL) { 7963 if (chatty) 7964 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 7965 } 7966 7967 // writer 7968 synchronized (mPackages) { 7969 mPackages.remove(pkg.applicationInfo.packageName); 7970 cleanPackageDataStructuresLILPw(pkg, chatty); 7971 } 7972 } 7973 7974 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 7975 int N = pkg.providers.size(); 7976 StringBuilder r = null; 7977 int i; 7978 for (i=0; i<N; i++) { 7979 PackageParser.Provider p = pkg.providers.get(i); 7980 mProviders.removeProvider(p); 7981 if (p.info.authority == null) { 7982 7983 /* There was another ContentProvider with this authority when 7984 * this app was installed so this authority is null, 7985 * Ignore it as we don't have to unregister the provider. 7986 */ 7987 continue; 7988 } 7989 String names[] = p.info.authority.split(";"); 7990 for (int j = 0; j < names.length; j++) { 7991 if (mProvidersByAuthority.get(names[j]) == p) { 7992 mProvidersByAuthority.remove(names[j]); 7993 if (DEBUG_REMOVE) { 7994 if (chatty) 7995 Log.d(TAG, "Unregistered content provider: " + names[j] 7996 + ", className = " + p.info.name + ", isSyncable = " 7997 + p.info.isSyncable); 7998 } 7999 } 8000 } 8001 if (DEBUG_REMOVE && chatty) { 8002 if (r == null) { 8003 r = new StringBuilder(256); 8004 } else { 8005 r.append(' '); 8006 } 8007 r.append(p.info.name); 8008 } 8009 } 8010 if (r != null) { 8011 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 8012 } 8013 8014 N = pkg.services.size(); 8015 r = null; 8016 for (i=0; i<N; i++) { 8017 PackageParser.Service s = pkg.services.get(i); 8018 mServices.removeService(s); 8019 if (chatty) { 8020 if (r == null) { 8021 r = new StringBuilder(256); 8022 } else { 8023 r.append(' '); 8024 } 8025 r.append(s.info.name); 8026 } 8027 } 8028 if (r != null) { 8029 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 8030 } 8031 8032 N = pkg.receivers.size(); 8033 r = null; 8034 for (i=0; i<N; i++) { 8035 PackageParser.Activity a = pkg.receivers.get(i); 8036 mReceivers.removeActivity(a, "receiver"); 8037 if (DEBUG_REMOVE && chatty) { 8038 if (r == null) { 8039 r = new StringBuilder(256); 8040 } else { 8041 r.append(' '); 8042 } 8043 r.append(a.info.name); 8044 } 8045 } 8046 if (r != null) { 8047 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 8048 } 8049 8050 N = pkg.activities.size(); 8051 r = null; 8052 for (i=0; i<N; i++) { 8053 PackageParser.Activity a = pkg.activities.get(i); 8054 mActivities.removeActivity(a, "activity"); 8055 if (DEBUG_REMOVE && chatty) { 8056 if (r == null) { 8057 r = new StringBuilder(256); 8058 } else { 8059 r.append(' '); 8060 } 8061 r.append(a.info.name); 8062 } 8063 } 8064 if (r != null) { 8065 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 8066 } 8067 8068 N = pkg.permissions.size(); 8069 r = null; 8070 for (i=0; i<N; i++) { 8071 PackageParser.Permission p = pkg.permissions.get(i); 8072 BasePermission bp = mSettings.mPermissions.get(p.info.name); 8073 if (bp == null) { 8074 bp = mSettings.mPermissionTrees.get(p.info.name); 8075 } 8076 if (bp != null && bp.perm == p) { 8077 bp.perm = null; 8078 if (DEBUG_REMOVE && chatty) { 8079 if (r == null) { 8080 r = new StringBuilder(256); 8081 } else { 8082 r.append(' '); 8083 } 8084 r.append(p.info.name); 8085 } 8086 } 8087 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8088 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 8089 if (appOpPerms != null) { 8090 appOpPerms.remove(pkg.packageName); 8091 } 8092 } 8093 } 8094 if (r != null) { 8095 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8096 } 8097 8098 N = pkg.requestedPermissions.size(); 8099 r = null; 8100 for (i=0; i<N; i++) { 8101 String perm = pkg.requestedPermissions.get(i); 8102 BasePermission bp = mSettings.mPermissions.get(perm); 8103 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8104 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 8105 if (appOpPerms != null) { 8106 appOpPerms.remove(pkg.packageName); 8107 if (appOpPerms.isEmpty()) { 8108 mAppOpPermissionPackages.remove(perm); 8109 } 8110 } 8111 } 8112 } 8113 if (r != null) { 8114 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8115 } 8116 8117 N = pkg.instrumentation.size(); 8118 r = null; 8119 for (i=0; i<N; i++) { 8120 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8121 mInstrumentation.remove(a.getComponentName()); 8122 if (DEBUG_REMOVE && chatty) { 8123 if (r == null) { 8124 r = new StringBuilder(256); 8125 } else { 8126 r.append(' '); 8127 } 8128 r.append(a.info.name); 8129 } 8130 } 8131 if (r != null) { 8132 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 8133 } 8134 8135 r = null; 8136 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8137 // Only system apps can hold shared libraries. 8138 if (pkg.libraryNames != null) { 8139 for (i=0; i<pkg.libraryNames.size(); i++) { 8140 String name = pkg.libraryNames.get(i); 8141 SharedLibraryEntry cur = mSharedLibraries.get(name); 8142 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 8143 mSharedLibraries.remove(name); 8144 if (DEBUG_REMOVE && chatty) { 8145 if (r == null) { 8146 r = new StringBuilder(256); 8147 } else { 8148 r.append(' '); 8149 } 8150 r.append(name); 8151 } 8152 } 8153 } 8154 } 8155 } 8156 if (r != null) { 8157 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 8158 } 8159 } 8160 8161 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 8162 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 8163 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 8164 return true; 8165 } 8166 } 8167 return false; 8168 } 8169 8170 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 8171 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 8172 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 8173 8174 private void updatePermissionsLPw(String changingPkg, 8175 PackageParser.Package pkgInfo, int flags) { 8176 // Make sure there are no dangling permission trees. 8177 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 8178 while (it.hasNext()) { 8179 final BasePermission bp = it.next(); 8180 if (bp.packageSetting == null) { 8181 // We may not yet have parsed the package, so just see if 8182 // we still know about its settings. 8183 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8184 } 8185 if (bp.packageSetting == null) { 8186 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 8187 + " from package " + bp.sourcePackage); 8188 it.remove(); 8189 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8190 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8191 Slog.i(TAG, "Removing old permission tree: " + bp.name 8192 + " from package " + bp.sourcePackage); 8193 flags |= UPDATE_PERMISSIONS_ALL; 8194 it.remove(); 8195 } 8196 } 8197 } 8198 8199 // Make sure all dynamic permissions have been assigned to a package, 8200 // and make sure there are no dangling permissions. 8201 it = mSettings.mPermissions.values().iterator(); 8202 while (it.hasNext()) { 8203 final BasePermission bp = it.next(); 8204 if (bp.type == BasePermission.TYPE_DYNAMIC) { 8205 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 8206 + bp.name + " pkg=" + bp.sourcePackage 8207 + " info=" + bp.pendingInfo); 8208 if (bp.packageSetting == null && bp.pendingInfo != null) { 8209 final BasePermission tree = findPermissionTreeLP(bp.name); 8210 if (tree != null && tree.perm != null) { 8211 bp.packageSetting = tree.packageSetting; 8212 bp.perm = new PackageParser.Permission(tree.perm.owner, 8213 new PermissionInfo(bp.pendingInfo)); 8214 bp.perm.info.packageName = tree.perm.info.packageName; 8215 bp.perm.info.name = bp.name; 8216 bp.uid = tree.uid; 8217 } 8218 } 8219 } 8220 if (bp.packageSetting == null) { 8221 // We may not yet have parsed the package, so just see if 8222 // we still know about its settings. 8223 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8224 } 8225 if (bp.packageSetting == null) { 8226 Slog.w(TAG, "Removing dangling permission: " + bp.name 8227 + " from package " + bp.sourcePackage); 8228 it.remove(); 8229 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8230 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8231 Slog.i(TAG, "Removing old permission: " + bp.name 8232 + " from package " + bp.sourcePackage); 8233 flags |= UPDATE_PERMISSIONS_ALL; 8234 it.remove(); 8235 } 8236 } 8237 } 8238 8239 // Now update the permissions for all packages, in particular 8240 // replace the granted permissions of the system packages. 8241 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 8242 for (PackageParser.Package pkg : mPackages.values()) { 8243 if (pkg != pkgInfo) { 8244 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 8245 changingPkg); 8246 } 8247 } 8248 } 8249 8250 if (pkgInfo != null) { 8251 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 8252 } 8253 } 8254 8255 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 8256 String packageOfInterest) { 8257 // IMPORTANT: There are two types of permissions: install and runtime. 8258 // Install time permissions are granted when the app is installed to 8259 // all device users and users added in the future. Runtime permissions 8260 // are granted at runtime explicitly to specific users. Normal and signature 8261 // protected permissions are install time permissions. Dangerous permissions 8262 // are install permissions if the app's target SDK is Lollipop MR1 or older, 8263 // otherwise they are runtime permissions. This function does not manage 8264 // runtime permissions except for the case an app targeting Lollipop MR1 8265 // being upgraded to target a newer SDK, in which case dangerous permissions 8266 // are transformed from install time to runtime ones. 8267 8268 final PackageSetting ps = (PackageSetting) pkg.mExtras; 8269 if (ps == null) { 8270 return; 8271 } 8272 8273 PermissionsState permissionsState = ps.getPermissionsState(); 8274 PermissionsState origPermissions = permissionsState; 8275 8276 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 8277 8278 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 8279 8280 boolean changedInstallPermission = false; 8281 8282 if (replace) { 8283 ps.installPermissionsFixed = false; 8284 if (!ps.isSharedUser()) { 8285 origPermissions = new PermissionsState(permissionsState); 8286 permissionsState.reset(); 8287 } 8288 } 8289 8290 permissionsState.setGlobalGids(mGlobalGids); 8291 8292 final int N = pkg.requestedPermissions.size(); 8293 for (int i=0; i<N; i++) { 8294 final String name = pkg.requestedPermissions.get(i); 8295 final BasePermission bp = mSettings.mPermissions.get(name); 8296 8297 if (DEBUG_INSTALL) { 8298 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 8299 } 8300 8301 if (bp == null || bp.packageSetting == null) { 8302 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8303 Slog.w(TAG, "Unknown permission " + name 8304 + " in package " + pkg.packageName); 8305 } 8306 continue; 8307 } 8308 8309 final String perm = bp.name; 8310 boolean allowedSig = false; 8311 int grant = GRANT_DENIED; 8312 8313 // Keep track of app op permissions. 8314 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8315 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 8316 if (pkgs == null) { 8317 pkgs = new ArraySet<>(); 8318 mAppOpPermissionPackages.put(bp.name, pkgs); 8319 } 8320 pkgs.add(pkg.packageName); 8321 } 8322 8323 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 8324 switch (level) { 8325 case PermissionInfo.PROTECTION_NORMAL: { 8326 // For all apps normal permissions are install time ones. 8327 grant = GRANT_INSTALL; 8328 } break; 8329 8330 case PermissionInfo.PROTECTION_DANGEROUS: { 8331 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 8332 // For legacy apps dangerous permissions are install time ones. 8333 grant = GRANT_INSTALL_LEGACY; 8334 } else if (origPermissions.hasInstallPermission(bp.name)) { 8335 // For legacy apps that became modern, install becomes runtime. 8336 grant = GRANT_UPGRADE; 8337 } else { 8338 // For modern apps keep runtime permissions unchanged. 8339 grant = GRANT_RUNTIME; 8340 } 8341 } break; 8342 8343 case PermissionInfo.PROTECTION_SIGNATURE: { 8344 // For all apps signature permissions are install time ones. 8345 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 8346 if (allowedSig) { 8347 grant = GRANT_INSTALL; 8348 } 8349 } break; 8350 } 8351 8352 if (DEBUG_INSTALL) { 8353 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 8354 } 8355 8356 if (grant != GRANT_DENIED) { 8357 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 8358 // If this is an existing, non-system package, then 8359 // we can't add any new permissions to it. 8360 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 8361 // Except... if this is a permission that was added 8362 // to the platform (note: need to only do this when 8363 // updating the platform). 8364 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 8365 grant = GRANT_DENIED; 8366 } 8367 } 8368 } 8369 8370 switch (grant) { 8371 case GRANT_INSTALL: { 8372 // Revoke this as runtime permission to handle the case of 8373 // a runtime permission being downgraded to an install one. 8374 for (int userId : UserManagerService.getInstance().getUserIds()) { 8375 if (origPermissions.getRuntimePermissionState( 8376 bp.name, userId) != null) { 8377 // Revoke the runtime permission and clear the flags. 8378 origPermissions.revokeRuntimePermission(bp, userId); 8379 origPermissions.updatePermissionFlags(bp, userId, 8380 PackageManager.MASK_PERMISSION_FLAGS, 0); 8381 // If we revoked a permission permission, we have to write. 8382 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8383 changedRuntimePermissionUserIds, userId); 8384 } 8385 } 8386 // Grant an install permission. 8387 if (permissionsState.grantInstallPermission(bp) != 8388 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8389 changedInstallPermission = true; 8390 } 8391 } break; 8392 8393 case GRANT_INSTALL_LEGACY: { 8394 // Grant an install permission. 8395 if (permissionsState.grantInstallPermission(bp) != 8396 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8397 changedInstallPermission = true; 8398 } 8399 } break; 8400 8401 case GRANT_RUNTIME: { 8402 // Grant previously granted runtime permissions. 8403 for (int userId : UserManagerService.getInstance().getUserIds()) { 8404 PermissionState permissionState = origPermissions 8405 .getRuntimePermissionState(bp.name, userId); 8406 final int flags = permissionState != null 8407 ? permissionState.getFlags() : 0; 8408 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8409 if (permissionsState.grantRuntimePermission(bp, userId) == 8410 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8411 // If we cannot put the permission as it was, we have to write. 8412 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8413 changedRuntimePermissionUserIds, userId); 8414 } 8415 } 8416 // Propagate the permission flags. 8417 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 8418 } 8419 } break; 8420 8421 case GRANT_UPGRADE: { 8422 // Grant runtime permissions for a previously held install permission. 8423 PermissionState permissionState = origPermissions 8424 .getInstallPermissionState(bp.name); 8425 final int flags = permissionState != null ? permissionState.getFlags() : 0; 8426 8427 if (origPermissions.revokeInstallPermission(bp) 8428 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 8429 // We will be transferring the permission flags, so clear them. 8430 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 8431 PackageManager.MASK_PERMISSION_FLAGS, 0); 8432 changedInstallPermission = true; 8433 } 8434 8435 // If the permission is not to be promoted to runtime we ignore it and 8436 // also its other flags as they are not applicable to install permissions. 8437 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 8438 for (int userId : currentUserIds) { 8439 if (permissionsState.grantRuntimePermission(bp, userId) != 8440 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8441 // Transfer the permission flags. 8442 permissionsState.updatePermissionFlags(bp, userId, 8443 flags, flags); 8444 // If we granted the permission, we have to write. 8445 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8446 changedRuntimePermissionUserIds, userId); 8447 } 8448 } 8449 } 8450 } break; 8451 8452 default: { 8453 if (packageOfInterest == null 8454 || packageOfInterest.equals(pkg.packageName)) { 8455 Slog.w(TAG, "Not granting permission " + perm 8456 + " to package " + pkg.packageName 8457 + " because it was previously installed without"); 8458 } 8459 } break; 8460 } 8461 } else { 8462 if (permissionsState.revokeInstallPermission(bp) != 8463 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8464 // Also drop the permission flags. 8465 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 8466 PackageManager.MASK_PERMISSION_FLAGS, 0); 8467 changedInstallPermission = true; 8468 Slog.i(TAG, "Un-granting permission " + perm 8469 + " from package " + pkg.packageName 8470 + " (protectionLevel=" + bp.protectionLevel 8471 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8472 + ")"); 8473 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 8474 // Don't print warning for app op permissions, since it is fine for them 8475 // not to be granted, there is a UI for the user to decide. 8476 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8477 Slog.w(TAG, "Not granting permission " + perm 8478 + " to package " + pkg.packageName 8479 + " (protectionLevel=" + bp.protectionLevel 8480 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8481 + ")"); 8482 } 8483 } 8484 } 8485 } 8486 8487 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 8488 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 8489 // This is the first that we have heard about this package, so the 8490 // permissions we have now selected are fixed until explicitly 8491 // changed. 8492 ps.installPermissionsFixed = true; 8493 } 8494 8495 // Persist the runtime permissions state for users with changes. 8496 for (int userId : changedRuntimePermissionUserIds) { 8497 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 8498 } 8499 } 8500 8501 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8502 boolean allowed = false; 8503 final int NP = PackageParser.NEW_PERMISSIONS.length; 8504 for (int ip=0; ip<NP; ip++) { 8505 final PackageParser.NewPermissionInfo npi 8506 = PackageParser.NEW_PERMISSIONS[ip]; 8507 if (npi.name.equals(perm) 8508 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8509 allowed = true; 8510 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8511 + pkg.packageName); 8512 break; 8513 } 8514 } 8515 return allowed; 8516 } 8517 8518 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 8519 BasePermission bp, PermissionsState origPermissions) { 8520 boolean allowed; 8521 allowed = (compareSignatures( 8522 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 8523 == PackageManager.SIGNATURE_MATCH) 8524 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 8525 == PackageManager.SIGNATURE_MATCH); 8526 if (!allowed && (bp.protectionLevel 8527 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 8528 if (isSystemApp(pkg)) { 8529 // For updated system applications, a system permission 8530 // is granted only if it had been defined by the original application. 8531 if (pkg.isUpdatedSystemApp()) { 8532 final PackageSetting sysPs = mSettings 8533 .getDisabledSystemPkgLPr(pkg.packageName); 8534 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 8535 // If the original was granted this permission, we take 8536 // that grant decision as read and propagate it to the 8537 // update. 8538 if (sysPs.isPrivileged()) { 8539 allowed = true; 8540 } 8541 } else { 8542 // The system apk may have been updated with an older 8543 // version of the one on the data partition, but which 8544 // granted a new system permission that it didn't have 8545 // before. In this case we do want to allow the app to 8546 // now get the new permission if the ancestral apk is 8547 // privileged to get it. 8548 if (sysPs.pkg != null && sysPs.isPrivileged()) { 8549 for (int j=0; 8550 j<sysPs.pkg.requestedPermissions.size(); j++) { 8551 if (perm.equals( 8552 sysPs.pkg.requestedPermissions.get(j))) { 8553 allowed = true; 8554 break; 8555 } 8556 } 8557 } 8558 } 8559 } else { 8560 allowed = isPrivilegedApp(pkg); 8561 } 8562 } 8563 } 8564 if (!allowed) { 8565 if (!allowed && (bp.protectionLevel 8566 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 8567 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.MNC) { 8568 // If this was a previously normal/dangerous permission that got moved 8569 // to a system permission as part of the runtime permission redesign, then 8570 // we still want to blindly grant it to old apps. 8571 allowed = true; 8572 } 8573 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 8574 && pkg.packageName.equals(mRequiredInstallerPackage)) { 8575 // If this permission is to be granted to the system installer and 8576 // this app is an installer, then it gets the permission. 8577 allowed = true; 8578 } 8579 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 8580 && pkg.packageName.equals(mRequiredVerifierPackage)) { 8581 // If this permission is to be granted to the system verifier and 8582 // this app is a verifier, then it gets the permission. 8583 allowed = true; 8584 } 8585 if (!allowed && (bp.protectionLevel 8586 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 8587 && isSystemApp(pkg)) { 8588 // Any pre-installed system app is allowed to get this permission. 8589 allowed = true; 8590 } 8591 if (!allowed && (bp.protectionLevel 8592 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 8593 // For development permissions, a development permission 8594 // is granted only if it was already granted. 8595 allowed = origPermissions.hasInstallPermission(perm); 8596 } 8597 } 8598 return allowed; 8599 } 8600 8601 final class ActivityIntentResolver 8602 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 8603 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8604 boolean defaultOnly, int userId) { 8605 if (!sUserManager.exists(userId)) return null; 8606 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8607 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8608 } 8609 8610 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8611 int userId) { 8612 if (!sUserManager.exists(userId)) return null; 8613 mFlags = flags; 8614 return super.queryIntent(intent, resolvedType, 8615 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8616 } 8617 8618 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8619 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 8620 if (!sUserManager.exists(userId)) return null; 8621 if (packageActivities == null) { 8622 return null; 8623 } 8624 mFlags = flags; 8625 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8626 final int N = packageActivities.size(); 8627 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 8628 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 8629 8630 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 8631 for (int i = 0; i < N; ++i) { 8632 intentFilters = packageActivities.get(i).intents; 8633 if (intentFilters != null && intentFilters.size() > 0) { 8634 PackageParser.ActivityIntentInfo[] array = 8635 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 8636 intentFilters.toArray(array); 8637 listCut.add(array); 8638 } 8639 } 8640 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8641 } 8642 8643 public final void addActivity(PackageParser.Activity a, String type) { 8644 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 8645 mActivities.put(a.getComponentName(), a); 8646 if (DEBUG_SHOW_INFO) 8647 Log.v( 8648 TAG, " " + type + " " + 8649 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 8650 if (DEBUG_SHOW_INFO) 8651 Log.v(TAG, " Class=" + a.info.name); 8652 final int NI = a.intents.size(); 8653 for (int j=0; j<NI; j++) { 8654 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8655 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 8656 intent.setPriority(0); 8657 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 8658 + a.className + " with priority > 0, forcing to 0"); 8659 } 8660 if (DEBUG_SHOW_INFO) { 8661 Log.v(TAG, " IntentFilter:"); 8662 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8663 } 8664 if (!intent.debugCheck()) { 8665 Log.w(TAG, "==> For Activity " + a.info.name); 8666 } 8667 addFilter(intent); 8668 } 8669 } 8670 8671 public final void removeActivity(PackageParser.Activity a, String type) { 8672 mActivities.remove(a.getComponentName()); 8673 if (DEBUG_SHOW_INFO) { 8674 Log.v(TAG, " " + type + " " 8675 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 8676 : a.info.name) + ":"); 8677 Log.v(TAG, " Class=" + a.info.name); 8678 } 8679 final int NI = a.intents.size(); 8680 for (int j=0; j<NI; j++) { 8681 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8682 if (DEBUG_SHOW_INFO) { 8683 Log.v(TAG, " IntentFilter:"); 8684 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8685 } 8686 removeFilter(intent); 8687 } 8688 } 8689 8690 @Override 8691 protected boolean allowFilterResult( 8692 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 8693 ActivityInfo filterAi = filter.activity.info; 8694 for (int i=dest.size()-1; i>=0; i--) { 8695 ActivityInfo destAi = dest.get(i).activityInfo; 8696 if (destAi.name == filterAi.name 8697 && destAi.packageName == filterAi.packageName) { 8698 return false; 8699 } 8700 } 8701 return true; 8702 } 8703 8704 @Override 8705 protected ActivityIntentInfo[] newArray(int size) { 8706 return new ActivityIntentInfo[size]; 8707 } 8708 8709 @Override 8710 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 8711 if (!sUserManager.exists(userId)) return true; 8712 PackageParser.Package p = filter.activity.owner; 8713 if (p != null) { 8714 PackageSetting ps = (PackageSetting)p.mExtras; 8715 if (ps != null) { 8716 // System apps are never considered stopped for purposes of 8717 // filtering, because there may be no way for the user to 8718 // actually re-launch them. 8719 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 8720 && ps.getStopped(userId); 8721 } 8722 } 8723 return false; 8724 } 8725 8726 @Override 8727 protected boolean isPackageForFilter(String packageName, 8728 PackageParser.ActivityIntentInfo info) { 8729 return packageName.equals(info.activity.owner.packageName); 8730 } 8731 8732 @Override 8733 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 8734 int match, int userId) { 8735 if (!sUserManager.exists(userId)) return null; 8736 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 8737 return null; 8738 } 8739 final PackageParser.Activity activity = info.activity; 8740 if (mSafeMode && (activity.info.applicationInfo.flags 8741 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8742 return null; 8743 } 8744 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 8745 if (ps == null) { 8746 return null; 8747 } 8748 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 8749 ps.readUserState(userId), userId); 8750 if (ai == null) { 8751 return null; 8752 } 8753 final ResolveInfo res = new ResolveInfo(); 8754 res.activityInfo = ai; 8755 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8756 res.filter = info; 8757 } 8758 if (info != null) { 8759 res.handleAllWebDataURI = info.handleAllWebDataURI(); 8760 } 8761 res.priority = info.getPriority(); 8762 res.preferredOrder = activity.owner.mPreferredOrder; 8763 //System.out.println("Result: " + res.activityInfo.className + 8764 // " = " + res.priority); 8765 res.match = match; 8766 res.isDefault = info.hasDefault; 8767 res.labelRes = info.labelRes; 8768 res.nonLocalizedLabel = info.nonLocalizedLabel; 8769 if (userNeedsBadging(userId)) { 8770 res.noResourceId = true; 8771 } else { 8772 res.icon = info.icon; 8773 } 8774 res.iconResourceId = info.icon; 8775 res.system = res.activityInfo.applicationInfo.isSystemApp(); 8776 return res; 8777 } 8778 8779 @Override 8780 protected void sortResults(List<ResolveInfo> results) { 8781 Collections.sort(results, mResolvePrioritySorter); 8782 } 8783 8784 @Override 8785 protected void dumpFilter(PrintWriter out, String prefix, 8786 PackageParser.ActivityIntentInfo filter) { 8787 out.print(prefix); out.print( 8788 Integer.toHexString(System.identityHashCode(filter.activity))); 8789 out.print(' '); 8790 filter.activity.printComponentShortName(out); 8791 out.print(" filter "); 8792 out.println(Integer.toHexString(System.identityHashCode(filter))); 8793 } 8794 8795 @Override 8796 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 8797 return filter.activity; 8798 } 8799 8800 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8801 PackageParser.Activity activity = (PackageParser.Activity)label; 8802 out.print(prefix); out.print( 8803 Integer.toHexString(System.identityHashCode(activity))); 8804 out.print(' '); 8805 activity.printComponentShortName(out); 8806 if (count > 1) { 8807 out.print(" ("); out.print(count); out.print(" filters)"); 8808 } 8809 out.println(); 8810 } 8811 8812// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8813// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8814// final List<ResolveInfo> retList = Lists.newArrayList(); 8815// while (i.hasNext()) { 8816// final ResolveInfo resolveInfo = i.next(); 8817// if (isEnabledLP(resolveInfo.activityInfo)) { 8818// retList.add(resolveInfo); 8819// } 8820// } 8821// return retList; 8822// } 8823 8824 // Keys are String (activity class name), values are Activity. 8825 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 8826 = new ArrayMap<ComponentName, PackageParser.Activity>(); 8827 private int mFlags; 8828 } 8829 8830 private final class ServiceIntentResolver 8831 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 8832 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8833 boolean defaultOnly, int userId) { 8834 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8835 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8836 } 8837 8838 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8839 int userId) { 8840 if (!sUserManager.exists(userId)) return null; 8841 mFlags = flags; 8842 return super.queryIntent(intent, resolvedType, 8843 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8844 } 8845 8846 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8847 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 8848 if (!sUserManager.exists(userId)) return null; 8849 if (packageServices == null) { 8850 return null; 8851 } 8852 mFlags = flags; 8853 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8854 final int N = packageServices.size(); 8855 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 8856 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 8857 8858 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 8859 for (int i = 0; i < N; ++i) { 8860 intentFilters = packageServices.get(i).intents; 8861 if (intentFilters != null && intentFilters.size() > 0) { 8862 PackageParser.ServiceIntentInfo[] array = 8863 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 8864 intentFilters.toArray(array); 8865 listCut.add(array); 8866 } 8867 } 8868 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8869 } 8870 8871 public final void addService(PackageParser.Service s) { 8872 mServices.put(s.getComponentName(), s); 8873 if (DEBUG_SHOW_INFO) { 8874 Log.v(TAG, " " 8875 + (s.info.nonLocalizedLabel != null 8876 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8877 Log.v(TAG, " Class=" + s.info.name); 8878 } 8879 final int NI = s.intents.size(); 8880 int j; 8881 for (j=0; j<NI; j++) { 8882 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8883 if (DEBUG_SHOW_INFO) { 8884 Log.v(TAG, " IntentFilter:"); 8885 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8886 } 8887 if (!intent.debugCheck()) { 8888 Log.w(TAG, "==> For Service " + s.info.name); 8889 } 8890 addFilter(intent); 8891 } 8892 } 8893 8894 public final void removeService(PackageParser.Service s) { 8895 mServices.remove(s.getComponentName()); 8896 if (DEBUG_SHOW_INFO) { 8897 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 8898 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8899 Log.v(TAG, " Class=" + s.info.name); 8900 } 8901 final int NI = s.intents.size(); 8902 int j; 8903 for (j=0; j<NI; j++) { 8904 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8905 if (DEBUG_SHOW_INFO) { 8906 Log.v(TAG, " IntentFilter:"); 8907 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8908 } 8909 removeFilter(intent); 8910 } 8911 } 8912 8913 @Override 8914 protected boolean allowFilterResult( 8915 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 8916 ServiceInfo filterSi = filter.service.info; 8917 for (int i=dest.size()-1; i>=0; i--) { 8918 ServiceInfo destAi = dest.get(i).serviceInfo; 8919 if (destAi.name == filterSi.name 8920 && destAi.packageName == filterSi.packageName) { 8921 return false; 8922 } 8923 } 8924 return true; 8925 } 8926 8927 @Override 8928 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 8929 return new PackageParser.ServiceIntentInfo[size]; 8930 } 8931 8932 @Override 8933 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 8934 if (!sUserManager.exists(userId)) return true; 8935 PackageParser.Package p = filter.service.owner; 8936 if (p != null) { 8937 PackageSetting ps = (PackageSetting)p.mExtras; 8938 if (ps != null) { 8939 // System apps are never considered stopped for purposes of 8940 // filtering, because there may be no way for the user to 8941 // actually re-launch them. 8942 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8943 && ps.getStopped(userId); 8944 } 8945 } 8946 return false; 8947 } 8948 8949 @Override 8950 protected boolean isPackageForFilter(String packageName, 8951 PackageParser.ServiceIntentInfo info) { 8952 return packageName.equals(info.service.owner.packageName); 8953 } 8954 8955 @Override 8956 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 8957 int match, int userId) { 8958 if (!sUserManager.exists(userId)) return null; 8959 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 8960 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 8961 return null; 8962 } 8963 final PackageParser.Service service = info.service; 8964 if (mSafeMode && (service.info.applicationInfo.flags 8965 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8966 return null; 8967 } 8968 PackageSetting ps = (PackageSetting) service.owner.mExtras; 8969 if (ps == null) { 8970 return null; 8971 } 8972 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 8973 ps.readUserState(userId), userId); 8974 if (si == null) { 8975 return null; 8976 } 8977 final ResolveInfo res = new ResolveInfo(); 8978 res.serviceInfo = si; 8979 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8980 res.filter = filter; 8981 } 8982 res.priority = info.getPriority(); 8983 res.preferredOrder = service.owner.mPreferredOrder; 8984 res.match = match; 8985 res.isDefault = info.hasDefault; 8986 res.labelRes = info.labelRes; 8987 res.nonLocalizedLabel = info.nonLocalizedLabel; 8988 res.icon = info.icon; 8989 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 8990 return res; 8991 } 8992 8993 @Override 8994 protected void sortResults(List<ResolveInfo> results) { 8995 Collections.sort(results, mResolvePrioritySorter); 8996 } 8997 8998 @Override 8999 protected void dumpFilter(PrintWriter out, String prefix, 9000 PackageParser.ServiceIntentInfo filter) { 9001 out.print(prefix); out.print( 9002 Integer.toHexString(System.identityHashCode(filter.service))); 9003 out.print(' '); 9004 filter.service.printComponentShortName(out); 9005 out.print(" filter "); 9006 out.println(Integer.toHexString(System.identityHashCode(filter))); 9007 } 9008 9009 @Override 9010 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 9011 return filter.service; 9012 } 9013 9014 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9015 PackageParser.Service service = (PackageParser.Service)label; 9016 out.print(prefix); out.print( 9017 Integer.toHexString(System.identityHashCode(service))); 9018 out.print(' '); 9019 service.printComponentShortName(out); 9020 if (count > 1) { 9021 out.print(" ("); out.print(count); out.print(" filters)"); 9022 } 9023 out.println(); 9024 } 9025 9026// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9027// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9028// final List<ResolveInfo> retList = Lists.newArrayList(); 9029// while (i.hasNext()) { 9030// final ResolveInfo resolveInfo = (ResolveInfo) i; 9031// if (isEnabledLP(resolveInfo.serviceInfo)) { 9032// retList.add(resolveInfo); 9033// } 9034// } 9035// return retList; 9036// } 9037 9038 // Keys are String (activity class name), values are Activity. 9039 private final ArrayMap<ComponentName, PackageParser.Service> mServices 9040 = new ArrayMap<ComponentName, PackageParser.Service>(); 9041 private int mFlags; 9042 }; 9043 9044 private final class ProviderIntentResolver 9045 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 9046 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9047 boolean defaultOnly, int userId) { 9048 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9049 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9050 } 9051 9052 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9053 int userId) { 9054 if (!sUserManager.exists(userId)) 9055 return null; 9056 mFlags = flags; 9057 return super.queryIntent(intent, resolvedType, 9058 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9059 } 9060 9061 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9062 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 9063 if (!sUserManager.exists(userId)) 9064 return null; 9065 if (packageProviders == null) { 9066 return null; 9067 } 9068 mFlags = flags; 9069 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 9070 final int N = packageProviders.size(); 9071 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 9072 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 9073 9074 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 9075 for (int i = 0; i < N; ++i) { 9076 intentFilters = packageProviders.get(i).intents; 9077 if (intentFilters != null && intentFilters.size() > 0) { 9078 PackageParser.ProviderIntentInfo[] array = 9079 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 9080 intentFilters.toArray(array); 9081 listCut.add(array); 9082 } 9083 } 9084 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9085 } 9086 9087 public final void addProvider(PackageParser.Provider p) { 9088 if (mProviders.containsKey(p.getComponentName())) { 9089 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 9090 return; 9091 } 9092 9093 mProviders.put(p.getComponentName(), p); 9094 if (DEBUG_SHOW_INFO) { 9095 Log.v(TAG, " " 9096 + (p.info.nonLocalizedLabel != null 9097 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9098 Log.v(TAG, " Class=" + p.info.name); 9099 } 9100 final int NI = p.intents.size(); 9101 int j; 9102 for (j = 0; j < NI; j++) { 9103 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9104 if (DEBUG_SHOW_INFO) { 9105 Log.v(TAG, " IntentFilter:"); 9106 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9107 } 9108 if (!intent.debugCheck()) { 9109 Log.w(TAG, "==> For Provider " + p.info.name); 9110 } 9111 addFilter(intent); 9112 } 9113 } 9114 9115 public final void removeProvider(PackageParser.Provider p) { 9116 mProviders.remove(p.getComponentName()); 9117 if (DEBUG_SHOW_INFO) { 9118 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 9119 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9120 Log.v(TAG, " Class=" + p.info.name); 9121 } 9122 final int NI = p.intents.size(); 9123 int j; 9124 for (j = 0; j < NI; j++) { 9125 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9126 if (DEBUG_SHOW_INFO) { 9127 Log.v(TAG, " IntentFilter:"); 9128 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9129 } 9130 removeFilter(intent); 9131 } 9132 } 9133 9134 @Override 9135 protected boolean allowFilterResult( 9136 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 9137 ProviderInfo filterPi = filter.provider.info; 9138 for (int i = dest.size() - 1; i >= 0; i--) { 9139 ProviderInfo destPi = dest.get(i).providerInfo; 9140 if (destPi.name == filterPi.name 9141 && destPi.packageName == filterPi.packageName) { 9142 return false; 9143 } 9144 } 9145 return true; 9146 } 9147 9148 @Override 9149 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 9150 return new PackageParser.ProviderIntentInfo[size]; 9151 } 9152 9153 @Override 9154 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 9155 if (!sUserManager.exists(userId)) 9156 return true; 9157 PackageParser.Package p = filter.provider.owner; 9158 if (p != null) { 9159 PackageSetting ps = (PackageSetting) p.mExtras; 9160 if (ps != null) { 9161 // System apps are never considered stopped for purposes of 9162 // filtering, because there may be no way for the user to 9163 // actually re-launch them. 9164 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9165 && ps.getStopped(userId); 9166 } 9167 } 9168 return false; 9169 } 9170 9171 @Override 9172 protected boolean isPackageForFilter(String packageName, 9173 PackageParser.ProviderIntentInfo info) { 9174 return packageName.equals(info.provider.owner.packageName); 9175 } 9176 9177 @Override 9178 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 9179 int match, int userId) { 9180 if (!sUserManager.exists(userId)) 9181 return null; 9182 final PackageParser.ProviderIntentInfo info = filter; 9183 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 9184 return null; 9185 } 9186 final PackageParser.Provider provider = info.provider; 9187 if (mSafeMode && (provider.info.applicationInfo.flags 9188 & ApplicationInfo.FLAG_SYSTEM) == 0) { 9189 return null; 9190 } 9191 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 9192 if (ps == null) { 9193 return null; 9194 } 9195 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 9196 ps.readUserState(userId), userId); 9197 if (pi == null) { 9198 return null; 9199 } 9200 final ResolveInfo res = new ResolveInfo(); 9201 res.providerInfo = pi; 9202 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 9203 res.filter = filter; 9204 } 9205 res.priority = info.getPriority(); 9206 res.preferredOrder = provider.owner.mPreferredOrder; 9207 res.match = match; 9208 res.isDefault = info.hasDefault; 9209 res.labelRes = info.labelRes; 9210 res.nonLocalizedLabel = info.nonLocalizedLabel; 9211 res.icon = info.icon; 9212 res.system = res.providerInfo.applicationInfo.isSystemApp(); 9213 return res; 9214 } 9215 9216 @Override 9217 protected void sortResults(List<ResolveInfo> results) { 9218 Collections.sort(results, mResolvePrioritySorter); 9219 } 9220 9221 @Override 9222 protected void dumpFilter(PrintWriter out, String prefix, 9223 PackageParser.ProviderIntentInfo filter) { 9224 out.print(prefix); 9225 out.print( 9226 Integer.toHexString(System.identityHashCode(filter.provider))); 9227 out.print(' '); 9228 filter.provider.printComponentShortName(out); 9229 out.print(" filter "); 9230 out.println(Integer.toHexString(System.identityHashCode(filter))); 9231 } 9232 9233 @Override 9234 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 9235 return filter.provider; 9236 } 9237 9238 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9239 PackageParser.Provider provider = (PackageParser.Provider)label; 9240 out.print(prefix); out.print( 9241 Integer.toHexString(System.identityHashCode(provider))); 9242 out.print(' '); 9243 provider.printComponentShortName(out); 9244 if (count > 1) { 9245 out.print(" ("); out.print(count); out.print(" filters)"); 9246 } 9247 out.println(); 9248 } 9249 9250 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 9251 = new ArrayMap<ComponentName, PackageParser.Provider>(); 9252 private int mFlags; 9253 }; 9254 9255 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 9256 new Comparator<ResolveInfo>() { 9257 public int compare(ResolveInfo r1, ResolveInfo r2) { 9258 int v1 = r1.priority; 9259 int v2 = r2.priority; 9260 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 9261 if (v1 != v2) { 9262 return (v1 > v2) ? -1 : 1; 9263 } 9264 v1 = r1.preferredOrder; 9265 v2 = r2.preferredOrder; 9266 if (v1 != v2) { 9267 return (v1 > v2) ? -1 : 1; 9268 } 9269 if (r1.isDefault != r2.isDefault) { 9270 return r1.isDefault ? -1 : 1; 9271 } 9272 v1 = r1.match; 9273 v2 = r2.match; 9274 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 9275 if (v1 != v2) { 9276 return (v1 > v2) ? -1 : 1; 9277 } 9278 if (r1.system != r2.system) { 9279 return r1.system ? -1 : 1; 9280 } 9281 return 0; 9282 } 9283 }; 9284 9285 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 9286 new Comparator<ProviderInfo>() { 9287 public int compare(ProviderInfo p1, ProviderInfo p2) { 9288 final int v1 = p1.initOrder; 9289 final int v2 = p2.initOrder; 9290 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 9291 } 9292 }; 9293 9294 final void sendPackageBroadcast(final String action, final String pkg, 9295 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 9296 final int[] userIds) { 9297 mHandler.post(new Runnable() { 9298 @Override 9299 public void run() { 9300 try { 9301 final IActivityManager am = ActivityManagerNative.getDefault(); 9302 if (am == null) return; 9303 final int[] resolvedUserIds; 9304 if (userIds == null) { 9305 resolvedUserIds = am.getRunningUserIds(); 9306 } else { 9307 resolvedUserIds = userIds; 9308 } 9309 for (int id : resolvedUserIds) { 9310 final Intent intent = new Intent(action, 9311 pkg != null ? Uri.fromParts("package", pkg, null) : null); 9312 if (extras != null) { 9313 intent.putExtras(extras); 9314 } 9315 if (targetPkg != null) { 9316 intent.setPackage(targetPkg); 9317 } 9318 // Modify the UID when posting to other users 9319 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 9320 if (uid > 0 && UserHandle.getUserId(uid) != id) { 9321 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 9322 intent.putExtra(Intent.EXTRA_UID, uid); 9323 } 9324 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 9325 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 9326 if (DEBUG_BROADCASTS) { 9327 RuntimeException here = new RuntimeException("here"); 9328 here.fillInStackTrace(); 9329 Slog.d(TAG, "Sending to user " + id + ": " 9330 + intent.toShortString(false, true, false, false) 9331 + " " + intent.getExtras(), here); 9332 } 9333 am.broadcastIntent(null, intent, null, finishedReceiver, 9334 0, null, null, null, android.app.AppOpsManager.OP_NONE, 9335 null, finishedReceiver != null, false, id); 9336 } 9337 } catch (RemoteException ex) { 9338 } 9339 } 9340 }); 9341 } 9342 9343 /** 9344 * Check if the external storage media is available. This is true if there 9345 * is a mounted external storage medium or if the external storage is 9346 * emulated. 9347 */ 9348 private boolean isExternalMediaAvailable() { 9349 return mMediaMounted || Environment.isExternalStorageEmulated(); 9350 } 9351 9352 @Override 9353 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 9354 // writer 9355 synchronized (mPackages) { 9356 if (!isExternalMediaAvailable()) { 9357 // If the external storage is no longer mounted at this point, 9358 // the caller may not have been able to delete all of this 9359 // packages files and can not delete any more. Bail. 9360 return null; 9361 } 9362 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 9363 if (lastPackage != null) { 9364 pkgs.remove(lastPackage); 9365 } 9366 if (pkgs.size() > 0) { 9367 return pkgs.get(0); 9368 } 9369 } 9370 return null; 9371 } 9372 9373 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 9374 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 9375 userId, andCode ? 1 : 0, packageName); 9376 if (mSystemReady) { 9377 msg.sendToTarget(); 9378 } else { 9379 if (mPostSystemReadyMessages == null) { 9380 mPostSystemReadyMessages = new ArrayList<>(); 9381 } 9382 mPostSystemReadyMessages.add(msg); 9383 } 9384 } 9385 9386 void startCleaningPackages() { 9387 // reader 9388 synchronized (mPackages) { 9389 if (!isExternalMediaAvailable()) { 9390 return; 9391 } 9392 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 9393 return; 9394 } 9395 } 9396 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 9397 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 9398 IActivityManager am = ActivityManagerNative.getDefault(); 9399 if (am != null) { 9400 try { 9401 am.startService(null, intent, null, mContext.getOpPackageName(), 9402 UserHandle.USER_OWNER); 9403 } catch (RemoteException e) { 9404 } 9405 } 9406 } 9407 9408 @Override 9409 public void installPackage(String originPath, IPackageInstallObserver2 observer, 9410 int installFlags, String installerPackageName, VerificationParams verificationParams, 9411 String packageAbiOverride) { 9412 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 9413 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 9414 } 9415 9416 @Override 9417 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 9418 int installFlags, String installerPackageName, VerificationParams verificationParams, 9419 String packageAbiOverride, int userId) { 9420 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 9421 9422 final int callingUid = Binder.getCallingUid(); 9423 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 9424 9425 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9426 try { 9427 if (observer != null) { 9428 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 9429 } 9430 } catch (RemoteException re) { 9431 } 9432 return; 9433 } 9434 9435 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 9436 installFlags |= PackageManager.INSTALL_FROM_ADB; 9437 9438 } else { 9439 // Caller holds INSTALL_PACKAGES permission, so we're less strict 9440 // about installerPackageName. 9441 9442 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 9443 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 9444 } 9445 9446 UserHandle user; 9447 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 9448 user = UserHandle.ALL; 9449 } else { 9450 user = new UserHandle(userId); 9451 } 9452 9453 // Only system components can circumvent runtime permissions when installing. 9454 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 9455 && mContext.checkCallingOrSelfPermission(Manifest.permission 9456 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 9457 throw new SecurityException("You need the " 9458 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 9459 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 9460 } 9461 9462 verificationParams.setInstallerUid(callingUid); 9463 9464 final File originFile = new File(originPath); 9465 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 9466 9467 final Message msg = mHandler.obtainMessage(INIT_COPY); 9468 msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName, 9469 null, verificationParams, user, packageAbiOverride, null); 9470 mHandler.sendMessage(msg); 9471 } 9472 9473 void installStage(String packageName, File stagedDir, String stagedCid, 9474 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 9475 String installerPackageName, int installerUid, UserHandle user) { 9476 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 9477 params.referrerUri, installerUid, null); 9478 verifParams.setInstallerUid(installerUid); 9479 9480 final OriginInfo origin; 9481 if (stagedDir != null) { 9482 origin = OriginInfo.fromStagedFile(stagedDir); 9483 } else { 9484 origin = OriginInfo.fromStagedContainer(stagedCid); 9485 } 9486 9487 final Message msg = mHandler.obtainMessage(INIT_COPY); 9488 msg.obj = new InstallParams(origin, null, observer, params.installFlags, 9489 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride, 9490 params.grantedRuntimePermissions); 9491 mHandler.sendMessage(msg); 9492 } 9493 9494 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 9495 Bundle extras = new Bundle(1); 9496 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 9497 9498 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 9499 packageName, extras, null, null, new int[] {userId}); 9500 try { 9501 IActivityManager am = ActivityManagerNative.getDefault(); 9502 final boolean isSystem = 9503 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 9504 if (isSystem && am.isUserRunning(userId, false)) { 9505 // The just-installed/enabled app is bundled on the system, so presumed 9506 // to be able to run automatically without needing an explicit launch. 9507 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 9508 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 9509 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 9510 .setPackage(packageName); 9511 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 9512 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 9513 } 9514 } catch (RemoteException e) { 9515 // shouldn't happen 9516 Slog.w(TAG, "Unable to bootstrap installed package", e); 9517 } 9518 } 9519 9520 @Override 9521 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 9522 int userId) { 9523 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9524 PackageSetting pkgSetting; 9525 final int uid = Binder.getCallingUid(); 9526 enforceCrossUserPermission(uid, userId, true, true, 9527 "setApplicationHiddenSetting for user " + userId); 9528 9529 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 9530 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 9531 return false; 9532 } 9533 9534 long callingId = Binder.clearCallingIdentity(); 9535 try { 9536 boolean sendAdded = false; 9537 boolean sendRemoved = false; 9538 // writer 9539 synchronized (mPackages) { 9540 pkgSetting = mSettings.mPackages.get(packageName); 9541 if (pkgSetting == null) { 9542 return false; 9543 } 9544 if (pkgSetting.getHidden(userId) != hidden) { 9545 pkgSetting.setHidden(hidden, userId); 9546 mSettings.writePackageRestrictionsLPr(userId); 9547 if (hidden) { 9548 sendRemoved = true; 9549 } else { 9550 sendAdded = true; 9551 } 9552 } 9553 } 9554 if (sendAdded) { 9555 sendPackageAddedForUser(packageName, pkgSetting, userId); 9556 return true; 9557 } 9558 if (sendRemoved) { 9559 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 9560 "hiding pkg"); 9561 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 9562 } 9563 } finally { 9564 Binder.restoreCallingIdentity(callingId); 9565 } 9566 return false; 9567 } 9568 9569 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 9570 int userId) { 9571 final PackageRemovedInfo info = new PackageRemovedInfo(); 9572 info.removedPackage = packageName; 9573 info.removedUsers = new int[] {userId}; 9574 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 9575 info.sendBroadcast(false, false, false); 9576 } 9577 9578 /** 9579 * Returns true if application is not found or there was an error. Otherwise it returns 9580 * the hidden state of the package for the given user. 9581 */ 9582 @Override 9583 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 9584 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9585 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 9586 false, "getApplicationHidden for user " + userId); 9587 PackageSetting pkgSetting; 9588 long callingId = Binder.clearCallingIdentity(); 9589 try { 9590 // writer 9591 synchronized (mPackages) { 9592 pkgSetting = mSettings.mPackages.get(packageName); 9593 if (pkgSetting == null) { 9594 return true; 9595 } 9596 return pkgSetting.getHidden(userId); 9597 } 9598 } finally { 9599 Binder.restoreCallingIdentity(callingId); 9600 } 9601 } 9602 9603 /** 9604 * @hide 9605 */ 9606 @Override 9607 public int installExistingPackageAsUser(String packageName, int userId) { 9608 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 9609 null); 9610 PackageSetting pkgSetting; 9611 final int uid = Binder.getCallingUid(); 9612 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 9613 + userId); 9614 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9615 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 9616 } 9617 9618 long callingId = Binder.clearCallingIdentity(); 9619 try { 9620 boolean sendAdded = false; 9621 9622 // writer 9623 synchronized (mPackages) { 9624 pkgSetting = mSettings.mPackages.get(packageName); 9625 if (pkgSetting == null) { 9626 return PackageManager.INSTALL_FAILED_INVALID_URI; 9627 } 9628 if (!pkgSetting.getInstalled(userId)) { 9629 pkgSetting.setInstalled(true, userId); 9630 pkgSetting.setHidden(false, userId); 9631 mSettings.writePackageRestrictionsLPr(userId); 9632 sendAdded = true; 9633 } 9634 } 9635 9636 if (sendAdded) { 9637 sendPackageAddedForUser(packageName, pkgSetting, userId); 9638 } 9639 } finally { 9640 Binder.restoreCallingIdentity(callingId); 9641 } 9642 9643 return PackageManager.INSTALL_SUCCEEDED; 9644 } 9645 9646 boolean isUserRestricted(int userId, String restrictionKey) { 9647 Bundle restrictions = sUserManager.getUserRestrictions(userId); 9648 if (restrictions.getBoolean(restrictionKey, false)) { 9649 Log.w(TAG, "User is restricted: " + restrictionKey); 9650 return true; 9651 } 9652 return false; 9653 } 9654 9655 @Override 9656 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 9657 mContext.enforceCallingOrSelfPermission( 9658 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9659 "Only package verification agents can verify applications"); 9660 9661 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9662 final PackageVerificationResponse response = new PackageVerificationResponse( 9663 verificationCode, Binder.getCallingUid()); 9664 msg.arg1 = id; 9665 msg.obj = response; 9666 mHandler.sendMessage(msg); 9667 } 9668 9669 @Override 9670 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 9671 long millisecondsToDelay) { 9672 mContext.enforceCallingOrSelfPermission( 9673 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9674 "Only package verification agents can extend verification timeouts"); 9675 9676 final PackageVerificationState state = mPendingVerification.get(id); 9677 final PackageVerificationResponse response = new PackageVerificationResponse( 9678 verificationCodeAtTimeout, Binder.getCallingUid()); 9679 9680 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 9681 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 9682 } 9683 if (millisecondsToDelay < 0) { 9684 millisecondsToDelay = 0; 9685 } 9686 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 9687 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 9688 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 9689 } 9690 9691 if ((state != null) && !state.timeoutExtended()) { 9692 state.extendTimeout(); 9693 9694 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9695 msg.arg1 = id; 9696 msg.obj = response; 9697 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 9698 } 9699 } 9700 9701 private void broadcastPackageVerified(int verificationId, Uri packageUri, 9702 int verificationCode, UserHandle user) { 9703 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 9704 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 9705 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9706 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9707 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 9708 9709 mContext.sendBroadcastAsUser(intent, user, 9710 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 9711 } 9712 9713 private ComponentName matchComponentForVerifier(String packageName, 9714 List<ResolveInfo> receivers) { 9715 ActivityInfo targetReceiver = null; 9716 9717 final int NR = receivers.size(); 9718 for (int i = 0; i < NR; i++) { 9719 final ResolveInfo info = receivers.get(i); 9720 if (info.activityInfo == null) { 9721 continue; 9722 } 9723 9724 if (packageName.equals(info.activityInfo.packageName)) { 9725 targetReceiver = info.activityInfo; 9726 break; 9727 } 9728 } 9729 9730 if (targetReceiver == null) { 9731 return null; 9732 } 9733 9734 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 9735 } 9736 9737 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 9738 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 9739 if (pkgInfo.verifiers.length == 0) { 9740 return null; 9741 } 9742 9743 final int N = pkgInfo.verifiers.length; 9744 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 9745 for (int i = 0; i < N; i++) { 9746 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 9747 9748 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 9749 receivers); 9750 if (comp == null) { 9751 continue; 9752 } 9753 9754 final int verifierUid = getUidForVerifier(verifierInfo); 9755 if (verifierUid == -1) { 9756 continue; 9757 } 9758 9759 if (DEBUG_VERIFY) { 9760 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 9761 + " with the correct signature"); 9762 } 9763 sufficientVerifiers.add(comp); 9764 verificationState.addSufficientVerifier(verifierUid); 9765 } 9766 9767 return sufficientVerifiers; 9768 } 9769 9770 private int getUidForVerifier(VerifierInfo verifierInfo) { 9771 synchronized (mPackages) { 9772 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 9773 if (pkg == null) { 9774 return -1; 9775 } else if (pkg.mSignatures.length != 1) { 9776 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9777 + " has more than one signature; ignoring"); 9778 return -1; 9779 } 9780 9781 /* 9782 * If the public key of the package's signature does not match 9783 * our expected public key, then this is a different package and 9784 * we should skip. 9785 */ 9786 9787 final byte[] expectedPublicKey; 9788 try { 9789 final Signature verifierSig = pkg.mSignatures[0]; 9790 final PublicKey publicKey = verifierSig.getPublicKey(); 9791 expectedPublicKey = publicKey.getEncoded(); 9792 } catch (CertificateException e) { 9793 return -1; 9794 } 9795 9796 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 9797 9798 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 9799 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9800 + " does not have the expected public key; ignoring"); 9801 return -1; 9802 } 9803 9804 return pkg.applicationInfo.uid; 9805 } 9806 } 9807 9808 @Override 9809 public void finishPackageInstall(int token) { 9810 enforceSystemOrRoot("Only the system is allowed to finish installs"); 9811 9812 if (DEBUG_INSTALL) { 9813 Slog.v(TAG, "BM finishing package install for " + token); 9814 } 9815 9816 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9817 mHandler.sendMessage(msg); 9818 } 9819 9820 /** 9821 * Get the verification agent timeout. 9822 * 9823 * @return verification timeout in milliseconds 9824 */ 9825 private long getVerificationTimeout() { 9826 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 9827 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 9828 DEFAULT_VERIFICATION_TIMEOUT); 9829 } 9830 9831 /** 9832 * Get the default verification agent response code. 9833 * 9834 * @return default verification response code 9835 */ 9836 private int getDefaultVerificationResponse() { 9837 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9838 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 9839 DEFAULT_VERIFICATION_RESPONSE); 9840 } 9841 9842 /** 9843 * Check whether or not package verification has been enabled. 9844 * 9845 * @return true if verification should be performed 9846 */ 9847 private boolean isVerificationEnabled(int userId, int installFlags) { 9848 if (!DEFAULT_VERIFY_ENABLE) { 9849 return false; 9850 } 9851 9852 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 9853 9854 // Check if installing from ADB 9855 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 9856 // Do not run verification in a test harness environment 9857 if (ActivityManager.isRunningInTestHarness()) { 9858 return false; 9859 } 9860 if (ensureVerifyAppsEnabled) { 9861 return true; 9862 } 9863 // Check if the developer does not want package verification for ADB installs 9864 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9865 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 9866 return false; 9867 } 9868 } 9869 9870 if (ensureVerifyAppsEnabled) { 9871 return true; 9872 } 9873 9874 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9875 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 9876 } 9877 9878 @Override 9879 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 9880 throws RemoteException { 9881 mContext.enforceCallingOrSelfPermission( 9882 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 9883 "Only intentfilter verification agents can verify applications"); 9884 9885 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 9886 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 9887 Binder.getCallingUid(), verificationCode, failedDomains); 9888 msg.arg1 = id; 9889 msg.obj = response; 9890 mHandler.sendMessage(msg); 9891 } 9892 9893 @Override 9894 public int getIntentVerificationStatus(String packageName, int userId) { 9895 synchronized (mPackages) { 9896 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 9897 } 9898 } 9899 9900 @Override 9901 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 9902 mContext.enforceCallingOrSelfPermission( 9903 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 9904 9905 boolean result = false; 9906 synchronized (mPackages) { 9907 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 9908 } 9909 if (result) { 9910 scheduleWritePackageRestrictionsLocked(userId); 9911 } 9912 return result; 9913 } 9914 9915 @Override 9916 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 9917 synchronized (mPackages) { 9918 return mSettings.getIntentFilterVerificationsLPr(packageName); 9919 } 9920 } 9921 9922 @Override 9923 public List<IntentFilter> getAllIntentFilters(String packageName) { 9924 if (TextUtils.isEmpty(packageName)) { 9925 return Collections.<IntentFilter>emptyList(); 9926 } 9927 synchronized (mPackages) { 9928 PackageParser.Package pkg = mPackages.get(packageName); 9929 if (pkg == null || pkg.activities == null) { 9930 return Collections.<IntentFilter>emptyList(); 9931 } 9932 final int count = pkg.activities.size(); 9933 ArrayList<IntentFilter> result = new ArrayList<>(); 9934 for (int n=0; n<count; n++) { 9935 PackageParser.Activity activity = pkg.activities.get(n); 9936 if (activity.intents != null || activity.intents.size() > 0) { 9937 result.addAll(activity.intents); 9938 } 9939 } 9940 return result; 9941 } 9942 } 9943 9944 @Override 9945 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 9946 mContext.enforceCallingOrSelfPermission( 9947 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 9948 9949 synchronized (mPackages) { 9950 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 9951 if (packageName != null) { 9952 result |= updateIntentVerificationStatus(packageName, 9953 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 9954 userId); 9955 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 9956 packageName, userId); 9957 } 9958 return result; 9959 } 9960 } 9961 9962 @Override 9963 public String getDefaultBrowserPackageName(int userId) { 9964 synchronized (mPackages) { 9965 return mSettings.getDefaultBrowserPackageNameLPw(userId); 9966 } 9967 } 9968 9969 /** 9970 * Get the "allow unknown sources" setting. 9971 * 9972 * @return the current "allow unknown sources" setting 9973 */ 9974 private int getUnknownSourcesSettings() { 9975 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9976 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 9977 -1); 9978 } 9979 9980 @Override 9981 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 9982 final int uid = Binder.getCallingUid(); 9983 // writer 9984 synchronized (mPackages) { 9985 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 9986 if (targetPackageSetting == null) { 9987 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 9988 } 9989 9990 PackageSetting installerPackageSetting; 9991 if (installerPackageName != null) { 9992 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 9993 if (installerPackageSetting == null) { 9994 throw new IllegalArgumentException("Unknown installer package: " 9995 + installerPackageName); 9996 } 9997 } else { 9998 installerPackageSetting = null; 9999 } 10000 10001 Signature[] callerSignature; 10002 Object obj = mSettings.getUserIdLPr(uid); 10003 if (obj != null) { 10004 if (obj instanceof SharedUserSetting) { 10005 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 10006 } else if (obj instanceof PackageSetting) { 10007 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 10008 } else { 10009 throw new SecurityException("Bad object " + obj + " for uid " + uid); 10010 } 10011 } else { 10012 throw new SecurityException("Unknown calling uid " + uid); 10013 } 10014 10015 // Verify: can't set installerPackageName to a package that is 10016 // not signed with the same cert as the caller. 10017 if (installerPackageSetting != null) { 10018 if (compareSignatures(callerSignature, 10019 installerPackageSetting.signatures.mSignatures) 10020 != PackageManager.SIGNATURE_MATCH) { 10021 throw new SecurityException( 10022 "Caller does not have same cert as new installer package " 10023 + installerPackageName); 10024 } 10025 } 10026 10027 // Verify: if target already has an installer package, it must 10028 // be signed with the same cert as the caller. 10029 if (targetPackageSetting.installerPackageName != null) { 10030 PackageSetting setting = mSettings.mPackages.get( 10031 targetPackageSetting.installerPackageName); 10032 // If the currently set package isn't valid, then it's always 10033 // okay to change it. 10034 if (setting != null) { 10035 if (compareSignatures(callerSignature, 10036 setting.signatures.mSignatures) 10037 != PackageManager.SIGNATURE_MATCH) { 10038 throw new SecurityException( 10039 "Caller does not have same cert as old installer package " 10040 + targetPackageSetting.installerPackageName); 10041 } 10042 } 10043 } 10044 10045 // Okay! 10046 targetPackageSetting.installerPackageName = installerPackageName; 10047 scheduleWriteSettingsLocked(); 10048 } 10049 } 10050 10051 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 10052 // Queue up an async operation since the package installation may take a little while. 10053 mHandler.post(new Runnable() { 10054 public void run() { 10055 mHandler.removeCallbacks(this); 10056 // Result object to be returned 10057 PackageInstalledInfo res = new PackageInstalledInfo(); 10058 res.returnCode = currentStatus; 10059 res.uid = -1; 10060 res.pkg = null; 10061 res.removedInfo = new PackageRemovedInfo(); 10062 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10063 args.doPreInstall(res.returnCode); 10064 synchronized (mInstallLock) { 10065 installPackageLI(args, res); 10066 } 10067 args.doPostInstall(res.returnCode, res.uid); 10068 } 10069 10070 // A restore should be performed at this point if (a) the install 10071 // succeeded, (b) the operation is not an update, and (c) the new 10072 // package has not opted out of backup participation. 10073 final boolean update = res.removedInfo.removedPackage != null; 10074 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 10075 boolean doRestore = !update 10076 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 10077 10078 // Set up the post-install work request bookkeeping. This will be used 10079 // and cleaned up by the post-install event handling regardless of whether 10080 // there's a restore pass performed. Token values are >= 1. 10081 int token; 10082 if (mNextInstallToken < 0) mNextInstallToken = 1; 10083 token = mNextInstallToken++; 10084 10085 PostInstallData data = new PostInstallData(args, res); 10086 mRunningInstalls.put(token, data); 10087 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 10088 10089 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 10090 // Pass responsibility to the Backup Manager. It will perform a 10091 // restore if appropriate, then pass responsibility back to the 10092 // Package Manager to run the post-install observer callbacks 10093 // and broadcasts. 10094 IBackupManager bm = IBackupManager.Stub.asInterface( 10095 ServiceManager.getService(Context.BACKUP_SERVICE)); 10096 if (bm != null) { 10097 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 10098 + " to BM for possible restore"); 10099 try { 10100 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 10101 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 10102 } else { 10103 doRestore = false; 10104 } 10105 } catch (RemoteException e) { 10106 // can't happen; the backup manager is local 10107 } catch (Exception e) { 10108 Slog.e(TAG, "Exception trying to enqueue restore", e); 10109 doRestore = false; 10110 } 10111 } else { 10112 Slog.e(TAG, "Backup Manager not found!"); 10113 doRestore = false; 10114 } 10115 } 10116 10117 if (!doRestore) { 10118 // No restore possible, or the Backup Manager was mysteriously not 10119 // available -- just fire the post-install work request directly. 10120 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 10121 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10122 mHandler.sendMessage(msg); 10123 } 10124 } 10125 }); 10126 } 10127 10128 private abstract class HandlerParams { 10129 private static final int MAX_RETRIES = 4; 10130 10131 /** 10132 * Number of times startCopy() has been attempted and had a non-fatal 10133 * error. 10134 */ 10135 private int mRetries = 0; 10136 10137 /** User handle for the user requesting the information or installation. */ 10138 private final UserHandle mUser; 10139 10140 HandlerParams(UserHandle user) { 10141 mUser = user; 10142 } 10143 10144 UserHandle getUser() { 10145 return mUser; 10146 } 10147 10148 final boolean startCopy() { 10149 boolean res; 10150 try { 10151 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 10152 10153 if (++mRetries > MAX_RETRIES) { 10154 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 10155 mHandler.sendEmptyMessage(MCS_GIVE_UP); 10156 handleServiceError(); 10157 return false; 10158 } else { 10159 handleStartCopy(); 10160 res = true; 10161 } 10162 } catch (RemoteException e) { 10163 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 10164 mHandler.sendEmptyMessage(MCS_RECONNECT); 10165 res = false; 10166 } 10167 handleReturnCode(); 10168 return res; 10169 } 10170 10171 final void serviceError() { 10172 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 10173 handleServiceError(); 10174 handleReturnCode(); 10175 } 10176 10177 abstract void handleStartCopy() throws RemoteException; 10178 abstract void handleServiceError(); 10179 abstract void handleReturnCode(); 10180 } 10181 10182 class MeasureParams extends HandlerParams { 10183 private final PackageStats mStats; 10184 private boolean mSuccess; 10185 10186 private final IPackageStatsObserver mObserver; 10187 10188 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 10189 super(new UserHandle(stats.userHandle)); 10190 mObserver = observer; 10191 mStats = stats; 10192 } 10193 10194 @Override 10195 public String toString() { 10196 return "MeasureParams{" 10197 + Integer.toHexString(System.identityHashCode(this)) 10198 + " " + mStats.packageName + "}"; 10199 } 10200 10201 @Override 10202 void handleStartCopy() throws RemoteException { 10203 synchronized (mInstallLock) { 10204 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 10205 } 10206 10207 if (mSuccess) { 10208 final boolean mounted; 10209 if (Environment.isExternalStorageEmulated()) { 10210 mounted = true; 10211 } else { 10212 final String status = Environment.getExternalStorageState(); 10213 mounted = (Environment.MEDIA_MOUNTED.equals(status) 10214 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 10215 } 10216 10217 if (mounted) { 10218 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 10219 10220 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 10221 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 10222 10223 mStats.externalDataSize = calculateDirectorySize(mContainerService, 10224 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 10225 10226 // Always subtract cache size, since it's a subdirectory 10227 mStats.externalDataSize -= mStats.externalCacheSize; 10228 10229 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 10230 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 10231 10232 mStats.externalObbSize = calculateDirectorySize(mContainerService, 10233 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 10234 } 10235 } 10236 } 10237 10238 @Override 10239 void handleReturnCode() { 10240 if (mObserver != null) { 10241 try { 10242 mObserver.onGetStatsCompleted(mStats, mSuccess); 10243 } catch (RemoteException e) { 10244 Slog.i(TAG, "Observer no longer exists."); 10245 } 10246 } 10247 } 10248 10249 @Override 10250 void handleServiceError() { 10251 Slog.e(TAG, "Could not measure application " + mStats.packageName 10252 + " external storage"); 10253 } 10254 } 10255 10256 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 10257 throws RemoteException { 10258 long result = 0; 10259 for (File path : paths) { 10260 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 10261 } 10262 return result; 10263 } 10264 10265 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 10266 for (File path : paths) { 10267 try { 10268 mcs.clearDirectory(path.getAbsolutePath()); 10269 } catch (RemoteException e) { 10270 } 10271 } 10272 } 10273 10274 static class OriginInfo { 10275 /** 10276 * Location where install is coming from, before it has been 10277 * copied/renamed into place. This could be a single monolithic APK 10278 * file, or a cluster directory. This location may be untrusted. 10279 */ 10280 final File file; 10281 final String cid; 10282 10283 /** 10284 * Flag indicating that {@link #file} or {@link #cid} has already been 10285 * staged, meaning downstream users don't need to defensively copy the 10286 * contents. 10287 */ 10288 final boolean staged; 10289 10290 /** 10291 * Flag indicating that {@link #file} or {@link #cid} is an already 10292 * installed app that is being moved. 10293 */ 10294 final boolean existing; 10295 10296 final String resolvedPath; 10297 final File resolvedFile; 10298 10299 static OriginInfo fromNothing() { 10300 return new OriginInfo(null, null, false, false); 10301 } 10302 10303 static OriginInfo fromUntrustedFile(File file) { 10304 return new OriginInfo(file, null, false, false); 10305 } 10306 10307 static OriginInfo fromExistingFile(File file) { 10308 return new OriginInfo(file, null, false, true); 10309 } 10310 10311 static OriginInfo fromStagedFile(File file) { 10312 return new OriginInfo(file, null, true, false); 10313 } 10314 10315 static OriginInfo fromStagedContainer(String cid) { 10316 return new OriginInfo(null, cid, true, false); 10317 } 10318 10319 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 10320 this.file = file; 10321 this.cid = cid; 10322 this.staged = staged; 10323 this.existing = existing; 10324 10325 if (cid != null) { 10326 resolvedPath = PackageHelper.getSdDir(cid); 10327 resolvedFile = new File(resolvedPath); 10328 } else if (file != null) { 10329 resolvedPath = file.getAbsolutePath(); 10330 resolvedFile = file; 10331 } else { 10332 resolvedPath = null; 10333 resolvedFile = null; 10334 } 10335 } 10336 } 10337 10338 class MoveInfo { 10339 final int moveId; 10340 final String fromUuid; 10341 final String toUuid; 10342 final String packageName; 10343 final String dataAppName; 10344 final int appId; 10345 final String seinfo; 10346 10347 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 10348 String dataAppName, int appId, String seinfo) { 10349 this.moveId = moveId; 10350 this.fromUuid = fromUuid; 10351 this.toUuid = toUuid; 10352 this.packageName = packageName; 10353 this.dataAppName = dataAppName; 10354 this.appId = appId; 10355 this.seinfo = seinfo; 10356 } 10357 } 10358 10359 class InstallParams extends HandlerParams { 10360 final OriginInfo origin; 10361 final MoveInfo move; 10362 final IPackageInstallObserver2 observer; 10363 int installFlags; 10364 final String installerPackageName; 10365 final String volumeUuid; 10366 final VerificationParams verificationParams; 10367 private InstallArgs mArgs; 10368 private int mRet; 10369 final String packageAbiOverride; 10370 final String[] grantedRuntimePermissions; 10371 10372 10373 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10374 int installFlags, String installerPackageName, String volumeUuid, 10375 VerificationParams verificationParams, UserHandle user, String packageAbiOverride, 10376 String[] grantedPermissions) { 10377 super(user); 10378 this.origin = origin; 10379 this.move = move; 10380 this.observer = observer; 10381 this.installFlags = installFlags; 10382 this.installerPackageName = installerPackageName; 10383 this.volumeUuid = volumeUuid; 10384 this.verificationParams = verificationParams; 10385 this.packageAbiOverride = packageAbiOverride; 10386 this.grantedRuntimePermissions = grantedPermissions; 10387 } 10388 10389 @Override 10390 public String toString() { 10391 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 10392 + " file=" + origin.file + " cid=" + origin.cid + "}"; 10393 } 10394 10395 public ManifestDigest getManifestDigest() { 10396 if (verificationParams == null) { 10397 return null; 10398 } 10399 return verificationParams.getManifestDigest(); 10400 } 10401 10402 private int installLocationPolicy(PackageInfoLite pkgLite) { 10403 String packageName = pkgLite.packageName; 10404 int installLocation = pkgLite.installLocation; 10405 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10406 // reader 10407 synchronized (mPackages) { 10408 PackageParser.Package pkg = mPackages.get(packageName); 10409 if (pkg != null) { 10410 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10411 // Check for downgrading. 10412 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 10413 try { 10414 checkDowngrade(pkg, pkgLite); 10415 } catch (PackageManagerException e) { 10416 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 10417 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 10418 } 10419 } 10420 // Check for updated system application. 10421 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10422 if (onSd) { 10423 Slog.w(TAG, "Cannot install update to system app on sdcard"); 10424 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 10425 } 10426 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10427 } else { 10428 if (onSd) { 10429 // Install flag overrides everything. 10430 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10431 } 10432 // If current upgrade specifies particular preference 10433 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 10434 // Application explicitly specified internal. 10435 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10436 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 10437 // App explictly prefers external. Let policy decide 10438 } else { 10439 // Prefer previous location 10440 if (isExternal(pkg)) { 10441 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10442 } 10443 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10444 } 10445 } 10446 } else { 10447 // Invalid install. Return error code 10448 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 10449 } 10450 } 10451 } 10452 // All the special cases have been taken care of. 10453 // Return result based on recommended install location. 10454 if (onSd) { 10455 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10456 } 10457 return pkgLite.recommendedInstallLocation; 10458 } 10459 10460 /* 10461 * Invoke remote method to get package information and install 10462 * location values. Override install location based on default 10463 * policy if needed and then create install arguments based 10464 * on the install location. 10465 */ 10466 public void handleStartCopy() throws RemoteException { 10467 int ret = PackageManager.INSTALL_SUCCEEDED; 10468 10469 // If we're already staged, we've firmly committed to an install location 10470 if (origin.staged) { 10471 if (origin.file != null) { 10472 installFlags |= PackageManager.INSTALL_INTERNAL; 10473 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10474 } else if (origin.cid != null) { 10475 installFlags |= PackageManager.INSTALL_EXTERNAL; 10476 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10477 } else { 10478 throw new IllegalStateException("Invalid stage location"); 10479 } 10480 } 10481 10482 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10483 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 10484 10485 PackageInfoLite pkgLite = null; 10486 10487 if (onInt && onSd) { 10488 // Check if both bits are set. 10489 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 10490 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10491 } else { 10492 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 10493 packageAbiOverride); 10494 10495 /* 10496 * If we have too little free space, try to free cache 10497 * before giving up. 10498 */ 10499 if (!origin.staged && pkgLite.recommendedInstallLocation 10500 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10501 // TODO: focus freeing disk space on the target device 10502 final StorageManager storage = StorageManager.from(mContext); 10503 final long lowThreshold = storage.getStorageLowBytes( 10504 Environment.getDataDirectory()); 10505 10506 final long sizeBytes = mContainerService.calculateInstalledSize( 10507 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 10508 10509 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 10510 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 10511 installFlags, packageAbiOverride); 10512 } 10513 10514 /* 10515 * The cache free must have deleted the file we 10516 * downloaded to install. 10517 * 10518 * TODO: fix the "freeCache" call to not delete 10519 * the file we care about. 10520 */ 10521 if (pkgLite.recommendedInstallLocation 10522 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10523 pkgLite.recommendedInstallLocation 10524 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 10525 } 10526 } 10527 } 10528 10529 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10530 int loc = pkgLite.recommendedInstallLocation; 10531 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 10532 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10533 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 10534 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 10535 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10536 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10537 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 10538 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 10539 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10540 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 10541 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 10542 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 10543 } else { 10544 // Override with defaults if needed. 10545 loc = installLocationPolicy(pkgLite); 10546 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 10547 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 10548 } else if (!onSd && !onInt) { 10549 // Override install location with flags 10550 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 10551 // Set the flag to install on external media. 10552 installFlags |= PackageManager.INSTALL_EXTERNAL; 10553 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10554 } else { 10555 // Make sure the flag for installing on external 10556 // media is unset 10557 installFlags |= PackageManager.INSTALL_INTERNAL; 10558 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10559 } 10560 } 10561 } 10562 } 10563 10564 final InstallArgs args = createInstallArgs(this); 10565 mArgs = args; 10566 10567 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10568 /* 10569 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 10570 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 10571 */ 10572 int userIdentifier = getUser().getIdentifier(); 10573 if (userIdentifier == UserHandle.USER_ALL 10574 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 10575 userIdentifier = UserHandle.USER_OWNER; 10576 } 10577 10578 /* 10579 * Determine if we have any installed package verifiers. If we 10580 * do, then we'll defer to them to verify the packages. 10581 */ 10582 final int requiredUid = mRequiredVerifierPackage == null ? -1 10583 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 10584 if (!origin.existing && requiredUid != -1 10585 && isVerificationEnabled(userIdentifier, installFlags)) { 10586 final Intent verification = new Intent( 10587 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 10588 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 10589 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 10590 PACKAGE_MIME_TYPE); 10591 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10592 10593 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 10594 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 10595 0 /* TODO: Which userId? */); 10596 10597 if (DEBUG_VERIFY) { 10598 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 10599 + verification.toString() + " with " + pkgLite.verifiers.length 10600 + " optional verifiers"); 10601 } 10602 10603 final int verificationId = mPendingVerificationToken++; 10604 10605 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10606 10607 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 10608 installerPackageName); 10609 10610 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 10611 installFlags); 10612 10613 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 10614 pkgLite.packageName); 10615 10616 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 10617 pkgLite.versionCode); 10618 10619 if (verificationParams != null) { 10620 if (verificationParams.getVerificationURI() != null) { 10621 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 10622 verificationParams.getVerificationURI()); 10623 } 10624 if (verificationParams.getOriginatingURI() != null) { 10625 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 10626 verificationParams.getOriginatingURI()); 10627 } 10628 if (verificationParams.getReferrer() != null) { 10629 verification.putExtra(Intent.EXTRA_REFERRER, 10630 verificationParams.getReferrer()); 10631 } 10632 if (verificationParams.getOriginatingUid() >= 0) { 10633 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 10634 verificationParams.getOriginatingUid()); 10635 } 10636 if (verificationParams.getInstallerUid() >= 0) { 10637 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 10638 verificationParams.getInstallerUid()); 10639 } 10640 } 10641 10642 final PackageVerificationState verificationState = new PackageVerificationState( 10643 requiredUid, args); 10644 10645 mPendingVerification.append(verificationId, verificationState); 10646 10647 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 10648 receivers, verificationState); 10649 10650 // Apps installed for "all" users use the device owner to verify the app 10651 UserHandle verifierUser = getUser(); 10652 if (verifierUser == UserHandle.ALL) { 10653 verifierUser = UserHandle.OWNER; 10654 } 10655 10656 /* 10657 * If any sufficient verifiers were listed in the package 10658 * manifest, attempt to ask them. 10659 */ 10660 if (sufficientVerifiers != null) { 10661 final int N = sufficientVerifiers.size(); 10662 if (N == 0) { 10663 Slog.i(TAG, "Additional verifiers required, but none installed."); 10664 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 10665 } else { 10666 for (int i = 0; i < N; i++) { 10667 final ComponentName verifierComponent = sufficientVerifiers.get(i); 10668 10669 final Intent sufficientIntent = new Intent(verification); 10670 sufficientIntent.setComponent(verifierComponent); 10671 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 10672 } 10673 } 10674 } 10675 10676 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 10677 mRequiredVerifierPackage, receivers); 10678 if (ret == PackageManager.INSTALL_SUCCEEDED 10679 && mRequiredVerifierPackage != null) { 10680 /* 10681 * Send the intent to the required verification agent, 10682 * but only start the verification timeout after the 10683 * target BroadcastReceivers have run. 10684 */ 10685 verification.setComponent(requiredVerifierComponent); 10686 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 10687 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10688 new BroadcastReceiver() { 10689 @Override 10690 public void onReceive(Context context, Intent intent) { 10691 final Message msg = mHandler 10692 .obtainMessage(CHECK_PENDING_VERIFICATION); 10693 msg.arg1 = verificationId; 10694 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 10695 } 10696 }, null, 0, null, null); 10697 10698 /* 10699 * We don't want the copy to proceed until verification 10700 * succeeds, so null out this field. 10701 */ 10702 mArgs = null; 10703 } 10704 } else { 10705 /* 10706 * No package verification is enabled, so immediately start 10707 * the remote call to initiate copy using temporary file. 10708 */ 10709 ret = args.copyApk(mContainerService, true); 10710 } 10711 } 10712 10713 mRet = ret; 10714 } 10715 10716 @Override 10717 void handleReturnCode() { 10718 // If mArgs is null, then MCS couldn't be reached. When it 10719 // reconnects, it will try again to install. At that point, this 10720 // will succeed. 10721 if (mArgs != null) { 10722 processPendingInstall(mArgs, mRet); 10723 } 10724 } 10725 10726 @Override 10727 void handleServiceError() { 10728 mArgs = createInstallArgs(this); 10729 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10730 } 10731 10732 public boolean isForwardLocked() { 10733 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10734 } 10735 } 10736 10737 /** 10738 * Used during creation of InstallArgs 10739 * 10740 * @param installFlags package installation flags 10741 * @return true if should be installed on external storage 10742 */ 10743 private static boolean installOnExternalAsec(int installFlags) { 10744 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 10745 return false; 10746 } 10747 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 10748 return true; 10749 } 10750 return false; 10751 } 10752 10753 /** 10754 * Used during creation of InstallArgs 10755 * 10756 * @param installFlags package installation flags 10757 * @return true if should be installed as forward locked 10758 */ 10759 private static boolean installForwardLocked(int installFlags) { 10760 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10761 } 10762 10763 private InstallArgs createInstallArgs(InstallParams params) { 10764 if (params.move != null) { 10765 return new MoveInstallArgs(params); 10766 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 10767 return new AsecInstallArgs(params); 10768 } else { 10769 return new FileInstallArgs(params); 10770 } 10771 } 10772 10773 /** 10774 * Create args that describe an existing installed package. Typically used 10775 * when cleaning up old installs, or used as a move source. 10776 */ 10777 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 10778 String resourcePath, String[] instructionSets) { 10779 final boolean isInAsec; 10780 if (installOnExternalAsec(installFlags)) { 10781 /* Apps on SD card are always in ASEC containers. */ 10782 isInAsec = true; 10783 } else if (installForwardLocked(installFlags) 10784 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 10785 /* 10786 * Forward-locked apps are only in ASEC containers if they're the 10787 * new style 10788 */ 10789 isInAsec = true; 10790 } else { 10791 isInAsec = false; 10792 } 10793 10794 if (isInAsec) { 10795 return new AsecInstallArgs(codePath, instructionSets, 10796 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 10797 } else { 10798 return new FileInstallArgs(codePath, resourcePath, instructionSets); 10799 } 10800 } 10801 10802 static abstract class InstallArgs { 10803 /** @see InstallParams#origin */ 10804 final OriginInfo origin; 10805 /** @see InstallParams#move */ 10806 final MoveInfo move; 10807 10808 final IPackageInstallObserver2 observer; 10809 // Always refers to PackageManager flags only 10810 final int installFlags; 10811 final String installerPackageName; 10812 final String volumeUuid; 10813 final ManifestDigest manifestDigest; 10814 final UserHandle user; 10815 final String abiOverride; 10816 final String[] installGrantPermissions; 10817 10818 // The list of instruction sets supported by this app. This is currently 10819 // only used during the rmdex() phase to clean up resources. We can get rid of this 10820 // if we move dex files under the common app path. 10821 /* nullable */ String[] instructionSets; 10822 10823 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10824 int installFlags, String installerPackageName, String volumeUuid, 10825 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 10826 String abiOverride, String[] installGrantPermissions) { 10827 this.origin = origin; 10828 this.move = move; 10829 this.installFlags = installFlags; 10830 this.observer = observer; 10831 this.installerPackageName = installerPackageName; 10832 this.volumeUuid = volumeUuid; 10833 this.manifestDigest = manifestDigest; 10834 this.user = user; 10835 this.instructionSets = instructionSets; 10836 this.abiOverride = abiOverride; 10837 this.installGrantPermissions = installGrantPermissions; 10838 } 10839 10840 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 10841 abstract int doPreInstall(int status); 10842 10843 /** 10844 * Rename package into final resting place. All paths on the given 10845 * scanned package should be updated to reflect the rename. 10846 */ 10847 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 10848 abstract int doPostInstall(int status, int uid); 10849 10850 /** @see PackageSettingBase#codePathString */ 10851 abstract String getCodePath(); 10852 /** @see PackageSettingBase#resourcePathString */ 10853 abstract String getResourcePath(); 10854 10855 // Need installer lock especially for dex file removal. 10856 abstract void cleanUpResourcesLI(); 10857 abstract boolean doPostDeleteLI(boolean delete); 10858 10859 /** 10860 * Called before the source arguments are copied. This is used mostly 10861 * for MoveParams when it needs to read the source file to put it in the 10862 * destination. 10863 */ 10864 int doPreCopy() { 10865 return PackageManager.INSTALL_SUCCEEDED; 10866 } 10867 10868 /** 10869 * Called after the source arguments are copied. This is used mostly for 10870 * MoveParams when it needs to read the source file to put it in the 10871 * destination. 10872 * 10873 * @return 10874 */ 10875 int doPostCopy(int uid) { 10876 return PackageManager.INSTALL_SUCCEEDED; 10877 } 10878 10879 protected boolean isFwdLocked() { 10880 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10881 } 10882 10883 protected boolean isExternalAsec() { 10884 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10885 } 10886 10887 UserHandle getUser() { 10888 return user; 10889 } 10890 } 10891 10892 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 10893 if (!allCodePaths.isEmpty()) { 10894 if (instructionSets == null) { 10895 throw new IllegalStateException("instructionSet == null"); 10896 } 10897 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 10898 for (String codePath : allCodePaths) { 10899 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 10900 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 10901 if (retCode < 0) { 10902 Slog.w(TAG, "Couldn't remove dex file for package: " 10903 + " at location " + codePath + ", retcode=" + retCode); 10904 // we don't consider this to be a failure of the core package deletion 10905 } 10906 } 10907 } 10908 } 10909 } 10910 10911 /** 10912 * Logic to handle installation of non-ASEC applications, including copying 10913 * and renaming logic. 10914 */ 10915 class FileInstallArgs extends InstallArgs { 10916 private File codeFile; 10917 private File resourceFile; 10918 10919 // Example topology: 10920 // /data/app/com.example/base.apk 10921 // /data/app/com.example/split_foo.apk 10922 // /data/app/com.example/lib/arm/libfoo.so 10923 // /data/app/com.example/lib/arm64/libfoo.so 10924 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 10925 10926 /** New install */ 10927 FileInstallArgs(InstallParams params) { 10928 super(params.origin, params.move, params.observer, params.installFlags, 10929 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10930 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 10931 params.grantedRuntimePermissions); 10932 if (isFwdLocked()) { 10933 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 10934 } 10935 } 10936 10937 /** Existing install */ 10938 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 10939 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 10940 null, null); 10941 this.codeFile = (codePath != null) ? new File(codePath) : null; 10942 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 10943 } 10944 10945 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10946 if (origin.staged) { 10947 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 10948 codeFile = origin.file; 10949 resourceFile = origin.file; 10950 return PackageManager.INSTALL_SUCCEEDED; 10951 } 10952 10953 try { 10954 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 10955 codeFile = tempDir; 10956 resourceFile = tempDir; 10957 } catch (IOException e) { 10958 Slog.w(TAG, "Failed to create copy file: " + e); 10959 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10960 } 10961 10962 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 10963 @Override 10964 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 10965 if (!FileUtils.isValidExtFilename(name)) { 10966 throw new IllegalArgumentException("Invalid filename: " + name); 10967 } 10968 try { 10969 final File file = new File(codeFile, name); 10970 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 10971 O_RDWR | O_CREAT, 0644); 10972 Os.chmod(file.getAbsolutePath(), 0644); 10973 return new ParcelFileDescriptor(fd); 10974 } catch (ErrnoException e) { 10975 throw new RemoteException("Failed to open: " + e.getMessage()); 10976 } 10977 } 10978 }; 10979 10980 int ret = PackageManager.INSTALL_SUCCEEDED; 10981 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 10982 if (ret != PackageManager.INSTALL_SUCCEEDED) { 10983 Slog.e(TAG, "Failed to copy package"); 10984 return ret; 10985 } 10986 10987 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 10988 NativeLibraryHelper.Handle handle = null; 10989 try { 10990 handle = NativeLibraryHelper.Handle.create(codeFile); 10991 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 10992 abiOverride); 10993 } catch (IOException e) { 10994 Slog.e(TAG, "Copying native libraries failed", e); 10995 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10996 } finally { 10997 IoUtils.closeQuietly(handle); 10998 } 10999 11000 return ret; 11001 } 11002 11003 int doPreInstall(int status) { 11004 if (status != PackageManager.INSTALL_SUCCEEDED) { 11005 cleanUp(); 11006 } 11007 return status; 11008 } 11009 11010 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11011 if (status != PackageManager.INSTALL_SUCCEEDED) { 11012 cleanUp(); 11013 return false; 11014 } 11015 11016 final File targetDir = codeFile.getParentFile(); 11017 final File beforeCodeFile = codeFile; 11018 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 11019 11020 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 11021 try { 11022 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 11023 } catch (ErrnoException e) { 11024 Slog.w(TAG, "Failed to rename", e); 11025 return false; 11026 } 11027 11028 if (!SELinux.restoreconRecursive(afterCodeFile)) { 11029 Slog.w(TAG, "Failed to restorecon"); 11030 return false; 11031 } 11032 11033 // Reflect the rename internally 11034 codeFile = afterCodeFile; 11035 resourceFile = afterCodeFile; 11036 11037 // Reflect the rename in scanned details 11038 pkg.codePath = afterCodeFile.getAbsolutePath(); 11039 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11040 pkg.baseCodePath); 11041 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11042 pkg.splitCodePaths); 11043 11044 // Reflect the rename in app info 11045 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11046 pkg.applicationInfo.setCodePath(pkg.codePath); 11047 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11048 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11049 pkg.applicationInfo.setResourcePath(pkg.codePath); 11050 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11051 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11052 11053 return true; 11054 } 11055 11056 int doPostInstall(int status, int uid) { 11057 if (status != PackageManager.INSTALL_SUCCEEDED) { 11058 cleanUp(); 11059 } 11060 return status; 11061 } 11062 11063 @Override 11064 String getCodePath() { 11065 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11066 } 11067 11068 @Override 11069 String getResourcePath() { 11070 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11071 } 11072 11073 private boolean cleanUp() { 11074 if (codeFile == null || !codeFile.exists()) { 11075 return false; 11076 } 11077 11078 if (codeFile.isDirectory()) { 11079 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11080 } else { 11081 codeFile.delete(); 11082 } 11083 11084 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 11085 resourceFile.delete(); 11086 } 11087 11088 return true; 11089 } 11090 11091 void cleanUpResourcesLI() { 11092 // Try enumerating all code paths before deleting 11093 List<String> allCodePaths = Collections.EMPTY_LIST; 11094 if (codeFile != null && codeFile.exists()) { 11095 try { 11096 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11097 allCodePaths = pkg.getAllCodePaths(); 11098 } catch (PackageParserException e) { 11099 // Ignored; we tried our best 11100 } 11101 } 11102 11103 cleanUp(); 11104 removeDexFiles(allCodePaths, instructionSets); 11105 } 11106 11107 boolean doPostDeleteLI(boolean delete) { 11108 // XXX err, shouldn't we respect the delete flag? 11109 cleanUpResourcesLI(); 11110 return true; 11111 } 11112 } 11113 11114 private boolean isAsecExternal(String cid) { 11115 final String asecPath = PackageHelper.getSdFilesystem(cid); 11116 return !asecPath.startsWith(mAsecInternalPath); 11117 } 11118 11119 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 11120 PackageManagerException { 11121 if (copyRet < 0) { 11122 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 11123 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 11124 throw new PackageManagerException(copyRet, message); 11125 } 11126 } 11127 } 11128 11129 /** 11130 * Extract the MountService "container ID" from the full code path of an 11131 * .apk. 11132 */ 11133 static String cidFromCodePath(String fullCodePath) { 11134 int eidx = fullCodePath.lastIndexOf("/"); 11135 String subStr1 = fullCodePath.substring(0, eidx); 11136 int sidx = subStr1.lastIndexOf("/"); 11137 return subStr1.substring(sidx+1, eidx); 11138 } 11139 11140 /** 11141 * Logic to handle installation of ASEC applications, including copying and 11142 * renaming logic. 11143 */ 11144 class AsecInstallArgs extends InstallArgs { 11145 static final String RES_FILE_NAME = "pkg.apk"; 11146 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 11147 11148 String cid; 11149 String packagePath; 11150 String resourcePath; 11151 11152 /** New install */ 11153 AsecInstallArgs(InstallParams params) { 11154 super(params.origin, params.move, params.observer, params.installFlags, 11155 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11156 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11157 params.grantedRuntimePermissions); 11158 } 11159 11160 /** Existing install */ 11161 AsecInstallArgs(String fullCodePath, String[] instructionSets, 11162 boolean isExternal, boolean isForwardLocked) { 11163 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 11164 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11165 instructionSets, null, null); 11166 // Hackily pretend we're still looking at a full code path 11167 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 11168 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 11169 } 11170 11171 // Extract cid from fullCodePath 11172 int eidx = fullCodePath.lastIndexOf("/"); 11173 String subStr1 = fullCodePath.substring(0, eidx); 11174 int sidx = subStr1.lastIndexOf("/"); 11175 cid = subStr1.substring(sidx+1, eidx); 11176 setMountPath(subStr1); 11177 } 11178 11179 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 11180 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 11181 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11182 instructionSets, null, null); 11183 this.cid = cid; 11184 setMountPath(PackageHelper.getSdDir(cid)); 11185 } 11186 11187 void createCopyFile() { 11188 cid = mInstallerService.allocateExternalStageCidLegacy(); 11189 } 11190 11191 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11192 if (origin.staged) { 11193 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 11194 cid = origin.cid; 11195 setMountPath(PackageHelper.getSdDir(cid)); 11196 return PackageManager.INSTALL_SUCCEEDED; 11197 } 11198 11199 if (temp) { 11200 createCopyFile(); 11201 } else { 11202 /* 11203 * Pre-emptively destroy the container since it's destroyed if 11204 * copying fails due to it existing anyway. 11205 */ 11206 PackageHelper.destroySdDir(cid); 11207 } 11208 11209 final String newMountPath = imcs.copyPackageToContainer( 11210 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 11211 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 11212 11213 if (newMountPath != null) { 11214 setMountPath(newMountPath); 11215 return PackageManager.INSTALL_SUCCEEDED; 11216 } else { 11217 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11218 } 11219 } 11220 11221 @Override 11222 String getCodePath() { 11223 return packagePath; 11224 } 11225 11226 @Override 11227 String getResourcePath() { 11228 return resourcePath; 11229 } 11230 11231 int doPreInstall(int status) { 11232 if (status != PackageManager.INSTALL_SUCCEEDED) { 11233 // Destroy container 11234 PackageHelper.destroySdDir(cid); 11235 } else { 11236 boolean mounted = PackageHelper.isContainerMounted(cid); 11237 if (!mounted) { 11238 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 11239 Process.SYSTEM_UID); 11240 if (newMountPath != null) { 11241 setMountPath(newMountPath); 11242 } else { 11243 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11244 } 11245 } 11246 } 11247 return status; 11248 } 11249 11250 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11251 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 11252 String newMountPath = null; 11253 if (PackageHelper.isContainerMounted(cid)) { 11254 // Unmount the container 11255 if (!PackageHelper.unMountSdDir(cid)) { 11256 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 11257 return false; 11258 } 11259 } 11260 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11261 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 11262 " which might be stale. Will try to clean up."); 11263 // Clean up the stale container and proceed to recreate. 11264 if (!PackageHelper.destroySdDir(newCacheId)) { 11265 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 11266 return false; 11267 } 11268 // Successfully cleaned up stale container. Try to rename again. 11269 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11270 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 11271 + " inspite of cleaning it up."); 11272 return false; 11273 } 11274 } 11275 if (!PackageHelper.isContainerMounted(newCacheId)) { 11276 Slog.w(TAG, "Mounting container " + newCacheId); 11277 newMountPath = PackageHelper.mountSdDir(newCacheId, 11278 getEncryptKey(), Process.SYSTEM_UID); 11279 } else { 11280 newMountPath = PackageHelper.getSdDir(newCacheId); 11281 } 11282 if (newMountPath == null) { 11283 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 11284 return false; 11285 } 11286 Log.i(TAG, "Succesfully renamed " + cid + 11287 " to " + newCacheId + 11288 " at new path: " + newMountPath); 11289 cid = newCacheId; 11290 11291 final File beforeCodeFile = new File(packagePath); 11292 setMountPath(newMountPath); 11293 final File afterCodeFile = new File(packagePath); 11294 11295 // Reflect the rename in scanned details 11296 pkg.codePath = afterCodeFile.getAbsolutePath(); 11297 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11298 pkg.baseCodePath); 11299 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11300 pkg.splitCodePaths); 11301 11302 // Reflect the rename in app info 11303 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11304 pkg.applicationInfo.setCodePath(pkg.codePath); 11305 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11306 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11307 pkg.applicationInfo.setResourcePath(pkg.codePath); 11308 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11309 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11310 11311 return true; 11312 } 11313 11314 private void setMountPath(String mountPath) { 11315 final File mountFile = new File(mountPath); 11316 11317 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 11318 if (monolithicFile.exists()) { 11319 packagePath = monolithicFile.getAbsolutePath(); 11320 if (isFwdLocked()) { 11321 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 11322 } else { 11323 resourcePath = packagePath; 11324 } 11325 } else { 11326 packagePath = mountFile.getAbsolutePath(); 11327 resourcePath = packagePath; 11328 } 11329 } 11330 11331 int doPostInstall(int status, int uid) { 11332 if (status != PackageManager.INSTALL_SUCCEEDED) { 11333 cleanUp(); 11334 } else { 11335 final int groupOwner; 11336 final String protectedFile; 11337 if (isFwdLocked()) { 11338 groupOwner = UserHandle.getSharedAppGid(uid); 11339 protectedFile = RES_FILE_NAME; 11340 } else { 11341 groupOwner = -1; 11342 protectedFile = null; 11343 } 11344 11345 if (uid < Process.FIRST_APPLICATION_UID 11346 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 11347 Slog.e(TAG, "Failed to finalize " + cid); 11348 PackageHelper.destroySdDir(cid); 11349 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11350 } 11351 11352 boolean mounted = PackageHelper.isContainerMounted(cid); 11353 if (!mounted) { 11354 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 11355 } 11356 } 11357 return status; 11358 } 11359 11360 private void cleanUp() { 11361 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 11362 11363 // Destroy secure container 11364 PackageHelper.destroySdDir(cid); 11365 } 11366 11367 private List<String> getAllCodePaths() { 11368 final File codeFile = new File(getCodePath()); 11369 if (codeFile != null && codeFile.exists()) { 11370 try { 11371 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11372 return pkg.getAllCodePaths(); 11373 } catch (PackageParserException e) { 11374 // Ignored; we tried our best 11375 } 11376 } 11377 return Collections.EMPTY_LIST; 11378 } 11379 11380 void cleanUpResourcesLI() { 11381 // Enumerate all code paths before deleting 11382 cleanUpResourcesLI(getAllCodePaths()); 11383 } 11384 11385 private void cleanUpResourcesLI(List<String> allCodePaths) { 11386 cleanUp(); 11387 removeDexFiles(allCodePaths, instructionSets); 11388 } 11389 11390 String getPackageName() { 11391 return getAsecPackageName(cid); 11392 } 11393 11394 boolean doPostDeleteLI(boolean delete) { 11395 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 11396 final List<String> allCodePaths = getAllCodePaths(); 11397 boolean mounted = PackageHelper.isContainerMounted(cid); 11398 if (mounted) { 11399 // Unmount first 11400 if (PackageHelper.unMountSdDir(cid)) { 11401 mounted = false; 11402 } 11403 } 11404 if (!mounted && delete) { 11405 cleanUpResourcesLI(allCodePaths); 11406 } 11407 return !mounted; 11408 } 11409 11410 @Override 11411 int doPreCopy() { 11412 if (isFwdLocked()) { 11413 if (!PackageHelper.fixSdPermissions(cid, 11414 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 11415 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11416 } 11417 } 11418 11419 return PackageManager.INSTALL_SUCCEEDED; 11420 } 11421 11422 @Override 11423 int doPostCopy(int uid) { 11424 if (isFwdLocked()) { 11425 if (uid < Process.FIRST_APPLICATION_UID 11426 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 11427 RES_FILE_NAME)) { 11428 Slog.e(TAG, "Failed to finalize " + cid); 11429 PackageHelper.destroySdDir(cid); 11430 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11431 } 11432 } 11433 11434 return PackageManager.INSTALL_SUCCEEDED; 11435 } 11436 } 11437 11438 /** 11439 * Logic to handle movement of existing installed applications. 11440 */ 11441 class MoveInstallArgs extends InstallArgs { 11442 private File codeFile; 11443 private File resourceFile; 11444 11445 /** New install */ 11446 MoveInstallArgs(InstallParams params) { 11447 super(params.origin, params.move, params.observer, params.installFlags, 11448 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11449 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11450 params.grantedRuntimePermissions); 11451 } 11452 11453 int copyApk(IMediaContainerService imcs, boolean temp) { 11454 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 11455 + move.fromUuid + " to " + move.toUuid); 11456 synchronized (mInstaller) { 11457 if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName, 11458 move.dataAppName, move.appId, move.seinfo) != 0) { 11459 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11460 } 11461 } 11462 11463 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 11464 resourceFile = codeFile; 11465 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 11466 11467 return PackageManager.INSTALL_SUCCEEDED; 11468 } 11469 11470 int doPreInstall(int status) { 11471 if (status != PackageManager.INSTALL_SUCCEEDED) { 11472 cleanUp(move.toUuid); 11473 } 11474 return status; 11475 } 11476 11477 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11478 if (status != PackageManager.INSTALL_SUCCEEDED) { 11479 cleanUp(move.toUuid); 11480 return false; 11481 } 11482 11483 // Reflect the move in app info 11484 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11485 pkg.applicationInfo.setCodePath(pkg.codePath); 11486 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11487 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11488 pkg.applicationInfo.setResourcePath(pkg.codePath); 11489 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11490 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11491 11492 return true; 11493 } 11494 11495 int doPostInstall(int status, int uid) { 11496 if (status == PackageManager.INSTALL_SUCCEEDED) { 11497 cleanUp(move.fromUuid); 11498 } else { 11499 cleanUp(move.toUuid); 11500 } 11501 return status; 11502 } 11503 11504 @Override 11505 String getCodePath() { 11506 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11507 } 11508 11509 @Override 11510 String getResourcePath() { 11511 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11512 } 11513 11514 private boolean cleanUp(String volumeUuid) { 11515 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 11516 move.dataAppName); 11517 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 11518 synchronized (mInstallLock) { 11519 // Clean up both app data and code 11520 removeDataDirsLI(volumeUuid, move.packageName); 11521 if (codeFile.isDirectory()) { 11522 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11523 } else { 11524 codeFile.delete(); 11525 } 11526 } 11527 return true; 11528 } 11529 11530 void cleanUpResourcesLI() { 11531 throw new UnsupportedOperationException(); 11532 } 11533 11534 boolean doPostDeleteLI(boolean delete) { 11535 throw new UnsupportedOperationException(); 11536 } 11537 } 11538 11539 static String getAsecPackageName(String packageCid) { 11540 int idx = packageCid.lastIndexOf("-"); 11541 if (idx == -1) { 11542 return packageCid; 11543 } 11544 return packageCid.substring(0, idx); 11545 } 11546 11547 // Utility method used to create code paths based on package name and available index. 11548 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 11549 String idxStr = ""; 11550 int idx = 1; 11551 // Fall back to default value of idx=1 if prefix is not 11552 // part of oldCodePath 11553 if (oldCodePath != null) { 11554 String subStr = oldCodePath; 11555 // Drop the suffix right away 11556 if (suffix != null && subStr.endsWith(suffix)) { 11557 subStr = subStr.substring(0, subStr.length() - suffix.length()); 11558 } 11559 // If oldCodePath already contains prefix find out the 11560 // ending index to either increment or decrement. 11561 int sidx = subStr.lastIndexOf(prefix); 11562 if (sidx != -1) { 11563 subStr = subStr.substring(sidx + prefix.length()); 11564 if (subStr != null) { 11565 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 11566 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 11567 } 11568 try { 11569 idx = Integer.parseInt(subStr); 11570 if (idx <= 1) { 11571 idx++; 11572 } else { 11573 idx--; 11574 } 11575 } catch(NumberFormatException e) { 11576 } 11577 } 11578 } 11579 } 11580 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 11581 return prefix + idxStr; 11582 } 11583 11584 private File getNextCodePath(File targetDir, String packageName) { 11585 int suffix = 1; 11586 File result; 11587 do { 11588 result = new File(targetDir, packageName + "-" + suffix); 11589 suffix++; 11590 } while (result.exists()); 11591 return result; 11592 } 11593 11594 // Utility method that returns the relative package path with respect 11595 // to the installation directory. Like say for /data/data/com.test-1.apk 11596 // string com.test-1 is returned. 11597 static String deriveCodePathName(String codePath) { 11598 if (codePath == null) { 11599 return null; 11600 } 11601 final File codeFile = new File(codePath); 11602 final String name = codeFile.getName(); 11603 if (codeFile.isDirectory()) { 11604 return name; 11605 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 11606 final int lastDot = name.lastIndexOf('.'); 11607 return name.substring(0, lastDot); 11608 } else { 11609 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 11610 return null; 11611 } 11612 } 11613 11614 class PackageInstalledInfo { 11615 String name; 11616 int uid; 11617 // The set of users that originally had this package installed. 11618 int[] origUsers; 11619 // The set of users that now have this package installed. 11620 int[] newUsers; 11621 PackageParser.Package pkg; 11622 int returnCode; 11623 String returnMsg; 11624 PackageRemovedInfo removedInfo; 11625 11626 public void setError(int code, String msg) { 11627 returnCode = code; 11628 returnMsg = msg; 11629 Slog.w(TAG, msg); 11630 } 11631 11632 public void setError(String msg, PackageParserException e) { 11633 returnCode = e.error; 11634 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11635 Slog.w(TAG, msg, e); 11636 } 11637 11638 public void setError(String msg, PackageManagerException e) { 11639 returnCode = e.error; 11640 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11641 Slog.w(TAG, msg, e); 11642 } 11643 11644 // In some error cases we want to convey more info back to the observer 11645 String origPackage; 11646 String origPermission; 11647 } 11648 11649 /* 11650 * Install a non-existing package. 11651 */ 11652 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11653 UserHandle user, String installerPackageName, String volumeUuid, 11654 PackageInstalledInfo res) { 11655 // Remember this for later, in case we need to rollback this install 11656 String pkgName = pkg.packageName; 11657 11658 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 11659 final boolean dataDirExists = Environment 11660 .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists(); 11661 synchronized(mPackages) { 11662 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 11663 // A package with the same name is already installed, though 11664 // it has been renamed to an older name. The package we 11665 // are trying to install should be installed as an update to 11666 // the existing one, but that has not been requested, so bail. 11667 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11668 + " without first uninstalling package running as " 11669 + mSettings.mRenamedPackages.get(pkgName)); 11670 return; 11671 } 11672 if (mPackages.containsKey(pkgName)) { 11673 // Don't allow installation over an existing package with the same name. 11674 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11675 + " without first uninstalling."); 11676 return; 11677 } 11678 } 11679 11680 try { 11681 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 11682 System.currentTimeMillis(), user); 11683 11684 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 11685 // delete the partially installed application. the data directory will have to be 11686 // restored if it was already existing 11687 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11688 // remove package from internal structures. Note that we want deletePackageX to 11689 // delete the package data and cache directories that it created in 11690 // scanPackageLocked, unless those directories existed before we even tried to 11691 // install. 11692 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 11693 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 11694 res.removedInfo, true); 11695 } 11696 11697 } catch (PackageManagerException e) { 11698 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11699 } 11700 } 11701 11702 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 11703 // Can't rotate keys during boot or if sharedUser. 11704 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 11705 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 11706 return false; 11707 } 11708 // app is using upgradeKeySets; make sure all are valid 11709 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11710 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 11711 for (int i = 0; i < upgradeKeySets.length; i++) { 11712 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 11713 Slog.wtf(TAG, "Package " 11714 + (oldPs.name != null ? oldPs.name : "<null>") 11715 + " contains upgrade-key-set reference to unknown key-set: " 11716 + upgradeKeySets[i] 11717 + " reverting to signatures check."); 11718 return false; 11719 } 11720 } 11721 return true; 11722 } 11723 11724 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 11725 // Upgrade keysets are being used. Determine if new package has a superset of the 11726 // required keys. 11727 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 11728 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11729 for (int i = 0; i < upgradeKeySets.length; i++) { 11730 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 11731 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 11732 return true; 11733 } 11734 } 11735 return false; 11736 } 11737 11738 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11739 UserHandle user, String installerPackageName, String volumeUuid, 11740 PackageInstalledInfo res) { 11741 final PackageParser.Package oldPackage; 11742 final String pkgName = pkg.packageName; 11743 final int[] allUsers; 11744 final boolean[] perUserInstalled; 11745 final boolean weFroze; 11746 11747 // First find the old package info and check signatures 11748 synchronized(mPackages) { 11749 oldPackage = mPackages.get(pkgName); 11750 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 11751 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11752 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 11753 if(!checkUpgradeKeySetLP(ps, pkg)) { 11754 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11755 "New package not signed by keys specified by upgrade-keysets: " 11756 + pkgName); 11757 return; 11758 } 11759 } else { 11760 // default to original signature matching 11761 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 11762 != PackageManager.SIGNATURE_MATCH) { 11763 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11764 "New package has a different signature: " + pkgName); 11765 return; 11766 } 11767 } 11768 11769 // In case of rollback, remember per-user/profile install state 11770 allUsers = sUserManager.getUserIds(); 11771 perUserInstalled = new boolean[allUsers.length]; 11772 for (int i = 0; i < allUsers.length; i++) { 11773 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11774 } 11775 11776 // Mark the app as frozen to prevent launching during the upgrade 11777 // process, and then kill all running instances 11778 if (!ps.frozen) { 11779 ps.frozen = true; 11780 weFroze = true; 11781 } else { 11782 weFroze = false; 11783 } 11784 } 11785 11786 // Now that we're guarded by frozen state, kill app during upgrade 11787 killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg"); 11788 11789 try { 11790 boolean sysPkg = (isSystemApp(oldPackage)); 11791 if (sysPkg) { 11792 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11793 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11794 } else { 11795 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11796 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11797 } 11798 } finally { 11799 // Regardless of success or failure of upgrade steps above, always 11800 // unfreeze the package if we froze it 11801 if (weFroze) { 11802 unfreezePackage(pkgName); 11803 } 11804 } 11805 } 11806 11807 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 11808 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11809 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11810 String volumeUuid, PackageInstalledInfo res) { 11811 String pkgName = deletedPackage.packageName; 11812 boolean deletedPkg = true; 11813 boolean updatedSettings = false; 11814 11815 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 11816 + deletedPackage); 11817 long origUpdateTime; 11818 if (pkg.mExtras != null) { 11819 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 11820 } else { 11821 origUpdateTime = 0; 11822 } 11823 11824 // First delete the existing package while retaining the data directory 11825 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 11826 res.removedInfo, true)) { 11827 // If the existing package wasn't successfully deleted 11828 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 11829 deletedPkg = false; 11830 } else { 11831 // Successfully deleted the old package; proceed with replace. 11832 11833 // If deleted package lived in a container, give users a chance to 11834 // relinquish resources before killing. 11835 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 11836 if (DEBUG_INSTALL) { 11837 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 11838 } 11839 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 11840 final ArrayList<String> pkgList = new ArrayList<String>(1); 11841 pkgList.add(deletedPackage.applicationInfo.packageName); 11842 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 11843 } 11844 11845 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 11846 try { 11847 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 11848 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 11849 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11850 perUserInstalled, res, user); 11851 updatedSettings = true; 11852 } catch (PackageManagerException e) { 11853 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11854 } 11855 } 11856 11857 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11858 // remove package from internal structures. Note that we want deletePackageX to 11859 // delete the package data and cache directories that it created in 11860 // scanPackageLocked, unless those directories existed before we even tried to 11861 // install. 11862 if(updatedSettings) { 11863 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 11864 deletePackageLI( 11865 pkgName, null, true, allUsers, perUserInstalled, 11866 PackageManager.DELETE_KEEP_DATA, 11867 res.removedInfo, true); 11868 } 11869 // Since we failed to install the new package we need to restore the old 11870 // package that we deleted. 11871 if (deletedPkg) { 11872 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 11873 File restoreFile = new File(deletedPackage.codePath); 11874 // Parse old package 11875 boolean oldExternal = isExternal(deletedPackage); 11876 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 11877 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 11878 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11879 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 11880 try { 11881 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 11882 } catch (PackageManagerException e) { 11883 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 11884 + e.getMessage()); 11885 return; 11886 } 11887 // Restore of old package succeeded. Update permissions. 11888 // writer 11889 synchronized (mPackages) { 11890 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 11891 UPDATE_PERMISSIONS_ALL); 11892 // can downgrade to reader 11893 mSettings.writeLPr(); 11894 } 11895 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 11896 } 11897 } 11898 } 11899 11900 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 11901 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11902 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11903 String volumeUuid, PackageInstalledInfo res) { 11904 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 11905 + ", old=" + deletedPackage); 11906 boolean disabledSystem = false; 11907 boolean updatedSettings = false; 11908 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 11909 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 11910 != 0) { 11911 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11912 } 11913 String packageName = deletedPackage.packageName; 11914 if (packageName == null) { 11915 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11916 "Attempt to delete null packageName."); 11917 return; 11918 } 11919 PackageParser.Package oldPkg; 11920 PackageSetting oldPkgSetting; 11921 // reader 11922 synchronized (mPackages) { 11923 oldPkg = mPackages.get(packageName); 11924 oldPkgSetting = mSettings.mPackages.get(packageName); 11925 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 11926 (oldPkgSetting == null)) { 11927 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11928 "Couldn't find package:" + packageName + " information"); 11929 return; 11930 } 11931 } 11932 11933 res.removedInfo.uid = oldPkg.applicationInfo.uid; 11934 res.removedInfo.removedPackage = packageName; 11935 // Remove existing system package 11936 removePackageLI(oldPkgSetting, true); 11937 // writer 11938 synchronized (mPackages) { 11939 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 11940 if (!disabledSystem && deletedPackage != null) { 11941 // We didn't need to disable the .apk as a current system package, 11942 // which means we are replacing another update that is already 11943 // installed. We need to make sure to delete the older one's .apk. 11944 res.removedInfo.args = createInstallArgsForExisting(0, 11945 deletedPackage.applicationInfo.getCodePath(), 11946 deletedPackage.applicationInfo.getResourcePath(), 11947 getAppDexInstructionSets(deletedPackage.applicationInfo)); 11948 } else { 11949 res.removedInfo.args = null; 11950 } 11951 } 11952 11953 // Successfully disabled the old package. Now proceed with re-installation 11954 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 11955 11956 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11957 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 11958 11959 PackageParser.Package newPackage = null; 11960 try { 11961 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 11962 if (newPackage.mExtras != null) { 11963 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 11964 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 11965 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 11966 11967 // is the update attempting to change shared user? that isn't going to work... 11968 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 11969 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 11970 "Forbidding shared user change from " + oldPkgSetting.sharedUser 11971 + " to " + newPkgSetting.sharedUser); 11972 updatedSettings = true; 11973 } 11974 } 11975 11976 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11977 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11978 perUserInstalled, res, user); 11979 updatedSettings = true; 11980 } 11981 11982 } catch (PackageManagerException e) { 11983 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11984 } 11985 11986 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11987 // Re installation failed. Restore old information 11988 // Remove new pkg information 11989 if (newPackage != null) { 11990 removeInstalledPackageLI(newPackage, true); 11991 } 11992 // Add back the old system package 11993 try { 11994 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 11995 } catch (PackageManagerException e) { 11996 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 11997 } 11998 // Restore the old system information in Settings 11999 synchronized (mPackages) { 12000 if (disabledSystem) { 12001 mSettings.enableSystemPackageLPw(packageName); 12002 } 12003 if (updatedSettings) { 12004 mSettings.setInstallerPackageName(packageName, 12005 oldPkgSetting.installerPackageName); 12006 } 12007 mSettings.writeLPr(); 12008 } 12009 } 12010 } 12011 12012 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 12013 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 12014 UserHandle user) { 12015 String pkgName = newPackage.packageName; 12016 synchronized (mPackages) { 12017 //write settings. the installStatus will be incomplete at this stage. 12018 //note that the new package setting would have already been 12019 //added to mPackages. It hasn't been persisted yet. 12020 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 12021 mSettings.writeLPr(); 12022 } 12023 12024 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 12025 12026 synchronized (mPackages) { 12027 updatePermissionsLPw(newPackage.packageName, newPackage, 12028 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 12029 ? UPDATE_PERMISSIONS_ALL : 0)); 12030 // For system-bundled packages, we assume that installing an upgraded version 12031 // of the package implies that the user actually wants to run that new code, 12032 // so we enable the package. 12033 PackageSetting ps = mSettings.mPackages.get(pkgName); 12034 if (ps != null) { 12035 if (isSystemApp(newPackage)) { 12036 // NB: implicit assumption that system package upgrades apply to all users 12037 if (DEBUG_INSTALL) { 12038 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 12039 } 12040 if (res.origUsers != null) { 12041 for (int userHandle : res.origUsers) { 12042 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 12043 userHandle, installerPackageName); 12044 } 12045 } 12046 // Also convey the prior install/uninstall state 12047 if (allUsers != null && perUserInstalled != null) { 12048 for (int i = 0; i < allUsers.length; i++) { 12049 if (DEBUG_INSTALL) { 12050 Slog.d(TAG, " user " + allUsers[i] 12051 + " => " + perUserInstalled[i]); 12052 } 12053 ps.setInstalled(perUserInstalled[i], allUsers[i]); 12054 } 12055 // these install state changes will be persisted in the 12056 // upcoming call to mSettings.writeLPr(). 12057 } 12058 } 12059 // It's implied that when a user requests installation, they want the app to be 12060 // installed and enabled. 12061 int userId = user.getIdentifier(); 12062 if (userId != UserHandle.USER_ALL) { 12063 ps.setInstalled(true, userId); 12064 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 12065 } 12066 } 12067 res.name = pkgName; 12068 res.uid = newPackage.applicationInfo.uid; 12069 res.pkg = newPackage; 12070 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 12071 mSettings.setInstallerPackageName(pkgName, installerPackageName); 12072 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12073 //to update install status 12074 mSettings.writeLPr(); 12075 } 12076 } 12077 12078 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 12079 final int installFlags = args.installFlags; 12080 final String installerPackageName = args.installerPackageName; 12081 final String volumeUuid = args.volumeUuid; 12082 final File tmpPackageFile = new File(args.getCodePath()); 12083 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 12084 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 12085 || (args.volumeUuid != null)); 12086 boolean replace = false; 12087 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 12088 if (args.move != null) { 12089 // moving a complete application; perfom an initial scan on the new install location 12090 scanFlags |= SCAN_INITIAL; 12091 } 12092 // Result object to be returned 12093 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12094 12095 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 12096 // Retrieve PackageSettings and parse package 12097 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 12098 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 12099 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 12100 PackageParser pp = new PackageParser(); 12101 pp.setSeparateProcesses(mSeparateProcesses); 12102 pp.setDisplayMetrics(mMetrics); 12103 12104 final PackageParser.Package pkg; 12105 try { 12106 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 12107 } catch (PackageParserException e) { 12108 res.setError("Failed parse during installPackageLI", e); 12109 return; 12110 } 12111 12112 // Mark that we have an install time CPU ABI override. 12113 pkg.cpuAbiOverride = args.abiOverride; 12114 12115 String pkgName = res.name = pkg.packageName; 12116 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 12117 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 12118 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 12119 return; 12120 } 12121 } 12122 12123 try { 12124 pp.collectCertificates(pkg, parseFlags); 12125 pp.collectManifestDigest(pkg); 12126 } catch (PackageParserException e) { 12127 res.setError("Failed collect during installPackageLI", e); 12128 return; 12129 } 12130 12131 /* If the installer passed in a manifest digest, compare it now. */ 12132 if (args.manifestDigest != null) { 12133 if (DEBUG_INSTALL) { 12134 final String parsedManifest = pkg.manifestDigest == null ? "null" 12135 : pkg.manifestDigest.toString(); 12136 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 12137 + parsedManifest); 12138 } 12139 12140 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 12141 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 12142 return; 12143 } 12144 } else if (DEBUG_INSTALL) { 12145 final String parsedManifest = pkg.manifestDigest == null 12146 ? "null" : pkg.manifestDigest.toString(); 12147 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 12148 } 12149 12150 // Get rid of all references to package scan path via parser. 12151 pp = null; 12152 String oldCodePath = null; 12153 boolean systemApp = false; 12154 synchronized (mPackages) { 12155 // Check if installing already existing package 12156 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12157 String oldName = mSettings.mRenamedPackages.get(pkgName); 12158 if (pkg.mOriginalPackages != null 12159 && pkg.mOriginalPackages.contains(oldName) 12160 && mPackages.containsKey(oldName)) { 12161 // This package is derived from an original package, 12162 // and this device has been updating from that original 12163 // name. We must continue using the original name, so 12164 // rename the new package here. 12165 pkg.setPackageName(oldName); 12166 pkgName = pkg.packageName; 12167 replace = true; 12168 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 12169 + oldName + " pkgName=" + pkgName); 12170 } else if (mPackages.containsKey(pkgName)) { 12171 // This package, under its official name, already exists 12172 // on the device; we should replace it. 12173 replace = true; 12174 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 12175 } 12176 12177 // Prevent apps opting out from runtime permissions 12178 if (replace) { 12179 PackageParser.Package oldPackage = mPackages.get(pkgName); 12180 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 12181 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 12182 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 12183 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 12184 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 12185 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 12186 + " doesn't support runtime permissions but the old" 12187 + " target SDK " + oldTargetSdk + " does."); 12188 return; 12189 } 12190 } 12191 } 12192 12193 PackageSetting ps = mSettings.mPackages.get(pkgName); 12194 if (ps != null) { 12195 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 12196 12197 // Quick sanity check that we're signed correctly if updating; 12198 // we'll check this again later when scanning, but we want to 12199 // bail early here before tripping over redefined permissions. 12200 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12201 if (!checkUpgradeKeySetLP(ps, pkg)) { 12202 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 12203 + pkg.packageName + " upgrade keys do not match the " 12204 + "previously installed version"); 12205 return; 12206 } 12207 } else { 12208 try { 12209 verifySignaturesLP(ps, pkg); 12210 } catch (PackageManagerException e) { 12211 res.setError(e.error, e.getMessage()); 12212 return; 12213 } 12214 } 12215 12216 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 12217 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 12218 systemApp = (ps.pkg.applicationInfo.flags & 12219 ApplicationInfo.FLAG_SYSTEM) != 0; 12220 } 12221 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12222 } 12223 12224 // Check whether the newly-scanned package wants to define an already-defined perm 12225 int N = pkg.permissions.size(); 12226 for (int i = N-1; i >= 0; i--) { 12227 PackageParser.Permission perm = pkg.permissions.get(i); 12228 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 12229 if (bp != null) { 12230 // If the defining package is signed with our cert, it's okay. This 12231 // also includes the "updating the same package" case, of course. 12232 // "updating same package" could also involve key-rotation. 12233 final boolean sigsOk; 12234 if (bp.sourcePackage.equals(pkg.packageName) 12235 && (bp.packageSetting instanceof PackageSetting) 12236 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 12237 scanFlags))) { 12238 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 12239 } else { 12240 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 12241 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 12242 } 12243 if (!sigsOk) { 12244 // If the owning package is the system itself, we log but allow 12245 // install to proceed; we fail the install on all other permission 12246 // redefinitions. 12247 if (!bp.sourcePackage.equals("android")) { 12248 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 12249 + pkg.packageName + " attempting to redeclare permission " 12250 + perm.info.name + " already owned by " + bp.sourcePackage); 12251 res.origPermission = perm.info.name; 12252 res.origPackage = bp.sourcePackage; 12253 return; 12254 } else { 12255 Slog.w(TAG, "Package " + pkg.packageName 12256 + " attempting to redeclare system permission " 12257 + perm.info.name + "; ignoring new declaration"); 12258 pkg.permissions.remove(i); 12259 } 12260 } 12261 } 12262 } 12263 12264 } 12265 12266 if (systemApp && onExternal) { 12267 // Disable updates to system apps on sdcard 12268 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 12269 "Cannot install updates to system apps on sdcard"); 12270 return; 12271 } 12272 12273 if (args.move != null) { 12274 // We did an in-place move, so dex is ready to roll 12275 scanFlags |= SCAN_NO_DEX; 12276 scanFlags |= SCAN_MOVE; 12277 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 12278 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 12279 scanFlags |= SCAN_NO_DEX; 12280 12281 try { 12282 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 12283 true /* extract libs */); 12284 } catch (PackageManagerException pme) { 12285 Slog.e(TAG, "Error deriving application ABI", pme); 12286 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 12287 return; 12288 } 12289 12290 // Run dexopt before old package gets removed, to minimize time when app is unavailable 12291 int result = mPackageDexOptimizer 12292 .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */, 12293 false /* defer */, false /* inclDependencies */); 12294 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 12295 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 12296 return; 12297 } 12298 } 12299 12300 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 12301 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 12302 return; 12303 } 12304 12305 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 12306 12307 if (replace) { 12308 replacePackageLI(pkg, parseFlags, scanFlags, args.user, 12309 installerPackageName, volumeUuid, res); 12310 } else { 12311 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 12312 args.user, installerPackageName, volumeUuid, res); 12313 } 12314 synchronized (mPackages) { 12315 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12316 if (ps != null) { 12317 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12318 } 12319 } 12320 } 12321 12322 private void startIntentFilterVerifications(int userId, boolean replacing, 12323 PackageParser.Package pkg) { 12324 if (mIntentFilterVerifierComponent == null) { 12325 Slog.w(TAG, "No IntentFilter verification will not be done as " 12326 + "there is no IntentFilterVerifier available!"); 12327 return; 12328 } 12329 12330 final int verifierUid = getPackageUid( 12331 mIntentFilterVerifierComponent.getPackageName(), 12332 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 12333 12334 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 12335 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 12336 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 12337 mHandler.sendMessage(msg); 12338 } 12339 12340 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 12341 PackageParser.Package pkg) { 12342 int size = pkg.activities.size(); 12343 if (size == 0) { 12344 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12345 "No activity, so no need to verify any IntentFilter!"); 12346 return; 12347 } 12348 12349 final boolean hasDomainURLs = hasDomainURLs(pkg); 12350 if (!hasDomainURLs) { 12351 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12352 "No domain URLs, so no need to verify any IntentFilter!"); 12353 return; 12354 } 12355 12356 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 12357 + " if any IntentFilter from the " + size 12358 + " Activities needs verification ..."); 12359 12360 int count = 0; 12361 final String packageName = pkg.packageName; 12362 12363 synchronized (mPackages) { 12364 // If this is a new install and we see that we've already run verification for this 12365 // package, we have nothing to do: it means the state was restored from backup. 12366 if (!replacing) { 12367 IntentFilterVerificationInfo ivi = 12368 mSettings.getIntentFilterVerificationLPr(packageName); 12369 if (ivi != null) { 12370 if (DEBUG_DOMAIN_VERIFICATION) { 12371 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 12372 + ivi.getStatusString()); 12373 } 12374 return; 12375 } 12376 } 12377 12378 // If any filters need to be verified, then all need to be. 12379 boolean needToVerify = false; 12380 for (PackageParser.Activity a : pkg.activities) { 12381 for (ActivityIntentInfo filter : a.intents) { 12382 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 12383 if (DEBUG_DOMAIN_VERIFICATION) { 12384 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 12385 } 12386 needToVerify = true; 12387 break; 12388 } 12389 } 12390 } 12391 12392 if (needToVerify) { 12393 final int verificationId = mIntentFilterVerificationToken++; 12394 for (PackageParser.Activity a : pkg.activities) { 12395 for (ActivityIntentInfo filter : a.intents) { 12396 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 12397 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12398 "Verification needed for IntentFilter:" + filter.toString()); 12399 mIntentFilterVerifier.addOneIntentFilterVerification( 12400 verifierUid, userId, verificationId, filter, packageName); 12401 count++; 12402 } 12403 } 12404 } 12405 } 12406 } 12407 12408 if (count > 0) { 12409 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 12410 + " IntentFilter verification" + (count > 1 ? "s" : "") 12411 + " for userId:" + userId); 12412 mIntentFilterVerifier.startVerifications(userId); 12413 } else { 12414 if (DEBUG_DOMAIN_VERIFICATION) { 12415 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 12416 } 12417 } 12418 } 12419 12420 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 12421 final ComponentName cn = filter.activity.getComponentName(); 12422 final String packageName = cn.getPackageName(); 12423 12424 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 12425 packageName); 12426 if (ivi == null) { 12427 return true; 12428 } 12429 int status = ivi.getStatus(); 12430 switch (status) { 12431 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 12432 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 12433 return true; 12434 12435 default: 12436 // Nothing to do 12437 return false; 12438 } 12439 } 12440 12441 private static boolean isMultiArch(PackageSetting ps) { 12442 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12443 } 12444 12445 private static boolean isMultiArch(ApplicationInfo info) { 12446 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12447 } 12448 12449 private static boolean isExternal(PackageParser.Package pkg) { 12450 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12451 } 12452 12453 private static boolean isExternal(PackageSetting ps) { 12454 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12455 } 12456 12457 private static boolean isExternal(ApplicationInfo info) { 12458 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12459 } 12460 12461 private static boolean isSystemApp(PackageParser.Package pkg) { 12462 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 12463 } 12464 12465 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 12466 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 12467 } 12468 12469 private static boolean hasDomainURLs(PackageParser.Package pkg) { 12470 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 12471 } 12472 12473 private static boolean isSystemApp(PackageSetting ps) { 12474 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 12475 } 12476 12477 private static boolean isUpdatedSystemApp(PackageSetting ps) { 12478 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 12479 } 12480 12481 private int packageFlagsToInstallFlags(PackageSetting ps) { 12482 int installFlags = 0; 12483 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 12484 // This existing package was an external ASEC install when we have 12485 // the external flag without a UUID 12486 installFlags |= PackageManager.INSTALL_EXTERNAL; 12487 } 12488 if (ps.isForwardLocked()) { 12489 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12490 } 12491 return installFlags; 12492 } 12493 12494 private void deleteTempPackageFiles() { 12495 final FilenameFilter filter = new FilenameFilter() { 12496 public boolean accept(File dir, String name) { 12497 return name.startsWith("vmdl") && name.endsWith(".tmp"); 12498 } 12499 }; 12500 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 12501 file.delete(); 12502 } 12503 } 12504 12505 @Override 12506 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 12507 int flags) { 12508 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 12509 flags); 12510 } 12511 12512 @Override 12513 public void deletePackage(final String packageName, 12514 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 12515 mContext.enforceCallingOrSelfPermission( 12516 android.Manifest.permission.DELETE_PACKAGES, null); 12517 Preconditions.checkNotNull(packageName); 12518 Preconditions.checkNotNull(observer); 12519 final int uid = Binder.getCallingUid(); 12520 if (UserHandle.getUserId(uid) != userId) { 12521 mContext.enforceCallingPermission( 12522 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 12523 "deletePackage for user " + userId); 12524 } 12525 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 12526 try { 12527 observer.onPackageDeleted(packageName, 12528 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 12529 } catch (RemoteException re) { 12530 } 12531 return; 12532 } 12533 12534 boolean uninstallBlocked = false; 12535 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 12536 int[] users = sUserManager.getUserIds(); 12537 for (int i = 0; i < users.length; ++i) { 12538 if (getBlockUninstallForUser(packageName, users[i])) { 12539 uninstallBlocked = true; 12540 break; 12541 } 12542 } 12543 } else { 12544 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 12545 } 12546 if (uninstallBlocked) { 12547 try { 12548 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 12549 null); 12550 } catch (RemoteException re) { 12551 } 12552 return; 12553 } 12554 12555 if (DEBUG_REMOVE) { 12556 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 12557 } 12558 // Queue up an async operation since the package deletion may take a little while. 12559 mHandler.post(new Runnable() { 12560 public void run() { 12561 mHandler.removeCallbacks(this); 12562 final int returnCode = deletePackageX(packageName, userId, flags); 12563 if (observer != null) { 12564 try { 12565 observer.onPackageDeleted(packageName, returnCode, null); 12566 } catch (RemoteException e) { 12567 Log.i(TAG, "Observer no longer exists."); 12568 } //end catch 12569 } //end if 12570 } //end run 12571 }); 12572 } 12573 12574 private boolean isPackageDeviceAdmin(String packageName, int userId) { 12575 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 12576 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 12577 try { 12578 if (dpm != null) { 12579 if (dpm.isDeviceOwner(packageName)) { 12580 return true; 12581 } 12582 int[] users; 12583 if (userId == UserHandle.USER_ALL) { 12584 users = sUserManager.getUserIds(); 12585 } else { 12586 users = new int[]{userId}; 12587 } 12588 for (int i = 0; i < users.length; ++i) { 12589 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 12590 return true; 12591 } 12592 } 12593 } 12594 } catch (RemoteException e) { 12595 } 12596 return false; 12597 } 12598 12599 /** 12600 * This method is an internal method that could be get invoked either 12601 * to delete an installed package or to clean up a failed installation. 12602 * After deleting an installed package, a broadcast is sent to notify any 12603 * listeners that the package has been installed. For cleaning up a failed 12604 * installation, the broadcast is not necessary since the package's 12605 * installation wouldn't have sent the initial broadcast either 12606 * The key steps in deleting a package are 12607 * deleting the package information in internal structures like mPackages, 12608 * deleting the packages base directories through installd 12609 * updating mSettings to reflect current status 12610 * persisting settings for later use 12611 * sending a broadcast if necessary 12612 */ 12613 private int deletePackageX(String packageName, int userId, int flags) { 12614 final PackageRemovedInfo info = new PackageRemovedInfo(); 12615 final boolean res; 12616 12617 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 12618 ? UserHandle.ALL : new UserHandle(userId); 12619 12620 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 12621 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 12622 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 12623 } 12624 12625 boolean removedForAllUsers = false; 12626 boolean systemUpdate = false; 12627 12628 // for the uninstall-updates case and restricted profiles, remember the per- 12629 // userhandle installed state 12630 int[] allUsers; 12631 boolean[] perUserInstalled; 12632 synchronized (mPackages) { 12633 PackageSetting ps = mSettings.mPackages.get(packageName); 12634 allUsers = sUserManager.getUserIds(); 12635 perUserInstalled = new boolean[allUsers.length]; 12636 for (int i = 0; i < allUsers.length; i++) { 12637 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12638 } 12639 } 12640 12641 synchronized (mInstallLock) { 12642 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 12643 res = deletePackageLI(packageName, removeForUser, 12644 true, allUsers, perUserInstalled, 12645 flags | REMOVE_CHATTY, info, true); 12646 systemUpdate = info.isRemovedPackageSystemUpdate; 12647 if (res && !systemUpdate && mPackages.get(packageName) == null) { 12648 removedForAllUsers = true; 12649 } 12650 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 12651 + " removedForAllUsers=" + removedForAllUsers); 12652 } 12653 12654 if (res) { 12655 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 12656 12657 // If the removed package was a system update, the old system package 12658 // was re-enabled; we need to broadcast this information 12659 if (systemUpdate) { 12660 Bundle extras = new Bundle(1); 12661 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 12662 ? info.removedAppId : info.uid); 12663 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12664 12665 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 12666 extras, null, null, null); 12667 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 12668 extras, null, null, null); 12669 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 12670 null, packageName, null, null); 12671 } 12672 } 12673 // Force a gc here. 12674 Runtime.getRuntime().gc(); 12675 // Delete the resources here after sending the broadcast to let 12676 // other processes clean up before deleting resources. 12677 if (info.args != null) { 12678 synchronized (mInstallLock) { 12679 info.args.doPostDeleteLI(true); 12680 } 12681 } 12682 12683 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 12684 } 12685 12686 class PackageRemovedInfo { 12687 String removedPackage; 12688 int uid = -1; 12689 int removedAppId = -1; 12690 int[] removedUsers = null; 12691 boolean isRemovedPackageSystemUpdate = false; 12692 // Clean up resources deleted packages. 12693 InstallArgs args = null; 12694 12695 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 12696 Bundle extras = new Bundle(1); 12697 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 12698 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 12699 if (replacing) { 12700 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12701 } 12702 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 12703 if (removedPackage != null) { 12704 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 12705 extras, null, null, removedUsers); 12706 if (fullRemove && !replacing) { 12707 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 12708 extras, null, null, removedUsers); 12709 } 12710 } 12711 if (removedAppId >= 0) { 12712 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 12713 removedUsers); 12714 } 12715 } 12716 } 12717 12718 /* 12719 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 12720 * flag is not set, the data directory is removed as well. 12721 * make sure this flag is set for partially installed apps. If not its meaningless to 12722 * delete a partially installed application. 12723 */ 12724 private void removePackageDataLI(PackageSetting ps, 12725 int[] allUserHandles, boolean[] perUserInstalled, 12726 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 12727 String packageName = ps.name; 12728 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 12729 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 12730 // Retrieve object to delete permissions for shared user later on 12731 final PackageSetting deletedPs; 12732 // reader 12733 synchronized (mPackages) { 12734 deletedPs = mSettings.mPackages.get(packageName); 12735 if (outInfo != null) { 12736 outInfo.removedPackage = packageName; 12737 outInfo.removedUsers = deletedPs != null 12738 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 12739 : null; 12740 } 12741 } 12742 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12743 removeDataDirsLI(ps.volumeUuid, packageName); 12744 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 12745 } 12746 // writer 12747 synchronized (mPackages) { 12748 if (deletedPs != null) { 12749 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12750 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 12751 clearDefaultBrowserIfNeeded(packageName); 12752 if (outInfo != null) { 12753 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 12754 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 12755 } 12756 updatePermissionsLPw(deletedPs.name, null, 0); 12757 if (deletedPs.sharedUser != null) { 12758 // Remove permissions associated with package. Since runtime 12759 // permissions are per user we have to kill the removed package 12760 // or packages running under the shared user of the removed 12761 // package if revoking the permissions requested only by the removed 12762 // package is successful and this causes a change in gids. 12763 for (int userId : UserManagerService.getInstance().getUserIds()) { 12764 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 12765 userId); 12766 if (userIdToKill == UserHandle.USER_ALL 12767 || userIdToKill >= UserHandle.USER_OWNER) { 12768 // If gids changed for this user, kill all affected packages. 12769 mHandler.post(new Runnable() { 12770 @Override 12771 public void run() { 12772 // This has to happen with no lock held. 12773 killSettingPackagesForUser(deletedPs, userIdToKill, 12774 KILL_APP_REASON_GIDS_CHANGED); 12775 } 12776 }); 12777 break; 12778 } 12779 } 12780 } 12781 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 12782 } 12783 // make sure to preserve per-user disabled state if this removal was just 12784 // a downgrade of a system app to the factory package 12785 if (allUserHandles != null && perUserInstalled != null) { 12786 if (DEBUG_REMOVE) { 12787 Slog.d(TAG, "Propagating install state across downgrade"); 12788 } 12789 for (int i = 0; i < allUserHandles.length; i++) { 12790 if (DEBUG_REMOVE) { 12791 Slog.d(TAG, " user " + allUserHandles[i] 12792 + " => " + perUserInstalled[i]); 12793 } 12794 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12795 } 12796 } 12797 } 12798 // can downgrade to reader 12799 if (writeSettings) { 12800 // Save settings now 12801 mSettings.writeLPr(); 12802 } 12803 } 12804 if (outInfo != null) { 12805 // A user ID was deleted here. Go through all users and remove it 12806 // from KeyStore. 12807 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 12808 } 12809 } 12810 12811 static boolean locationIsPrivileged(File path) { 12812 try { 12813 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 12814 .getCanonicalPath(); 12815 return path.getCanonicalPath().startsWith(privilegedAppDir); 12816 } catch (IOException e) { 12817 Slog.e(TAG, "Unable to access code path " + path); 12818 } 12819 return false; 12820 } 12821 12822 /* 12823 * Tries to delete system package. 12824 */ 12825 private boolean deleteSystemPackageLI(PackageSetting newPs, 12826 int[] allUserHandles, boolean[] perUserInstalled, 12827 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 12828 final boolean applyUserRestrictions 12829 = (allUserHandles != null) && (perUserInstalled != null); 12830 PackageSetting disabledPs = null; 12831 // Confirm if the system package has been updated 12832 // An updated system app can be deleted. This will also have to restore 12833 // the system pkg from system partition 12834 // reader 12835 synchronized (mPackages) { 12836 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 12837 } 12838 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 12839 + " disabledPs=" + disabledPs); 12840 if (disabledPs == null) { 12841 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 12842 return false; 12843 } else if (DEBUG_REMOVE) { 12844 Slog.d(TAG, "Deleting system pkg from data partition"); 12845 } 12846 if (DEBUG_REMOVE) { 12847 if (applyUserRestrictions) { 12848 Slog.d(TAG, "Remembering install states:"); 12849 for (int i = 0; i < allUserHandles.length; i++) { 12850 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 12851 } 12852 } 12853 } 12854 // Delete the updated package 12855 outInfo.isRemovedPackageSystemUpdate = true; 12856 if (disabledPs.versionCode < newPs.versionCode) { 12857 // Delete data for downgrades 12858 flags &= ~PackageManager.DELETE_KEEP_DATA; 12859 } else { 12860 // Preserve data by setting flag 12861 flags |= PackageManager.DELETE_KEEP_DATA; 12862 } 12863 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 12864 allUserHandles, perUserInstalled, outInfo, writeSettings); 12865 if (!ret) { 12866 return false; 12867 } 12868 // writer 12869 synchronized (mPackages) { 12870 // Reinstate the old system package 12871 mSettings.enableSystemPackageLPw(newPs.name); 12872 // Remove any native libraries from the upgraded package. 12873 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 12874 } 12875 // Install the system package 12876 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 12877 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 12878 if (locationIsPrivileged(disabledPs.codePath)) { 12879 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12880 } 12881 12882 final PackageParser.Package newPkg; 12883 try { 12884 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 12885 } catch (PackageManagerException e) { 12886 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 12887 return false; 12888 } 12889 12890 // writer 12891 synchronized (mPackages) { 12892 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 12893 12894 // Propagate the permissions state as we do want to drop on the floor 12895 // runtime permissions. The update permissions method below will take 12896 // care of removing obsolete permissions and grant install permissions. 12897 ps.getPermissionsState().copyFrom(disabledPs.getPermissionsState()); 12898 updatePermissionsLPw(newPkg.packageName, newPkg, 12899 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 12900 12901 if (applyUserRestrictions) { 12902 if (DEBUG_REMOVE) { 12903 Slog.d(TAG, "Propagating install state across reinstall"); 12904 } 12905 for (int i = 0; i < allUserHandles.length; i++) { 12906 if (DEBUG_REMOVE) { 12907 Slog.d(TAG, " user " + allUserHandles[i] 12908 + " => " + perUserInstalled[i]); 12909 } 12910 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12911 } 12912 // Regardless of writeSettings we need to ensure that this restriction 12913 // state propagation is persisted 12914 mSettings.writeAllUsersPackageRestrictionsLPr(); 12915 } 12916 // can downgrade to reader here 12917 if (writeSettings) { 12918 mSettings.writeLPr(); 12919 } 12920 } 12921 return true; 12922 } 12923 12924 private boolean deleteInstalledPackageLI(PackageSetting ps, 12925 boolean deleteCodeAndResources, int flags, 12926 int[] allUserHandles, boolean[] perUserInstalled, 12927 PackageRemovedInfo outInfo, boolean writeSettings) { 12928 if (outInfo != null) { 12929 outInfo.uid = ps.appId; 12930 } 12931 12932 // Delete package data from internal structures and also remove data if flag is set 12933 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 12934 12935 // Delete application code and resources 12936 if (deleteCodeAndResources && (outInfo != null)) { 12937 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 12938 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 12939 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 12940 } 12941 return true; 12942 } 12943 12944 @Override 12945 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 12946 int userId) { 12947 mContext.enforceCallingOrSelfPermission( 12948 android.Manifest.permission.DELETE_PACKAGES, null); 12949 synchronized (mPackages) { 12950 PackageSetting ps = mSettings.mPackages.get(packageName); 12951 if (ps == null) { 12952 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 12953 return false; 12954 } 12955 if (!ps.getInstalled(userId)) { 12956 // Can't block uninstall for an app that is not installed or enabled. 12957 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 12958 return false; 12959 } 12960 ps.setBlockUninstall(blockUninstall, userId); 12961 mSettings.writePackageRestrictionsLPr(userId); 12962 } 12963 return true; 12964 } 12965 12966 @Override 12967 public boolean getBlockUninstallForUser(String packageName, int userId) { 12968 synchronized (mPackages) { 12969 PackageSetting ps = mSettings.mPackages.get(packageName); 12970 if (ps == null) { 12971 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 12972 return false; 12973 } 12974 return ps.getBlockUninstall(userId); 12975 } 12976 } 12977 12978 /* 12979 * This method handles package deletion in general 12980 */ 12981 private boolean deletePackageLI(String packageName, UserHandle user, 12982 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 12983 int flags, PackageRemovedInfo outInfo, 12984 boolean writeSettings) { 12985 if (packageName == null) { 12986 Slog.w(TAG, "Attempt to delete null packageName."); 12987 return false; 12988 } 12989 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 12990 PackageSetting ps; 12991 boolean dataOnly = false; 12992 int removeUser = -1; 12993 int appId = -1; 12994 synchronized (mPackages) { 12995 ps = mSettings.mPackages.get(packageName); 12996 if (ps == null) { 12997 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12998 return false; 12999 } 13000 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 13001 && user.getIdentifier() != UserHandle.USER_ALL) { 13002 // The caller is asking that the package only be deleted for a single 13003 // user. To do this, we just mark its uninstalled state and delete 13004 // its data. If this is a system app, we only allow this to happen if 13005 // they have set the special DELETE_SYSTEM_APP which requests different 13006 // semantics than normal for uninstalling system apps. 13007 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 13008 ps.setUserState(user.getIdentifier(), 13009 COMPONENT_ENABLED_STATE_DEFAULT, 13010 false, //installed 13011 true, //stopped 13012 true, //notLaunched 13013 false, //hidden 13014 null, null, null, 13015 false, // blockUninstall 13016 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED, 0); 13017 if (!isSystemApp(ps)) { 13018 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 13019 // Other user still have this package installed, so all 13020 // we need to do is clear this user's data and save that 13021 // it is uninstalled. 13022 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 13023 removeUser = user.getIdentifier(); 13024 appId = ps.appId; 13025 scheduleWritePackageRestrictionsLocked(removeUser); 13026 } else { 13027 // We need to set it back to 'installed' so the uninstall 13028 // broadcasts will be sent correctly. 13029 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 13030 ps.setInstalled(true, user.getIdentifier()); 13031 } 13032 } else { 13033 // This is a system app, so we assume that the 13034 // other users still have this package installed, so all 13035 // we need to do is clear this user's data and save that 13036 // it is uninstalled. 13037 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 13038 removeUser = user.getIdentifier(); 13039 appId = ps.appId; 13040 scheduleWritePackageRestrictionsLocked(removeUser); 13041 } 13042 } 13043 } 13044 13045 if (removeUser >= 0) { 13046 // From above, we determined that we are deleting this only 13047 // for a single user. Continue the work here. 13048 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 13049 if (outInfo != null) { 13050 outInfo.removedPackage = packageName; 13051 outInfo.removedAppId = appId; 13052 outInfo.removedUsers = new int[] {removeUser}; 13053 } 13054 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 13055 removeKeystoreDataIfNeeded(removeUser, appId); 13056 schedulePackageCleaning(packageName, removeUser, false); 13057 synchronized (mPackages) { 13058 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 13059 scheduleWritePackageRestrictionsLocked(removeUser); 13060 } 13061 resetUserChangesToRuntimePermissionsAndFlagsLocked(ps, removeUser); 13062 } 13063 return true; 13064 } 13065 13066 if (dataOnly) { 13067 // Delete application data first 13068 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 13069 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 13070 return true; 13071 } 13072 13073 boolean ret = false; 13074 if (isSystemApp(ps)) { 13075 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 13076 // When an updated system application is deleted we delete the existing resources as well and 13077 // fall back to existing code in system partition 13078 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 13079 flags, outInfo, writeSettings); 13080 } else { 13081 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 13082 // Kill application pre-emptively especially for apps on sd. 13083 killApplication(packageName, ps.appId, "uninstall pkg"); 13084 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 13085 allUserHandles, perUserInstalled, 13086 outInfo, writeSettings); 13087 } 13088 13089 return ret; 13090 } 13091 13092 private final class ClearStorageConnection implements ServiceConnection { 13093 IMediaContainerService mContainerService; 13094 13095 @Override 13096 public void onServiceConnected(ComponentName name, IBinder service) { 13097 synchronized (this) { 13098 mContainerService = IMediaContainerService.Stub.asInterface(service); 13099 notifyAll(); 13100 } 13101 } 13102 13103 @Override 13104 public void onServiceDisconnected(ComponentName name) { 13105 } 13106 } 13107 13108 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 13109 final boolean mounted; 13110 if (Environment.isExternalStorageEmulated()) { 13111 mounted = true; 13112 } else { 13113 final String status = Environment.getExternalStorageState(); 13114 13115 mounted = status.equals(Environment.MEDIA_MOUNTED) 13116 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 13117 } 13118 13119 if (!mounted) { 13120 return; 13121 } 13122 13123 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 13124 int[] users; 13125 if (userId == UserHandle.USER_ALL) { 13126 users = sUserManager.getUserIds(); 13127 } else { 13128 users = new int[] { userId }; 13129 } 13130 final ClearStorageConnection conn = new ClearStorageConnection(); 13131 if (mContext.bindServiceAsUser( 13132 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 13133 try { 13134 for (int curUser : users) { 13135 long timeout = SystemClock.uptimeMillis() + 5000; 13136 synchronized (conn) { 13137 long now = SystemClock.uptimeMillis(); 13138 while (conn.mContainerService == null && now < timeout) { 13139 try { 13140 conn.wait(timeout - now); 13141 } catch (InterruptedException e) { 13142 } 13143 } 13144 } 13145 if (conn.mContainerService == null) { 13146 return; 13147 } 13148 13149 final UserEnvironment userEnv = new UserEnvironment(curUser); 13150 clearDirectory(conn.mContainerService, 13151 userEnv.buildExternalStorageAppCacheDirs(packageName)); 13152 if (allData) { 13153 clearDirectory(conn.mContainerService, 13154 userEnv.buildExternalStorageAppDataDirs(packageName)); 13155 clearDirectory(conn.mContainerService, 13156 userEnv.buildExternalStorageAppMediaDirs(packageName)); 13157 } 13158 } 13159 } finally { 13160 mContext.unbindService(conn); 13161 } 13162 } 13163 } 13164 13165 @Override 13166 public void clearApplicationUserData(final String packageName, 13167 final IPackageDataObserver observer, final int userId) { 13168 mContext.enforceCallingOrSelfPermission( 13169 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 13170 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 13171 // Queue up an async operation since the package deletion may take a little while. 13172 mHandler.post(new Runnable() { 13173 public void run() { 13174 mHandler.removeCallbacks(this); 13175 final boolean succeeded; 13176 synchronized (mInstallLock) { 13177 succeeded = clearApplicationUserDataLI(packageName, userId); 13178 } 13179 clearExternalStorageDataSync(packageName, userId, true); 13180 if (succeeded) { 13181 // invoke DeviceStorageMonitor's update method to clear any notifications 13182 DeviceStorageMonitorInternal 13183 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13184 if (dsm != null) { 13185 dsm.checkMemory(); 13186 } 13187 } 13188 if(observer != null) { 13189 try { 13190 observer.onRemoveCompleted(packageName, succeeded); 13191 } catch (RemoteException e) { 13192 Log.i(TAG, "Observer no longer exists."); 13193 } 13194 } //end if observer 13195 } //end run 13196 }); 13197 } 13198 13199 private boolean clearApplicationUserDataLI(String packageName, int userId) { 13200 if (packageName == null) { 13201 Slog.w(TAG, "Attempt to delete null packageName."); 13202 return false; 13203 } 13204 13205 // Try finding details about the requested package 13206 PackageParser.Package pkg; 13207 synchronized (mPackages) { 13208 pkg = mPackages.get(packageName); 13209 if (pkg == null) { 13210 final PackageSetting ps = mSettings.mPackages.get(packageName); 13211 if (ps != null) { 13212 pkg = ps.pkg; 13213 } 13214 } 13215 13216 if (pkg == null) { 13217 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13218 return false; 13219 } 13220 13221 PackageSetting ps = (PackageSetting) pkg.mExtras; 13222 resetUserChangesToRuntimePermissionsAndFlagsLocked(ps, userId); 13223 } 13224 13225 // Always delete data directories for package, even if we found no other 13226 // record of app. This helps users recover from UID mismatches without 13227 // resorting to a full data wipe. 13228 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 13229 if (retCode < 0) { 13230 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 13231 return false; 13232 } 13233 13234 final int appId = pkg.applicationInfo.uid; 13235 removeKeystoreDataIfNeeded(userId, appId); 13236 13237 // Create a native library symlink only if we have native libraries 13238 // and if the native libraries are 32 bit libraries. We do not provide 13239 // this symlink for 64 bit libraries. 13240 if (pkg.applicationInfo.primaryCpuAbi != null && 13241 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 13242 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 13243 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 13244 nativeLibPath, userId) < 0) { 13245 Slog.w(TAG, "Failed linking native library dir"); 13246 return false; 13247 } 13248 } 13249 13250 return true; 13251 } 13252 13253 /** 13254 * Reverts user permission state changes (permissions and flags). 13255 * 13256 * @param ps The package for which to reset. 13257 * @param userId The device user for which to do a reset. 13258 */ 13259 private void resetUserChangesToRuntimePermissionsAndFlagsLocked( 13260 final PackageSetting ps, final int userId) { 13261 if (ps.pkg == null) { 13262 return; 13263 } 13264 13265 final int userSettableFlags = FLAG_PERMISSION_USER_SET 13266 | FLAG_PERMISSION_USER_FIXED 13267 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 13268 13269 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 13270 | FLAG_PERMISSION_POLICY_FIXED; 13271 13272 boolean writeInstallPermissions = false; 13273 boolean writeRuntimePermissions = false; 13274 13275 final int permissionCount = ps.pkg.requestedPermissions.size(); 13276 for (int i = 0; i < permissionCount; i++) { 13277 String permission = ps.pkg.requestedPermissions.get(i); 13278 13279 BasePermission bp = mSettings.mPermissions.get(permission); 13280 if (bp == null) { 13281 continue; 13282 } 13283 13284 // If shared user we just reset the state to which only this app contributed. 13285 if (ps.sharedUser != null) { 13286 boolean used = false; 13287 final int packageCount = ps.sharedUser.packages.size(); 13288 for (int j = 0; j < packageCount; j++) { 13289 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 13290 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 13291 && pkg.pkg.requestedPermissions.contains(permission)) { 13292 used = true; 13293 break; 13294 } 13295 } 13296 if (used) { 13297 continue; 13298 } 13299 } 13300 13301 PermissionsState permissionsState = ps.getPermissionsState(); 13302 13303 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 13304 13305 // Always clear the user settable flags. 13306 final boolean hasInstallState = permissionsState.getInstallPermissionState( 13307 bp.name) != null; 13308 if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) { 13309 if (hasInstallState) { 13310 writeInstallPermissions = true; 13311 } else { 13312 writeRuntimePermissions = true; 13313 } 13314 } 13315 13316 // Below is only runtime permission handling. 13317 if (!bp.isRuntime()) { 13318 continue; 13319 } 13320 13321 // Never clobber system or policy. 13322 if ((oldFlags & policyOrSystemFlags) != 0) { 13323 continue; 13324 } 13325 13326 // If this permission was granted by default, make sure it is. 13327 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 13328 if (permissionsState.grantRuntimePermission(bp, userId) 13329 != PERMISSION_OPERATION_FAILURE) { 13330 writeRuntimePermissions = true; 13331 } 13332 } else { 13333 // Otherwise, reset the permission. 13334 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 13335 switch (revokeResult) { 13336 case PERMISSION_OPERATION_SUCCESS: { 13337 writeRuntimePermissions = true; 13338 } break; 13339 13340 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 13341 writeRuntimePermissions = true; 13342 // If gids changed for this user, kill all affected packages. 13343 mHandler.post(new Runnable() { 13344 @Override 13345 public void run() { 13346 // This has to happen with no lock held. 13347 killSettingPackagesForUser(ps, userId, 13348 KILL_APP_REASON_GIDS_CHANGED); 13349 } 13350 }); 13351 } break; 13352 } 13353 } 13354 } 13355 13356 // Synchronously write as we are taking permissions away. 13357 if (writeRuntimePermissions) { 13358 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 13359 } 13360 13361 // Synchronously write as we are taking permissions away. 13362 if (writeInstallPermissions) { 13363 mSettings.writeLPr(); 13364 } 13365 } 13366 13367 /** 13368 * Remove entries from the keystore daemon. Will only remove it if the 13369 * {@code appId} is valid. 13370 */ 13371 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 13372 if (appId < 0) { 13373 return; 13374 } 13375 13376 final KeyStore keyStore = KeyStore.getInstance(); 13377 if (keyStore != null) { 13378 if (userId == UserHandle.USER_ALL) { 13379 for (final int individual : sUserManager.getUserIds()) { 13380 keyStore.clearUid(UserHandle.getUid(individual, appId)); 13381 } 13382 } else { 13383 keyStore.clearUid(UserHandle.getUid(userId, appId)); 13384 } 13385 } else { 13386 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 13387 } 13388 } 13389 13390 @Override 13391 public void deleteApplicationCacheFiles(final String packageName, 13392 final IPackageDataObserver observer) { 13393 mContext.enforceCallingOrSelfPermission( 13394 android.Manifest.permission.DELETE_CACHE_FILES, null); 13395 // Queue up an async operation since the package deletion may take a little while. 13396 final int userId = UserHandle.getCallingUserId(); 13397 mHandler.post(new Runnable() { 13398 public void run() { 13399 mHandler.removeCallbacks(this); 13400 final boolean succeded; 13401 synchronized (mInstallLock) { 13402 succeded = deleteApplicationCacheFilesLI(packageName, userId); 13403 } 13404 clearExternalStorageDataSync(packageName, userId, false); 13405 if (observer != null) { 13406 try { 13407 observer.onRemoveCompleted(packageName, succeded); 13408 } catch (RemoteException e) { 13409 Log.i(TAG, "Observer no longer exists."); 13410 } 13411 } //end if observer 13412 } //end run 13413 }); 13414 } 13415 13416 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 13417 if (packageName == null) { 13418 Slog.w(TAG, "Attempt to delete null packageName."); 13419 return false; 13420 } 13421 PackageParser.Package p; 13422 synchronized (mPackages) { 13423 p = mPackages.get(packageName); 13424 } 13425 if (p == null) { 13426 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13427 return false; 13428 } 13429 final ApplicationInfo applicationInfo = p.applicationInfo; 13430 if (applicationInfo == null) { 13431 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13432 return false; 13433 } 13434 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 13435 if (retCode < 0) { 13436 Slog.w(TAG, "Couldn't remove cache files for package: " 13437 + packageName + " u" + userId); 13438 return false; 13439 } 13440 return true; 13441 } 13442 13443 @Override 13444 public void getPackageSizeInfo(final String packageName, int userHandle, 13445 final IPackageStatsObserver observer) { 13446 mContext.enforceCallingOrSelfPermission( 13447 android.Manifest.permission.GET_PACKAGE_SIZE, null); 13448 if (packageName == null) { 13449 throw new IllegalArgumentException("Attempt to get size of null packageName"); 13450 } 13451 13452 PackageStats stats = new PackageStats(packageName, userHandle); 13453 13454 /* 13455 * Queue up an async operation since the package measurement may take a 13456 * little while. 13457 */ 13458 Message msg = mHandler.obtainMessage(INIT_COPY); 13459 msg.obj = new MeasureParams(stats, observer); 13460 mHandler.sendMessage(msg); 13461 } 13462 13463 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 13464 PackageStats pStats) { 13465 if (packageName == null) { 13466 Slog.w(TAG, "Attempt to get size of null packageName."); 13467 return false; 13468 } 13469 PackageParser.Package p; 13470 boolean dataOnly = false; 13471 String libDirRoot = null; 13472 String asecPath = null; 13473 PackageSetting ps = null; 13474 synchronized (mPackages) { 13475 p = mPackages.get(packageName); 13476 ps = mSettings.mPackages.get(packageName); 13477 if(p == null) { 13478 dataOnly = true; 13479 if((ps == null) || (ps.pkg == null)) { 13480 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13481 return false; 13482 } 13483 p = ps.pkg; 13484 } 13485 if (ps != null) { 13486 libDirRoot = ps.legacyNativeLibraryPathString; 13487 } 13488 if (p != null && (isExternal(p) || p.isForwardLocked())) { 13489 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 13490 if (secureContainerId != null) { 13491 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 13492 } 13493 } 13494 } 13495 String publicSrcDir = null; 13496 if(!dataOnly) { 13497 final ApplicationInfo applicationInfo = p.applicationInfo; 13498 if (applicationInfo == null) { 13499 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13500 return false; 13501 } 13502 if (p.isForwardLocked()) { 13503 publicSrcDir = applicationInfo.getBaseResourcePath(); 13504 } 13505 } 13506 // TODO: extend to measure size of split APKs 13507 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 13508 // not just the first level. 13509 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 13510 // just the primary. 13511 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 13512 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath, 13513 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 13514 if (res < 0) { 13515 return false; 13516 } 13517 13518 // Fix-up for forward-locked applications in ASEC containers. 13519 if (!isExternal(p)) { 13520 pStats.codeSize += pStats.externalCodeSize; 13521 pStats.externalCodeSize = 0L; 13522 } 13523 13524 return true; 13525 } 13526 13527 13528 @Override 13529 public void addPackageToPreferred(String packageName) { 13530 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 13531 } 13532 13533 @Override 13534 public void removePackageFromPreferred(String packageName) { 13535 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 13536 } 13537 13538 @Override 13539 public List<PackageInfo> getPreferredPackages(int flags) { 13540 return new ArrayList<PackageInfo>(); 13541 } 13542 13543 private int getUidTargetSdkVersionLockedLPr(int uid) { 13544 Object obj = mSettings.getUserIdLPr(uid); 13545 if (obj instanceof SharedUserSetting) { 13546 final SharedUserSetting sus = (SharedUserSetting) obj; 13547 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 13548 final Iterator<PackageSetting> it = sus.packages.iterator(); 13549 while (it.hasNext()) { 13550 final PackageSetting ps = it.next(); 13551 if (ps.pkg != null) { 13552 int v = ps.pkg.applicationInfo.targetSdkVersion; 13553 if (v < vers) vers = v; 13554 } 13555 } 13556 return vers; 13557 } else if (obj instanceof PackageSetting) { 13558 final PackageSetting ps = (PackageSetting) obj; 13559 if (ps.pkg != null) { 13560 return ps.pkg.applicationInfo.targetSdkVersion; 13561 } 13562 } 13563 return Build.VERSION_CODES.CUR_DEVELOPMENT; 13564 } 13565 13566 @Override 13567 public void addPreferredActivity(IntentFilter filter, int match, 13568 ComponentName[] set, ComponentName activity, int userId) { 13569 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13570 "Adding preferred"); 13571 } 13572 13573 private void addPreferredActivityInternal(IntentFilter filter, int match, 13574 ComponentName[] set, ComponentName activity, boolean always, int userId, 13575 String opname) { 13576 // writer 13577 int callingUid = Binder.getCallingUid(); 13578 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 13579 if (filter.countActions() == 0) { 13580 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13581 return; 13582 } 13583 synchronized (mPackages) { 13584 if (mContext.checkCallingOrSelfPermission( 13585 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13586 != PackageManager.PERMISSION_GRANTED) { 13587 if (getUidTargetSdkVersionLockedLPr(callingUid) 13588 < Build.VERSION_CODES.FROYO) { 13589 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 13590 + callingUid); 13591 return; 13592 } 13593 mContext.enforceCallingOrSelfPermission( 13594 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13595 } 13596 13597 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 13598 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 13599 + userId + ":"); 13600 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13601 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 13602 scheduleWritePackageRestrictionsLocked(userId); 13603 } 13604 } 13605 13606 @Override 13607 public void replacePreferredActivity(IntentFilter filter, int match, 13608 ComponentName[] set, ComponentName activity, int userId) { 13609 if (filter.countActions() != 1) { 13610 throw new IllegalArgumentException( 13611 "replacePreferredActivity expects filter to have only 1 action."); 13612 } 13613 if (filter.countDataAuthorities() != 0 13614 || filter.countDataPaths() != 0 13615 || filter.countDataSchemes() > 1 13616 || filter.countDataTypes() != 0) { 13617 throw new IllegalArgumentException( 13618 "replacePreferredActivity expects filter to have no data authorities, " + 13619 "paths, or types; and at most one scheme."); 13620 } 13621 13622 final int callingUid = Binder.getCallingUid(); 13623 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 13624 synchronized (mPackages) { 13625 if (mContext.checkCallingOrSelfPermission( 13626 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13627 != PackageManager.PERMISSION_GRANTED) { 13628 if (getUidTargetSdkVersionLockedLPr(callingUid) 13629 < Build.VERSION_CODES.FROYO) { 13630 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 13631 + Binder.getCallingUid()); 13632 return; 13633 } 13634 mContext.enforceCallingOrSelfPermission( 13635 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13636 } 13637 13638 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13639 if (pir != null) { 13640 // Get all of the existing entries that exactly match this filter. 13641 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 13642 if (existing != null && existing.size() == 1) { 13643 PreferredActivity cur = existing.get(0); 13644 if (DEBUG_PREFERRED) { 13645 Slog.i(TAG, "Checking replace of preferred:"); 13646 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13647 if (!cur.mPref.mAlways) { 13648 Slog.i(TAG, " -- CUR; not mAlways!"); 13649 } else { 13650 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 13651 Slog.i(TAG, " -- CUR: mSet=" 13652 + Arrays.toString(cur.mPref.mSetComponents)); 13653 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 13654 Slog.i(TAG, " -- NEW: mMatch=" 13655 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 13656 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 13657 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 13658 } 13659 } 13660 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 13661 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 13662 && cur.mPref.sameSet(set)) { 13663 // Setting the preferred activity to what it happens to be already 13664 if (DEBUG_PREFERRED) { 13665 Slog.i(TAG, "Replacing with same preferred activity " 13666 + cur.mPref.mShortComponent + " for user " 13667 + userId + ":"); 13668 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13669 } 13670 return; 13671 } 13672 } 13673 13674 if (existing != null) { 13675 if (DEBUG_PREFERRED) { 13676 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 13677 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13678 } 13679 for (int i = 0; i < existing.size(); i++) { 13680 PreferredActivity pa = existing.get(i); 13681 if (DEBUG_PREFERRED) { 13682 Slog.i(TAG, "Removing existing preferred activity " 13683 + pa.mPref.mComponent + ":"); 13684 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 13685 } 13686 pir.removeFilter(pa); 13687 } 13688 } 13689 } 13690 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13691 "Replacing preferred"); 13692 } 13693 } 13694 13695 @Override 13696 public void clearPackagePreferredActivities(String packageName) { 13697 final int uid = Binder.getCallingUid(); 13698 // writer 13699 synchronized (mPackages) { 13700 PackageParser.Package pkg = mPackages.get(packageName); 13701 if (pkg == null || pkg.applicationInfo.uid != uid) { 13702 if (mContext.checkCallingOrSelfPermission( 13703 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13704 != PackageManager.PERMISSION_GRANTED) { 13705 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 13706 < Build.VERSION_CODES.FROYO) { 13707 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 13708 + Binder.getCallingUid()); 13709 return; 13710 } 13711 mContext.enforceCallingOrSelfPermission( 13712 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13713 } 13714 } 13715 13716 int user = UserHandle.getCallingUserId(); 13717 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 13718 scheduleWritePackageRestrictionsLocked(user); 13719 } 13720 } 13721 } 13722 13723 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13724 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 13725 ArrayList<PreferredActivity> removed = null; 13726 boolean changed = false; 13727 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13728 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 13729 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13730 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 13731 continue; 13732 } 13733 Iterator<PreferredActivity> it = pir.filterIterator(); 13734 while (it.hasNext()) { 13735 PreferredActivity pa = it.next(); 13736 // Mark entry for removal only if it matches the package name 13737 // and the entry is of type "always". 13738 if (packageName == null || 13739 (pa.mPref.mComponent.getPackageName().equals(packageName) 13740 && pa.mPref.mAlways)) { 13741 if (removed == null) { 13742 removed = new ArrayList<PreferredActivity>(); 13743 } 13744 removed.add(pa); 13745 } 13746 } 13747 if (removed != null) { 13748 for (int j=0; j<removed.size(); j++) { 13749 PreferredActivity pa = removed.get(j); 13750 pir.removeFilter(pa); 13751 } 13752 changed = true; 13753 } 13754 } 13755 return changed; 13756 } 13757 13758 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13759 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 13760 if (userId == UserHandle.USER_ALL) { 13761 if (mSettings.removeIntentFilterVerificationLPw(packageName, 13762 sUserManager.getUserIds())) { 13763 for (int oneUserId : sUserManager.getUserIds()) { 13764 scheduleWritePackageRestrictionsLocked(oneUserId); 13765 } 13766 } 13767 } else { 13768 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 13769 scheduleWritePackageRestrictionsLocked(userId); 13770 } 13771 } 13772 } 13773 13774 13775 void clearDefaultBrowserIfNeeded(String packageName) { 13776 for (int oneUserId : sUserManager.getUserIds()) { 13777 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 13778 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 13779 if (packageName.equals(defaultBrowserPackageName)) { 13780 setDefaultBrowserPackageName(null, oneUserId); 13781 } 13782 } 13783 } 13784 13785 @Override 13786 public void resetPreferredActivities(int userId) { 13787 mContext.enforceCallingOrSelfPermission( 13788 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13789 // writer 13790 synchronized (mPackages) { 13791 clearPackagePreferredActivitiesLPw(null, userId); 13792 mSettings.applyDefaultPreferredAppsLPw(this, userId); 13793 applyFactoryDefaultBrowserLPw(userId); 13794 primeDomainVerificationsLPw(userId); 13795 13796 scheduleWritePackageRestrictionsLocked(userId); 13797 } 13798 } 13799 13800 @Override 13801 public int getPreferredActivities(List<IntentFilter> outFilters, 13802 List<ComponentName> outActivities, String packageName) { 13803 13804 int num = 0; 13805 final int userId = UserHandle.getCallingUserId(); 13806 // reader 13807 synchronized (mPackages) { 13808 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13809 if (pir != null) { 13810 final Iterator<PreferredActivity> it = pir.filterIterator(); 13811 while (it.hasNext()) { 13812 final PreferredActivity pa = it.next(); 13813 if (packageName == null 13814 || (pa.mPref.mComponent.getPackageName().equals(packageName) 13815 && pa.mPref.mAlways)) { 13816 if (outFilters != null) { 13817 outFilters.add(new IntentFilter(pa)); 13818 } 13819 if (outActivities != null) { 13820 outActivities.add(pa.mPref.mComponent); 13821 } 13822 } 13823 } 13824 } 13825 } 13826 13827 return num; 13828 } 13829 13830 @Override 13831 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 13832 int userId) { 13833 int callingUid = Binder.getCallingUid(); 13834 if (callingUid != Process.SYSTEM_UID) { 13835 throw new SecurityException( 13836 "addPersistentPreferredActivity can only be run by the system"); 13837 } 13838 if (filter.countActions() == 0) { 13839 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13840 return; 13841 } 13842 synchronized (mPackages) { 13843 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 13844 " :"); 13845 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13846 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 13847 new PersistentPreferredActivity(filter, activity)); 13848 scheduleWritePackageRestrictionsLocked(userId); 13849 } 13850 } 13851 13852 @Override 13853 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 13854 int callingUid = Binder.getCallingUid(); 13855 if (callingUid != Process.SYSTEM_UID) { 13856 throw new SecurityException( 13857 "clearPackagePersistentPreferredActivities can only be run by the system"); 13858 } 13859 ArrayList<PersistentPreferredActivity> removed = null; 13860 boolean changed = false; 13861 synchronized (mPackages) { 13862 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 13863 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 13864 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 13865 .valueAt(i); 13866 if (userId != thisUserId) { 13867 continue; 13868 } 13869 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 13870 while (it.hasNext()) { 13871 PersistentPreferredActivity ppa = it.next(); 13872 // Mark entry for removal only if it matches the package name. 13873 if (ppa.mComponent.getPackageName().equals(packageName)) { 13874 if (removed == null) { 13875 removed = new ArrayList<PersistentPreferredActivity>(); 13876 } 13877 removed.add(ppa); 13878 } 13879 } 13880 if (removed != null) { 13881 for (int j=0; j<removed.size(); j++) { 13882 PersistentPreferredActivity ppa = removed.get(j); 13883 ppir.removeFilter(ppa); 13884 } 13885 changed = true; 13886 } 13887 } 13888 13889 if (changed) { 13890 scheduleWritePackageRestrictionsLocked(userId); 13891 } 13892 } 13893 } 13894 13895 /** 13896 * Common machinery for picking apart a restored XML blob and passing 13897 * it to a caller-supplied functor to be applied to the running system. 13898 */ 13899 private void restoreFromXml(XmlPullParser parser, int userId, 13900 String expectedStartTag, BlobXmlRestorer functor) 13901 throws IOException, XmlPullParserException { 13902 int type; 13903 while ((type = parser.next()) != XmlPullParser.START_TAG 13904 && type != XmlPullParser.END_DOCUMENT) { 13905 } 13906 if (type != XmlPullParser.START_TAG) { 13907 // oops didn't find a start tag?! 13908 if (DEBUG_BACKUP) { 13909 Slog.e(TAG, "Didn't find start tag during restore"); 13910 } 13911 return; 13912 } 13913 13914 // this is supposed to be TAG_PREFERRED_BACKUP 13915 if (!expectedStartTag.equals(parser.getName())) { 13916 if (DEBUG_BACKUP) { 13917 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 13918 } 13919 return; 13920 } 13921 13922 // skip interfering stuff, then we're aligned with the backing implementation 13923 while ((type = parser.next()) == XmlPullParser.TEXT) { } 13924 functor.apply(parser, userId); 13925 } 13926 13927 private interface BlobXmlRestorer { 13928 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 13929 } 13930 13931 /** 13932 * Non-Binder method, support for the backup/restore mechanism: write the 13933 * full set of preferred activities in its canonical XML format. Returns the 13934 * XML output as a byte array, or null if there is none. 13935 */ 13936 @Override 13937 public byte[] getPreferredActivityBackup(int userId) { 13938 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13939 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 13940 } 13941 13942 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13943 try { 13944 final XmlSerializer serializer = new FastXmlSerializer(); 13945 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13946 serializer.startDocument(null, true); 13947 serializer.startTag(null, TAG_PREFERRED_BACKUP); 13948 13949 synchronized (mPackages) { 13950 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 13951 } 13952 13953 serializer.endTag(null, TAG_PREFERRED_BACKUP); 13954 serializer.endDocument(); 13955 serializer.flush(); 13956 } catch (Exception e) { 13957 if (DEBUG_BACKUP) { 13958 Slog.e(TAG, "Unable to write preferred activities for backup", e); 13959 } 13960 return null; 13961 } 13962 13963 return dataStream.toByteArray(); 13964 } 13965 13966 @Override 13967 public void restorePreferredActivities(byte[] backup, int userId) { 13968 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13969 throw new SecurityException("Only the system may call restorePreferredActivities()"); 13970 } 13971 13972 try { 13973 final XmlPullParser parser = Xml.newPullParser(); 13974 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13975 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 13976 new BlobXmlRestorer() { 13977 @Override 13978 public void apply(XmlPullParser parser, int userId) 13979 throws XmlPullParserException, IOException { 13980 synchronized (mPackages) { 13981 mSettings.readPreferredActivitiesLPw(parser, userId); 13982 } 13983 } 13984 } ); 13985 } catch (Exception e) { 13986 if (DEBUG_BACKUP) { 13987 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 13988 } 13989 } 13990 } 13991 13992 /** 13993 * Non-Binder method, support for the backup/restore mechanism: write the 13994 * default browser (etc) settings in its canonical XML format. Returns the default 13995 * browser XML representation as a byte array, or null if there is none. 13996 */ 13997 @Override 13998 public byte[] getDefaultAppsBackup(int userId) { 13999 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14000 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 14001 } 14002 14003 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14004 try { 14005 final XmlSerializer serializer = new FastXmlSerializer(); 14006 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14007 serializer.startDocument(null, true); 14008 serializer.startTag(null, TAG_DEFAULT_APPS); 14009 14010 synchronized (mPackages) { 14011 mSettings.writeDefaultAppsLPr(serializer, userId); 14012 } 14013 14014 serializer.endTag(null, TAG_DEFAULT_APPS); 14015 serializer.endDocument(); 14016 serializer.flush(); 14017 } catch (Exception e) { 14018 if (DEBUG_BACKUP) { 14019 Slog.e(TAG, "Unable to write default apps for backup", e); 14020 } 14021 return null; 14022 } 14023 14024 return dataStream.toByteArray(); 14025 } 14026 14027 @Override 14028 public void restoreDefaultApps(byte[] backup, int userId) { 14029 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14030 throw new SecurityException("Only the system may call restoreDefaultApps()"); 14031 } 14032 14033 try { 14034 final XmlPullParser parser = Xml.newPullParser(); 14035 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14036 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 14037 new BlobXmlRestorer() { 14038 @Override 14039 public void apply(XmlPullParser parser, int userId) 14040 throws XmlPullParserException, IOException { 14041 synchronized (mPackages) { 14042 mSettings.readDefaultAppsLPw(parser, userId); 14043 } 14044 } 14045 } ); 14046 } catch (Exception e) { 14047 if (DEBUG_BACKUP) { 14048 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 14049 } 14050 } 14051 } 14052 14053 @Override 14054 public byte[] getIntentFilterVerificationBackup(int userId) { 14055 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14056 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 14057 } 14058 14059 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14060 try { 14061 final XmlSerializer serializer = new FastXmlSerializer(); 14062 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14063 serializer.startDocument(null, true); 14064 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 14065 14066 synchronized (mPackages) { 14067 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 14068 } 14069 14070 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 14071 serializer.endDocument(); 14072 serializer.flush(); 14073 } catch (Exception e) { 14074 if (DEBUG_BACKUP) { 14075 Slog.e(TAG, "Unable to write default apps for backup", e); 14076 } 14077 return null; 14078 } 14079 14080 return dataStream.toByteArray(); 14081 } 14082 14083 @Override 14084 public void restoreIntentFilterVerification(byte[] backup, int userId) { 14085 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14086 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14087 } 14088 14089 try { 14090 final XmlPullParser parser = Xml.newPullParser(); 14091 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14092 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 14093 new BlobXmlRestorer() { 14094 @Override 14095 public void apply(XmlPullParser parser, int userId) 14096 throws XmlPullParserException, IOException { 14097 synchronized (mPackages) { 14098 mSettings.readAllDomainVerificationsLPr(parser, userId); 14099 mSettings.writeLPr(); 14100 } 14101 } 14102 } ); 14103 } catch (Exception e) { 14104 if (DEBUG_BACKUP) { 14105 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14106 } 14107 } 14108 } 14109 14110 @Override 14111 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 14112 int sourceUserId, int targetUserId, int flags) { 14113 mContext.enforceCallingOrSelfPermission( 14114 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14115 int callingUid = Binder.getCallingUid(); 14116 enforceOwnerRights(ownerPackage, callingUid); 14117 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14118 if (intentFilter.countActions() == 0) { 14119 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 14120 return; 14121 } 14122 synchronized (mPackages) { 14123 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 14124 ownerPackage, targetUserId, flags); 14125 CrossProfileIntentResolver resolver = 14126 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14127 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 14128 // We have all those whose filter is equal. Now checking if the rest is equal as well. 14129 if (existing != null) { 14130 int size = existing.size(); 14131 for (int i = 0; i < size; i++) { 14132 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 14133 return; 14134 } 14135 } 14136 } 14137 resolver.addFilter(newFilter); 14138 scheduleWritePackageRestrictionsLocked(sourceUserId); 14139 } 14140 } 14141 14142 @Override 14143 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 14144 mContext.enforceCallingOrSelfPermission( 14145 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14146 int callingUid = Binder.getCallingUid(); 14147 enforceOwnerRights(ownerPackage, callingUid); 14148 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14149 synchronized (mPackages) { 14150 CrossProfileIntentResolver resolver = 14151 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14152 ArraySet<CrossProfileIntentFilter> set = 14153 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 14154 for (CrossProfileIntentFilter filter : set) { 14155 if (filter.getOwnerPackage().equals(ownerPackage)) { 14156 resolver.removeFilter(filter); 14157 } 14158 } 14159 scheduleWritePackageRestrictionsLocked(sourceUserId); 14160 } 14161 } 14162 14163 // Enforcing that callingUid is owning pkg on userId 14164 private void enforceOwnerRights(String pkg, int callingUid) { 14165 // The system owns everything. 14166 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 14167 return; 14168 } 14169 int callingUserId = UserHandle.getUserId(callingUid); 14170 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 14171 if (pi == null) { 14172 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 14173 + callingUserId); 14174 } 14175 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 14176 throw new SecurityException("Calling uid " + callingUid 14177 + " does not own package " + pkg); 14178 } 14179 } 14180 14181 @Override 14182 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 14183 Intent intent = new Intent(Intent.ACTION_MAIN); 14184 intent.addCategory(Intent.CATEGORY_HOME); 14185 14186 final int callingUserId = UserHandle.getCallingUserId(); 14187 List<ResolveInfo> list = queryIntentActivities(intent, null, 14188 PackageManager.GET_META_DATA, callingUserId); 14189 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 14190 true, false, false, callingUserId); 14191 14192 allHomeCandidates.clear(); 14193 if (list != null) { 14194 for (ResolveInfo ri : list) { 14195 allHomeCandidates.add(ri); 14196 } 14197 } 14198 return (preferred == null || preferred.activityInfo == null) 14199 ? null 14200 : new ComponentName(preferred.activityInfo.packageName, 14201 preferred.activityInfo.name); 14202 } 14203 14204 @Override 14205 public void setApplicationEnabledSetting(String appPackageName, 14206 int newState, int flags, int userId, String callingPackage) { 14207 if (!sUserManager.exists(userId)) return; 14208 if (callingPackage == null) { 14209 callingPackage = Integer.toString(Binder.getCallingUid()); 14210 } 14211 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 14212 } 14213 14214 @Override 14215 public void setComponentEnabledSetting(ComponentName componentName, 14216 int newState, int flags, int userId) { 14217 if (!sUserManager.exists(userId)) return; 14218 setEnabledSetting(componentName.getPackageName(), 14219 componentName.getClassName(), newState, flags, userId, null); 14220 } 14221 14222 private void setEnabledSetting(final String packageName, String className, int newState, 14223 final int flags, int userId, String callingPackage) { 14224 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 14225 || newState == COMPONENT_ENABLED_STATE_ENABLED 14226 || newState == COMPONENT_ENABLED_STATE_DISABLED 14227 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 14228 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 14229 throw new IllegalArgumentException("Invalid new component state: " 14230 + newState); 14231 } 14232 PackageSetting pkgSetting; 14233 final int uid = Binder.getCallingUid(); 14234 final int permission = mContext.checkCallingOrSelfPermission( 14235 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14236 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 14237 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14238 boolean sendNow = false; 14239 boolean isApp = (className == null); 14240 String componentName = isApp ? packageName : className; 14241 int packageUid = -1; 14242 ArrayList<String> components; 14243 14244 // writer 14245 synchronized (mPackages) { 14246 pkgSetting = mSettings.mPackages.get(packageName); 14247 if (pkgSetting == null) { 14248 if (className == null) { 14249 throw new IllegalArgumentException( 14250 "Unknown package: " + packageName); 14251 } 14252 throw new IllegalArgumentException( 14253 "Unknown component: " + packageName 14254 + "/" + className); 14255 } 14256 // Allow root and verify that userId is not being specified by a different user 14257 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 14258 throw new SecurityException( 14259 "Permission Denial: attempt to change component state from pid=" 14260 + Binder.getCallingPid() 14261 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 14262 } 14263 if (className == null) { 14264 // We're dealing with an application/package level state change 14265 if (pkgSetting.getEnabled(userId) == newState) { 14266 // Nothing to do 14267 return; 14268 } 14269 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 14270 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 14271 // Don't care about who enables an app. 14272 callingPackage = null; 14273 } 14274 pkgSetting.setEnabled(newState, userId, callingPackage); 14275 // pkgSetting.pkg.mSetEnabled = newState; 14276 } else { 14277 // We're dealing with a component level state change 14278 // First, verify that this is a valid class name. 14279 PackageParser.Package pkg = pkgSetting.pkg; 14280 if (pkg == null || !pkg.hasComponentClassName(className)) { 14281 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 14282 throw new IllegalArgumentException("Component class " + className 14283 + " does not exist in " + packageName); 14284 } else { 14285 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 14286 + className + " does not exist in " + packageName); 14287 } 14288 } 14289 switch (newState) { 14290 case COMPONENT_ENABLED_STATE_ENABLED: 14291 if (!pkgSetting.enableComponentLPw(className, userId)) { 14292 return; 14293 } 14294 break; 14295 case COMPONENT_ENABLED_STATE_DISABLED: 14296 if (!pkgSetting.disableComponentLPw(className, userId)) { 14297 return; 14298 } 14299 break; 14300 case COMPONENT_ENABLED_STATE_DEFAULT: 14301 if (!pkgSetting.restoreComponentLPw(className, userId)) { 14302 return; 14303 } 14304 break; 14305 default: 14306 Slog.e(TAG, "Invalid new component state: " + newState); 14307 return; 14308 } 14309 } 14310 scheduleWritePackageRestrictionsLocked(userId); 14311 components = mPendingBroadcasts.get(userId, packageName); 14312 final boolean newPackage = components == null; 14313 if (newPackage) { 14314 components = new ArrayList<String>(); 14315 } 14316 if (!components.contains(componentName)) { 14317 components.add(componentName); 14318 } 14319 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 14320 sendNow = true; 14321 // Purge entry from pending broadcast list if another one exists already 14322 // since we are sending one right away. 14323 mPendingBroadcasts.remove(userId, packageName); 14324 } else { 14325 if (newPackage) { 14326 mPendingBroadcasts.put(userId, packageName, components); 14327 } 14328 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 14329 // Schedule a message 14330 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 14331 } 14332 } 14333 } 14334 14335 long callingId = Binder.clearCallingIdentity(); 14336 try { 14337 if (sendNow) { 14338 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 14339 sendPackageChangedBroadcast(packageName, 14340 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 14341 } 14342 } finally { 14343 Binder.restoreCallingIdentity(callingId); 14344 } 14345 } 14346 14347 private void sendPackageChangedBroadcast(String packageName, 14348 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 14349 if (DEBUG_INSTALL) 14350 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 14351 + componentNames); 14352 Bundle extras = new Bundle(4); 14353 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 14354 String nameList[] = new String[componentNames.size()]; 14355 componentNames.toArray(nameList); 14356 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 14357 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 14358 extras.putInt(Intent.EXTRA_UID, packageUid); 14359 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 14360 new int[] {UserHandle.getUserId(packageUid)}); 14361 } 14362 14363 @Override 14364 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 14365 if (!sUserManager.exists(userId)) return; 14366 final int uid = Binder.getCallingUid(); 14367 final int permission = mContext.checkCallingOrSelfPermission( 14368 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14369 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14370 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 14371 // writer 14372 synchronized (mPackages) { 14373 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 14374 allowedByPermission, uid, userId)) { 14375 scheduleWritePackageRestrictionsLocked(userId); 14376 } 14377 } 14378 } 14379 14380 @Override 14381 public String getInstallerPackageName(String packageName) { 14382 // reader 14383 synchronized (mPackages) { 14384 return mSettings.getInstallerPackageNameLPr(packageName); 14385 } 14386 } 14387 14388 @Override 14389 public int getApplicationEnabledSetting(String packageName, int userId) { 14390 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14391 int uid = Binder.getCallingUid(); 14392 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 14393 // reader 14394 synchronized (mPackages) { 14395 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 14396 } 14397 } 14398 14399 @Override 14400 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 14401 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14402 int uid = Binder.getCallingUid(); 14403 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 14404 // reader 14405 synchronized (mPackages) { 14406 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 14407 } 14408 } 14409 14410 @Override 14411 public void enterSafeMode() { 14412 enforceSystemOrRoot("Only the system can request entering safe mode"); 14413 14414 if (!mSystemReady) { 14415 mSafeMode = true; 14416 } 14417 } 14418 14419 @Override 14420 public void systemReady() { 14421 mSystemReady = true; 14422 14423 // Read the compatibilty setting when the system is ready. 14424 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 14425 mContext.getContentResolver(), 14426 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 14427 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 14428 if (DEBUG_SETTINGS) { 14429 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 14430 } 14431 14432 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 14433 14434 synchronized (mPackages) { 14435 // Verify that all of the preferred activity components actually 14436 // exist. It is possible for applications to be updated and at 14437 // that point remove a previously declared activity component that 14438 // had been set as a preferred activity. We try to clean this up 14439 // the next time we encounter that preferred activity, but it is 14440 // possible for the user flow to never be able to return to that 14441 // situation so here we do a sanity check to make sure we haven't 14442 // left any junk around. 14443 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 14444 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14445 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14446 removed.clear(); 14447 for (PreferredActivity pa : pir.filterSet()) { 14448 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 14449 removed.add(pa); 14450 } 14451 } 14452 if (removed.size() > 0) { 14453 for (int r=0; r<removed.size(); r++) { 14454 PreferredActivity pa = removed.get(r); 14455 Slog.w(TAG, "Removing dangling preferred activity: " 14456 + pa.mPref.mComponent); 14457 pir.removeFilter(pa); 14458 } 14459 mSettings.writePackageRestrictionsLPr( 14460 mSettings.mPreferredActivities.keyAt(i)); 14461 } 14462 } 14463 14464 for (int userId : UserManagerService.getInstance().getUserIds()) { 14465 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 14466 grantPermissionsUserIds = ArrayUtils.appendInt( 14467 grantPermissionsUserIds, userId); 14468 } 14469 } 14470 } 14471 sUserManager.systemReady(); 14472 14473 // If we upgraded grant all default permissions before kicking off. 14474 for (int userId : grantPermissionsUserIds) { 14475 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 14476 } 14477 14478 // Kick off any messages waiting for system ready 14479 if (mPostSystemReadyMessages != null) { 14480 for (Message msg : mPostSystemReadyMessages) { 14481 msg.sendToTarget(); 14482 } 14483 mPostSystemReadyMessages = null; 14484 } 14485 14486 // Watch for external volumes that come and go over time 14487 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14488 storage.registerListener(mStorageListener); 14489 14490 mInstallerService.systemReady(); 14491 mPackageDexOptimizer.systemReady(); 14492 14493 MountServiceInternal mountServiceInternal = LocalServices.getService( 14494 MountServiceInternal.class); 14495 mountServiceInternal.addExternalStoragePolicy( 14496 new MountServiceInternal.ExternalStorageMountPolicy() { 14497 @Override 14498 public int getMountMode(int uid, String packageName) { 14499 if (Process.isIsolated(uid)) { 14500 return Zygote.MOUNT_EXTERNAL_NONE; 14501 } 14502 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 14503 return Zygote.MOUNT_EXTERNAL_DEFAULT; 14504 } 14505 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 14506 return Zygote.MOUNT_EXTERNAL_DEFAULT; 14507 } 14508 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 14509 return Zygote.MOUNT_EXTERNAL_READ; 14510 } 14511 return Zygote.MOUNT_EXTERNAL_WRITE; 14512 } 14513 14514 @Override 14515 public boolean hasExternalStorage(int uid, String packageName) { 14516 return true; 14517 } 14518 }); 14519 } 14520 14521 @Override 14522 public boolean isSafeMode() { 14523 return mSafeMode; 14524 } 14525 14526 @Override 14527 public boolean hasSystemUidErrors() { 14528 return mHasSystemUidErrors; 14529 } 14530 14531 static String arrayToString(int[] array) { 14532 StringBuffer buf = new StringBuffer(128); 14533 buf.append('['); 14534 if (array != null) { 14535 for (int i=0; i<array.length; i++) { 14536 if (i > 0) buf.append(", "); 14537 buf.append(array[i]); 14538 } 14539 } 14540 buf.append(']'); 14541 return buf.toString(); 14542 } 14543 14544 static class DumpState { 14545 public static final int DUMP_LIBS = 1 << 0; 14546 public static final int DUMP_FEATURES = 1 << 1; 14547 public static final int DUMP_RESOLVERS = 1 << 2; 14548 public static final int DUMP_PERMISSIONS = 1 << 3; 14549 public static final int DUMP_PACKAGES = 1 << 4; 14550 public static final int DUMP_SHARED_USERS = 1 << 5; 14551 public static final int DUMP_MESSAGES = 1 << 6; 14552 public static final int DUMP_PROVIDERS = 1 << 7; 14553 public static final int DUMP_VERIFIERS = 1 << 8; 14554 public static final int DUMP_PREFERRED = 1 << 9; 14555 public static final int DUMP_PREFERRED_XML = 1 << 10; 14556 public static final int DUMP_KEYSETS = 1 << 11; 14557 public static final int DUMP_VERSION = 1 << 12; 14558 public static final int DUMP_INSTALLS = 1 << 13; 14559 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 14560 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 14561 14562 public static final int OPTION_SHOW_FILTERS = 1 << 0; 14563 14564 private int mTypes; 14565 14566 private int mOptions; 14567 14568 private boolean mTitlePrinted; 14569 14570 private SharedUserSetting mSharedUser; 14571 14572 public boolean isDumping(int type) { 14573 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 14574 return true; 14575 } 14576 14577 return (mTypes & type) != 0; 14578 } 14579 14580 public void setDump(int type) { 14581 mTypes |= type; 14582 } 14583 14584 public boolean isOptionEnabled(int option) { 14585 return (mOptions & option) != 0; 14586 } 14587 14588 public void setOptionEnabled(int option) { 14589 mOptions |= option; 14590 } 14591 14592 public boolean onTitlePrinted() { 14593 final boolean printed = mTitlePrinted; 14594 mTitlePrinted = true; 14595 return printed; 14596 } 14597 14598 public boolean getTitlePrinted() { 14599 return mTitlePrinted; 14600 } 14601 14602 public void setTitlePrinted(boolean enabled) { 14603 mTitlePrinted = enabled; 14604 } 14605 14606 public SharedUserSetting getSharedUser() { 14607 return mSharedUser; 14608 } 14609 14610 public void setSharedUser(SharedUserSetting user) { 14611 mSharedUser = user; 14612 } 14613 } 14614 14615 @Override 14616 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 14617 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 14618 != PackageManager.PERMISSION_GRANTED) { 14619 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 14620 + Binder.getCallingPid() 14621 + ", uid=" + Binder.getCallingUid() 14622 + " without permission " 14623 + android.Manifest.permission.DUMP); 14624 return; 14625 } 14626 14627 DumpState dumpState = new DumpState(); 14628 boolean fullPreferred = false; 14629 boolean checkin = false; 14630 14631 String packageName = null; 14632 ArraySet<String> permissionNames = null; 14633 14634 int opti = 0; 14635 while (opti < args.length) { 14636 String opt = args[opti]; 14637 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 14638 break; 14639 } 14640 opti++; 14641 14642 if ("-a".equals(opt)) { 14643 // Right now we only know how to print all. 14644 } else if ("-h".equals(opt)) { 14645 pw.println("Package manager dump options:"); 14646 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 14647 pw.println(" --checkin: dump for a checkin"); 14648 pw.println(" -f: print details of intent filters"); 14649 pw.println(" -h: print this help"); 14650 pw.println(" cmd may be one of:"); 14651 pw.println(" l[ibraries]: list known shared libraries"); 14652 pw.println(" f[ibraries]: list device features"); 14653 pw.println(" k[eysets]: print known keysets"); 14654 pw.println(" r[esolvers]: dump intent resolvers"); 14655 pw.println(" perm[issions]: dump permissions"); 14656 pw.println(" permission [name ...]: dump declaration and use of given permission"); 14657 pw.println(" pref[erred]: print preferred package settings"); 14658 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 14659 pw.println(" prov[iders]: dump content providers"); 14660 pw.println(" p[ackages]: dump installed packages"); 14661 pw.println(" s[hared-users]: dump shared user IDs"); 14662 pw.println(" m[essages]: print collected runtime messages"); 14663 pw.println(" v[erifiers]: print package verifier info"); 14664 pw.println(" version: print database version info"); 14665 pw.println(" write: write current settings now"); 14666 pw.println(" <package.name>: info about given package"); 14667 pw.println(" installs: details about install sessions"); 14668 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 14669 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 14670 return; 14671 } else if ("--checkin".equals(opt)) { 14672 checkin = true; 14673 } else if ("-f".equals(opt)) { 14674 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14675 } else { 14676 pw.println("Unknown argument: " + opt + "; use -h for help"); 14677 } 14678 } 14679 14680 // Is the caller requesting to dump a particular piece of data? 14681 if (opti < args.length) { 14682 String cmd = args[opti]; 14683 opti++; 14684 // Is this a package name? 14685 if ("android".equals(cmd) || cmd.contains(".")) { 14686 packageName = cmd; 14687 // When dumping a single package, we always dump all of its 14688 // filter information since the amount of data will be reasonable. 14689 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14690 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 14691 dumpState.setDump(DumpState.DUMP_LIBS); 14692 } else if ("f".equals(cmd) || "features".equals(cmd)) { 14693 dumpState.setDump(DumpState.DUMP_FEATURES); 14694 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 14695 dumpState.setDump(DumpState.DUMP_RESOLVERS); 14696 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 14697 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 14698 } else if ("permission".equals(cmd)) { 14699 if (opti >= args.length) { 14700 pw.println("Error: permission requires permission name"); 14701 return; 14702 } 14703 permissionNames = new ArraySet<>(); 14704 while (opti < args.length) { 14705 permissionNames.add(args[opti]); 14706 opti++; 14707 } 14708 dumpState.setDump(DumpState.DUMP_PERMISSIONS 14709 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 14710 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 14711 dumpState.setDump(DumpState.DUMP_PREFERRED); 14712 } else if ("preferred-xml".equals(cmd)) { 14713 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 14714 if (opti < args.length && "--full".equals(args[opti])) { 14715 fullPreferred = true; 14716 opti++; 14717 } 14718 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 14719 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 14720 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 14721 dumpState.setDump(DumpState.DUMP_PACKAGES); 14722 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 14723 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 14724 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 14725 dumpState.setDump(DumpState.DUMP_PROVIDERS); 14726 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 14727 dumpState.setDump(DumpState.DUMP_MESSAGES); 14728 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 14729 dumpState.setDump(DumpState.DUMP_VERIFIERS); 14730 } else if ("i".equals(cmd) || "ifv".equals(cmd) 14731 || "intent-filter-verifiers".equals(cmd)) { 14732 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 14733 } else if ("version".equals(cmd)) { 14734 dumpState.setDump(DumpState.DUMP_VERSION); 14735 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 14736 dumpState.setDump(DumpState.DUMP_KEYSETS); 14737 } else if ("installs".equals(cmd)) { 14738 dumpState.setDump(DumpState.DUMP_INSTALLS); 14739 } else if ("write".equals(cmd)) { 14740 synchronized (mPackages) { 14741 mSettings.writeLPr(); 14742 pw.println("Settings written."); 14743 return; 14744 } 14745 } 14746 } 14747 14748 if (checkin) { 14749 pw.println("vers,1"); 14750 } 14751 14752 // reader 14753 synchronized (mPackages) { 14754 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 14755 if (!checkin) { 14756 if (dumpState.onTitlePrinted()) 14757 pw.println(); 14758 pw.println("Database versions:"); 14759 pw.print(" SDK Version:"); 14760 pw.print(" internal="); 14761 pw.print(mSettings.mInternalSdkPlatform); 14762 pw.print(" external="); 14763 pw.println(mSettings.mExternalSdkPlatform); 14764 pw.print(" DB Version:"); 14765 pw.print(" internal="); 14766 pw.print(mSettings.mInternalDatabaseVersion); 14767 pw.print(" external="); 14768 pw.println(mSettings.mExternalDatabaseVersion); 14769 } 14770 } 14771 14772 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 14773 if (!checkin) { 14774 if (dumpState.onTitlePrinted()) 14775 pw.println(); 14776 pw.println("Verifiers:"); 14777 pw.print(" Required: "); 14778 pw.print(mRequiredVerifierPackage); 14779 pw.print(" (uid="); 14780 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 14781 pw.println(")"); 14782 } else if (mRequiredVerifierPackage != null) { 14783 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 14784 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 14785 } 14786 } 14787 14788 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 14789 packageName == null) { 14790 if (mIntentFilterVerifierComponent != null) { 14791 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 14792 if (!checkin) { 14793 if (dumpState.onTitlePrinted()) 14794 pw.println(); 14795 pw.println("Intent Filter Verifier:"); 14796 pw.print(" Using: "); 14797 pw.print(verifierPackageName); 14798 pw.print(" (uid="); 14799 pw.print(getPackageUid(verifierPackageName, 0)); 14800 pw.println(")"); 14801 } else if (verifierPackageName != null) { 14802 pw.print("ifv,"); pw.print(verifierPackageName); 14803 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 14804 } 14805 } else { 14806 pw.println(); 14807 pw.println("No Intent Filter Verifier available!"); 14808 } 14809 } 14810 14811 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 14812 boolean printedHeader = false; 14813 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 14814 while (it.hasNext()) { 14815 String name = it.next(); 14816 SharedLibraryEntry ent = mSharedLibraries.get(name); 14817 if (!checkin) { 14818 if (!printedHeader) { 14819 if (dumpState.onTitlePrinted()) 14820 pw.println(); 14821 pw.println("Libraries:"); 14822 printedHeader = true; 14823 } 14824 pw.print(" "); 14825 } else { 14826 pw.print("lib,"); 14827 } 14828 pw.print(name); 14829 if (!checkin) { 14830 pw.print(" -> "); 14831 } 14832 if (ent.path != null) { 14833 if (!checkin) { 14834 pw.print("(jar) "); 14835 pw.print(ent.path); 14836 } else { 14837 pw.print(",jar,"); 14838 pw.print(ent.path); 14839 } 14840 } else { 14841 if (!checkin) { 14842 pw.print("(apk) "); 14843 pw.print(ent.apk); 14844 } else { 14845 pw.print(",apk,"); 14846 pw.print(ent.apk); 14847 } 14848 } 14849 pw.println(); 14850 } 14851 } 14852 14853 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 14854 if (dumpState.onTitlePrinted()) 14855 pw.println(); 14856 if (!checkin) { 14857 pw.println("Features:"); 14858 } 14859 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 14860 while (it.hasNext()) { 14861 String name = it.next(); 14862 if (!checkin) { 14863 pw.print(" "); 14864 } else { 14865 pw.print("feat,"); 14866 } 14867 pw.println(name); 14868 } 14869 } 14870 14871 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 14872 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 14873 : "Activity Resolver Table:", " ", packageName, 14874 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14875 dumpState.setTitlePrinted(true); 14876 } 14877 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 14878 : "Receiver Resolver Table:", " ", packageName, 14879 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14880 dumpState.setTitlePrinted(true); 14881 } 14882 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 14883 : "Service Resolver Table:", " ", packageName, 14884 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14885 dumpState.setTitlePrinted(true); 14886 } 14887 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 14888 : "Provider Resolver Table:", " ", packageName, 14889 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14890 dumpState.setTitlePrinted(true); 14891 } 14892 } 14893 14894 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 14895 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14896 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14897 int user = mSettings.mPreferredActivities.keyAt(i); 14898 if (pir.dump(pw, 14899 dumpState.getTitlePrinted() 14900 ? "\nPreferred Activities User " + user + ":" 14901 : "Preferred Activities User " + user + ":", " ", 14902 packageName, true, false)) { 14903 dumpState.setTitlePrinted(true); 14904 } 14905 } 14906 } 14907 14908 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 14909 pw.flush(); 14910 FileOutputStream fout = new FileOutputStream(fd); 14911 BufferedOutputStream str = new BufferedOutputStream(fout); 14912 XmlSerializer serializer = new FastXmlSerializer(); 14913 try { 14914 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 14915 serializer.startDocument(null, true); 14916 serializer.setFeature( 14917 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 14918 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 14919 serializer.endDocument(); 14920 serializer.flush(); 14921 } catch (IllegalArgumentException e) { 14922 pw.println("Failed writing: " + e); 14923 } catch (IllegalStateException e) { 14924 pw.println("Failed writing: " + e); 14925 } catch (IOException e) { 14926 pw.println("Failed writing: " + e); 14927 } 14928 } 14929 14930 if (!checkin 14931 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 14932 && packageName == null) { 14933 pw.println(); 14934 int count = mSettings.mPackages.size(); 14935 if (count == 0) { 14936 pw.println("No applications!"); 14937 pw.println(); 14938 } else { 14939 final String prefix = " "; 14940 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 14941 if (allPackageSettings.size() == 0) { 14942 pw.println("No domain preferred apps!"); 14943 pw.println(); 14944 } else { 14945 pw.println("App verification status:"); 14946 pw.println(); 14947 count = 0; 14948 for (PackageSetting ps : allPackageSettings) { 14949 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 14950 if (ivi == null || ivi.getPackageName() == null) continue; 14951 pw.println(prefix + "Package: " + ivi.getPackageName()); 14952 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 14953 pw.println(prefix + "Status: " + ivi.getStatusString()); 14954 pw.println(); 14955 count++; 14956 } 14957 if (count == 0) { 14958 pw.println(prefix + "No app verification established."); 14959 pw.println(); 14960 } 14961 for (int userId : sUserManager.getUserIds()) { 14962 pw.println("App linkages for user " + userId + ":"); 14963 pw.println(); 14964 count = 0; 14965 for (PackageSetting ps : allPackageSettings) { 14966 final long status = ps.getDomainVerificationStatusForUser(userId); 14967 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 14968 continue; 14969 } 14970 pw.println(prefix + "Package: " + ps.name); 14971 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 14972 String statusStr = IntentFilterVerificationInfo. 14973 getStatusStringFromValue(status); 14974 pw.println(prefix + "Status: " + statusStr); 14975 pw.println(); 14976 count++; 14977 } 14978 if (count == 0) { 14979 pw.println(prefix + "No configured app linkages."); 14980 pw.println(); 14981 } 14982 } 14983 } 14984 } 14985 } 14986 14987 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 14988 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 14989 if (packageName == null && permissionNames == null) { 14990 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 14991 if (iperm == 0) { 14992 if (dumpState.onTitlePrinted()) 14993 pw.println(); 14994 pw.println("AppOp Permissions:"); 14995 } 14996 pw.print(" AppOp Permission "); 14997 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 14998 pw.println(":"); 14999 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 15000 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 15001 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 15002 } 15003 } 15004 } 15005 } 15006 15007 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 15008 boolean printedSomething = false; 15009 for (PackageParser.Provider p : mProviders.mProviders.values()) { 15010 if (packageName != null && !packageName.equals(p.info.packageName)) { 15011 continue; 15012 } 15013 if (!printedSomething) { 15014 if (dumpState.onTitlePrinted()) 15015 pw.println(); 15016 pw.println("Registered ContentProviders:"); 15017 printedSomething = true; 15018 } 15019 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 15020 pw.print(" "); pw.println(p.toString()); 15021 } 15022 printedSomething = false; 15023 for (Map.Entry<String, PackageParser.Provider> entry : 15024 mProvidersByAuthority.entrySet()) { 15025 PackageParser.Provider p = entry.getValue(); 15026 if (packageName != null && !packageName.equals(p.info.packageName)) { 15027 continue; 15028 } 15029 if (!printedSomething) { 15030 if (dumpState.onTitlePrinted()) 15031 pw.println(); 15032 pw.println("ContentProvider Authorities:"); 15033 printedSomething = true; 15034 } 15035 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 15036 pw.print(" "); pw.println(p.toString()); 15037 if (p.info != null && p.info.applicationInfo != null) { 15038 final String appInfo = p.info.applicationInfo.toString(); 15039 pw.print(" applicationInfo="); pw.println(appInfo); 15040 } 15041 } 15042 } 15043 15044 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 15045 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 15046 } 15047 15048 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 15049 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 15050 } 15051 15052 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 15053 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 15054 } 15055 15056 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 15057 // XXX should handle packageName != null by dumping only install data that 15058 // the given package is involved with. 15059 if (dumpState.onTitlePrinted()) pw.println(); 15060 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 15061 } 15062 15063 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 15064 if (dumpState.onTitlePrinted()) pw.println(); 15065 mSettings.dumpReadMessagesLPr(pw, dumpState); 15066 15067 pw.println(); 15068 pw.println("Package warning messages:"); 15069 BufferedReader in = null; 15070 String line = null; 15071 try { 15072 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15073 while ((line = in.readLine()) != null) { 15074 if (line.contains("ignored: updated version")) continue; 15075 pw.println(line); 15076 } 15077 } catch (IOException ignored) { 15078 } finally { 15079 IoUtils.closeQuietly(in); 15080 } 15081 } 15082 15083 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 15084 BufferedReader in = null; 15085 String line = null; 15086 try { 15087 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15088 while ((line = in.readLine()) != null) { 15089 if (line.contains("ignored: updated version")) continue; 15090 pw.print("msg,"); 15091 pw.println(line); 15092 } 15093 } catch (IOException ignored) { 15094 } finally { 15095 IoUtils.closeQuietly(in); 15096 } 15097 } 15098 } 15099 } 15100 15101 private String dumpDomainString(String packageName) { 15102 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName); 15103 List<IntentFilter> filters = getAllIntentFilters(packageName); 15104 15105 ArraySet<String> result = new ArraySet<>(); 15106 if (iviList.size() > 0) { 15107 for (IntentFilterVerificationInfo ivi : iviList) { 15108 for (String host : ivi.getDomains()) { 15109 result.add(host); 15110 } 15111 } 15112 } 15113 if (filters != null && filters.size() > 0) { 15114 for (IntentFilter filter : filters) { 15115 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 15116 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 15117 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 15118 result.addAll(filter.getHostsList()); 15119 } 15120 } 15121 } 15122 15123 StringBuilder sb = new StringBuilder(result.size() * 16); 15124 for (String domain : result) { 15125 if (sb.length() > 0) sb.append(" "); 15126 sb.append(domain); 15127 } 15128 return sb.toString(); 15129 } 15130 15131 // ------- apps on sdcard specific code ------- 15132 static final boolean DEBUG_SD_INSTALL = false; 15133 15134 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 15135 15136 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 15137 15138 private boolean mMediaMounted = false; 15139 15140 static String getEncryptKey() { 15141 try { 15142 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 15143 SD_ENCRYPTION_KEYSTORE_NAME); 15144 if (sdEncKey == null) { 15145 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 15146 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 15147 if (sdEncKey == null) { 15148 Slog.e(TAG, "Failed to create encryption keys"); 15149 return null; 15150 } 15151 } 15152 return sdEncKey; 15153 } catch (NoSuchAlgorithmException nsae) { 15154 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 15155 return null; 15156 } catch (IOException ioe) { 15157 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 15158 return null; 15159 } 15160 } 15161 15162 /* 15163 * Update media status on PackageManager. 15164 */ 15165 @Override 15166 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 15167 int callingUid = Binder.getCallingUid(); 15168 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 15169 throw new SecurityException("Media status can only be updated by the system"); 15170 } 15171 // reader; this apparently protects mMediaMounted, but should probably 15172 // be a different lock in that case. 15173 synchronized (mPackages) { 15174 Log.i(TAG, "Updating external media status from " 15175 + (mMediaMounted ? "mounted" : "unmounted") + " to " 15176 + (mediaStatus ? "mounted" : "unmounted")); 15177 if (DEBUG_SD_INSTALL) 15178 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 15179 + ", mMediaMounted=" + mMediaMounted); 15180 if (mediaStatus == mMediaMounted) { 15181 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 15182 : 0, -1); 15183 mHandler.sendMessage(msg); 15184 return; 15185 } 15186 mMediaMounted = mediaStatus; 15187 } 15188 // Queue up an async operation since the package installation may take a 15189 // little while. 15190 mHandler.post(new Runnable() { 15191 public void run() { 15192 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 15193 } 15194 }); 15195 } 15196 15197 /** 15198 * Called by MountService when the initial ASECs to scan are available. 15199 * Should block until all the ASEC containers are finished being scanned. 15200 */ 15201 public void scanAvailableAsecs() { 15202 updateExternalMediaStatusInner(true, false, false); 15203 if (mShouldRestoreconData) { 15204 SELinuxMMAC.setRestoreconDone(); 15205 mShouldRestoreconData = false; 15206 } 15207 } 15208 15209 /* 15210 * Collect information of applications on external media, map them against 15211 * existing containers and update information based on current mount status. 15212 * Please note that we always have to report status if reportStatus has been 15213 * set to true especially when unloading packages. 15214 */ 15215 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 15216 boolean externalStorage) { 15217 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 15218 int[] uidArr = EmptyArray.INT; 15219 15220 final String[] list = PackageHelper.getSecureContainerList(); 15221 if (ArrayUtils.isEmpty(list)) { 15222 Log.i(TAG, "No secure containers found"); 15223 } else { 15224 // Process list of secure containers and categorize them 15225 // as active or stale based on their package internal state. 15226 15227 // reader 15228 synchronized (mPackages) { 15229 for (String cid : list) { 15230 // Leave stages untouched for now; installer service owns them 15231 if (PackageInstallerService.isStageName(cid)) continue; 15232 15233 if (DEBUG_SD_INSTALL) 15234 Log.i(TAG, "Processing container " + cid); 15235 String pkgName = getAsecPackageName(cid); 15236 if (pkgName == null) { 15237 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 15238 continue; 15239 } 15240 if (DEBUG_SD_INSTALL) 15241 Log.i(TAG, "Looking for pkg : " + pkgName); 15242 15243 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15244 if (ps == null) { 15245 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 15246 continue; 15247 } 15248 15249 /* 15250 * Skip packages that are not external if we're unmounting 15251 * external storage. 15252 */ 15253 if (externalStorage && !isMounted && !isExternal(ps)) { 15254 continue; 15255 } 15256 15257 final AsecInstallArgs args = new AsecInstallArgs(cid, 15258 getAppDexInstructionSets(ps), ps.isForwardLocked()); 15259 // The package status is changed only if the code path 15260 // matches between settings and the container id. 15261 if (ps.codePathString != null 15262 && ps.codePathString.startsWith(args.getCodePath())) { 15263 if (DEBUG_SD_INSTALL) { 15264 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 15265 + " at code path: " + ps.codePathString); 15266 } 15267 15268 // We do have a valid package installed on sdcard 15269 processCids.put(args, ps.codePathString); 15270 final int uid = ps.appId; 15271 if (uid != -1) { 15272 uidArr = ArrayUtils.appendInt(uidArr, uid); 15273 } 15274 } else { 15275 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 15276 + ps.codePathString); 15277 } 15278 } 15279 } 15280 15281 Arrays.sort(uidArr); 15282 } 15283 15284 // Process packages with valid entries. 15285 if (isMounted) { 15286 if (DEBUG_SD_INSTALL) 15287 Log.i(TAG, "Loading packages"); 15288 loadMediaPackages(processCids, uidArr); 15289 startCleaningPackages(); 15290 mInstallerService.onSecureContainersAvailable(); 15291 } else { 15292 if (DEBUG_SD_INSTALL) 15293 Log.i(TAG, "Unloading packages"); 15294 unloadMediaPackages(processCids, uidArr, reportStatus); 15295 } 15296 } 15297 15298 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15299 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 15300 final int size = infos.size(); 15301 final String[] packageNames = new String[size]; 15302 final int[] packageUids = new int[size]; 15303 for (int i = 0; i < size; i++) { 15304 final ApplicationInfo info = infos.get(i); 15305 packageNames[i] = info.packageName; 15306 packageUids[i] = info.uid; 15307 } 15308 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 15309 finishedReceiver); 15310 } 15311 15312 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15313 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15314 sendResourcesChangedBroadcast(mediaStatus, replacing, 15315 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 15316 } 15317 15318 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15319 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15320 int size = pkgList.length; 15321 if (size > 0) { 15322 // Send broadcasts here 15323 Bundle extras = new Bundle(); 15324 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 15325 if (uidArr != null) { 15326 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 15327 } 15328 if (replacing) { 15329 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 15330 } 15331 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 15332 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 15333 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 15334 } 15335 } 15336 15337 /* 15338 * Look at potentially valid container ids from processCids If package 15339 * information doesn't match the one on record or package scanning fails, 15340 * the cid is added to list of removeCids. We currently don't delete stale 15341 * containers. 15342 */ 15343 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 15344 ArrayList<String> pkgList = new ArrayList<String>(); 15345 Set<AsecInstallArgs> keys = processCids.keySet(); 15346 15347 for (AsecInstallArgs args : keys) { 15348 String codePath = processCids.get(args); 15349 if (DEBUG_SD_INSTALL) 15350 Log.i(TAG, "Loading container : " + args.cid); 15351 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15352 try { 15353 // Make sure there are no container errors first. 15354 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 15355 Slog.e(TAG, "Failed to mount cid : " + args.cid 15356 + " when installing from sdcard"); 15357 continue; 15358 } 15359 // Check code path here. 15360 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 15361 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 15362 + " does not match one in settings " + codePath); 15363 continue; 15364 } 15365 // Parse package 15366 int parseFlags = mDefParseFlags; 15367 if (args.isExternalAsec()) { 15368 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 15369 } 15370 if (args.isFwdLocked()) { 15371 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 15372 } 15373 15374 synchronized (mInstallLock) { 15375 PackageParser.Package pkg = null; 15376 try { 15377 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 15378 } catch (PackageManagerException e) { 15379 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 15380 } 15381 // Scan the package 15382 if (pkg != null) { 15383 /* 15384 * TODO why is the lock being held? doPostInstall is 15385 * called in other places without the lock. This needs 15386 * to be straightened out. 15387 */ 15388 // writer 15389 synchronized (mPackages) { 15390 retCode = PackageManager.INSTALL_SUCCEEDED; 15391 pkgList.add(pkg.packageName); 15392 // Post process args 15393 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 15394 pkg.applicationInfo.uid); 15395 } 15396 } else { 15397 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 15398 } 15399 } 15400 15401 } finally { 15402 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 15403 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 15404 } 15405 } 15406 } 15407 // writer 15408 synchronized (mPackages) { 15409 // If the platform SDK has changed since the last time we booted, 15410 // we need to re-grant app permission to catch any new ones that 15411 // appear. This is really a hack, and means that apps can in some 15412 // cases get permissions that the user didn't initially explicitly 15413 // allow... it would be nice to have some better way to handle 15414 // this situation. 15415 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 15416 if (regrantPermissions) 15417 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 15418 + mSdkVersion + "; regranting permissions for external storage"); 15419 mSettings.mExternalSdkPlatform = mSdkVersion; 15420 15421 // Make sure group IDs have been assigned, and any permission 15422 // changes in other apps are accounted for 15423 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 15424 | (regrantPermissions 15425 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 15426 : 0)); 15427 15428 mSettings.updateExternalDatabaseVersion(); 15429 15430 // can downgrade to reader 15431 // Persist settings 15432 mSettings.writeLPr(); 15433 } 15434 // Send a broadcast to let everyone know we are done processing 15435 if (pkgList.size() > 0) { 15436 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 15437 } 15438 } 15439 15440 /* 15441 * Utility method to unload a list of specified containers 15442 */ 15443 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 15444 // Just unmount all valid containers. 15445 for (AsecInstallArgs arg : cidArgs) { 15446 synchronized (mInstallLock) { 15447 arg.doPostDeleteLI(false); 15448 } 15449 } 15450 } 15451 15452 /* 15453 * Unload packages mounted on external media. This involves deleting package 15454 * data from internal structures, sending broadcasts about diabled packages, 15455 * gc'ing to free up references, unmounting all secure containers 15456 * corresponding to packages on external media, and posting a 15457 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 15458 * that we always have to post this message if status has been requested no 15459 * matter what. 15460 */ 15461 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 15462 final boolean reportStatus) { 15463 if (DEBUG_SD_INSTALL) 15464 Log.i(TAG, "unloading media packages"); 15465 ArrayList<String> pkgList = new ArrayList<String>(); 15466 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 15467 final Set<AsecInstallArgs> keys = processCids.keySet(); 15468 for (AsecInstallArgs args : keys) { 15469 String pkgName = args.getPackageName(); 15470 if (DEBUG_SD_INSTALL) 15471 Log.i(TAG, "Trying to unload pkg : " + pkgName); 15472 // Delete package internally 15473 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15474 synchronized (mInstallLock) { 15475 boolean res = deletePackageLI(pkgName, null, false, null, null, 15476 PackageManager.DELETE_KEEP_DATA, outInfo, false); 15477 if (res) { 15478 pkgList.add(pkgName); 15479 } else { 15480 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 15481 failedList.add(args); 15482 } 15483 } 15484 } 15485 15486 // reader 15487 synchronized (mPackages) { 15488 // We didn't update the settings after removing each package; 15489 // write them now for all packages. 15490 mSettings.writeLPr(); 15491 } 15492 15493 // We have to absolutely send UPDATED_MEDIA_STATUS only 15494 // after confirming that all the receivers processed the ordered 15495 // broadcast when packages get disabled, force a gc to clean things up. 15496 // and unload all the containers. 15497 if (pkgList.size() > 0) { 15498 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 15499 new IIntentReceiver.Stub() { 15500 public void performReceive(Intent intent, int resultCode, String data, 15501 Bundle extras, boolean ordered, boolean sticky, 15502 int sendingUser) throws RemoteException { 15503 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 15504 reportStatus ? 1 : 0, 1, keys); 15505 mHandler.sendMessage(msg); 15506 } 15507 }); 15508 } else { 15509 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 15510 keys); 15511 mHandler.sendMessage(msg); 15512 } 15513 } 15514 15515 private void loadPrivatePackages(VolumeInfo vol) { 15516 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 15517 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 15518 synchronized (mInstallLock) { 15519 synchronized (mPackages) { 15520 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15521 for (PackageSetting ps : packages) { 15522 final PackageParser.Package pkg; 15523 try { 15524 pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null); 15525 loaded.add(pkg.applicationInfo); 15526 } catch (PackageManagerException e) { 15527 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 15528 } 15529 } 15530 15531 // TODO: regrant any permissions that changed based since original install 15532 15533 mSettings.writeLPr(); 15534 } 15535 } 15536 15537 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 15538 sendResourcesChangedBroadcast(true, false, loaded, null); 15539 } 15540 15541 private void unloadPrivatePackages(VolumeInfo vol) { 15542 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 15543 synchronized (mInstallLock) { 15544 synchronized (mPackages) { 15545 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15546 for (PackageSetting ps : packages) { 15547 if (ps.pkg == null) continue; 15548 15549 final ApplicationInfo info = ps.pkg.applicationInfo; 15550 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15551 if (deletePackageLI(ps.name, null, false, null, null, 15552 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 15553 unloaded.add(info); 15554 } else { 15555 Slog.w(TAG, "Failed to unload " + ps.codePath); 15556 } 15557 } 15558 15559 mSettings.writeLPr(); 15560 } 15561 } 15562 15563 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 15564 sendResourcesChangedBroadcast(false, false, unloaded, null); 15565 } 15566 15567 /** 15568 * Examine all users present on given mounted volume, and destroy data 15569 * belonging to users that are no longer valid, or whose user ID has been 15570 * recycled. 15571 */ 15572 private void reconcileUsers(String volumeUuid) { 15573 final File[] files = Environment.getDataUserDirectory(volumeUuid).listFiles(); 15574 if (ArrayUtils.isEmpty(files)) { 15575 Slog.d(TAG, "No users found on " + volumeUuid); 15576 return; 15577 } 15578 15579 for (File file : files) { 15580 if (!file.isDirectory()) continue; 15581 15582 final int userId; 15583 final UserInfo info; 15584 try { 15585 userId = Integer.parseInt(file.getName()); 15586 info = sUserManager.getUserInfo(userId); 15587 } catch (NumberFormatException e) { 15588 Slog.w(TAG, "Invalid user directory " + file); 15589 continue; 15590 } 15591 15592 boolean destroyUser = false; 15593 if (info == null) { 15594 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15595 + " because no matching user was found"); 15596 destroyUser = true; 15597 } else { 15598 try { 15599 UserManagerService.enforceSerialNumber(file, info.serialNumber); 15600 } catch (IOException e) { 15601 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15602 + " because we failed to enforce serial number: " + e); 15603 destroyUser = true; 15604 } 15605 } 15606 15607 if (destroyUser) { 15608 synchronized (mInstallLock) { 15609 mInstaller.removeUserDataDirs(volumeUuid, userId); 15610 } 15611 } 15612 } 15613 15614 final UserManager um = mContext.getSystemService(UserManager.class); 15615 for (UserInfo user : um.getUsers()) { 15616 final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id); 15617 if (userDir.exists()) continue; 15618 15619 try { 15620 UserManagerService.prepareUserDirectory(userDir); 15621 UserManagerService.enforceSerialNumber(userDir, user.serialNumber); 15622 } catch (IOException e) { 15623 Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e); 15624 } 15625 } 15626 } 15627 15628 /** 15629 * Examine all apps present on given mounted volume, and destroy apps that 15630 * aren't expected, either due to uninstallation or reinstallation on 15631 * another volume. 15632 */ 15633 private void reconcileApps(String volumeUuid) { 15634 final File[] files = Environment.getDataAppDirectory(volumeUuid).listFiles(); 15635 if (ArrayUtils.isEmpty(files)) { 15636 Slog.d(TAG, "No apps found on " + volumeUuid); 15637 return; 15638 } 15639 15640 for (File file : files) { 15641 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 15642 && !PackageInstallerService.isStageName(file.getName()); 15643 if (!isPackage) { 15644 // Ignore entries which are not packages 15645 continue; 15646 } 15647 15648 boolean destroyApp = false; 15649 String packageName = null; 15650 try { 15651 final PackageLite pkg = PackageParser.parsePackageLite(file, 15652 PackageParser.PARSE_MUST_BE_APK); 15653 packageName = pkg.packageName; 15654 15655 synchronized (mPackages) { 15656 final PackageSetting ps = mSettings.mPackages.get(packageName); 15657 if (ps == null) { 15658 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + " 15659 + volumeUuid + " because we found no install record"); 15660 destroyApp = true; 15661 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 15662 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on " 15663 + volumeUuid + " because we expected it on " + ps.volumeUuid); 15664 destroyApp = true; 15665 } 15666 } 15667 15668 } catch (PackageParserException e) { 15669 logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e); 15670 destroyApp = true; 15671 } 15672 15673 if (destroyApp) { 15674 synchronized (mInstallLock) { 15675 if (packageName != null) { 15676 removeDataDirsLI(volumeUuid, packageName); 15677 } 15678 if (file.isDirectory()) { 15679 mInstaller.rmPackageDir(file.getAbsolutePath()); 15680 } else { 15681 file.delete(); 15682 } 15683 } 15684 } 15685 } 15686 } 15687 15688 private void unfreezePackage(String packageName) { 15689 synchronized (mPackages) { 15690 final PackageSetting ps = mSettings.mPackages.get(packageName); 15691 if (ps != null) { 15692 ps.frozen = false; 15693 } 15694 } 15695 } 15696 15697 @Override 15698 public int movePackage(final String packageName, final String volumeUuid) { 15699 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15700 15701 final int moveId = mNextMoveId.getAndIncrement(); 15702 try { 15703 movePackageInternal(packageName, volumeUuid, moveId); 15704 } catch (PackageManagerException e) { 15705 Slog.w(TAG, "Failed to move " + packageName, e); 15706 mMoveCallbacks.notifyStatusChanged(moveId, 15707 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15708 } 15709 return moveId; 15710 } 15711 15712 private void movePackageInternal(final String packageName, final String volumeUuid, 15713 final int moveId) throws PackageManagerException { 15714 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 15715 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15716 final PackageManager pm = mContext.getPackageManager(); 15717 15718 final boolean currentAsec; 15719 final String currentVolumeUuid; 15720 final File codeFile; 15721 final String installerPackageName; 15722 final String packageAbiOverride; 15723 final int appId; 15724 final String seinfo; 15725 final String label; 15726 15727 // reader 15728 synchronized (mPackages) { 15729 final PackageParser.Package pkg = mPackages.get(packageName); 15730 final PackageSetting ps = mSettings.mPackages.get(packageName); 15731 if (pkg == null || ps == null) { 15732 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 15733 } 15734 15735 if (pkg.applicationInfo.isSystemApp()) { 15736 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 15737 "Cannot move system application"); 15738 } 15739 15740 if (Objects.equals(ps.volumeUuid, volumeUuid)) { 15741 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15742 "Package already moved to " + volumeUuid); 15743 } 15744 15745 final File probe = new File(pkg.codePath); 15746 final File probeOat = new File(probe, "oat"); 15747 if (!probe.isDirectory() || !probeOat.isDirectory()) { 15748 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15749 "Move only supported for modern cluster style installs"); 15750 } 15751 15752 if (ps.frozen) { 15753 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 15754 "Failed to move already frozen package"); 15755 } 15756 ps.frozen = true; 15757 15758 currentAsec = pkg.applicationInfo.isForwardLocked() 15759 || pkg.applicationInfo.isExternalAsec(); 15760 currentVolumeUuid = ps.volumeUuid; 15761 codeFile = new File(pkg.codePath); 15762 installerPackageName = ps.installerPackageName; 15763 packageAbiOverride = ps.cpuAbiOverrideString; 15764 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 15765 seinfo = pkg.applicationInfo.seinfo; 15766 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 15767 } 15768 15769 // Now that we're guarded by frozen state, kill app during move 15770 killApplication(packageName, appId, "move pkg"); 15771 15772 final Bundle extras = new Bundle(); 15773 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 15774 extras.putString(Intent.EXTRA_TITLE, label); 15775 mMoveCallbacks.notifyCreated(moveId, extras); 15776 15777 int installFlags; 15778 final boolean moveCompleteApp; 15779 final File measurePath; 15780 15781 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 15782 installFlags = INSTALL_INTERNAL; 15783 moveCompleteApp = !currentAsec; 15784 measurePath = Environment.getDataAppDirectory(volumeUuid); 15785 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 15786 installFlags = INSTALL_EXTERNAL; 15787 moveCompleteApp = false; 15788 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 15789 } else { 15790 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 15791 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 15792 || !volume.isMountedWritable()) { 15793 unfreezePackage(packageName); 15794 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15795 "Move location not mounted private volume"); 15796 } 15797 15798 Preconditions.checkState(!currentAsec); 15799 15800 installFlags = INSTALL_INTERNAL; 15801 moveCompleteApp = true; 15802 measurePath = Environment.getDataAppDirectory(volumeUuid); 15803 } 15804 15805 final PackageStats stats = new PackageStats(null, -1); 15806 synchronized (mInstaller) { 15807 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 15808 unfreezePackage(packageName); 15809 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15810 "Failed to measure package size"); 15811 } 15812 } 15813 15814 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 15815 + stats.dataSize); 15816 15817 final long startFreeBytes = measurePath.getFreeSpace(); 15818 final long sizeBytes; 15819 if (moveCompleteApp) { 15820 sizeBytes = stats.codeSize + stats.dataSize; 15821 } else { 15822 sizeBytes = stats.codeSize; 15823 } 15824 15825 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 15826 unfreezePackage(packageName); 15827 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15828 "Not enough free space to move"); 15829 } 15830 15831 mMoveCallbacks.notifyStatusChanged(moveId, 10); 15832 15833 final CountDownLatch installedLatch = new CountDownLatch(1); 15834 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 15835 @Override 15836 public void onUserActionRequired(Intent intent) throws RemoteException { 15837 throw new IllegalStateException(); 15838 } 15839 15840 @Override 15841 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 15842 Bundle extras) throws RemoteException { 15843 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 15844 + PackageManager.installStatusToString(returnCode, msg)); 15845 15846 installedLatch.countDown(); 15847 15848 // Regardless of success or failure of the move operation, 15849 // always unfreeze the package 15850 unfreezePackage(packageName); 15851 15852 final int status = PackageManager.installStatusToPublicStatus(returnCode); 15853 switch (status) { 15854 case PackageInstaller.STATUS_SUCCESS: 15855 mMoveCallbacks.notifyStatusChanged(moveId, 15856 PackageManager.MOVE_SUCCEEDED); 15857 break; 15858 case PackageInstaller.STATUS_FAILURE_STORAGE: 15859 mMoveCallbacks.notifyStatusChanged(moveId, 15860 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 15861 break; 15862 default: 15863 mMoveCallbacks.notifyStatusChanged(moveId, 15864 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15865 break; 15866 } 15867 } 15868 }; 15869 15870 final MoveInfo move; 15871 if (moveCompleteApp) { 15872 // Kick off a thread to report progress estimates 15873 new Thread() { 15874 @Override 15875 public void run() { 15876 while (true) { 15877 try { 15878 if (installedLatch.await(1, TimeUnit.SECONDS)) { 15879 break; 15880 } 15881 } catch (InterruptedException ignored) { 15882 } 15883 15884 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 15885 final int progress = 10 + (int) MathUtils.constrain( 15886 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 15887 mMoveCallbacks.notifyStatusChanged(moveId, progress); 15888 } 15889 } 15890 }.start(); 15891 15892 final String dataAppName = codeFile.getName(); 15893 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 15894 dataAppName, appId, seinfo); 15895 } else { 15896 move = null; 15897 } 15898 15899 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 15900 15901 final Message msg = mHandler.obtainMessage(INIT_COPY); 15902 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 15903 msg.obj = new InstallParams(origin, move, installObserver, installFlags, 15904 installerPackageName, volumeUuid, null, user, packageAbiOverride, null); 15905 mHandler.sendMessage(msg); 15906 } 15907 15908 @Override 15909 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 15910 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15911 15912 final int realMoveId = mNextMoveId.getAndIncrement(); 15913 final Bundle extras = new Bundle(); 15914 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 15915 mMoveCallbacks.notifyCreated(realMoveId, extras); 15916 15917 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 15918 @Override 15919 public void onCreated(int moveId, Bundle extras) { 15920 // Ignored 15921 } 15922 15923 @Override 15924 public void onStatusChanged(int moveId, int status, long estMillis) { 15925 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 15926 } 15927 }; 15928 15929 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15930 storage.setPrimaryStorageUuid(volumeUuid, callback); 15931 return realMoveId; 15932 } 15933 15934 @Override 15935 public int getMoveStatus(int moveId) { 15936 mContext.enforceCallingOrSelfPermission( 15937 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15938 return mMoveCallbacks.mLastStatus.get(moveId); 15939 } 15940 15941 @Override 15942 public void registerMoveCallback(IPackageMoveObserver callback) { 15943 mContext.enforceCallingOrSelfPermission( 15944 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15945 mMoveCallbacks.register(callback); 15946 } 15947 15948 @Override 15949 public void unregisterMoveCallback(IPackageMoveObserver callback) { 15950 mContext.enforceCallingOrSelfPermission( 15951 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15952 mMoveCallbacks.unregister(callback); 15953 } 15954 15955 @Override 15956 public boolean setInstallLocation(int loc) { 15957 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 15958 null); 15959 if (getInstallLocation() == loc) { 15960 return true; 15961 } 15962 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 15963 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 15964 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 15965 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 15966 return true; 15967 } 15968 return false; 15969 } 15970 15971 @Override 15972 public int getInstallLocation() { 15973 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 15974 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 15975 PackageHelper.APP_INSTALL_AUTO); 15976 } 15977 15978 /** Called by UserManagerService */ 15979 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 15980 mDirtyUsers.remove(userHandle); 15981 mSettings.removeUserLPw(userHandle); 15982 mPendingBroadcasts.remove(userHandle); 15983 if (mInstaller != null) { 15984 // Technically, we shouldn't be doing this with the package lock 15985 // held. However, this is very rare, and there is already so much 15986 // other disk I/O going on, that we'll let it slide for now. 15987 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15988 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 15989 final String volumeUuid = vol.getFsUuid(); 15990 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 15991 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 15992 } 15993 } 15994 mUserNeedsBadging.delete(userHandle); 15995 removeUnusedPackagesLILPw(userManager, userHandle); 15996 } 15997 15998 /** 15999 * We're removing userHandle and would like to remove any downloaded packages 16000 * that are no longer in use by any other user. 16001 * @param userHandle the user being removed 16002 */ 16003 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 16004 final boolean DEBUG_CLEAN_APKS = false; 16005 int [] users = userManager.getUserIdsLPr(); 16006 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 16007 while (psit.hasNext()) { 16008 PackageSetting ps = psit.next(); 16009 if (ps.pkg == null) { 16010 continue; 16011 } 16012 final String packageName = ps.pkg.packageName; 16013 // Skip over if system app 16014 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 16015 continue; 16016 } 16017 if (DEBUG_CLEAN_APKS) { 16018 Slog.i(TAG, "Checking package " + packageName); 16019 } 16020 boolean keep = false; 16021 for (int i = 0; i < users.length; i++) { 16022 if (users[i] != userHandle && ps.getInstalled(users[i])) { 16023 keep = true; 16024 if (DEBUG_CLEAN_APKS) { 16025 Slog.i(TAG, " Keeping package " + packageName + " for user " 16026 + users[i]); 16027 } 16028 break; 16029 } 16030 } 16031 if (!keep) { 16032 if (DEBUG_CLEAN_APKS) { 16033 Slog.i(TAG, " Removing package " + packageName); 16034 } 16035 mHandler.post(new Runnable() { 16036 public void run() { 16037 deletePackageX(packageName, userHandle, 0); 16038 } //end run 16039 }); 16040 } 16041 } 16042 } 16043 16044 /** Called by UserManagerService */ 16045 void createNewUserLILPw(int userHandle) { 16046 if (mInstaller != null) { 16047 mInstaller.createUserConfig(userHandle); 16048 mSettings.createNewUserLILPw(this, mInstaller, userHandle); 16049 applyFactoryDefaultBrowserLPw(userHandle); 16050 primeDomainVerificationsLPw(userHandle); 16051 } 16052 } 16053 16054 void newUserCreated(final int userHandle) { 16055 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 16056 } 16057 16058 @Override 16059 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 16060 mContext.enforceCallingOrSelfPermission( 16061 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 16062 "Only package verification agents can read the verifier device identity"); 16063 16064 synchronized (mPackages) { 16065 return mSettings.getVerifierDeviceIdentityLPw(); 16066 } 16067 } 16068 16069 @Override 16070 public void setPermissionEnforced(String permission, boolean enforced) { 16071 // TODO: Now that we no longer change GID for storage, this should to away. 16072 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 16073 "setPermissionEnforced"); 16074 if (READ_EXTERNAL_STORAGE.equals(permission)) { 16075 synchronized (mPackages) { 16076 if (mSettings.mReadExternalStorageEnforced == null 16077 || mSettings.mReadExternalStorageEnforced != enforced) { 16078 mSettings.mReadExternalStorageEnforced = enforced; 16079 mSettings.writeLPr(); 16080 } 16081 } 16082 // kill any non-foreground processes so we restart them and 16083 // grant/revoke the GID. 16084 final IActivityManager am = ActivityManagerNative.getDefault(); 16085 if (am != null) { 16086 final long token = Binder.clearCallingIdentity(); 16087 try { 16088 am.killProcessesBelowForeground("setPermissionEnforcement"); 16089 } catch (RemoteException e) { 16090 } finally { 16091 Binder.restoreCallingIdentity(token); 16092 } 16093 } 16094 } else { 16095 throw new IllegalArgumentException("No selective enforcement for " + permission); 16096 } 16097 } 16098 16099 @Override 16100 @Deprecated 16101 public boolean isPermissionEnforced(String permission) { 16102 return true; 16103 } 16104 16105 @Override 16106 public boolean isStorageLow() { 16107 final long token = Binder.clearCallingIdentity(); 16108 try { 16109 final DeviceStorageMonitorInternal 16110 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 16111 if (dsm != null) { 16112 return dsm.isMemoryLow(); 16113 } else { 16114 return false; 16115 } 16116 } finally { 16117 Binder.restoreCallingIdentity(token); 16118 } 16119 } 16120 16121 @Override 16122 public IPackageInstaller getPackageInstaller() { 16123 return mInstallerService; 16124 } 16125 16126 private boolean userNeedsBadging(int userId) { 16127 int index = mUserNeedsBadging.indexOfKey(userId); 16128 if (index < 0) { 16129 final UserInfo userInfo; 16130 final long token = Binder.clearCallingIdentity(); 16131 try { 16132 userInfo = sUserManager.getUserInfo(userId); 16133 } finally { 16134 Binder.restoreCallingIdentity(token); 16135 } 16136 final boolean b; 16137 if (userInfo != null && userInfo.isManagedProfile()) { 16138 b = true; 16139 } else { 16140 b = false; 16141 } 16142 mUserNeedsBadging.put(userId, b); 16143 return b; 16144 } 16145 return mUserNeedsBadging.valueAt(index); 16146 } 16147 16148 @Override 16149 public KeySet getKeySetByAlias(String packageName, String alias) { 16150 if (packageName == null || alias == null) { 16151 return null; 16152 } 16153 synchronized(mPackages) { 16154 final PackageParser.Package pkg = mPackages.get(packageName); 16155 if (pkg == null) { 16156 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16157 throw new IllegalArgumentException("Unknown package: " + packageName); 16158 } 16159 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16160 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 16161 } 16162 } 16163 16164 @Override 16165 public KeySet getSigningKeySet(String packageName) { 16166 if (packageName == null) { 16167 return null; 16168 } 16169 synchronized(mPackages) { 16170 final PackageParser.Package pkg = mPackages.get(packageName); 16171 if (pkg == null) { 16172 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16173 throw new IllegalArgumentException("Unknown package: " + packageName); 16174 } 16175 if (pkg.applicationInfo.uid != Binder.getCallingUid() 16176 && Process.SYSTEM_UID != Binder.getCallingUid()) { 16177 throw new SecurityException("May not access signing KeySet of other apps."); 16178 } 16179 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16180 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 16181 } 16182 } 16183 16184 @Override 16185 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 16186 if (packageName == null || ks == null) { 16187 return false; 16188 } 16189 synchronized(mPackages) { 16190 final PackageParser.Package pkg = mPackages.get(packageName); 16191 if (pkg == null) { 16192 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16193 throw new IllegalArgumentException("Unknown package: " + packageName); 16194 } 16195 IBinder ksh = ks.getToken(); 16196 if (ksh instanceof KeySetHandle) { 16197 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16198 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 16199 } 16200 return false; 16201 } 16202 } 16203 16204 @Override 16205 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 16206 if (packageName == null || ks == null) { 16207 return false; 16208 } 16209 synchronized(mPackages) { 16210 final PackageParser.Package pkg = mPackages.get(packageName); 16211 if (pkg == null) { 16212 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16213 throw new IllegalArgumentException("Unknown package: " + packageName); 16214 } 16215 IBinder ksh = ks.getToken(); 16216 if (ksh instanceof KeySetHandle) { 16217 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16218 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 16219 } 16220 return false; 16221 } 16222 } 16223 16224 public void getUsageStatsIfNoPackageUsageInfo() { 16225 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 16226 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 16227 if (usm == null) { 16228 throw new IllegalStateException("UsageStatsManager must be initialized"); 16229 } 16230 long now = System.currentTimeMillis(); 16231 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 16232 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 16233 String packageName = entry.getKey(); 16234 PackageParser.Package pkg = mPackages.get(packageName); 16235 if (pkg == null) { 16236 continue; 16237 } 16238 UsageStats usage = entry.getValue(); 16239 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 16240 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 16241 } 16242 } 16243 } 16244 16245 /** 16246 * Check and throw if the given before/after packages would be considered a 16247 * downgrade. 16248 */ 16249 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 16250 throws PackageManagerException { 16251 if (after.versionCode < before.mVersionCode) { 16252 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16253 "Update version code " + after.versionCode + " is older than current " 16254 + before.mVersionCode); 16255 } else if (after.versionCode == before.mVersionCode) { 16256 if (after.baseRevisionCode < before.baseRevisionCode) { 16257 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16258 "Update base revision code " + after.baseRevisionCode 16259 + " is older than current " + before.baseRevisionCode); 16260 } 16261 16262 if (!ArrayUtils.isEmpty(after.splitNames)) { 16263 for (int i = 0; i < after.splitNames.length; i++) { 16264 final String splitName = after.splitNames[i]; 16265 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 16266 if (j != -1) { 16267 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 16268 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16269 "Update split " + splitName + " revision code " 16270 + after.splitRevisionCodes[i] + " is older than current " 16271 + before.splitRevisionCodes[j]); 16272 } 16273 } 16274 } 16275 } 16276 } 16277 } 16278 16279 private static class MoveCallbacks extends Handler { 16280 private static final int MSG_CREATED = 1; 16281 private static final int MSG_STATUS_CHANGED = 2; 16282 16283 private final RemoteCallbackList<IPackageMoveObserver> 16284 mCallbacks = new RemoteCallbackList<>(); 16285 16286 private final SparseIntArray mLastStatus = new SparseIntArray(); 16287 16288 public MoveCallbacks(Looper looper) { 16289 super(looper); 16290 } 16291 16292 public void register(IPackageMoveObserver callback) { 16293 mCallbacks.register(callback); 16294 } 16295 16296 public void unregister(IPackageMoveObserver callback) { 16297 mCallbacks.unregister(callback); 16298 } 16299 16300 @Override 16301 public void handleMessage(Message msg) { 16302 final SomeArgs args = (SomeArgs) msg.obj; 16303 final int n = mCallbacks.beginBroadcast(); 16304 for (int i = 0; i < n; i++) { 16305 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 16306 try { 16307 invokeCallback(callback, msg.what, args); 16308 } catch (RemoteException ignored) { 16309 } 16310 } 16311 mCallbacks.finishBroadcast(); 16312 args.recycle(); 16313 } 16314 16315 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 16316 throws RemoteException { 16317 switch (what) { 16318 case MSG_CREATED: { 16319 callback.onCreated(args.argi1, (Bundle) args.arg2); 16320 break; 16321 } 16322 case MSG_STATUS_CHANGED: { 16323 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 16324 break; 16325 } 16326 } 16327 } 16328 16329 private void notifyCreated(int moveId, Bundle extras) { 16330 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 16331 16332 final SomeArgs args = SomeArgs.obtain(); 16333 args.argi1 = moveId; 16334 args.arg2 = extras; 16335 obtainMessage(MSG_CREATED, args).sendToTarget(); 16336 } 16337 16338 private void notifyStatusChanged(int moveId, int status) { 16339 notifyStatusChanged(moveId, status, -1); 16340 } 16341 16342 private void notifyStatusChanged(int moveId, int status, long estMillis) { 16343 Slog.v(TAG, "Move " + moveId + " status " + status); 16344 16345 final SomeArgs args = SomeArgs.obtain(); 16346 args.argi1 = moveId; 16347 args.argi2 = status; 16348 args.arg3 = estMillis; 16349 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 16350 16351 synchronized (mLastStatus) { 16352 mLastStatus.put(moveId, status); 16353 } 16354 } 16355 } 16356 16357 private final class OnPermissionChangeListeners extends Handler { 16358 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 16359 16360 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 16361 new RemoteCallbackList<>(); 16362 16363 public OnPermissionChangeListeners(Looper looper) { 16364 super(looper); 16365 } 16366 16367 @Override 16368 public void handleMessage(Message msg) { 16369 switch (msg.what) { 16370 case MSG_ON_PERMISSIONS_CHANGED: { 16371 final int uid = msg.arg1; 16372 handleOnPermissionsChanged(uid); 16373 } break; 16374 } 16375 } 16376 16377 public void addListenerLocked(IOnPermissionsChangeListener listener) { 16378 mPermissionListeners.register(listener); 16379 16380 } 16381 16382 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 16383 mPermissionListeners.unregister(listener); 16384 } 16385 16386 public void onPermissionsChanged(int uid) { 16387 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 16388 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 16389 } 16390 } 16391 16392 private void handleOnPermissionsChanged(int uid) { 16393 final int count = mPermissionListeners.beginBroadcast(); 16394 try { 16395 for (int i = 0; i < count; i++) { 16396 IOnPermissionsChangeListener callback = mPermissionListeners 16397 .getBroadcastItem(i); 16398 try { 16399 callback.onPermissionsChanged(uid); 16400 } catch (RemoteException e) { 16401 Log.e(TAG, "Permission listener is dead", e); 16402 } 16403 } 16404 } finally { 16405 mPermissionListeners.finishBroadcast(); 16406 } 16407 } 16408 } 16409 16410 private class PackageManagerInternalImpl extends PackageManagerInternal { 16411 @Override 16412 public void setLocationPackagesProvider(PackagesProvider provider) { 16413 synchronized (mPackages) { 16414 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 16415 } 16416 } 16417 16418 @Override 16419 public void setImePackagesProvider(PackagesProvider provider) { 16420 synchronized (mPackages) { 16421 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 16422 } 16423 } 16424 16425 @Override 16426 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 16427 synchronized (mPackages) { 16428 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 16429 } 16430 } 16431 16432 @Override 16433 public void setSmsAppPackagesProvider(PackagesProvider provider) { 16434 synchronized (mPackages) { 16435 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 16436 } 16437 } 16438 16439 @Override 16440 public void setDialerAppPackagesProvider(PackagesProvider provider) { 16441 synchronized (mPackages) { 16442 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 16443 } 16444 } 16445 16446 @Override 16447 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 16448 synchronized (mPackages) { 16449 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 16450 } 16451 } 16452 16453 @Override 16454 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 16455 synchronized (mPackages) { 16456 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 16457 packageName, userId); 16458 } 16459 } 16460 16461 @Override 16462 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 16463 synchronized (mPackages) { 16464 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 16465 packageName, userId); 16466 } 16467 } 16468 } 16469 16470 @Override 16471 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 16472 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 16473 synchronized (mPackages) { 16474 final long identity = Binder.clearCallingIdentity(); 16475 try { 16476 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 16477 packageNames, userId); 16478 } finally { 16479 Binder.restoreCallingIdentity(identity); 16480 } 16481 } 16482 } 16483 16484 private static void enforceSystemOrPhoneCaller(String tag) { 16485 int callingUid = Binder.getCallingUid(); 16486 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 16487 throw new SecurityException( 16488 "Cannot call " + tag + " from UID " + callingUid); 16489 } 16490 } 16491} 16492