PackageManagerService.java revision 2d9d59053fcb8504914f358a1417e67a94c0f8f1
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 21import static android.Manifest.permission.WRITE_MEDIA_STORAGE; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 27import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 28import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 29import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 30import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 31import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 32import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 33import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 34import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 35import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 36import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 37import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 39import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 40import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 41import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 42import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 43import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 44import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 45import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 46import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 47import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 48import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED; 49import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 50import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 51import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 52import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 53import static android.content.pm.PackageManager.INSTALL_INTERNAL; 54import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 55import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 59import static android.content.pm.PackageManager.MATCH_ALL; 60import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 61import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 62import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 63import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 64import static android.content.pm.PackageManager.PERMISSION_DENIED; 65import static android.content.pm.PackageManager.PERMISSION_GRANTED; 66import static android.content.pm.PackageParser.isApkFile; 67import static android.os.Process.PACKAGE_INFO_GID; 68import static android.os.Process.SYSTEM_UID; 69import static android.system.OsConstants.O_CREAT; 70import static android.system.OsConstants.O_RDWR; 71import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 72import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER; 73import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 74import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 75import static com.android.internal.util.ArrayUtils.appendInt; 76import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 77import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 78import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 79import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 80import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 81import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 82import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 83import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 84 85import android.Manifest; 86import android.app.ActivityManager; 87import android.app.ActivityManagerNative; 88import android.app.AppGlobals; 89import android.app.IActivityManager; 90import android.app.admin.IDevicePolicyManager; 91import android.app.backup.IBackupManager; 92import android.app.usage.UsageStats; 93import android.app.usage.UsageStatsManager; 94import android.content.BroadcastReceiver; 95import android.content.ComponentName; 96import android.content.Context; 97import android.content.IIntentReceiver; 98import android.content.Intent; 99import android.content.IntentFilter; 100import android.content.IntentSender; 101import android.content.IntentSender.SendIntentException; 102import android.content.ServiceConnection; 103import android.content.pm.ActivityInfo; 104import android.content.pm.ApplicationInfo; 105import android.content.pm.FeatureInfo; 106import android.content.pm.IOnPermissionsChangeListener; 107import android.content.pm.IPackageDataObserver; 108import android.content.pm.IPackageDeleteObserver; 109import android.content.pm.IPackageDeleteObserver2; 110import android.content.pm.IPackageInstallObserver2; 111import android.content.pm.IPackageInstaller; 112import android.content.pm.IPackageManager; 113import android.content.pm.IPackageMoveObserver; 114import android.content.pm.IPackageStatsObserver; 115import android.content.pm.InstrumentationInfo; 116import android.content.pm.IntentFilterVerificationInfo; 117import android.content.pm.KeySet; 118import android.content.pm.ManifestDigest; 119import android.content.pm.PackageCleanItem; 120import android.content.pm.PackageInfo; 121import android.content.pm.PackageInfoLite; 122import android.content.pm.PackageInstaller; 123import android.content.pm.PackageManager; 124import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 125import android.content.pm.PackageManagerInternal; 126import android.content.pm.PackageParser; 127import android.content.pm.PackageParser.ActivityIntentInfo; 128import android.content.pm.PackageParser.PackageLite; 129import android.content.pm.PackageParser.PackageParserException; 130import android.content.pm.PackageStats; 131import android.content.pm.PackageUserState; 132import android.content.pm.ParceledListSlice; 133import android.content.pm.PermissionGroupInfo; 134import android.content.pm.PermissionInfo; 135import android.content.pm.ProviderInfo; 136import android.content.pm.ResolveInfo; 137import android.content.pm.ServiceInfo; 138import android.content.pm.Signature; 139import android.content.pm.UserInfo; 140import android.content.pm.VerificationParams; 141import android.content.pm.VerifierDeviceIdentity; 142import android.content.pm.VerifierInfo; 143import android.content.res.Resources; 144import android.hardware.display.DisplayManager; 145import android.net.Uri; 146import android.os.Debug; 147import android.os.Binder; 148import android.os.Build; 149import android.os.Bundle; 150import android.os.Environment; 151import android.os.Environment.UserEnvironment; 152import android.os.FileUtils; 153import android.os.Handler; 154import android.os.IBinder; 155import android.os.Looper; 156import android.os.Message; 157import android.os.Parcel; 158import android.os.ParcelFileDescriptor; 159import android.os.Process; 160import android.os.RemoteCallbackList; 161import android.os.RemoteException; 162import android.os.SELinux; 163import android.os.ServiceManager; 164import android.os.SystemClock; 165import android.os.SystemProperties; 166import android.os.UserHandle; 167import android.os.UserManager; 168import android.os.storage.IMountService; 169import android.os.storage.MountServiceInternal; 170import android.os.storage.StorageEventListener; 171import android.os.storage.StorageManager; 172import android.os.storage.VolumeInfo; 173import android.os.storage.VolumeRecord; 174import android.security.KeyStore; 175import android.security.SystemKeyStore; 176import android.system.ErrnoException; 177import android.system.Os; 178import android.system.StructStat; 179import android.text.TextUtils; 180import android.text.format.DateUtils; 181import android.util.ArrayMap; 182import android.util.ArraySet; 183import android.util.AtomicFile; 184import android.util.DisplayMetrics; 185import android.util.EventLog; 186import android.util.ExceptionUtils; 187import android.util.Log; 188import android.util.LogPrinter; 189import android.util.MathUtils; 190import android.util.PrintStreamPrinter; 191import android.util.Slog; 192import android.util.SparseArray; 193import android.util.SparseBooleanArray; 194import android.util.SparseIntArray; 195import android.util.Xml; 196import android.view.Display; 197 198import dalvik.system.DexFile; 199import dalvik.system.VMRuntime; 200 201import libcore.io.IoUtils; 202import libcore.util.EmptyArray; 203 204import com.android.internal.R; 205import com.android.internal.annotations.GuardedBy; 206import com.android.internal.app.IMediaContainerService; 207import com.android.internal.app.ResolverActivity; 208import com.android.internal.content.NativeLibraryHelper; 209import com.android.internal.content.PackageHelper; 210import com.android.internal.os.IParcelFileDescriptorFactory; 211import com.android.internal.os.SomeArgs; 212import com.android.internal.os.Zygote; 213import com.android.internal.util.ArrayUtils; 214import com.android.internal.util.FastPrintWriter; 215import com.android.internal.util.FastXmlSerializer; 216import com.android.internal.util.IndentingPrintWriter; 217import com.android.internal.util.Preconditions; 218import com.android.server.EventLogTags; 219import com.android.server.FgThread; 220import com.android.server.IntentResolver; 221import com.android.server.LocalServices; 222import com.android.server.ServiceThread; 223import com.android.server.SystemConfig; 224import com.android.server.Watchdog; 225import com.android.server.pm.PermissionsState.PermissionState; 226import com.android.server.pm.Settings.DatabaseVersion; 227import com.android.server.pm.Settings.VersionInfo; 228import com.android.server.storage.DeviceStorageMonitorInternal; 229 230import org.xmlpull.v1.XmlPullParser; 231import org.xmlpull.v1.XmlPullParserException; 232import org.xmlpull.v1.XmlSerializer; 233 234import java.io.BufferedInputStream; 235import java.io.BufferedOutputStream; 236import java.io.BufferedReader; 237import java.io.ByteArrayInputStream; 238import java.io.ByteArrayOutputStream; 239import java.io.File; 240import java.io.FileDescriptor; 241import java.io.FileNotFoundException; 242import java.io.FileOutputStream; 243import java.io.FileReader; 244import java.io.FilenameFilter; 245import java.io.IOException; 246import java.io.InputStream; 247import java.io.PrintWriter; 248import java.nio.charset.StandardCharsets; 249import java.security.NoSuchAlgorithmException; 250import java.security.PublicKey; 251import java.security.cert.CertificateEncodingException; 252import java.security.cert.CertificateException; 253import java.text.SimpleDateFormat; 254import java.util.ArrayList; 255import java.util.Arrays; 256import java.util.Collection; 257import java.util.Collections; 258import java.util.Comparator; 259import java.util.Date; 260import java.util.Iterator; 261import java.util.List; 262import java.util.Map; 263import java.util.Objects; 264import java.util.Set; 265import java.util.concurrent.CountDownLatch; 266import java.util.concurrent.TimeUnit; 267import java.util.concurrent.atomic.AtomicBoolean; 268import java.util.concurrent.atomic.AtomicInteger; 269import java.util.concurrent.atomic.AtomicLong; 270 271/** 272 * Keep track of all those .apks everywhere. 273 * 274 * This is very central to the platform's security; please run the unit 275 * tests whenever making modifications here: 276 * 277mmm frameworks/base/tests/AndroidTests 278adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 279adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 280 * 281 * {@hide} 282 */ 283public class PackageManagerService extends IPackageManager.Stub { 284 static final String TAG = "PackageManager"; 285 static final boolean DEBUG_SETTINGS = false; 286 static final boolean DEBUG_PREFERRED = false; 287 static final boolean DEBUG_UPGRADE = false; 288 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 289 private static final boolean DEBUG_BACKUP = false; 290 private static final boolean DEBUG_INSTALL = false; 291 private static final boolean DEBUG_REMOVE = false; 292 private static final boolean DEBUG_BROADCASTS = false; 293 private static final boolean DEBUG_SHOW_INFO = false; 294 private static final boolean DEBUG_PACKAGE_INFO = false; 295 private static final boolean DEBUG_INTENT_MATCHING = false; 296 private static final boolean DEBUG_PACKAGE_SCANNING = false; 297 private static final boolean DEBUG_VERIFY = false; 298 private static final boolean DEBUG_DEXOPT = false; 299 private static final boolean DEBUG_ABI_SELECTION = false; 300 301 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = Build.IS_DEBUGGABLE; 302 303 private static final int RADIO_UID = Process.PHONE_UID; 304 private static final int LOG_UID = Process.LOG_UID; 305 private static final int NFC_UID = Process.NFC_UID; 306 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 307 private static final int SHELL_UID = Process.SHELL_UID; 308 309 // Cap the size of permission trees that 3rd party apps can define 310 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 311 312 // Suffix used during package installation when copying/moving 313 // package apks to install directory. 314 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 315 316 static final int SCAN_NO_DEX = 1<<1; 317 static final int SCAN_FORCE_DEX = 1<<2; 318 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 319 static final int SCAN_NEW_INSTALL = 1<<4; 320 static final int SCAN_NO_PATHS = 1<<5; 321 static final int SCAN_UPDATE_TIME = 1<<6; 322 static final int SCAN_DEFER_DEX = 1<<7; 323 static final int SCAN_BOOTING = 1<<8; 324 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 325 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 326 static final int SCAN_REQUIRE_KNOWN = 1<<12; 327 static final int SCAN_MOVE = 1<<13; 328 static final int SCAN_INITIAL = 1<<14; 329 330 static final int REMOVE_CHATTY = 1<<16; 331 332 private static final int[] EMPTY_INT_ARRAY = new int[0]; 333 334 /** 335 * Timeout (in milliseconds) after which the watchdog should declare that 336 * our handler thread is wedged. The usual default for such things is one 337 * minute but we sometimes do very lengthy I/O operations on this thread, 338 * such as installing multi-gigabyte applications, so ours needs to be longer. 339 */ 340 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 341 342 /** 343 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 344 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 345 * settings entry if available, otherwise we use the hardcoded default. If it's been 346 * more than this long since the last fstrim, we force one during the boot sequence. 347 * 348 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 349 * one gets run at the next available charging+idle time. This final mandatory 350 * no-fstrim check kicks in only of the other scheduling criteria is never met. 351 */ 352 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 353 354 /** 355 * Whether verification is enabled by default. 356 */ 357 private static final boolean DEFAULT_VERIFY_ENABLE = true; 358 359 /** 360 * The default maximum time to wait for the verification agent to return in 361 * milliseconds. 362 */ 363 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 364 365 /** 366 * The default response for package verification timeout. 367 * 368 * This can be either PackageManager.VERIFICATION_ALLOW or 369 * PackageManager.VERIFICATION_REJECT. 370 */ 371 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 372 373 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 374 375 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 376 DEFAULT_CONTAINER_PACKAGE, 377 "com.android.defcontainer.DefaultContainerService"); 378 379 private static final String KILL_APP_REASON_GIDS_CHANGED = 380 "permission grant or revoke changed gids"; 381 382 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 383 "permissions revoked"; 384 385 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 386 387 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 388 389 /** Permission grant: not grant the permission. */ 390 private static final int GRANT_DENIED = 1; 391 392 /** Permission grant: grant the permission as an install permission. */ 393 private static final int GRANT_INSTALL = 2; 394 395 /** Permission grant: grant the permission as an install permission for a legacy app. */ 396 private static final int GRANT_INSTALL_LEGACY = 3; 397 398 /** Permission grant: grant the permission as a runtime one. */ 399 private static final int GRANT_RUNTIME = 4; 400 401 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 402 private static final int GRANT_UPGRADE = 5; 403 404 /** Canonical intent used to identify what counts as a "web browser" app */ 405 private static final Intent sBrowserIntent; 406 static { 407 sBrowserIntent = new Intent(); 408 sBrowserIntent.setAction(Intent.ACTION_VIEW); 409 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 410 sBrowserIntent.setData(Uri.parse("http:")); 411 } 412 413 final ServiceThread mHandlerThread; 414 415 final PackageHandler mHandler; 416 417 /** 418 * Messages for {@link #mHandler} that need to wait for system ready before 419 * being dispatched. 420 */ 421 private ArrayList<Message> mPostSystemReadyMessages; 422 423 final int mSdkVersion = Build.VERSION.SDK_INT; 424 425 final Context mContext; 426 final boolean mFactoryTest; 427 final boolean mOnlyCore; 428 final boolean mLazyDexOpt; 429 final long mDexOptLRUThresholdInMills; 430 final DisplayMetrics mMetrics; 431 final int mDefParseFlags; 432 final String[] mSeparateProcesses; 433 final boolean mIsUpgrade; 434 435 // This is where all application persistent data goes. 436 final File mAppDataDir; 437 438 // This is where all application persistent data goes for secondary users. 439 final File mUserAppDataDir; 440 441 /** The location for ASEC container files on internal storage. */ 442 final String mAsecInternalPath; 443 444 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 445 // LOCK HELD. Can be called with mInstallLock held. 446 @GuardedBy("mInstallLock") 447 final Installer mInstaller; 448 449 /** Directory where installed third-party apps stored */ 450 final File mAppInstallDir; 451 452 /** 453 * Directory to which applications installed internally have their 454 * 32 bit native libraries copied. 455 */ 456 private File mAppLib32InstallDir; 457 458 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 459 // apps. 460 final File mDrmAppPrivateInstallDir; 461 462 // ---------------------------------------------------------------- 463 464 // Lock for state used when installing and doing other long running 465 // operations. Methods that must be called with this lock held have 466 // the suffix "LI". 467 final Object mInstallLock = new Object(); 468 469 // ---------------------------------------------------------------- 470 471 // Keys are String (package name), values are Package. This also serves 472 // as the lock for the global state. Methods that must be called with 473 // this lock held have the prefix "LP". 474 @GuardedBy("mPackages") 475 final ArrayMap<String, PackageParser.Package> mPackages = 476 new ArrayMap<String, PackageParser.Package>(); 477 478 // Tracks available target package names -> overlay package paths. 479 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 480 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 481 482 /** 483 * Tracks new system packages [receiving in an OTA] that we expect to 484 * find updated user-installed versions. Keys are package name, values 485 * are package location. 486 */ 487 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 488 489 final Settings mSettings; 490 boolean mRestoredSettings; 491 492 // System configuration read by SystemConfig. 493 final int[] mGlobalGids; 494 final SparseArray<ArraySet<String>> mSystemPermissions; 495 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 496 497 // If mac_permissions.xml was found for seinfo labeling. 498 boolean mFoundPolicyFile; 499 500 // If a recursive restorecon of /data/data/<pkg> is needed. 501 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 502 503 public static final class SharedLibraryEntry { 504 public final String path; 505 public final String apk; 506 507 SharedLibraryEntry(String _path, String _apk) { 508 path = _path; 509 apk = _apk; 510 } 511 } 512 513 // Currently known shared libraries. 514 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 515 new ArrayMap<String, SharedLibraryEntry>(); 516 517 // All available activities, for your resolving pleasure. 518 final ActivityIntentResolver mActivities = 519 new ActivityIntentResolver(); 520 521 // All available receivers, for your resolving pleasure. 522 final ActivityIntentResolver mReceivers = 523 new ActivityIntentResolver(); 524 525 // All available services, for your resolving pleasure. 526 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 527 528 // All available providers, for your resolving pleasure. 529 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 530 531 // Mapping from provider base names (first directory in content URI codePath) 532 // to the provider information. 533 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 534 new ArrayMap<String, PackageParser.Provider>(); 535 536 // Mapping from instrumentation class names to info about them. 537 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 538 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 539 540 // Mapping from permission names to info about them. 541 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 542 new ArrayMap<String, PackageParser.PermissionGroup>(); 543 544 // Packages whose data we have transfered into another package, thus 545 // should no longer exist. 546 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 547 548 // Broadcast actions that are only available to the system. 549 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 550 551 /** List of packages waiting for verification. */ 552 final SparseArray<PackageVerificationState> mPendingVerification 553 = new SparseArray<PackageVerificationState>(); 554 555 /** Set of packages associated with each app op permission. */ 556 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 557 558 final PackageInstallerService mInstallerService; 559 560 private final PackageDexOptimizer mPackageDexOptimizer; 561 562 private AtomicInteger mNextMoveId = new AtomicInteger(); 563 private final MoveCallbacks mMoveCallbacks; 564 565 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 566 567 // Cache of users who need badging. 568 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 569 570 /** Token for keys in mPendingVerification. */ 571 private int mPendingVerificationToken = 0; 572 573 volatile boolean mSystemReady; 574 volatile boolean mSafeMode; 575 volatile boolean mHasSystemUidErrors; 576 577 ApplicationInfo mAndroidApplication; 578 final ActivityInfo mResolveActivity = new ActivityInfo(); 579 final ResolveInfo mResolveInfo = new ResolveInfo(); 580 ComponentName mResolveComponentName; 581 PackageParser.Package mPlatformPackage; 582 ComponentName mCustomResolverComponentName; 583 584 boolean mResolverReplaced = false; 585 586 private final ComponentName mIntentFilterVerifierComponent; 587 private int mIntentFilterVerificationToken = 0; 588 589 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 590 = new SparseArray<IntentFilterVerificationState>(); 591 592 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 593 new DefaultPermissionGrantPolicy(this); 594 595 private static class IFVerificationParams { 596 PackageParser.Package pkg; 597 boolean replacing; 598 int userId; 599 int verifierUid; 600 601 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 602 int _userId, int _verifierUid) { 603 pkg = _pkg; 604 replacing = _replacing; 605 userId = _userId; 606 replacing = _replacing; 607 verifierUid = _verifierUid; 608 } 609 } 610 611 private interface IntentFilterVerifier<T extends IntentFilter> { 612 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 613 T filter, String packageName); 614 void startVerifications(int userId); 615 void receiveVerificationResponse(int verificationId); 616 } 617 618 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 619 private Context mContext; 620 private ComponentName mIntentFilterVerifierComponent; 621 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 622 623 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 624 mContext = context; 625 mIntentFilterVerifierComponent = verifierComponent; 626 } 627 628 private String getDefaultScheme() { 629 return IntentFilter.SCHEME_HTTPS; 630 } 631 632 @Override 633 public void startVerifications(int userId) { 634 // Launch verifications requests 635 int count = mCurrentIntentFilterVerifications.size(); 636 for (int n=0; n<count; n++) { 637 int verificationId = mCurrentIntentFilterVerifications.get(n); 638 final IntentFilterVerificationState ivs = 639 mIntentFilterVerificationStates.get(verificationId); 640 641 String packageName = ivs.getPackageName(); 642 643 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 644 final int filterCount = filters.size(); 645 ArraySet<String> domainsSet = new ArraySet<>(); 646 for (int m=0; m<filterCount; m++) { 647 PackageParser.ActivityIntentInfo filter = filters.get(m); 648 domainsSet.addAll(filter.getHostsList()); 649 } 650 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 651 synchronized (mPackages) { 652 if (mSettings.createIntentFilterVerificationIfNeededLPw( 653 packageName, domainsList) != null) { 654 scheduleWriteSettingsLocked(); 655 } 656 } 657 sendVerificationRequest(userId, verificationId, ivs); 658 } 659 mCurrentIntentFilterVerifications.clear(); 660 } 661 662 private void sendVerificationRequest(int userId, int verificationId, 663 IntentFilterVerificationState ivs) { 664 665 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 666 verificationIntent.putExtra( 667 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 668 verificationId); 669 verificationIntent.putExtra( 670 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 671 getDefaultScheme()); 672 verificationIntent.putExtra( 673 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 674 ivs.getHostsString()); 675 verificationIntent.putExtra( 676 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 677 ivs.getPackageName()); 678 verificationIntent.setComponent(mIntentFilterVerifierComponent); 679 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 680 681 UserHandle user = new UserHandle(userId); 682 mContext.sendBroadcastAsUser(verificationIntent, user); 683 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 684 "Sending IntentFilter verification broadcast"); 685 } 686 687 public void receiveVerificationResponse(int verificationId) { 688 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 689 690 final boolean verified = ivs.isVerified(); 691 692 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 693 final int count = filters.size(); 694 if (DEBUG_DOMAIN_VERIFICATION) { 695 Slog.i(TAG, "Received verification response " + verificationId 696 + " for " + count + " filters, verified=" + verified); 697 } 698 for (int n=0; n<count; n++) { 699 PackageParser.ActivityIntentInfo filter = filters.get(n); 700 filter.setVerified(verified); 701 702 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 703 + " verified with result:" + verified + " and hosts:" 704 + ivs.getHostsString()); 705 } 706 707 mIntentFilterVerificationStates.remove(verificationId); 708 709 final String packageName = ivs.getPackageName(); 710 IntentFilterVerificationInfo ivi = null; 711 712 synchronized (mPackages) { 713 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 714 } 715 if (ivi == null) { 716 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 717 + verificationId + " packageName:" + packageName); 718 return; 719 } 720 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 721 "Updating IntentFilterVerificationInfo for package " + packageName 722 +" verificationId:" + verificationId); 723 724 synchronized (mPackages) { 725 if (verified) { 726 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 727 } else { 728 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 729 } 730 scheduleWriteSettingsLocked(); 731 732 final int userId = ivs.getUserId(); 733 if (userId != UserHandle.USER_ALL) { 734 final int userStatus = 735 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 736 737 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 738 boolean needUpdate = false; 739 740 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 741 // already been set by the User thru the Disambiguation dialog 742 switch (userStatus) { 743 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 744 if (verified) { 745 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 746 } else { 747 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 748 } 749 needUpdate = true; 750 break; 751 752 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 753 if (verified) { 754 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 755 needUpdate = true; 756 } 757 break; 758 759 default: 760 // Nothing to do 761 } 762 763 if (needUpdate) { 764 mSettings.updateIntentFilterVerificationStatusLPw( 765 packageName, updatedStatus, userId); 766 scheduleWritePackageRestrictionsLocked(userId); 767 } 768 } 769 } 770 } 771 772 @Override 773 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 774 ActivityIntentInfo filter, String packageName) { 775 if (!hasValidDomains(filter)) { 776 return false; 777 } 778 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 779 if (ivs == null) { 780 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 781 packageName); 782 } 783 if (DEBUG_DOMAIN_VERIFICATION) { 784 Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter); 785 } 786 ivs.addFilter(filter); 787 return true; 788 } 789 790 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 791 int userId, int verificationId, String packageName) { 792 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 793 verifierUid, userId, packageName); 794 ivs.setPendingState(); 795 synchronized (mPackages) { 796 mIntentFilterVerificationStates.append(verificationId, ivs); 797 mCurrentIntentFilterVerifications.add(verificationId); 798 } 799 return ivs; 800 } 801 } 802 803 private static boolean hasValidDomains(ActivityIntentInfo filter) { 804 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 805 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 806 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 807 } 808 809 private IntentFilterVerifier mIntentFilterVerifier; 810 811 // Set of pending broadcasts for aggregating enable/disable of components. 812 static class PendingPackageBroadcasts { 813 // for each user id, a map of <package name -> components within that package> 814 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 815 816 public PendingPackageBroadcasts() { 817 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 818 } 819 820 public ArrayList<String> get(int userId, String packageName) { 821 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 822 return packages.get(packageName); 823 } 824 825 public void put(int userId, String packageName, ArrayList<String> components) { 826 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 827 packages.put(packageName, components); 828 } 829 830 public void remove(int userId, String packageName) { 831 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 832 if (packages != null) { 833 packages.remove(packageName); 834 } 835 } 836 837 public void remove(int userId) { 838 mUidMap.remove(userId); 839 } 840 841 public int userIdCount() { 842 return mUidMap.size(); 843 } 844 845 public int userIdAt(int n) { 846 return mUidMap.keyAt(n); 847 } 848 849 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 850 return mUidMap.get(userId); 851 } 852 853 public int size() { 854 // total number of pending broadcast entries across all userIds 855 int num = 0; 856 for (int i = 0; i< mUidMap.size(); i++) { 857 num += mUidMap.valueAt(i).size(); 858 } 859 return num; 860 } 861 862 public void clear() { 863 mUidMap.clear(); 864 } 865 866 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 867 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 868 if (map == null) { 869 map = new ArrayMap<String, ArrayList<String>>(); 870 mUidMap.put(userId, map); 871 } 872 return map; 873 } 874 } 875 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 876 877 // Service Connection to remote media container service to copy 878 // package uri's from external media onto secure containers 879 // or internal storage. 880 private IMediaContainerService mContainerService = null; 881 882 static final int SEND_PENDING_BROADCAST = 1; 883 static final int MCS_BOUND = 3; 884 static final int END_COPY = 4; 885 static final int INIT_COPY = 5; 886 static final int MCS_UNBIND = 6; 887 static final int START_CLEANING_PACKAGE = 7; 888 static final int FIND_INSTALL_LOC = 8; 889 static final int POST_INSTALL = 9; 890 static final int MCS_RECONNECT = 10; 891 static final int MCS_GIVE_UP = 11; 892 static final int UPDATED_MEDIA_STATUS = 12; 893 static final int WRITE_SETTINGS = 13; 894 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 895 static final int PACKAGE_VERIFIED = 15; 896 static final int CHECK_PENDING_VERIFICATION = 16; 897 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 898 static final int INTENT_FILTER_VERIFIED = 18; 899 900 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 901 902 // Delay time in millisecs 903 static final int BROADCAST_DELAY = 10 * 1000; 904 905 static UserManagerService sUserManager; 906 907 // Stores a list of users whose package restrictions file needs to be updated 908 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 909 910 final private DefaultContainerConnection mDefContainerConn = 911 new DefaultContainerConnection(); 912 class DefaultContainerConnection implements ServiceConnection { 913 public void onServiceConnected(ComponentName name, IBinder service) { 914 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 915 IMediaContainerService imcs = 916 IMediaContainerService.Stub.asInterface(service); 917 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 918 } 919 920 public void onServiceDisconnected(ComponentName name) { 921 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 922 } 923 } 924 925 // Recordkeeping of restore-after-install operations that are currently in flight 926 // between the Package Manager and the Backup Manager 927 class PostInstallData { 928 public InstallArgs args; 929 public PackageInstalledInfo res; 930 931 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 932 args = _a; 933 res = _r; 934 } 935 } 936 937 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 938 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 939 940 // XML tags for backup/restore of various bits of state 941 private static final String TAG_PREFERRED_BACKUP = "pa"; 942 private static final String TAG_DEFAULT_APPS = "da"; 943 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 944 945 final String mRequiredVerifierPackage; 946 final String mRequiredInstallerPackage; 947 948 private final PackageUsage mPackageUsage = new PackageUsage(); 949 950 private class PackageUsage { 951 private static final int WRITE_INTERVAL 952 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 953 954 private final Object mFileLock = new Object(); 955 private final AtomicLong mLastWritten = new AtomicLong(0); 956 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 957 958 private boolean mIsHistoricalPackageUsageAvailable = true; 959 960 boolean isHistoricalPackageUsageAvailable() { 961 return mIsHistoricalPackageUsageAvailable; 962 } 963 964 void write(boolean force) { 965 if (force) { 966 writeInternal(); 967 return; 968 } 969 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 970 && !DEBUG_DEXOPT) { 971 return; 972 } 973 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 974 new Thread("PackageUsage_DiskWriter") { 975 @Override 976 public void run() { 977 try { 978 writeInternal(); 979 } finally { 980 mBackgroundWriteRunning.set(false); 981 } 982 } 983 }.start(); 984 } 985 } 986 987 private void writeInternal() { 988 synchronized (mPackages) { 989 synchronized (mFileLock) { 990 AtomicFile file = getFile(); 991 FileOutputStream f = null; 992 try { 993 f = file.startWrite(); 994 BufferedOutputStream out = new BufferedOutputStream(f); 995 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 996 StringBuilder sb = new StringBuilder(); 997 for (PackageParser.Package pkg : mPackages.values()) { 998 if (pkg.mLastPackageUsageTimeInMills == 0) { 999 continue; 1000 } 1001 sb.setLength(0); 1002 sb.append(pkg.packageName); 1003 sb.append(' '); 1004 sb.append((long)pkg.mLastPackageUsageTimeInMills); 1005 sb.append('\n'); 1006 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1007 } 1008 out.flush(); 1009 file.finishWrite(f); 1010 } catch (IOException e) { 1011 if (f != null) { 1012 file.failWrite(f); 1013 } 1014 Log.e(TAG, "Failed to write package usage times", e); 1015 } 1016 } 1017 } 1018 mLastWritten.set(SystemClock.elapsedRealtime()); 1019 } 1020 1021 void readLP() { 1022 synchronized (mFileLock) { 1023 AtomicFile file = getFile(); 1024 BufferedInputStream in = null; 1025 try { 1026 in = new BufferedInputStream(file.openRead()); 1027 StringBuffer sb = new StringBuffer(); 1028 while (true) { 1029 String packageName = readToken(in, sb, ' '); 1030 if (packageName == null) { 1031 break; 1032 } 1033 String timeInMillisString = readToken(in, sb, '\n'); 1034 if (timeInMillisString == null) { 1035 throw new IOException("Failed to find last usage time for package " 1036 + packageName); 1037 } 1038 PackageParser.Package pkg = mPackages.get(packageName); 1039 if (pkg == null) { 1040 continue; 1041 } 1042 long timeInMillis; 1043 try { 1044 timeInMillis = Long.parseLong(timeInMillisString.toString()); 1045 } catch (NumberFormatException e) { 1046 throw new IOException("Failed to parse " + timeInMillisString 1047 + " as a long.", e); 1048 } 1049 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1050 } 1051 } catch (FileNotFoundException expected) { 1052 mIsHistoricalPackageUsageAvailable = false; 1053 } catch (IOException e) { 1054 Log.w(TAG, "Failed to read package usage times", e); 1055 } finally { 1056 IoUtils.closeQuietly(in); 1057 } 1058 } 1059 mLastWritten.set(SystemClock.elapsedRealtime()); 1060 } 1061 1062 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1063 throws IOException { 1064 sb.setLength(0); 1065 while (true) { 1066 int ch = in.read(); 1067 if (ch == -1) { 1068 if (sb.length() == 0) { 1069 return null; 1070 } 1071 throw new IOException("Unexpected EOF"); 1072 } 1073 if (ch == endOfToken) { 1074 return sb.toString(); 1075 } 1076 sb.append((char)ch); 1077 } 1078 } 1079 1080 private AtomicFile getFile() { 1081 File dataDir = Environment.getDataDirectory(); 1082 File systemDir = new File(dataDir, "system"); 1083 File fname = new File(systemDir, "package-usage.list"); 1084 return new AtomicFile(fname); 1085 } 1086 } 1087 1088 class PackageHandler extends Handler { 1089 private boolean mBound = false; 1090 final ArrayList<HandlerParams> mPendingInstalls = 1091 new ArrayList<HandlerParams>(); 1092 1093 private boolean connectToService() { 1094 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1095 " DefaultContainerService"); 1096 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1097 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1098 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1099 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 1100 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1101 mBound = true; 1102 return true; 1103 } 1104 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1105 return false; 1106 } 1107 1108 private void disconnectService() { 1109 mContainerService = null; 1110 mBound = false; 1111 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1112 mContext.unbindService(mDefContainerConn); 1113 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1114 } 1115 1116 PackageHandler(Looper looper) { 1117 super(looper); 1118 } 1119 1120 public void handleMessage(Message msg) { 1121 try { 1122 doHandleMessage(msg); 1123 } finally { 1124 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1125 } 1126 } 1127 1128 void doHandleMessage(Message msg) { 1129 switch (msg.what) { 1130 case INIT_COPY: { 1131 HandlerParams params = (HandlerParams) msg.obj; 1132 int idx = mPendingInstalls.size(); 1133 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1134 // If a bind was already initiated we dont really 1135 // need to do anything. The pending install 1136 // will be processed later on. 1137 if (!mBound) { 1138 // If this is the only one pending we might 1139 // have to bind to the service again. 1140 if (!connectToService()) { 1141 Slog.e(TAG, "Failed to bind to media container service"); 1142 params.serviceError(); 1143 return; 1144 } else { 1145 // Once we bind to the service, the first 1146 // pending request will be processed. 1147 mPendingInstalls.add(idx, params); 1148 } 1149 } else { 1150 mPendingInstalls.add(idx, params); 1151 // Already bound to the service. Just make 1152 // sure we trigger off processing the first request. 1153 if (idx == 0) { 1154 mHandler.sendEmptyMessage(MCS_BOUND); 1155 } 1156 } 1157 break; 1158 } 1159 case MCS_BOUND: { 1160 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1161 if (msg.obj != null) { 1162 mContainerService = (IMediaContainerService) msg.obj; 1163 } 1164 if (mContainerService == null) { 1165 if (!mBound) { 1166 // Something seriously wrong since we are not bound and we are not 1167 // waiting for connection. Bail out. 1168 Slog.e(TAG, "Cannot bind to media container service"); 1169 for (HandlerParams params : mPendingInstalls) { 1170 // Indicate service bind error 1171 params.serviceError(); 1172 } 1173 mPendingInstalls.clear(); 1174 } else { 1175 Slog.w(TAG, "Waiting to connect to media container service"); 1176 } 1177 } else if (mPendingInstalls.size() > 0) { 1178 HandlerParams params = mPendingInstalls.get(0); 1179 if (params != null) { 1180 if (params.startCopy()) { 1181 // We are done... look for more work or to 1182 // go idle. 1183 if (DEBUG_SD_INSTALL) Log.i(TAG, 1184 "Checking for more work or unbind..."); 1185 // Delete pending install 1186 if (mPendingInstalls.size() > 0) { 1187 mPendingInstalls.remove(0); 1188 } 1189 if (mPendingInstalls.size() == 0) { 1190 if (mBound) { 1191 if (DEBUG_SD_INSTALL) Log.i(TAG, 1192 "Posting delayed MCS_UNBIND"); 1193 removeMessages(MCS_UNBIND); 1194 Message ubmsg = obtainMessage(MCS_UNBIND); 1195 // Unbind after a little delay, to avoid 1196 // continual thrashing. 1197 sendMessageDelayed(ubmsg, 10000); 1198 } 1199 } else { 1200 // There are more pending requests in queue. 1201 // Just post MCS_BOUND message to trigger processing 1202 // of next pending install. 1203 if (DEBUG_SD_INSTALL) Log.i(TAG, 1204 "Posting MCS_BOUND for next work"); 1205 mHandler.sendEmptyMessage(MCS_BOUND); 1206 } 1207 } 1208 } 1209 } else { 1210 // Should never happen ideally. 1211 Slog.w(TAG, "Empty queue"); 1212 } 1213 break; 1214 } 1215 case MCS_RECONNECT: { 1216 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1217 if (mPendingInstalls.size() > 0) { 1218 if (mBound) { 1219 disconnectService(); 1220 } 1221 if (!connectToService()) { 1222 Slog.e(TAG, "Failed to bind to media container service"); 1223 for (HandlerParams params : mPendingInstalls) { 1224 // Indicate service bind error 1225 params.serviceError(); 1226 } 1227 mPendingInstalls.clear(); 1228 } 1229 } 1230 break; 1231 } 1232 case MCS_UNBIND: { 1233 // If there is no actual work left, then time to unbind. 1234 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1235 1236 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1237 if (mBound) { 1238 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1239 1240 disconnectService(); 1241 } 1242 } else if (mPendingInstalls.size() > 0) { 1243 // There are more pending requests in queue. 1244 // Just post MCS_BOUND message to trigger processing 1245 // of next pending install. 1246 mHandler.sendEmptyMessage(MCS_BOUND); 1247 } 1248 1249 break; 1250 } 1251 case MCS_GIVE_UP: { 1252 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1253 mPendingInstalls.remove(0); 1254 break; 1255 } 1256 case SEND_PENDING_BROADCAST: { 1257 String packages[]; 1258 ArrayList<String> components[]; 1259 int size = 0; 1260 int uids[]; 1261 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1262 synchronized (mPackages) { 1263 if (mPendingBroadcasts == null) { 1264 return; 1265 } 1266 size = mPendingBroadcasts.size(); 1267 if (size <= 0) { 1268 // Nothing to be done. Just return 1269 return; 1270 } 1271 packages = new String[size]; 1272 components = new ArrayList[size]; 1273 uids = new int[size]; 1274 int i = 0; // filling out the above arrays 1275 1276 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1277 int packageUserId = mPendingBroadcasts.userIdAt(n); 1278 Iterator<Map.Entry<String, ArrayList<String>>> it 1279 = mPendingBroadcasts.packagesForUserId(packageUserId) 1280 .entrySet().iterator(); 1281 while (it.hasNext() && i < size) { 1282 Map.Entry<String, ArrayList<String>> ent = it.next(); 1283 packages[i] = ent.getKey(); 1284 components[i] = ent.getValue(); 1285 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1286 uids[i] = (ps != null) 1287 ? UserHandle.getUid(packageUserId, ps.appId) 1288 : -1; 1289 i++; 1290 } 1291 } 1292 size = i; 1293 mPendingBroadcasts.clear(); 1294 } 1295 // Send broadcasts 1296 for (int i = 0; i < size; i++) { 1297 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1298 } 1299 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1300 break; 1301 } 1302 case START_CLEANING_PACKAGE: { 1303 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1304 final String packageName = (String)msg.obj; 1305 final int userId = msg.arg1; 1306 final boolean andCode = msg.arg2 != 0; 1307 synchronized (mPackages) { 1308 if (userId == UserHandle.USER_ALL) { 1309 int[] users = sUserManager.getUserIds(); 1310 for (int user : users) { 1311 mSettings.addPackageToCleanLPw( 1312 new PackageCleanItem(user, packageName, andCode)); 1313 } 1314 } else { 1315 mSettings.addPackageToCleanLPw( 1316 new PackageCleanItem(userId, packageName, andCode)); 1317 } 1318 } 1319 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1320 startCleaningPackages(); 1321 } break; 1322 case POST_INSTALL: { 1323 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1324 PostInstallData data = mRunningInstalls.get(msg.arg1); 1325 mRunningInstalls.delete(msg.arg1); 1326 boolean deleteOld = false; 1327 1328 if (data != null) { 1329 InstallArgs args = data.args; 1330 PackageInstalledInfo res = data.res; 1331 1332 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1333 final String packageName = res.pkg.applicationInfo.packageName; 1334 res.removedInfo.sendBroadcast(false, true, false); 1335 Bundle extras = new Bundle(1); 1336 extras.putInt(Intent.EXTRA_UID, res.uid); 1337 1338 // Now that we successfully installed the package, grant runtime 1339 // permissions if requested before broadcasting the install. 1340 if ((args.installFlags 1341 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1342 grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(), 1343 args.installGrantPermissions); 1344 } 1345 1346 // Determine the set of users who are adding this 1347 // package for the first time vs. those who are seeing 1348 // an update. 1349 int[] firstUsers; 1350 int[] updateUsers = new int[0]; 1351 if (res.origUsers == null || res.origUsers.length == 0) { 1352 firstUsers = res.newUsers; 1353 } else { 1354 firstUsers = new int[0]; 1355 for (int i=0; i<res.newUsers.length; i++) { 1356 int user = res.newUsers[i]; 1357 boolean isNew = true; 1358 for (int j=0; j<res.origUsers.length; j++) { 1359 if (res.origUsers[j] == user) { 1360 isNew = false; 1361 break; 1362 } 1363 } 1364 if (isNew) { 1365 int[] newFirst = new int[firstUsers.length+1]; 1366 System.arraycopy(firstUsers, 0, newFirst, 0, 1367 firstUsers.length); 1368 newFirst[firstUsers.length] = user; 1369 firstUsers = newFirst; 1370 } else { 1371 int[] newUpdate = new int[updateUsers.length+1]; 1372 System.arraycopy(updateUsers, 0, newUpdate, 0, 1373 updateUsers.length); 1374 newUpdate[updateUsers.length] = user; 1375 updateUsers = newUpdate; 1376 } 1377 } 1378 } 1379 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1380 packageName, extras, null, null, firstUsers); 1381 final boolean update = res.removedInfo.removedPackage != null; 1382 if (update) { 1383 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1384 } 1385 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1386 packageName, extras, null, null, updateUsers); 1387 if (update) { 1388 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1389 packageName, extras, null, null, updateUsers); 1390 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1391 null, null, packageName, null, updateUsers); 1392 1393 // treat asec-hosted packages like removable media on upgrade 1394 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1395 if (DEBUG_INSTALL) { 1396 Slog.i(TAG, "upgrading pkg " + res.pkg 1397 + " is ASEC-hosted -> AVAILABLE"); 1398 } 1399 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1400 ArrayList<String> pkgList = new ArrayList<String>(1); 1401 pkgList.add(packageName); 1402 sendResourcesChangedBroadcast(true, true, 1403 pkgList,uidArray, null); 1404 } 1405 } 1406 if (res.removedInfo.args != null) { 1407 // Remove the replaced package's older resources safely now 1408 deleteOld = true; 1409 } 1410 1411 // If this app is a browser and it's newly-installed for some 1412 // users, clear any default-browser state in those users 1413 if (firstUsers.length > 0) { 1414 // the app's nature doesn't depend on the user, so we can just 1415 // check its browser nature in any user and generalize. 1416 if (packageIsBrowser(packageName, firstUsers[0])) { 1417 synchronized (mPackages) { 1418 for (int userId : firstUsers) { 1419 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1420 } 1421 } 1422 } 1423 } 1424 // Log current value of "unknown sources" setting 1425 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1426 getUnknownSourcesSettings()); 1427 } 1428 // Force a gc to clear up things 1429 Runtime.getRuntime().gc(); 1430 // We delete after a gc for applications on sdcard. 1431 if (deleteOld) { 1432 synchronized (mInstallLock) { 1433 res.removedInfo.args.doPostDeleteLI(true); 1434 } 1435 } 1436 if (args.observer != null) { 1437 try { 1438 Bundle extras = extrasForInstallResult(res); 1439 args.observer.onPackageInstalled(res.name, res.returnCode, 1440 res.returnMsg, extras); 1441 } catch (RemoteException e) { 1442 Slog.i(TAG, "Observer no longer exists."); 1443 } 1444 } 1445 } else { 1446 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1447 } 1448 } break; 1449 case UPDATED_MEDIA_STATUS: { 1450 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1451 boolean reportStatus = msg.arg1 == 1; 1452 boolean doGc = msg.arg2 == 1; 1453 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1454 if (doGc) { 1455 // Force a gc to clear up stale containers. 1456 Runtime.getRuntime().gc(); 1457 } 1458 if (msg.obj != null) { 1459 @SuppressWarnings("unchecked") 1460 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1461 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1462 // Unload containers 1463 unloadAllContainers(args); 1464 } 1465 if (reportStatus) { 1466 try { 1467 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1468 PackageHelper.getMountService().finishMediaUpdate(); 1469 } catch (RemoteException e) { 1470 Log.e(TAG, "MountService not running?"); 1471 } 1472 } 1473 } break; 1474 case WRITE_SETTINGS: { 1475 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1476 synchronized (mPackages) { 1477 removeMessages(WRITE_SETTINGS); 1478 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1479 mSettings.writeLPr(); 1480 mDirtyUsers.clear(); 1481 } 1482 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1483 } break; 1484 case WRITE_PACKAGE_RESTRICTIONS: { 1485 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1486 synchronized (mPackages) { 1487 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1488 for (int userId : mDirtyUsers) { 1489 mSettings.writePackageRestrictionsLPr(userId); 1490 } 1491 mDirtyUsers.clear(); 1492 } 1493 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1494 } break; 1495 case CHECK_PENDING_VERIFICATION: { 1496 final int verificationId = msg.arg1; 1497 final PackageVerificationState state = mPendingVerification.get(verificationId); 1498 1499 if ((state != null) && !state.timeoutExtended()) { 1500 final InstallArgs args = state.getInstallArgs(); 1501 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1502 1503 Slog.i(TAG, "Verification timed out for " + originUri); 1504 mPendingVerification.remove(verificationId); 1505 1506 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1507 1508 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1509 Slog.i(TAG, "Continuing with installation of " + originUri); 1510 state.setVerifierResponse(Binder.getCallingUid(), 1511 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1512 broadcastPackageVerified(verificationId, originUri, 1513 PackageManager.VERIFICATION_ALLOW, 1514 state.getInstallArgs().getUser()); 1515 try { 1516 ret = args.copyApk(mContainerService, true); 1517 } catch (RemoteException e) { 1518 Slog.e(TAG, "Could not contact the ContainerService"); 1519 } 1520 } else { 1521 broadcastPackageVerified(verificationId, originUri, 1522 PackageManager.VERIFICATION_REJECT, 1523 state.getInstallArgs().getUser()); 1524 } 1525 1526 processPendingInstall(args, ret); 1527 mHandler.sendEmptyMessage(MCS_UNBIND); 1528 } 1529 break; 1530 } 1531 case PACKAGE_VERIFIED: { 1532 final int verificationId = msg.arg1; 1533 1534 final PackageVerificationState state = mPendingVerification.get(verificationId); 1535 if (state == null) { 1536 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1537 break; 1538 } 1539 1540 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1541 1542 state.setVerifierResponse(response.callerUid, response.code); 1543 1544 if (state.isVerificationComplete()) { 1545 mPendingVerification.remove(verificationId); 1546 1547 final InstallArgs args = state.getInstallArgs(); 1548 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1549 1550 int ret; 1551 if (state.isInstallAllowed()) { 1552 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1553 broadcastPackageVerified(verificationId, originUri, 1554 response.code, state.getInstallArgs().getUser()); 1555 try { 1556 ret = args.copyApk(mContainerService, true); 1557 } catch (RemoteException e) { 1558 Slog.e(TAG, "Could not contact the ContainerService"); 1559 } 1560 } else { 1561 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1562 } 1563 1564 processPendingInstall(args, ret); 1565 1566 mHandler.sendEmptyMessage(MCS_UNBIND); 1567 } 1568 1569 break; 1570 } 1571 case START_INTENT_FILTER_VERIFICATIONS: { 1572 IFVerificationParams params = (IFVerificationParams) msg.obj; 1573 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1574 params.replacing, params.pkg); 1575 break; 1576 } 1577 case INTENT_FILTER_VERIFIED: { 1578 final int verificationId = msg.arg1; 1579 1580 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1581 verificationId); 1582 if (state == null) { 1583 Slog.w(TAG, "Invalid IntentFilter verification token " 1584 + verificationId + " received"); 1585 break; 1586 } 1587 1588 final int userId = state.getUserId(); 1589 1590 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1591 "Processing IntentFilter verification with token:" 1592 + verificationId + " and userId:" + userId); 1593 1594 final IntentFilterVerificationResponse response = 1595 (IntentFilterVerificationResponse) msg.obj; 1596 1597 state.setVerifierResponse(response.callerUid, response.code); 1598 1599 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1600 "IntentFilter verification with token:" + verificationId 1601 + " and userId:" + userId 1602 + " is settings verifier response with response code:" 1603 + response.code); 1604 1605 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1606 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1607 + response.getFailedDomainsString()); 1608 } 1609 1610 if (state.isVerificationComplete()) { 1611 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1612 } else { 1613 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1614 "IntentFilter verification with token:" + verificationId 1615 + " was not said to be complete"); 1616 } 1617 1618 break; 1619 } 1620 } 1621 } 1622 } 1623 1624 private StorageEventListener mStorageListener = new StorageEventListener() { 1625 @Override 1626 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1627 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1628 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1629 final String volumeUuid = vol.getFsUuid(); 1630 1631 // Clean up any users or apps that were removed or recreated 1632 // while this volume was missing 1633 reconcileUsers(volumeUuid); 1634 reconcileApps(volumeUuid); 1635 1636 // Clean up any install sessions that expired or were 1637 // cancelled while this volume was missing 1638 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1639 1640 loadPrivatePackages(vol); 1641 1642 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1643 unloadPrivatePackages(vol); 1644 } 1645 } 1646 1647 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1648 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1649 updateExternalMediaStatus(true, false); 1650 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1651 updateExternalMediaStatus(false, false); 1652 } 1653 } 1654 } 1655 1656 @Override 1657 public void onVolumeForgotten(String fsUuid) { 1658 if (TextUtils.isEmpty(fsUuid)) { 1659 Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1660 return; 1661 } 1662 1663 // Remove any apps installed on the forgotten volume 1664 synchronized (mPackages) { 1665 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1666 for (PackageSetting ps : packages) { 1667 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1668 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1669 UserHandle.USER_OWNER, PackageManager.DELETE_ALL_USERS); 1670 } 1671 1672 mSettings.onVolumeForgotten(fsUuid); 1673 mSettings.writeLPr(); 1674 } 1675 } 1676 }; 1677 1678 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId, 1679 String[] grantedPermissions) { 1680 if (userId >= UserHandle.USER_OWNER) { 1681 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1682 } else if (userId == UserHandle.USER_ALL) { 1683 final int[] userIds; 1684 synchronized (mPackages) { 1685 userIds = UserManagerService.getInstance().getUserIds(); 1686 } 1687 for (int someUserId : userIds) { 1688 grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions); 1689 } 1690 } 1691 1692 // We could have touched GID membership, so flush out packages.list 1693 synchronized (mPackages) { 1694 mSettings.writePackageListLPr(); 1695 } 1696 } 1697 1698 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1699 String[] grantedPermissions) { 1700 SettingBase sb = (SettingBase) pkg.mExtras; 1701 if (sb == null) { 1702 return; 1703 } 1704 1705 PermissionsState permissionsState = sb.getPermissionsState(); 1706 1707 for (String permission : pkg.requestedPermissions) { 1708 BasePermission bp = mSettings.mPermissions.get(permission); 1709 if (bp != null && bp.isRuntime() && (grantedPermissions == null 1710 || ArrayUtils.contains(grantedPermissions, permission))) { 1711 permissionsState.grantRuntimePermission(bp, userId); 1712 } 1713 } 1714 } 1715 1716 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1717 Bundle extras = null; 1718 switch (res.returnCode) { 1719 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1720 extras = new Bundle(); 1721 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1722 res.origPermission); 1723 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1724 res.origPackage); 1725 break; 1726 } 1727 case PackageManager.INSTALL_SUCCEEDED: { 1728 extras = new Bundle(); 1729 extras.putBoolean(Intent.EXTRA_REPLACING, 1730 res.removedInfo != null && res.removedInfo.removedPackage != null); 1731 break; 1732 } 1733 } 1734 return extras; 1735 } 1736 1737 void scheduleWriteSettingsLocked() { 1738 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1739 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1740 } 1741 } 1742 1743 void scheduleWritePackageRestrictionsLocked(int userId) { 1744 if (!sUserManager.exists(userId)) return; 1745 mDirtyUsers.add(userId); 1746 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1747 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1748 } 1749 } 1750 1751 public static PackageManagerService main(Context context, Installer installer, 1752 boolean factoryTest, boolean onlyCore) { 1753 PackageManagerService m = new PackageManagerService(context, installer, 1754 factoryTest, onlyCore); 1755 ServiceManager.addService("package", m); 1756 return m; 1757 } 1758 1759 static String[] splitString(String str, char sep) { 1760 int count = 1; 1761 int i = 0; 1762 while ((i=str.indexOf(sep, i)) >= 0) { 1763 count++; 1764 i++; 1765 } 1766 1767 String[] res = new String[count]; 1768 i=0; 1769 count = 0; 1770 int lastI=0; 1771 while ((i=str.indexOf(sep, i)) >= 0) { 1772 res[count] = str.substring(lastI, i); 1773 count++; 1774 i++; 1775 lastI = i; 1776 } 1777 res[count] = str.substring(lastI, str.length()); 1778 return res; 1779 } 1780 1781 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1782 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1783 Context.DISPLAY_SERVICE); 1784 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1785 } 1786 1787 public PackageManagerService(Context context, Installer installer, 1788 boolean factoryTest, boolean onlyCore) { 1789 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1790 SystemClock.uptimeMillis()); 1791 1792 if (mSdkVersion <= 0) { 1793 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1794 } 1795 1796 mContext = context; 1797 mFactoryTest = factoryTest; 1798 mOnlyCore = onlyCore; 1799 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1800 mMetrics = new DisplayMetrics(); 1801 mSettings = new Settings(mPackages); 1802 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1803 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1804 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1805 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1806 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1807 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1808 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1809 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1810 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1811 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1812 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1813 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1814 1815 // TODO: add a property to control this? 1816 long dexOptLRUThresholdInMinutes; 1817 if (mLazyDexOpt) { 1818 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1819 } else { 1820 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1821 } 1822 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1823 1824 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1825 if (separateProcesses != null && separateProcesses.length() > 0) { 1826 if ("*".equals(separateProcesses)) { 1827 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1828 mSeparateProcesses = null; 1829 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1830 } else { 1831 mDefParseFlags = 0; 1832 mSeparateProcesses = separateProcesses.split(","); 1833 Slog.w(TAG, "Running with debug.separate_processes: " 1834 + separateProcesses); 1835 } 1836 } else { 1837 mDefParseFlags = 0; 1838 mSeparateProcesses = null; 1839 } 1840 1841 mInstaller = installer; 1842 mPackageDexOptimizer = new PackageDexOptimizer(this); 1843 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1844 1845 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 1846 FgThread.get().getLooper()); 1847 1848 getDefaultDisplayMetrics(context, mMetrics); 1849 1850 SystemConfig systemConfig = SystemConfig.getInstance(); 1851 mGlobalGids = systemConfig.getGlobalGids(); 1852 mSystemPermissions = systemConfig.getSystemPermissions(); 1853 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1854 1855 synchronized (mInstallLock) { 1856 // writer 1857 synchronized (mPackages) { 1858 mHandlerThread = new ServiceThread(TAG, 1859 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1860 mHandlerThread.start(); 1861 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1862 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1863 1864 File dataDir = Environment.getDataDirectory(); 1865 mAppDataDir = new File(dataDir, "data"); 1866 mAppInstallDir = new File(dataDir, "app"); 1867 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1868 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1869 mUserAppDataDir = new File(dataDir, "user"); 1870 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1871 1872 sUserManager = new UserManagerService(context, this, 1873 mInstallLock, mPackages); 1874 1875 // Propagate permission configuration in to package manager. 1876 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1877 = systemConfig.getPermissions(); 1878 for (int i=0; i<permConfig.size(); i++) { 1879 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1880 BasePermission bp = mSettings.mPermissions.get(perm.name); 1881 if (bp == null) { 1882 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1883 mSettings.mPermissions.put(perm.name, bp); 1884 } 1885 if (perm.gids != null) { 1886 bp.setGids(perm.gids, perm.perUser); 1887 } 1888 } 1889 1890 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1891 for (int i=0; i<libConfig.size(); i++) { 1892 mSharedLibraries.put(libConfig.keyAt(i), 1893 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1894 } 1895 1896 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1897 1898 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1899 mSdkVersion, mOnlyCore); 1900 1901 String customResolverActivity = Resources.getSystem().getString( 1902 R.string.config_customResolverActivity); 1903 if (TextUtils.isEmpty(customResolverActivity)) { 1904 customResolverActivity = null; 1905 } else { 1906 mCustomResolverComponentName = ComponentName.unflattenFromString( 1907 customResolverActivity); 1908 } 1909 1910 long startTime = SystemClock.uptimeMillis(); 1911 1912 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1913 startTime); 1914 1915 // Set flag to monitor and not change apk file paths when 1916 // scanning install directories. 1917 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 1918 1919 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1920 1921 /** 1922 * Add everything in the in the boot class path to the 1923 * list of process files because dexopt will have been run 1924 * if necessary during zygote startup. 1925 */ 1926 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1927 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1928 1929 if (bootClassPath != null) { 1930 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1931 for (String element : bootClassPathElements) { 1932 alreadyDexOpted.add(element); 1933 } 1934 } else { 1935 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1936 } 1937 1938 if (systemServerClassPath != null) { 1939 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1940 for (String element : systemServerClassPathElements) { 1941 alreadyDexOpted.add(element); 1942 } 1943 } else { 1944 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1945 } 1946 1947 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1948 final String[] dexCodeInstructionSets = 1949 getDexCodeInstructionSets( 1950 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1951 1952 /** 1953 * Ensure all external libraries have had dexopt run on them. 1954 */ 1955 if (mSharedLibraries.size() > 0) { 1956 // NOTE: For now, we're compiling these system "shared libraries" 1957 // (and framework jars) into all available architectures. It's possible 1958 // to compile them only when we come across an app that uses them (there's 1959 // already logic for that in scanPackageLI) but that adds some complexity. 1960 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1961 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1962 final String lib = libEntry.path; 1963 if (lib == null) { 1964 continue; 1965 } 1966 1967 try { 1968 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 1969 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1970 alreadyDexOpted.add(lib); 1971 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1972 } 1973 } catch (FileNotFoundException e) { 1974 Slog.w(TAG, "Library not found: " + lib); 1975 } catch (IOException e) { 1976 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1977 + e.getMessage()); 1978 } 1979 } 1980 } 1981 } 1982 1983 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1984 1985 // Gross hack for now: we know this file doesn't contain any 1986 // code, so don't dexopt it to avoid the resulting log spew. 1987 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1988 1989 // Gross hack for now: we know this file is only part of 1990 // the boot class path for art, so don't dexopt it to 1991 // avoid the resulting log spew. 1992 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1993 1994 /** 1995 * There are a number of commands implemented in Java, which 1996 * we currently need to do the dexopt on so that they can be 1997 * run from a non-root shell. 1998 */ 1999 String[] frameworkFiles = frameworkDir.list(); 2000 if (frameworkFiles != null) { 2001 // TODO: We could compile these only for the most preferred ABI. We should 2002 // first double check that the dex files for these commands are not referenced 2003 // by other system apps. 2004 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2005 for (int i=0; i<frameworkFiles.length; i++) { 2006 File libPath = new File(frameworkDir, frameworkFiles[i]); 2007 String path = libPath.getPath(); 2008 // Skip the file if we already did it. 2009 if (alreadyDexOpted.contains(path)) { 2010 continue; 2011 } 2012 // Skip the file if it is not a type we want to dexopt. 2013 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 2014 continue; 2015 } 2016 try { 2017 int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false); 2018 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2019 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 2020 } 2021 } catch (FileNotFoundException e) { 2022 Slog.w(TAG, "Jar not found: " + path); 2023 } catch (IOException e) { 2024 Slog.w(TAG, "Exception reading jar: " + path, e); 2025 } 2026 } 2027 } 2028 } 2029 2030 // Collect vendor overlay packages. 2031 // (Do this before scanning any apps.) 2032 // For security and version matching reason, only consider 2033 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2034 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2035 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2036 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2037 2038 // Find base frameworks (resource packages without code). 2039 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2040 | PackageParser.PARSE_IS_SYSTEM_DIR 2041 | PackageParser.PARSE_IS_PRIVILEGED, 2042 scanFlags | SCAN_NO_DEX, 0); 2043 2044 // Collected privileged system packages. 2045 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2046 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2047 | PackageParser.PARSE_IS_SYSTEM_DIR 2048 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2049 2050 // Collect ordinary system packages. 2051 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2052 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2053 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2054 2055 // Collect all vendor packages. 2056 File vendorAppDir = new File("/vendor/app"); 2057 try { 2058 vendorAppDir = vendorAppDir.getCanonicalFile(); 2059 } catch (IOException e) { 2060 // failed to look up canonical path, continue with original one 2061 } 2062 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2063 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2064 2065 // Collect all OEM packages. 2066 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2067 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2068 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2069 2070 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 2071 mInstaller.moveFiles(); 2072 2073 // Prune any system packages that no longer exist. 2074 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2075 if (!mOnlyCore) { 2076 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2077 while (psit.hasNext()) { 2078 PackageSetting ps = psit.next(); 2079 2080 /* 2081 * If this is not a system app, it can't be a 2082 * disable system app. 2083 */ 2084 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2085 continue; 2086 } 2087 2088 /* 2089 * If the package is scanned, it's not erased. 2090 */ 2091 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2092 if (scannedPkg != null) { 2093 /* 2094 * If the system app is both scanned and in the 2095 * disabled packages list, then it must have been 2096 * added via OTA. Remove it from the currently 2097 * scanned package so the previously user-installed 2098 * application can be scanned. 2099 */ 2100 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2101 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2102 + ps.name + "; removing system app. Last known codePath=" 2103 + ps.codePathString + ", installStatus=" + ps.installStatus 2104 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2105 + scannedPkg.mVersionCode); 2106 removePackageLI(ps, true); 2107 mExpectingBetter.put(ps.name, ps.codePath); 2108 } 2109 2110 continue; 2111 } 2112 2113 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2114 psit.remove(); 2115 logCriticalInfo(Log.WARN, "System package " + ps.name 2116 + " no longer exists; wiping its data"); 2117 removeDataDirsLI(null, ps.name); 2118 } else { 2119 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2120 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2121 possiblyDeletedUpdatedSystemApps.add(ps.name); 2122 } 2123 } 2124 } 2125 } 2126 2127 //look for any incomplete package installations 2128 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2129 //clean up list 2130 for(int i = 0; i < deletePkgsList.size(); i++) { 2131 //clean up here 2132 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2133 } 2134 //delete tmp files 2135 deleteTempPackageFiles(); 2136 2137 // Remove any shared userIDs that have no associated packages 2138 mSettings.pruneSharedUsersLPw(); 2139 2140 if (!mOnlyCore) { 2141 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2142 SystemClock.uptimeMillis()); 2143 scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2144 2145 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2146 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2147 2148 /** 2149 * Remove disable package settings for any updated system 2150 * apps that were removed via an OTA. If they're not a 2151 * previously-updated app, remove them completely. 2152 * Otherwise, just revoke their system-level permissions. 2153 */ 2154 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2155 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2156 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2157 2158 String msg; 2159 if (deletedPkg == null) { 2160 msg = "Updated system package " + deletedAppName 2161 + " no longer exists; wiping its data"; 2162 removeDataDirsLI(null, deletedAppName); 2163 } else { 2164 msg = "Updated system app + " + deletedAppName 2165 + " no longer present; removing system privileges for " 2166 + deletedAppName; 2167 2168 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2169 2170 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2171 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2172 } 2173 logCriticalInfo(Log.WARN, msg); 2174 } 2175 2176 /** 2177 * Make sure all system apps that we expected to appear on 2178 * the userdata partition actually showed up. If they never 2179 * appeared, crawl back and revive the system version. 2180 */ 2181 for (int i = 0; i < mExpectingBetter.size(); i++) { 2182 final String packageName = mExpectingBetter.keyAt(i); 2183 if (!mPackages.containsKey(packageName)) { 2184 final File scanFile = mExpectingBetter.valueAt(i); 2185 2186 logCriticalInfo(Log.WARN, "Expected better " + packageName 2187 + " but never showed up; reverting to system"); 2188 2189 final int reparseFlags; 2190 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2191 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2192 | PackageParser.PARSE_IS_SYSTEM_DIR 2193 | PackageParser.PARSE_IS_PRIVILEGED; 2194 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2195 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2196 | PackageParser.PARSE_IS_SYSTEM_DIR; 2197 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2198 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2199 | PackageParser.PARSE_IS_SYSTEM_DIR; 2200 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2201 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2202 | PackageParser.PARSE_IS_SYSTEM_DIR; 2203 } else { 2204 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2205 continue; 2206 } 2207 2208 mSettings.enableSystemPackageLPw(packageName); 2209 2210 try { 2211 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 2212 } catch (PackageManagerException e) { 2213 Slog.e(TAG, "Failed to parse original system package: " 2214 + e.getMessage()); 2215 } 2216 } 2217 } 2218 } 2219 mExpectingBetter.clear(); 2220 2221 // Now that we know all of the shared libraries, update all clients to have 2222 // the correct library paths. 2223 updateAllSharedLibrariesLPw(); 2224 2225 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2226 // NOTE: We ignore potential failures here during a system scan (like 2227 // the rest of the commands above) because there's precious little we 2228 // can do about it. A settings error is reported, though. 2229 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2230 false /* force dexopt */, false /* defer dexopt */); 2231 } 2232 2233 // Now that we know all the packages we are keeping, 2234 // read and update their last usage times. 2235 mPackageUsage.readLP(); 2236 2237 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2238 SystemClock.uptimeMillis()); 2239 Slog.i(TAG, "Time to scan packages: " 2240 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2241 + " seconds"); 2242 2243 // If the platform SDK has changed since the last time we booted, 2244 // we need to re-grant app permission to catch any new ones that 2245 // appear. This is really a hack, and means that apps can in some 2246 // cases get permissions that the user didn't initially explicitly 2247 // allow... it would be nice to have some better way to handle 2248 // this situation. 2249 final VersionInfo ver = mSettings.getInternalVersion(); 2250 2251 int updateFlags = UPDATE_PERMISSIONS_ALL; 2252 if (ver.sdkVersion != mSdkVersion) { 2253 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2254 + mSdkVersion + "; regranting permissions for internal storage"); 2255 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2256 } 2257 updatePermissionsLPw(null, null, updateFlags); 2258 ver.sdkVersion = mSdkVersion; 2259 2260 // If this is the first boot, and it is a normal boot, then 2261 // we need to initialize the default preferred apps. 2262 if (!mRestoredSettings && !onlyCore) { 2263 mSettings.applyDefaultPreferredAppsLPw(this, UserHandle.USER_OWNER); 2264 applyFactoryDefaultBrowserLPw(UserHandle.USER_OWNER); 2265 primeDomainVerificationsLPw(UserHandle.USER_OWNER); 2266 } 2267 2268 // If this is first boot after an OTA, and a normal boot, then 2269 // we need to clear code cache directories. 2270 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2271 if (mIsUpgrade && !onlyCore) { 2272 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2273 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2274 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2275 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2276 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2277 } 2278 } 2279 ver.fingerprint = Build.FINGERPRINT; 2280 } 2281 2282 checkDefaultBrowser(); 2283 2284 // All the changes are done during package scanning. 2285 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2286 2287 // can downgrade to reader 2288 mSettings.writeLPr(); 2289 2290 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2291 SystemClock.uptimeMillis()); 2292 2293 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2294 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2295 2296 mInstallerService = new PackageInstallerService(context, this); 2297 2298 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2299 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2300 mIntentFilterVerifierComponent); 2301 2302 } // synchronized (mPackages) 2303 } // synchronized (mInstallLock) 2304 2305 // Now after opening every single application zip, make sure they 2306 // are all flushed. Not really needed, but keeps things nice and 2307 // tidy. 2308 Runtime.getRuntime().gc(); 2309 2310 // Expose private service for system components to use. 2311 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2312 } 2313 2314 @Override 2315 public boolean isFirstBoot() { 2316 return !mRestoredSettings; 2317 } 2318 2319 @Override 2320 public boolean isOnlyCoreApps() { 2321 return mOnlyCore; 2322 } 2323 2324 @Override 2325 public boolean isUpgrade() { 2326 return mIsUpgrade; 2327 } 2328 2329 private String getRequiredVerifierLPr() { 2330 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2331 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2332 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 2333 2334 String requiredVerifier = null; 2335 2336 final int N = receivers.size(); 2337 for (int i = 0; i < N; i++) { 2338 final ResolveInfo info = receivers.get(i); 2339 2340 if (info.activityInfo == null) { 2341 continue; 2342 } 2343 2344 final String packageName = info.activityInfo.packageName; 2345 2346 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2347 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2348 continue; 2349 } 2350 2351 if (requiredVerifier != null) { 2352 throw new RuntimeException("There can be only one required verifier"); 2353 } 2354 2355 requiredVerifier = packageName; 2356 } 2357 2358 return requiredVerifier; 2359 } 2360 2361 private String getRequiredInstallerLPr() { 2362 Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2363 installerIntent.addCategory(Intent.CATEGORY_DEFAULT); 2364 installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2365 2366 final List<ResolveInfo> installers = queryIntentActivities(installerIntent, 2367 PACKAGE_MIME_TYPE, 0, 0); 2368 2369 String requiredInstaller = null; 2370 2371 final int N = installers.size(); 2372 for (int i = 0; i < N; i++) { 2373 final ResolveInfo info = installers.get(i); 2374 final String packageName = info.activityInfo.packageName; 2375 2376 if (!info.activityInfo.applicationInfo.isSystemApp()) { 2377 continue; 2378 } 2379 2380 if (requiredInstaller != null) { 2381 throw new RuntimeException("There must be one required installer"); 2382 } 2383 2384 requiredInstaller = packageName; 2385 } 2386 2387 if (requiredInstaller == null) { 2388 throw new RuntimeException("There must be one required installer"); 2389 } 2390 2391 return requiredInstaller; 2392 } 2393 2394 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2395 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2396 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2397 PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */); 2398 2399 ComponentName verifierComponentName = null; 2400 2401 int priority = -1000; 2402 final int N = receivers.size(); 2403 for (int i = 0; i < N; i++) { 2404 final ResolveInfo info = receivers.get(i); 2405 2406 if (info.activityInfo == null) { 2407 continue; 2408 } 2409 2410 final String packageName = info.activityInfo.packageName; 2411 2412 final PackageSetting ps = mSettings.mPackages.get(packageName); 2413 if (ps == null) { 2414 continue; 2415 } 2416 2417 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2418 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2419 continue; 2420 } 2421 2422 // Select the IntentFilterVerifier with the highest priority 2423 if (priority < info.priority) { 2424 priority = info.priority; 2425 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2426 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: " 2427 + verifierComponentName + " with priority: " + info.priority); 2428 } 2429 } 2430 2431 return verifierComponentName; 2432 } 2433 2434 private void primeDomainVerificationsLPw(int userId) { 2435 if (DEBUG_DOMAIN_VERIFICATION) { 2436 Slog.d(TAG, "Priming domain verifications in user " + userId); 2437 } 2438 2439 SystemConfig systemConfig = SystemConfig.getInstance(); 2440 ArraySet<String> packages = systemConfig.getLinkedApps(); 2441 ArraySet<String> domains = new ArraySet<String>(); 2442 2443 for (String packageName : packages) { 2444 PackageParser.Package pkg = mPackages.get(packageName); 2445 if (pkg != null) { 2446 if (!pkg.isSystemApp()) { 2447 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2448 continue; 2449 } 2450 2451 domains.clear(); 2452 for (PackageParser.Activity a : pkg.activities) { 2453 for (ActivityIntentInfo filter : a.intents) { 2454 if (hasValidDomains(filter)) { 2455 domains.addAll(filter.getHostsList()); 2456 } 2457 } 2458 } 2459 2460 if (domains.size() > 0) { 2461 if (DEBUG_DOMAIN_VERIFICATION) { 2462 Slog.v(TAG, " + " + packageName); 2463 } 2464 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2465 // state w.r.t. the formal app-linkage "no verification attempted" state; 2466 // and then 'always' in the per-user state actually used for intent resolution. 2467 final IntentFilterVerificationInfo ivi; 2468 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2469 new ArrayList<String>(domains)); 2470 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2471 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2472 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2473 } else { 2474 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2475 + "' does not handle web links"); 2476 } 2477 } else { 2478 Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>"); 2479 } 2480 } 2481 2482 scheduleWritePackageRestrictionsLocked(userId); 2483 scheduleWriteSettingsLocked(); 2484 } 2485 2486 private void applyFactoryDefaultBrowserLPw(int userId) { 2487 // The default browser app's package name is stored in a string resource, 2488 // with a product-specific overlay used for vendor customization. 2489 String browserPkg = mContext.getResources().getString( 2490 com.android.internal.R.string.default_browser); 2491 if (!TextUtils.isEmpty(browserPkg)) { 2492 // non-empty string => required to be a known package 2493 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2494 if (ps == null) { 2495 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2496 browserPkg = null; 2497 } else { 2498 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2499 } 2500 } 2501 2502 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2503 // default. If there's more than one, just leave everything alone. 2504 if (browserPkg == null) { 2505 calculateDefaultBrowserLPw(userId); 2506 } 2507 } 2508 2509 private void calculateDefaultBrowserLPw(int userId) { 2510 List<String> allBrowsers = resolveAllBrowserApps(userId); 2511 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2512 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2513 } 2514 2515 private List<String> resolveAllBrowserApps(int userId) { 2516 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2517 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2518 PackageManager.MATCH_ALL, userId); 2519 2520 final int count = list.size(); 2521 List<String> result = new ArrayList<String>(count); 2522 for (int i=0; i<count; i++) { 2523 ResolveInfo info = list.get(i); 2524 if (info.activityInfo == null 2525 || !info.handleAllWebDataURI 2526 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2527 || result.contains(info.activityInfo.packageName)) { 2528 continue; 2529 } 2530 result.add(info.activityInfo.packageName); 2531 } 2532 2533 return result; 2534 } 2535 2536 private boolean packageIsBrowser(String packageName, int userId) { 2537 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2538 PackageManager.MATCH_ALL, userId); 2539 final int N = list.size(); 2540 for (int i = 0; i < N; i++) { 2541 ResolveInfo info = list.get(i); 2542 if (packageName.equals(info.activityInfo.packageName)) { 2543 return true; 2544 } 2545 } 2546 return false; 2547 } 2548 2549 private void checkDefaultBrowser() { 2550 final int myUserId = UserHandle.myUserId(); 2551 final String packageName = getDefaultBrowserPackageName(myUserId); 2552 if (packageName != null) { 2553 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2554 if (info == null) { 2555 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2556 synchronized (mPackages) { 2557 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2558 } 2559 } 2560 } 2561 } 2562 2563 @Override 2564 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2565 throws RemoteException { 2566 try { 2567 return super.onTransact(code, data, reply, flags); 2568 } catch (RuntimeException e) { 2569 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2570 Slog.wtf(TAG, "Package Manager Crash", e); 2571 } 2572 throw e; 2573 } 2574 } 2575 2576 void cleanupInstallFailedPackage(PackageSetting ps) { 2577 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2578 2579 removeDataDirsLI(ps.volumeUuid, ps.name); 2580 if (ps.codePath != null) { 2581 if (ps.codePath.isDirectory()) { 2582 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2583 } else { 2584 ps.codePath.delete(); 2585 } 2586 } 2587 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2588 if (ps.resourcePath.isDirectory()) { 2589 FileUtils.deleteContents(ps.resourcePath); 2590 } 2591 ps.resourcePath.delete(); 2592 } 2593 mSettings.removePackageLPw(ps.name); 2594 } 2595 2596 static int[] appendInts(int[] cur, int[] add) { 2597 if (add == null) return cur; 2598 if (cur == null) return add; 2599 final int N = add.length; 2600 for (int i=0; i<N; i++) { 2601 cur = appendInt(cur, add[i]); 2602 } 2603 return cur; 2604 } 2605 2606 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2607 if (!sUserManager.exists(userId)) return null; 2608 final PackageSetting ps = (PackageSetting) p.mExtras; 2609 if (ps == null) { 2610 return null; 2611 } 2612 2613 final PermissionsState permissionsState = ps.getPermissionsState(); 2614 2615 final int[] gids = permissionsState.computeGids(userId); 2616 final Set<String> permissions = permissionsState.getPermissions(userId); 2617 final PackageUserState state = ps.readUserState(userId); 2618 2619 return PackageParser.generatePackageInfo(p, gids, flags, 2620 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2621 } 2622 2623 @Override 2624 public boolean isPackageFrozen(String packageName) { 2625 synchronized (mPackages) { 2626 final PackageSetting ps = mSettings.mPackages.get(packageName); 2627 if (ps != null) { 2628 return ps.frozen; 2629 } 2630 } 2631 Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen"); 2632 return true; 2633 } 2634 2635 @Override 2636 public boolean isPackageAvailable(String packageName, int userId) { 2637 if (!sUserManager.exists(userId)) return false; 2638 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2639 synchronized (mPackages) { 2640 PackageParser.Package p = mPackages.get(packageName); 2641 if (p != null) { 2642 final PackageSetting ps = (PackageSetting) p.mExtras; 2643 if (ps != null) { 2644 final PackageUserState state = ps.readUserState(userId); 2645 if (state != null) { 2646 return PackageParser.isAvailable(state); 2647 } 2648 } 2649 } 2650 } 2651 return false; 2652 } 2653 2654 @Override 2655 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2656 if (!sUserManager.exists(userId)) return null; 2657 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2658 // reader 2659 synchronized (mPackages) { 2660 PackageParser.Package p = mPackages.get(packageName); 2661 if (DEBUG_PACKAGE_INFO) 2662 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2663 if (p != null) { 2664 return generatePackageInfo(p, flags, userId); 2665 } 2666 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2667 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2668 } 2669 } 2670 return null; 2671 } 2672 2673 @Override 2674 public String[] currentToCanonicalPackageNames(String[] names) { 2675 String[] out = new String[names.length]; 2676 // reader 2677 synchronized (mPackages) { 2678 for (int i=names.length-1; i>=0; i--) { 2679 PackageSetting ps = mSettings.mPackages.get(names[i]); 2680 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2681 } 2682 } 2683 return out; 2684 } 2685 2686 @Override 2687 public String[] canonicalToCurrentPackageNames(String[] names) { 2688 String[] out = new String[names.length]; 2689 // reader 2690 synchronized (mPackages) { 2691 for (int i=names.length-1; i>=0; i--) { 2692 String cur = mSettings.mRenamedPackages.get(names[i]); 2693 out[i] = cur != null ? cur : names[i]; 2694 } 2695 } 2696 return out; 2697 } 2698 2699 @Override 2700 public int getPackageUid(String packageName, int userId) { 2701 if (!sUserManager.exists(userId)) return -1; 2702 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2703 2704 // reader 2705 synchronized (mPackages) { 2706 PackageParser.Package p = mPackages.get(packageName); 2707 if(p != null) { 2708 return UserHandle.getUid(userId, p.applicationInfo.uid); 2709 } 2710 PackageSetting ps = mSettings.mPackages.get(packageName); 2711 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2712 return -1; 2713 } 2714 p = ps.pkg; 2715 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2716 } 2717 } 2718 2719 @Override 2720 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2721 if (!sUserManager.exists(userId)) { 2722 return null; 2723 } 2724 2725 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2726 "getPackageGids"); 2727 2728 // reader 2729 synchronized (mPackages) { 2730 PackageParser.Package p = mPackages.get(packageName); 2731 if (DEBUG_PACKAGE_INFO) { 2732 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2733 } 2734 if (p != null) { 2735 PackageSetting ps = (PackageSetting) p.mExtras; 2736 return ps.getPermissionsState().computeGids(userId); 2737 } 2738 } 2739 2740 return null; 2741 } 2742 2743 static PermissionInfo generatePermissionInfo( 2744 BasePermission bp, int flags) { 2745 if (bp.perm != null) { 2746 return PackageParser.generatePermissionInfo(bp.perm, flags); 2747 } 2748 PermissionInfo pi = new PermissionInfo(); 2749 pi.name = bp.name; 2750 pi.packageName = bp.sourcePackage; 2751 pi.nonLocalizedLabel = bp.name; 2752 pi.protectionLevel = bp.protectionLevel; 2753 return pi; 2754 } 2755 2756 @Override 2757 public PermissionInfo getPermissionInfo(String name, int flags) { 2758 // reader 2759 synchronized (mPackages) { 2760 final BasePermission p = mSettings.mPermissions.get(name); 2761 if (p != null) { 2762 return generatePermissionInfo(p, flags); 2763 } 2764 return null; 2765 } 2766 } 2767 2768 @Override 2769 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2770 // reader 2771 synchronized (mPackages) { 2772 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2773 for (BasePermission p : mSettings.mPermissions.values()) { 2774 if (group == null) { 2775 if (p.perm == null || p.perm.info.group == null) { 2776 out.add(generatePermissionInfo(p, flags)); 2777 } 2778 } else { 2779 if (p.perm != null && group.equals(p.perm.info.group)) { 2780 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2781 } 2782 } 2783 } 2784 2785 if (out.size() > 0) { 2786 return out; 2787 } 2788 return mPermissionGroups.containsKey(group) ? out : null; 2789 } 2790 } 2791 2792 @Override 2793 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2794 // reader 2795 synchronized (mPackages) { 2796 return PackageParser.generatePermissionGroupInfo( 2797 mPermissionGroups.get(name), flags); 2798 } 2799 } 2800 2801 @Override 2802 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2803 // reader 2804 synchronized (mPackages) { 2805 final int N = mPermissionGroups.size(); 2806 ArrayList<PermissionGroupInfo> out 2807 = new ArrayList<PermissionGroupInfo>(N); 2808 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2809 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2810 } 2811 return out; 2812 } 2813 } 2814 2815 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2816 int userId) { 2817 if (!sUserManager.exists(userId)) return null; 2818 PackageSetting ps = mSettings.mPackages.get(packageName); 2819 if (ps != null) { 2820 if (ps.pkg == null) { 2821 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2822 flags, userId); 2823 if (pInfo != null) { 2824 return pInfo.applicationInfo; 2825 } 2826 return null; 2827 } 2828 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2829 ps.readUserState(userId), userId); 2830 } 2831 return null; 2832 } 2833 2834 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2835 int userId) { 2836 if (!sUserManager.exists(userId)) return null; 2837 PackageSetting ps = mSettings.mPackages.get(packageName); 2838 if (ps != null) { 2839 PackageParser.Package pkg = ps.pkg; 2840 if (pkg == null) { 2841 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2842 return null; 2843 } 2844 // Only data remains, so we aren't worried about code paths 2845 pkg = new PackageParser.Package(packageName); 2846 pkg.applicationInfo.packageName = packageName; 2847 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2848 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2849 pkg.applicationInfo.dataDir = Environment 2850 .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName) 2851 .getAbsolutePath(); 2852 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2853 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2854 } 2855 return generatePackageInfo(pkg, flags, userId); 2856 } 2857 return null; 2858 } 2859 2860 @Override 2861 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2862 if (!sUserManager.exists(userId)) return null; 2863 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2864 // writer 2865 synchronized (mPackages) { 2866 PackageParser.Package p = mPackages.get(packageName); 2867 if (DEBUG_PACKAGE_INFO) Log.v( 2868 TAG, "getApplicationInfo " + packageName 2869 + ": " + p); 2870 if (p != null) { 2871 PackageSetting ps = mSettings.mPackages.get(packageName); 2872 if (ps == null) return null; 2873 // Note: isEnabledLP() does not apply here - always return info 2874 return PackageParser.generateApplicationInfo( 2875 p, flags, ps.readUserState(userId), userId); 2876 } 2877 if ("android".equals(packageName)||"system".equals(packageName)) { 2878 return mAndroidApplication; 2879 } 2880 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2881 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2882 } 2883 } 2884 return null; 2885 } 2886 2887 @Override 2888 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2889 final IPackageDataObserver observer) { 2890 mContext.enforceCallingOrSelfPermission( 2891 android.Manifest.permission.CLEAR_APP_CACHE, null); 2892 // Queue up an async operation since clearing cache may take a little while. 2893 mHandler.post(new Runnable() { 2894 public void run() { 2895 mHandler.removeCallbacks(this); 2896 int retCode = -1; 2897 synchronized (mInstallLock) { 2898 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2899 if (retCode < 0) { 2900 Slog.w(TAG, "Couldn't clear application caches"); 2901 } 2902 } 2903 if (observer != null) { 2904 try { 2905 observer.onRemoveCompleted(null, (retCode >= 0)); 2906 } catch (RemoteException e) { 2907 Slog.w(TAG, "RemoveException when invoking call back"); 2908 } 2909 } 2910 } 2911 }); 2912 } 2913 2914 @Override 2915 public void freeStorage(final String volumeUuid, final long freeStorageSize, 2916 final IntentSender pi) { 2917 mContext.enforceCallingOrSelfPermission( 2918 android.Manifest.permission.CLEAR_APP_CACHE, null); 2919 // Queue up an async operation since clearing cache may take a little while. 2920 mHandler.post(new Runnable() { 2921 public void run() { 2922 mHandler.removeCallbacks(this); 2923 int retCode = -1; 2924 synchronized (mInstallLock) { 2925 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2926 if (retCode < 0) { 2927 Slog.w(TAG, "Couldn't clear application caches"); 2928 } 2929 } 2930 if(pi != null) { 2931 try { 2932 // Callback via pending intent 2933 int code = (retCode >= 0) ? 1 : 0; 2934 pi.sendIntent(null, code, null, 2935 null, null); 2936 } catch (SendIntentException e1) { 2937 Slog.i(TAG, "Failed to send pending intent"); 2938 } 2939 } 2940 } 2941 }); 2942 } 2943 2944 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 2945 synchronized (mInstallLock) { 2946 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 2947 throw new IOException("Failed to free enough space"); 2948 } 2949 } 2950 } 2951 2952 @Override 2953 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2954 if (!sUserManager.exists(userId)) return null; 2955 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2956 synchronized (mPackages) { 2957 PackageParser.Activity a = mActivities.mActivities.get(component); 2958 2959 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2960 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2961 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2962 if (ps == null) return null; 2963 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2964 userId); 2965 } 2966 if (mResolveComponentName.equals(component)) { 2967 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2968 new PackageUserState(), userId); 2969 } 2970 } 2971 return null; 2972 } 2973 2974 @Override 2975 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2976 String resolvedType) { 2977 synchronized (mPackages) { 2978 if (component.equals(mResolveComponentName)) { 2979 // The resolver supports EVERYTHING! 2980 return true; 2981 } 2982 PackageParser.Activity a = mActivities.mActivities.get(component); 2983 if (a == null) { 2984 return false; 2985 } 2986 for (int i=0; i<a.intents.size(); i++) { 2987 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2988 intent.getData(), intent.getCategories(), TAG) >= 0) { 2989 return true; 2990 } 2991 } 2992 return false; 2993 } 2994 } 2995 2996 @Override 2997 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2998 if (!sUserManager.exists(userId)) return null; 2999 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 3000 synchronized (mPackages) { 3001 PackageParser.Activity a = mReceivers.mActivities.get(component); 3002 if (DEBUG_PACKAGE_INFO) Log.v( 3003 TAG, "getReceiverInfo " + component + ": " + a); 3004 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 3005 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3006 if (ps == null) return null; 3007 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3008 userId); 3009 } 3010 } 3011 return null; 3012 } 3013 3014 @Override 3015 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3016 if (!sUserManager.exists(userId)) return null; 3017 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 3018 synchronized (mPackages) { 3019 PackageParser.Service s = mServices.mServices.get(component); 3020 if (DEBUG_PACKAGE_INFO) Log.v( 3021 TAG, "getServiceInfo " + component + ": " + s); 3022 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 3023 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3024 if (ps == null) return null; 3025 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3026 userId); 3027 } 3028 } 3029 return null; 3030 } 3031 3032 @Override 3033 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3034 if (!sUserManager.exists(userId)) return null; 3035 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 3036 synchronized (mPackages) { 3037 PackageParser.Provider p = mProviders.mProviders.get(component); 3038 if (DEBUG_PACKAGE_INFO) Log.v( 3039 TAG, "getProviderInfo " + component + ": " + p); 3040 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 3041 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3042 if (ps == null) return null; 3043 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3044 userId); 3045 } 3046 } 3047 return null; 3048 } 3049 3050 @Override 3051 public String[] getSystemSharedLibraryNames() { 3052 Set<String> libSet; 3053 synchronized (mPackages) { 3054 libSet = mSharedLibraries.keySet(); 3055 int size = libSet.size(); 3056 if (size > 0) { 3057 String[] libs = new String[size]; 3058 libSet.toArray(libs); 3059 return libs; 3060 } 3061 } 3062 return null; 3063 } 3064 3065 /** 3066 * @hide 3067 */ 3068 PackageParser.Package findSharedNonSystemLibrary(String libName) { 3069 synchronized (mPackages) { 3070 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 3071 if (lib != null && lib.apk != null) { 3072 return mPackages.get(lib.apk); 3073 } 3074 } 3075 return null; 3076 } 3077 3078 @Override 3079 public FeatureInfo[] getSystemAvailableFeatures() { 3080 Collection<FeatureInfo> featSet; 3081 synchronized (mPackages) { 3082 featSet = mAvailableFeatures.values(); 3083 int size = featSet.size(); 3084 if (size > 0) { 3085 FeatureInfo[] features = new FeatureInfo[size+1]; 3086 featSet.toArray(features); 3087 FeatureInfo fi = new FeatureInfo(); 3088 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3089 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3090 features[size] = fi; 3091 return features; 3092 } 3093 } 3094 return null; 3095 } 3096 3097 @Override 3098 public boolean hasSystemFeature(String name) { 3099 synchronized (mPackages) { 3100 return mAvailableFeatures.containsKey(name); 3101 } 3102 } 3103 3104 private void checkValidCaller(int uid, int userId) { 3105 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 3106 return; 3107 3108 throw new SecurityException("Caller uid=" + uid 3109 + " is not privileged to communicate with user=" + userId); 3110 } 3111 3112 @Override 3113 public int checkPermission(String permName, String pkgName, int userId) { 3114 if (!sUserManager.exists(userId)) { 3115 return PackageManager.PERMISSION_DENIED; 3116 } 3117 3118 synchronized (mPackages) { 3119 final PackageParser.Package p = mPackages.get(pkgName); 3120 if (p != null && p.mExtras != null) { 3121 final PackageSetting ps = (PackageSetting) p.mExtras; 3122 if (ps.getPermissionsState().hasPermission(permName, userId)) { 3123 return PackageManager.PERMISSION_GRANTED; 3124 } 3125 } 3126 } 3127 3128 return PackageManager.PERMISSION_DENIED; 3129 } 3130 3131 @Override 3132 public int checkUidPermission(String permName, int uid) { 3133 final int userId = UserHandle.getUserId(uid); 3134 3135 if (!sUserManager.exists(userId)) { 3136 return PackageManager.PERMISSION_DENIED; 3137 } 3138 3139 synchronized (mPackages) { 3140 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3141 if (obj != null) { 3142 final SettingBase ps = (SettingBase) obj; 3143 if (ps.getPermissionsState().hasPermission(permName, userId)) { 3144 return PackageManager.PERMISSION_GRANTED; 3145 } 3146 } else { 3147 ArraySet<String> perms = mSystemPermissions.get(uid); 3148 if (perms != null && perms.contains(permName)) { 3149 return PackageManager.PERMISSION_GRANTED; 3150 } 3151 } 3152 } 3153 3154 return PackageManager.PERMISSION_DENIED; 3155 } 3156 3157 @Override 3158 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3159 if (UserHandle.getCallingUserId() != userId) { 3160 mContext.enforceCallingPermission( 3161 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3162 "isPermissionRevokedByPolicy for user " + userId); 3163 } 3164 3165 if (checkPermission(permission, packageName, userId) 3166 == PackageManager.PERMISSION_GRANTED) { 3167 return false; 3168 } 3169 3170 final long identity = Binder.clearCallingIdentity(); 3171 try { 3172 final int flags = getPermissionFlags(permission, packageName, userId); 3173 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3174 } finally { 3175 Binder.restoreCallingIdentity(identity); 3176 } 3177 } 3178 3179 /** 3180 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3181 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3182 * @param checkShell TODO(yamasani): 3183 * @param message the message to log on security exception 3184 */ 3185 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3186 boolean checkShell, String message) { 3187 if (userId < 0) { 3188 throw new IllegalArgumentException("Invalid userId " + userId); 3189 } 3190 if (checkShell) { 3191 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3192 } 3193 if (userId == UserHandle.getUserId(callingUid)) return; 3194 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3195 if (requireFullPermission) { 3196 mContext.enforceCallingOrSelfPermission( 3197 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3198 } else { 3199 try { 3200 mContext.enforceCallingOrSelfPermission( 3201 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3202 } catch (SecurityException se) { 3203 mContext.enforceCallingOrSelfPermission( 3204 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3205 } 3206 } 3207 } 3208 } 3209 3210 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3211 if (callingUid == Process.SHELL_UID) { 3212 if (userHandle >= 0 3213 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3214 throw new SecurityException("Shell does not have permission to access user " 3215 + userHandle); 3216 } else if (userHandle < 0) { 3217 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3218 + Debug.getCallers(3)); 3219 } 3220 } 3221 } 3222 3223 private BasePermission findPermissionTreeLP(String permName) { 3224 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3225 if (permName.startsWith(bp.name) && 3226 permName.length() > bp.name.length() && 3227 permName.charAt(bp.name.length()) == '.') { 3228 return bp; 3229 } 3230 } 3231 return null; 3232 } 3233 3234 private BasePermission checkPermissionTreeLP(String permName) { 3235 if (permName != null) { 3236 BasePermission bp = findPermissionTreeLP(permName); 3237 if (bp != null) { 3238 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3239 return bp; 3240 } 3241 throw new SecurityException("Calling uid " 3242 + Binder.getCallingUid() 3243 + " is not allowed to add to permission tree " 3244 + bp.name + " owned by uid " + bp.uid); 3245 } 3246 } 3247 throw new SecurityException("No permission tree found for " + permName); 3248 } 3249 3250 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3251 if (s1 == null) { 3252 return s2 == null; 3253 } 3254 if (s2 == null) { 3255 return false; 3256 } 3257 if (s1.getClass() != s2.getClass()) { 3258 return false; 3259 } 3260 return s1.equals(s2); 3261 } 3262 3263 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3264 if (pi1.icon != pi2.icon) return false; 3265 if (pi1.logo != pi2.logo) return false; 3266 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3267 if (!compareStrings(pi1.name, pi2.name)) return false; 3268 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3269 // We'll take care of setting this one. 3270 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3271 // These are not currently stored in settings. 3272 //if (!compareStrings(pi1.group, pi2.group)) return false; 3273 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3274 //if (pi1.labelRes != pi2.labelRes) return false; 3275 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3276 return true; 3277 } 3278 3279 int permissionInfoFootprint(PermissionInfo info) { 3280 int size = info.name.length(); 3281 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3282 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3283 return size; 3284 } 3285 3286 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3287 int size = 0; 3288 for (BasePermission perm : mSettings.mPermissions.values()) { 3289 if (perm.uid == tree.uid) { 3290 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3291 } 3292 } 3293 return size; 3294 } 3295 3296 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3297 // We calculate the max size of permissions defined by this uid and throw 3298 // if that plus the size of 'info' would exceed our stated maximum. 3299 if (tree.uid != Process.SYSTEM_UID) { 3300 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3301 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3302 throw new SecurityException("Permission tree size cap exceeded"); 3303 } 3304 } 3305 } 3306 3307 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3308 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3309 throw new SecurityException("Label must be specified in permission"); 3310 } 3311 BasePermission tree = checkPermissionTreeLP(info.name); 3312 BasePermission bp = mSettings.mPermissions.get(info.name); 3313 boolean added = bp == null; 3314 boolean changed = true; 3315 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3316 if (added) { 3317 enforcePermissionCapLocked(info, tree); 3318 bp = new BasePermission(info.name, tree.sourcePackage, 3319 BasePermission.TYPE_DYNAMIC); 3320 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3321 throw new SecurityException( 3322 "Not allowed to modify non-dynamic permission " 3323 + info.name); 3324 } else { 3325 if (bp.protectionLevel == fixedLevel 3326 && bp.perm.owner.equals(tree.perm.owner) 3327 && bp.uid == tree.uid 3328 && comparePermissionInfos(bp.perm.info, info)) { 3329 changed = false; 3330 } 3331 } 3332 bp.protectionLevel = fixedLevel; 3333 info = new PermissionInfo(info); 3334 info.protectionLevel = fixedLevel; 3335 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3336 bp.perm.info.packageName = tree.perm.info.packageName; 3337 bp.uid = tree.uid; 3338 if (added) { 3339 mSettings.mPermissions.put(info.name, bp); 3340 } 3341 if (changed) { 3342 if (!async) { 3343 mSettings.writeLPr(); 3344 } else { 3345 scheduleWriteSettingsLocked(); 3346 } 3347 } 3348 return added; 3349 } 3350 3351 @Override 3352 public boolean addPermission(PermissionInfo info) { 3353 synchronized (mPackages) { 3354 return addPermissionLocked(info, false); 3355 } 3356 } 3357 3358 @Override 3359 public boolean addPermissionAsync(PermissionInfo info) { 3360 synchronized (mPackages) { 3361 return addPermissionLocked(info, true); 3362 } 3363 } 3364 3365 @Override 3366 public void removePermission(String name) { 3367 synchronized (mPackages) { 3368 checkPermissionTreeLP(name); 3369 BasePermission bp = mSettings.mPermissions.get(name); 3370 if (bp != null) { 3371 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3372 throw new SecurityException( 3373 "Not allowed to modify non-dynamic permission " 3374 + name); 3375 } 3376 mSettings.mPermissions.remove(name); 3377 mSettings.writeLPr(); 3378 } 3379 } 3380 } 3381 3382 private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg, 3383 BasePermission bp) { 3384 int index = pkg.requestedPermissions.indexOf(bp.name); 3385 if (index == -1) { 3386 throw new SecurityException("Package " + pkg.packageName 3387 + " has not requested permission " + bp.name); 3388 } 3389 if (!bp.isRuntime()) { 3390 throw new SecurityException("Permission " + bp.name 3391 + " is not a changeable permission type"); 3392 } 3393 } 3394 3395 @Override 3396 public void grantRuntimePermission(String packageName, String name, final int userId) { 3397 if (!sUserManager.exists(userId)) { 3398 Log.e(TAG, "No such user:" + userId); 3399 return; 3400 } 3401 3402 mContext.enforceCallingOrSelfPermission( 3403 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3404 "grantRuntimePermission"); 3405 3406 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3407 "grantRuntimePermission"); 3408 3409 final int uid; 3410 final SettingBase sb; 3411 3412 synchronized (mPackages) { 3413 final PackageParser.Package pkg = mPackages.get(packageName); 3414 if (pkg == null) { 3415 throw new IllegalArgumentException("Unknown package: " + packageName); 3416 } 3417 3418 final BasePermission bp = mSettings.mPermissions.get(name); 3419 if (bp == null) { 3420 throw new IllegalArgumentException("Unknown permission: " + name); 3421 } 3422 3423 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3424 3425 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3426 sb = (SettingBase) pkg.mExtras; 3427 if (sb == null) { 3428 throw new IllegalArgumentException("Unknown package: " + packageName); 3429 } 3430 3431 final PermissionsState permissionsState = sb.getPermissionsState(); 3432 3433 final int flags = permissionsState.getPermissionFlags(name, userId); 3434 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3435 throw new SecurityException("Cannot grant system fixed permission: " 3436 + name + " for package: " + packageName); 3437 } 3438 3439 final int result = permissionsState.grantRuntimePermission(bp, userId); 3440 switch (result) { 3441 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3442 return; 3443 } 3444 3445 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3446 mHandler.post(new Runnable() { 3447 @Override 3448 public void run() { 3449 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED); 3450 } 3451 }); 3452 } break; 3453 } 3454 3455 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3456 3457 // Not critical if that is lost - app has to request again. 3458 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3459 } 3460 3461 // Only need to do this if user is initialized. Otherwise it's a new user 3462 // and there are no processes running as the user yet and there's no need 3463 // to make an expensive call to remount processes for the changed permissions. 3464 if (READ_EXTERNAL_STORAGE.equals(name) 3465 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3466 final long token = Binder.clearCallingIdentity(); 3467 try { 3468 if (sUserManager.isInitialized(userId)) { 3469 MountServiceInternal mountServiceInternal = LocalServices.getService( 3470 MountServiceInternal.class); 3471 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 3472 } 3473 } finally { 3474 Binder.restoreCallingIdentity(token); 3475 } 3476 } 3477 } 3478 3479 @Override 3480 public void revokeRuntimePermission(String packageName, String name, int userId) { 3481 if (!sUserManager.exists(userId)) { 3482 Log.e(TAG, "No such user:" + userId); 3483 return; 3484 } 3485 3486 mContext.enforceCallingOrSelfPermission( 3487 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3488 "revokeRuntimePermission"); 3489 3490 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3491 "revokeRuntimePermission"); 3492 3493 final SettingBase sb; 3494 3495 synchronized (mPackages) { 3496 final PackageParser.Package pkg = mPackages.get(packageName); 3497 if (pkg == null) { 3498 throw new IllegalArgumentException("Unknown package: " + packageName); 3499 } 3500 3501 final BasePermission bp = mSettings.mPermissions.get(name); 3502 if (bp == null) { 3503 throw new IllegalArgumentException("Unknown permission: " + name); 3504 } 3505 3506 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3507 3508 sb = (SettingBase) pkg.mExtras; 3509 if (sb == null) { 3510 throw new IllegalArgumentException("Unknown package: " + packageName); 3511 } 3512 3513 final PermissionsState permissionsState = sb.getPermissionsState(); 3514 3515 final int flags = permissionsState.getPermissionFlags(name, userId); 3516 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3517 throw new SecurityException("Cannot revoke system fixed permission: " 3518 + name + " for package: " + packageName); 3519 } 3520 3521 if (permissionsState.revokeRuntimePermission(bp, userId) == 3522 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3523 return; 3524 } 3525 3526 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3527 3528 // Critical, after this call app should never have the permission. 3529 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3530 } 3531 3532 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3533 } 3534 3535 @Override 3536 public void resetRuntimePermissions() { 3537 mContext.enforceCallingOrSelfPermission( 3538 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3539 "revokeRuntimePermission"); 3540 3541 int callingUid = Binder.getCallingUid(); 3542 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3543 mContext.enforceCallingOrSelfPermission( 3544 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3545 "resetRuntimePermissions"); 3546 } 3547 3548 synchronized (mPackages) { 3549 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 3550 for (int userId : UserManagerService.getInstance().getUserIds()) { 3551 final int packageCount = mPackages.size(); 3552 for (int i = 0; i < packageCount; i++) { 3553 PackageParser.Package pkg = mPackages.valueAt(i); 3554 if (!(pkg.mExtras instanceof PackageSetting)) { 3555 continue; 3556 } 3557 PackageSetting ps = (PackageSetting) pkg.mExtras; 3558 resetUserChangesToRuntimePermissionsAndFlagsLocked(ps, userId); 3559 } 3560 } 3561 } 3562 } 3563 3564 @Override 3565 public int getPermissionFlags(String name, String packageName, int userId) { 3566 if (!sUserManager.exists(userId)) { 3567 return 0; 3568 } 3569 3570 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 3571 3572 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3573 "getPermissionFlags"); 3574 3575 synchronized (mPackages) { 3576 final PackageParser.Package pkg = mPackages.get(packageName); 3577 if (pkg == null) { 3578 throw new IllegalArgumentException("Unknown package: " + packageName); 3579 } 3580 3581 final BasePermission bp = mSettings.mPermissions.get(name); 3582 if (bp == null) { 3583 throw new IllegalArgumentException("Unknown permission: " + name); 3584 } 3585 3586 SettingBase sb = (SettingBase) pkg.mExtras; 3587 if (sb == null) { 3588 throw new IllegalArgumentException("Unknown package: " + packageName); 3589 } 3590 3591 PermissionsState permissionsState = sb.getPermissionsState(); 3592 return permissionsState.getPermissionFlags(name, userId); 3593 } 3594 } 3595 3596 @Override 3597 public void updatePermissionFlags(String name, String packageName, int flagMask, 3598 int flagValues, int userId) { 3599 if (!sUserManager.exists(userId)) { 3600 return; 3601 } 3602 3603 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 3604 3605 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3606 "updatePermissionFlags"); 3607 3608 // Only the system can change system fixed flags. 3609 if (getCallingUid() != Process.SYSTEM_UID) { 3610 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3611 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3612 } 3613 3614 synchronized (mPackages) { 3615 final PackageParser.Package pkg = mPackages.get(packageName); 3616 if (pkg == null) { 3617 throw new IllegalArgumentException("Unknown package: " + packageName); 3618 } 3619 3620 final BasePermission bp = mSettings.mPermissions.get(name); 3621 if (bp == null) { 3622 throw new IllegalArgumentException("Unknown permission: " + name); 3623 } 3624 3625 SettingBase sb = (SettingBase) pkg.mExtras; 3626 if (sb == null) { 3627 throw new IllegalArgumentException("Unknown package: " + packageName); 3628 } 3629 3630 PermissionsState permissionsState = sb.getPermissionsState(); 3631 3632 // Only the package manager can change flags for system component permissions. 3633 final int flags = permissionsState.getPermissionFlags(bp.name, userId); 3634 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3635 return; 3636 } 3637 3638 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 3639 3640 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3641 // Install and runtime permissions are stored in different places, 3642 // so figure out what permission changed and persist the change. 3643 if (permissionsState.getInstallPermissionState(name) != null) { 3644 scheduleWriteSettingsLocked(); 3645 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 3646 || hadState) { 3647 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3648 } 3649 } 3650 } 3651 } 3652 3653 /** 3654 * Update the permission flags for all packages and runtime permissions of a user in order 3655 * to allow device or profile owner to remove POLICY_FIXED. 3656 */ 3657 @Override 3658 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 3659 if (!sUserManager.exists(userId)) { 3660 return; 3661 } 3662 3663 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 3664 3665 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3666 "updatePermissionFlagsForAllApps"); 3667 3668 // Only the system can change system fixed flags. 3669 if (getCallingUid() != Process.SYSTEM_UID) { 3670 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3671 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3672 } 3673 3674 synchronized (mPackages) { 3675 boolean changed = false; 3676 final int packageCount = mPackages.size(); 3677 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 3678 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 3679 SettingBase sb = (SettingBase) pkg.mExtras; 3680 if (sb == null) { 3681 continue; 3682 } 3683 PermissionsState permissionsState = sb.getPermissionsState(); 3684 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 3685 userId, flagMask, flagValues); 3686 } 3687 if (changed) { 3688 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3689 } 3690 } 3691 } 3692 3693 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 3694 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 3695 != PackageManager.PERMISSION_GRANTED 3696 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 3697 != PackageManager.PERMISSION_GRANTED) { 3698 throw new SecurityException(message + " requires " 3699 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 3700 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 3701 } 3702 } 3703 3704 @Override 3705 public boolean shouldShowRequestPermissionRationale(String permissionName, 3706 String packageName, int userId) { 3707 if (UserHandle.getCallingUserId() != userId) { 3708 mContext.enforceCallingPermission( 3709 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3710 "canShowRequestPermissionRationale for user " + userId); 3711 } 3712 3713 final int uid = getPackageUid(packageName, userId); 3714 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 3715 return false; 3716 } 3717 3718 if (checkPermission(permissionName, packageName, userId) 3719 == PackageManager.PERMISSION_GRANTED) { 3720 return false; 3721 } 3722 3723 final int flags; 3724 3725 final long identity = Binder.clearCallingIdentity(); 3726 try { 3727 flags = getPermissionFlags(permissionName, 3728 packageName, userId); 3729 } finally { 3730 Binder.restoreCallingIdentity(identity); 3731 } 3732 3733 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 3734 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 3735 | PackageManager.FLAG_PERMISSION_USER_FIXED; 3736 3737 if ((flags & fixedFlags) != 0) { 3738 return false; 3739 } 3740 3741 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 3742 } 3743 3744 void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) { 3745 BasePermission bp = mSettings.mPermissions.get(permission); 3746 if (bp == null) { 3747 throw new SecurityException("Missing " + permission + " permission"); 3748 } 3749 3750 SettingBase sb = (SettingBase) pkg.mExtras; 3751 PermissionsState permissionsState = sb.getPermissionsState(); 3752 3753 if (permissionsState.grantInstallPermission(bp) != 3754 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3755 scheduleWriteSettingsLocked(); 3756 } 3757 } 3758 3759 @Override 3760 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3761 mContext.enforceCallingOrSelfPermission( 3762 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 3763 "addOnPermissionsChangeListener"); 3764 3765 synchronized (mPackages) { 3766 mOnPermissionChangeListeners.addListenerLocked(listener); 3767 } 3768 } 3769 3770 @Override 3771 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3772 synchronized (mPackages) { 3773 mOnPermissionChangeListeners.removeListenerLocked(listener); 3774 } 3775 } 3776 3777 @Override 3778 public boolean isProtectedBroadcast(String actionName) { 3779 synchronized (mPackages) { 3780 return mProtectedBroadcasts.contains(actionName); 3781 } 3782 } 3783 3784 @Override 3785 public int checkSignatures(String pkg1, String pkg2) { 3786 synchronized (mPackages) { 3787 final PackageParser.Package p1 = mPackages.get(pkg1); 3788 final PackageParser.Package p2 = mPackages.get(pkg2); 3789 if (p1 == null || p1.mExtras == null 3790 || p2 == null || p2.mExtras == null) { 3791 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3792 } 3793 return compareSignatures(p1.mSignatures, p2.mSignatures); 3794 } 3795 } 3796 3797 @Override 3798 public int checkUidSignatures(int uid1, int uid2) { 3799 // Map to base uids. 3800 uid1 = UserHandle.getAppId(uid1); 3801 uid2 = UserHandle.getAppId(uid2); 3802 // reader 3803 synchronized (mPackages) { 3804 Signature[] s1; 3805 Signature[] s2; 3806 Object obj = mSettings.getUserIdLPr(uid1); 3807 if (obj != null) { 3808 if (obj instanceof SharedUserSetting) { 3809 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3810 } else if (obj instanceof PackageSetting) { 3811 s1 = ((PackageSetting)obj).signatures.mSignatures; 3812 } else { 3813 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3814 } 3815 } else { 3816 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3817 } 3818 obj = mSettings.getUserIdLPr(uid2); 3819 if (obj != null) { 3820 if (obj instanceof SharedUserSetting) { 3821 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3822 } else if (obj instanceof PackageSetting) { 3823 s2 = ((PackageSetting)obj).signatures.mSignatures; 3824 } else { 3825 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3826 } 3827 } else { 3828 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3829 } 3830 return compareSignatures(s1, s2); 3831 } 3832 } 3833 3834 private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) { 3835 final long identity = Binder.clearCallingIdentity(); 3836 try { 3837 if (sb instanceof SharedUserSetting) { 3838 SharedUserSetting sus = (SharedUserSetting) sb; 3839 final int packageCount = sus.packages.size(); 3840 for (int i = 0; i < packageCount; i++) { 3841 PackageSetting susPs = sus.packages.valueAt(i); 3842 if (userId == UserHandle.USER_ALL) { 3843 killApplication(susPs.pkg.packageName, susPs.appId, reason); 3844 } else { 3845 final int uid = UserHandle.getUid(userId, susPs.appId); 3846 killUid(uid, reason); 3847 } 3848 } 3849 } else if (sb instanceof PackageSetting) { 3850 PackageSetting ps = (PackageSetting) sb; 3851 if (userId == UserHandle.USER_ALL) { 3852 killApplication(ps.pkg.packageName, ps.appId, reason); 3853 } else { 3854 final int uid = UserHandle.getUid(userId, ps.appId); 3855 killUid(uid, reason); 3856 } 3857 } 3858 } finally { 3859 Binder.restoreCallingIdentity(identity); 3860 } 3861 } 3862 3863 private static void killUid(int uid, String reason) { 3864 IActivityManager am = ActivityManagerNative.getDefault(); 3865 if (am != null) { 3866 try { 3867 am.killUid(uid, reason); 3868 } catch (RemoteException e) { 3869 /* ignore - same process */ 3870 } 3871 } 3872 } 3873 3874 /** 3875 * Compares two sets of signatures. Returns: 3876 * <br /> 3877 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3878 * <br /> 3879 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3880 * <br /> 3881 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3882 * <br /> 3883 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3884 * <br /> 3885 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3886 */ 3887 static int compareSignatures(Signature[] s1, Signature[] s2) { 3888 if (s1 == null) { 3889 return s2 == null 3890 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3891 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3892 } 3893 3894 if (s2 == null) { 3895 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3896 } 3897 3898 if (s1.length != s2.length) { 3899 return PackageManager.SIGNATURE_NO_MATCH; 3900 } 3901 3902 // Since both signature sets are of size 1, we can compare without HashSets. 3903 if (s1.length == 1) { 3904 return s1[0].equals(s2[0]) ? 3905 PackageManager.SIGNATURE_MATCH : 3906 PackageManager.SIGNATURE_NO_MATCH; 3907 } 3908 3909 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3910 for (Signature sig : s1) { 3911 set1.add(sig); 3912 } 3913 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3914 for (Signature sig : s2) { 3915 set2.add(sig); 3916 } 3917 // Make sure s2 contains all signatures in s1. 3918 if (set1.equals(set2)) { 3919 return PackageManager.SIGNATURE_MATCH; 3920 } 3921 return PackageManager.SIGNATURE_NO_MATCH; 3922 } 3923 3924 /** 3925 * If the database version for this type of package (internal storage or 3926 * external storage) is less than the version where package signatures 3927 * were updated, return true. 3928 */ 3929 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3930 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 3931 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 3932 } 3933 3934 /** 3935 * Used for backward compatibility to make sure any packages with 3936 * certificate chains get upgraded to the new style. {@code existingSigs} 3937 * will be in the old format (since they were stored on disk from before the 3938 * system upgrade) and {@code scannedSigs} will be in the newer format. 3939 */ 3940 private int compareSignaturesCompat(PackageSignatures existingSigs, 3941 PackageParser.Package scannedPkg) { 3942 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 3943 return PackageManager.SIGNATURE_NO_MATCH; 3944 } 3945 3946 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 3947 for (Signature sig : existingSigs.mSignatures) { 3948 existingSet.add(sig); 3949 } 3950 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 3951 for (Signature sig : scannedPkg.mSignatures) { 3952 try { 3953 Signature[] chainSignatures = sig.getChainSignatures(); 3954 for (Signature chainSig : chainSignatures) { 3955 scannedCompatSet.add(chainSig); 3956 } 3957 } catch (CertificateEncodingException e) { 3958 scannedCompatSet.add(sig); 3959 } 3960 } 3961 /* 3962 * Make sure the expanded scanned set contains all signatures in the 3963 * existing one. 3964 */ 3965 if (scannedCompatSet.equals(existingSet)) { 3966 // Migrate the old signatures to the new scheme. 3967 existingSigs.assignSignatures(scannedPkg.mSignatures); 3968 // The new KeySets will be re-added later in the scanning process. 3969 synchronized (mPackages) { 3970 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 3971 } 3972 return PackageManager.SIGNATURE_MATCH; 3973 } 3974 return PackageManager.SIGNATURE_NO_MATCH; 3975 } 3976 3977 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3978 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 3979 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 3980 } 3981 3982 private int compareSignaturesRecover(PackageSignatures existingSigs, 3983 PackageParser.Package scannedPkg) { 3984 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 3985 return PackageManager.SIGNATURE_NO_MATCH; 3986 } 3987 3988 String msg = null; 3989 try { 3990 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 3991 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 3992 + scannedPkg.packageName); 3993 return PackageManager.SIGNATURE_MATCH; 3994 } 3995 } catch (CertificateException e) { 3996 msg = e.getMessage(); 3997 } 3998 3999 logCriticalInfo(Log.INFO, 4000 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4001 return PackageManager.SIGNATURE_NO_MATCH; 4002 } 4003 4004 @Override 4005 public String[] getPackagesForUid(int uid) { 4006 uid = UserHandle.getAppId(uid); 4007 // reader 4008 synchronized (mPackages) { 4009 Object obj = mSettings.getUserIdLPr(uid); 4010 if (obj instanceof SharedUserSetting) { 4011 final SharedUserSetting sus = (SharedUserSetting) obj; 4012 final int N = sus.packages.size(); 4013 final String[] res = new String[N]; 4014 final Iterator<PackageSetting> it = sus.packages.iterator(); 4015 int i = 0; 4016 while (it.hasNext()) { 4017 res[i++] = it.next().name; 4018 } 4019 return res; 4020 } else if (obj instanceof PackageSetting) { 4021 final PackageSetting ps = (PackageSetting) obj; 4022 return new String[] { ps.name }; 4023 } 4024 } 4025 return null; 4026 } 4027 4028 @Override 4029 public String getNameForUid(int uid) { 4030 // reader 4031 synchronized (mPackages) { 4032 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4033 if (obj instanceof SharedUserSetting) { 4034 final SharedUserSetting sus = (SharedUserSetting) obj; 4035 return sus.name + ":" + sus.userId; 4036 } else if (obj instanceof PackageSetting) { 4037 final PackageSetting ps = (PackageSetting) obj; 4038 return ps.name; 4039 } 4040 } 4041 return null; 4042 } 4043 4044 @Override 4045 public int getUidForSharedUser(String sharedUserName) { 4046 if(sharedUserName == null) { 4047 return -1; 4048 } 4049 // reader 4050 synchronized (mPackages) { 4051 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4052 if (suid == null) { 4053 return -1; 4054 } 4055 return suid.userId; 4056 } 4057 } 4058 4059 @Override 4060 public int getFlagsForUid(int uid) { 4061 synchronized (mPackages) { 4062 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4063 if (obj instanceof SharedUserSetting) { 4064 final SharedUserSetting sus = (SharedUserSetting) obj; 4065 return sus.pkgFlags; 4066 } else if (obj instanceof PackageSetting) { 4067 final PackageSetting ps = (PackageSetting) obj; 4068 return ps.pkgFlags; 4069 } 4070 } 4071 return 0; 4072 } 4073 4074 @Override 4075 public int getPrivateFlagsForUid(int uid) { 4076 synchronized (mPackages) { 4077 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4078 if (obj instanceof SharedUserSetting) { 4079 final SharedUserSetting sus = (SharedUserSetting) obj; 4080 return sus.pkgPrivateFlags; 4081 } else if (obj instanceof PackageSetting) { 4082 final PackageSetting ps = (PackageSetting) obj; 4083 return ps.pkgPrivateFlags; 4084 } 4085 } 4086 return 0; 4087 } 4088 4089 @Override 4090 public boolean isUidPrivileged(int uid) { 4091 uid = UserHandle.getAppId(uid); 4092 // reader 4093 synchronized (mPackages) { 4094 Object obj = mSettings.getUserIdLPr(uid); 4095 if (obj instanceof SharedUserSetting) { 4096 final SharedUserSetting sus = (SharedUserSetting) obj; 4097 final Iterator<PackageSetting> it = sus.packages.iterator(); 4098 while (it.hasNext()) { 4099 if (it.next().isPrivileged()) { 4100 return true; 4101 } 4102 } 4103 } else if (obj instanceof PackageSetting) { 4104 final PackageSetting ps = (PackageSetting) obj; 4105 return ps.isPrivileged(); 4106 } 4107 } 4108 return false; 4109 } 4110 4111 @Override 4112 public String[] getAppOpPermissionPackages(String permissionName) { 4113 synchronized (mPackages) { 4114 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4115 if (pkgs == null) { 4116 return null; 4117 } 4118 return pkgs.toArray(new String[pkgs.size()]); 4119 } 4120 } 4121 4122 @Override 4123 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4124 int flags, int userId) { 4125 if (!sUserManager.exists(userId)) return null; 4126 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 4127 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4128 return chooseBestActivity(intent, resolvedType, flags, query, userId); 4129 } 4130 4131 @Override 4132 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4133 IntentFilter filter, int match, ComponentName activity) { 4134 final int userId = UserHandle.getCallingUserId(); 4135 if (DEBUG_PREFERRED) { 4136 Log.v(TAG, "setLastChosenActivity intent=" + intent 4137 + " resolvedType=" + resolvedType 4138 + " flags=" + flags 4139 + " filter=" + filter 4140 + " match=" + match 4141 + " activity=" + activity); 4142 filter.dump(new PrintStreamPrinter(System.out), " "); 4143 } 4144 intent.setComponent(null); 4145 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4146 // Find any earlier preferred or last chosen entries and nuke them 4147 findPreferredActivity(intent, resolvedType, 4148 flags, query, 0, false, true, false, userId); 4149 // Add the new activity as the last chosen for this filter 4150 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4151 "Setting last chosen"); 4152 } 4153 4154 @Override 4155 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4156 final int userId = UserHandle.getCallingUserId(); 4157 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4158 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4159 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4160 false, false, false, userId); 4161 } 4162 4163 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4164 int flags, List<ResolveInfo> query, int userId) { 4165 if (query != null) { 4166 final int N = query.size(); 4167 if (N == 1) { 4168 return query.get(0); 4169 } else if (N > 1) { 4170 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4171 // If there is more than one activity with the same priority, 4172 // then let the user decide between them. 4173 ResolveInfo r0 = query.get(0); 4174 ResolveInfo r1 = query.get(1); 4175 if (DEBUG_INTENT_MATCHING || debug) { 4176 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4177 + r1.activityInfo.name + "=" + r1.priority); 4178 } 4179 // If the first activity has a higher priority, or a different 4180 // default, then it is always desireable to pick it. 4181 if (r0.priority != r1.priority 4182 || r0.preferredOrder != r1.preferredOrder 4183 || r0.isDefault != r1.isDefault) { 4184 return query.get(0); 4185 } 4186 // If we have saved a preference for a preferred activity for 4187 // this Intent, use that. 4188 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4189 flags, query, r0.priority, true, false, debug, userId); 4190 if (ri != null) { 4191 return ri; 4192 } 4193 if (userId != 0) { 4194 ri = new ResolveInfo(mResolveInfo); 4195 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4196 ri.activityInfo.applicationInfo = new ApplicationInfo( 4197 ri.activityInfo.applicationInfo); 4198 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4199 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4200 return ri; 4201 } 4202 return mResolveInfo; 4203 } 4204 } 4205 return null; 4206 } 4207 4208 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4209 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4210 final int N = query.size(); 4211 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4212 .get(userId); 4213 // Get the list of persistent preferred activities that handle the intent 4214 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4215 List<PersistentPreferredActivity> pprefs = ppir != null 4216 ? ppir.queryIntent(intent, resolvedType, 4217 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4218 : null; 4219 if (pprefs != null && pprefs.size() > 0) { 4220 final int M = pprefs.size(); 4221 for (int i=0; i<M; i++) { 4222 final PersistentPreferredActivity ppa = pprefs.get(i); 4223 if (DEBUG_PREFERRED || debug) { 4224 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4225 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4226 + "\n component=" + ppa.mComponent); 4227 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4228 } 4229 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4230 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4231 if (DEBUG_PREFERRED || debug) { 4232 Slog.v(TAG, "Found persistent preferred activity:"); 4233 if (ai != null) { 4234 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4235 } else { 4236 Slog.v(TAG, " null"); 4237 } 4238 } 4239 if (ai == null) { 4240 // This previously registered persistent preferred activity 4241 // component is no longer known. Ignore it and do NOT remove it. 4242 continue; 4243 } 4244 for (int j=0; j<N; j++) { 4245 final ResolveInfo ri = query.get(j); 4246 if (!ri.activityInfo.applicationInfo.packageName 4247 .equals(ai.applicationInfo.packageName)) { 4248 continue; 4249 } 4250 if (!ri.activityInfo.name.equals(ai.name)) { 4251 continue; 4252 } 4253 // Found a persistent preference that can handle the intent. 4254 if (DEBUG_PREFERRED || debug) { 4255 Slog.v(TAG, "Returning persistent preferred activity: " + 4256 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4257 } 4258 return ri; 4259 } 4260 } 4261 } 4262 return null; 4263 } 4264 4265 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4266 List<ResolveInfo> query, int priority, boolean always, 4267 boolean removeMatches, boolean debug, int userId) { 4268 if (!sUserManager.exists(userId)) return null; 4269 // writer 4270 synchronized (mPackages) { 4271 if (intent.getSelector() != null) { 4272 intent = intent.getSelector(); 4273 } 4274 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4275 4276 // Try to find a matching persistent preferred activity. 4277 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4278 debug, userId); 4279 4280 // If a persistent preferred activity matched, use it. 4281 if (pri != null) { 4282 return pri; 4283 } 4284 4285 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4286 // Get the list of preferred activities that handle the intent 4287 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4288 List<PreferredActivity> prefs = pir != null 4289 ? pir.queryIntent(intent, resolvedType, 4290 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4291 : null; 4292 if (prefs != null && prefs.size() > 0) { 4293 boolean changed = false; 4294 try { 4295 // First figure out how good the original match set is. 4296 // We will only allow preferred activities that came 4297 // from the same match quality. 4298 int match = 0; 4299 4300 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4301 4302 final int N = query.size(); 4303 for (int j=0; j<N; j++) { 4304 final ResolveInfo ri = query.get(j); 4305 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4306 + ": 0x" + Integer.toHexString(match)); 4307 if (ri.match > match) { 4308 match = ri.match; 4309 } 4310 } 4311 4312 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4313 + Integer.toHexString(match)); 4314 4315 match &= IntentFilter.MATCH_CATEGORY_MASK; 4316 final int M = prefs.size(); 4317 for (int i=0; i<M; i++) { 4318 final PreferredActivity pa = prefs.get(i); 4319 if (DEBUG_PREFERRED || debug) { 4320 Slog.v(TAG, "Checking PreferredActivity ds=" 4321 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4322 + "\n component=" + pa.mPref.mComponent); 4323 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4324 } 4325 if (pa.mPref.mMatch != match) { 4326 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4327 + Integer.toHexString(pa.mPref.mMatch)); 4328 continue; 4329 } 4330 // If it's not an "always" type preferred activity and that's what we're 4331 // looking for, skip it. 4332 if (always && !pa.mPref.mAlways) { 4333 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4334 continue; 4335 } 4336 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4337 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4338 if (DEBUG_PREFERRED || debug) { 4339 Slog.v(TAG, "Found preferred activity:"); 4340 if (ai != null) { 4341 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4342 } else { 4343 Slog.v(TAG, " null"); 4344 } 4345 } 4346 if (ai == null) { 4347 // This previously registered preferred activity 4348 // component is no longer known. Most likely an update 4349 // to the app was installed and in the new version this 4350 // component no longer exists. Clean it up by removing 4351 // it from the preferred activities list, and skip it. 4352 Slog.w(TAG, "Removing dangling preferred activity: " 4353 + pa.mPref.mComponent); 4354 pir.removeFilter(pa); 4355 changed = true; 4356 continue; 4357 } 4358 for (int j=0; j<N; j++) { 4359 final ResolveInfo ri = query.get(j); 4360 if (!ri.activityInfo.applicationInfo.packageName 4361 .equals(ai.applicationInfo.packageName)) { 4362 continue; 4363 } 4364 if (!ri.activityInfo.name.equals(ai.name)) { 4365 continue; 4366 } 4367 4368 if (removeMatches) { 4369 pir.removeFilter(pa); 4370 changed = true; 4371 if (DEBUG_PREFERRED) { 4372 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4373 } 4374 break; 4375 } 4376 4377 // Okay we found a previously set preferred or last chosen app. 4378 // If the result set is different from when this 4379 // was created, we need to clear it and re-ask the 4380 // user their preference, if we're looking for an "always" type entry. 4381 if (always && !pa.mPref.sameSet(query)) { 4382 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4383 + intent + " type " + resolvedType); 4384 if (DEBUG_PREFERRED) { 4385 Slog.v(TAG, "Removing preferred activity since set changed " 4386 + pa.mPref.mComponent); 4387 } 4388 pir.removeFilter(pa); 4389 // Re-add the filter as a "last chosen" entry (!always) 4390 PreferredActivity lastChosen = new PreferredActivity( 4391 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4392 pir.addFilter(lastChosen); 4393 changed = true; 4394 return null; 4395 } 4396 4397 // Yay! Either the set matched or we're looking for the last chosen 4398 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4399 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4400 return ri; 4401 } 4402 } 4403 } finally { 4404 if (changed) { 4405 if (DEBUG_PREFERRED) { 4406 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4407 } 4408 scheduleWritePackageRestrictionsLocked(userId); 4409 } 4410 } 4411 } 4412 } 4413 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4414 return null; 4415 } 4416 4417 /* 4418 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4419 */ 4420 @Override 4421 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4422 int targetUserId) { 4423 mContext.enforceCallingOrSelfPermission( 4424 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4425 List<CrossProfileIntentFilter> matches = 4426 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4427 if (matches != null) { 4428 int size = matches.size(); 4429 for (int i = 0; i < size; i++) { 4430 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4431 } 4432 } 4433 if (hasWebURI(intent)) { 4434 // cross-profile app linking works only towards the parent. 4435 final UserInfo parent = getProfileParent(sourceUserId); 4436 synchronized(mPackages) { 4437 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 4438 intent, resolvedType, 0, sourceUserId, parent.id); 4439 return xpDomainInfo != null; 4440 } 4441 } 4442 return false; 4443 } 4444 4445 private UserInfo getProfileParent(int userId) { 4446 final long identity = Binder.clearCallingIdentity(); 4447 try { 4448 return sUserManager.getProfileParent(userId); 4449 } finally { 4450 Binder.restoreCallingIdentity(identity); 4451 } 4452 } 4453 4454 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4455 String resolvedType, int userId) { 4456 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4457 if (resolver != null) { 4458 return resolver.queryIntent(intent, resolvedType, false, userId); 4459 } 4460 return null; 4461 } 4462 4463 @Override 4464 public List<ResolveInfo> queryIntentActivities(Intent intent, 4465 String resolvedType, int flags, int userId) { 4466 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4467 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4468 ComponentName comp = intent.getComponent(); 4469 if (comp == null) { 4470 if (intent.getSelector() != null) { 4471 intent = intent.getSelector(); 4472 comp = intent.getComponent(); 4473 } 4474 } 4475 4476 if (comp != null) { 4477 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4478 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4479 if (ai != null) { 4480 final ResolveInfo ri = new ResolveInfo(); 4481 ri.activityInfo = ai; 4482 list.add(ri); 4483 } 4484 return list; 4485 } 4486 4487 // reader 4488 synchronized (mPackages) { 4489 final String pkgName = intent.getPackage(); 4490 if (pkgName == null) { 4491 List<CrossProfileIntentFilter> matchingFilters = 4492 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4493 // Check for results that need to skip the current profile. 4494 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4495 resolvedType, flags, userId); 4496 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4497 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4498 result.add(xpResolveInfo); 4499 return filterIfNotPrimaryUser(result, userId); 4500 } 4501 4502 // Check for results in the current profile. 4503 List<ResolveInfo> result = mActivities.queryIntent( 4504 intent, resolvedType, flags, userId); 4505 4506 // Check for cross profile results. 4507 xpResolveInfo = queryCrossProfileIntents( 4508 matchingFilters, intent, resolvedType, flags, userId); 4509 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4510 result.add(xpResolveInfo); 4511 Collections.sort(result, mResolvePrioritySorter); 4512 } 4513 result = filterIfNotPrimaryUser(result, userId); 4514 if (hasWebURI(intent)) { 4515 CrossProfileDomainInfo xpDomainInfo = null; 4516 final UserInfo parent = getProfileParent(userId); 4517 if (parent != null) { 4518 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 4519 flags, userId, parent.id); 4520 } 4521 if (xpDomainInfo != null) { 4522 if (xpResolveInfo != null) { 4523 // If we didn't remove it, the cross-profile ResolveInfo would be twice 4524 // in the result. 4525 result.remove(xpResolveInfo); 4526 } 4527 if (result.size() == 0) { 4528 result.add(xpDomainInfo.resolveInfo); 4529 return result; 4530 } 4531 } else if (result.size() <= 1) { 4532 return result; 4533 } 4534 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 4535 xpDomainInfo, userId); 4536 Collections.sort(result, mResolvePrioritySorter); 4537 } 4538 return result; 4539 } 4540 final PackageParser.Package pkg = mPackages.get(pkgName); 4541 if (pkg != null) { 4542 return filterIfNotPrimaryUser( 4543 mActivities.queryIntentForPackage( 4544 intent, resolvedType, flags, pkg.activities, userId), 4545 userId); 4546 } 4547 return new ArrayList<ResolveInfo>(); 4548 } 4549 } 4550 4551 private static class CrossProfileDomainInfo { 4552 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 4553 ResolveInfo resolveInfo; 4554 /* Best domain verification status of the activities found in the other profile */ 4555 int bestDomainVerificationStatus; 4556 } 4557 4558 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 4559 String resolvedType, int flags, int sourceUserId, int parentUserId) { 4560 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 4561 sourceUserId)) { 4562 return null; 4563 } 4564 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4565 resolvedType, flags, parentUserId); 4566 4567 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 4568 return null; 4569 } 4570 CrossProfileDomainInfo result = null; 4571 int size = resultTargetUser.size(); 4572 for (int i = 0; i < size; i++) { 4573 ResolveInfo riTargetUser = resultTargetUser.get(i); 4574 // Intent filter verification is only for filters that specify a host. So don't return 4575 // those that handle all web uris. 4576 if (riTargetUser.handleAllWebDataURI) { 4577 continue; 4578 } 4579 String packageName = riTargetUser.activityInfo.packageName; 4580 PackageSetting ps = mSettings.mPackages.get(packageName); 4581 if (ps == null) { 4582 continue; 4583 } 4584 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 4585 int status = (int)(verificationState >> 32); 4586 if (result == null) { 4587 result = new CrossProfileDomainInfo(); 4588 result.resolveInfo = 4589 createForwardingResolveInfo(null, sourceUserId, parentUserId); 4590 result.bestDomainVerificationStatus = status; 4591 } else { 4592 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 4593 result.bestDomainVerificationStatus); 4594 } 4595 } 4596 // Don't consider matches with status NEVER across profiles. 4597 if (result != null && result.bestDomainVerificationStatus 4598 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4599 return null; 4600 } 4601 return result; 4602 } 4603 4604 /** 4605 * Verification statuses are ordered from the worse to the best, except for 4606 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 4607 */ 4608 private int bestDomainVerificationStatus(int status1, int status2) { 4609 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4610 return status2; 4611 } 4612 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4613 return status1; 4614 } 4615 return (int) MathUtils.max(status1, status2); 4616 } 4617 4618 private boolean isUserEnabled(int userId) { 4619 long callingId = Binder.clearCallingIdentity(); 4620 try { 4621 UserInfo userInfo = sUserManager.getUserInfo(userId); 4622 return userInfo != null && userInfo.isEnabled(); 4623 } finally { 4624 Binder.restoreCallingIdentity(callingId); 4625 } 4626 } 4627 4628 /** 4629 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 4630 * 4631 * @return filtered list 4632 */ 4633 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 4634 if (userId == UserHandle.USER_OWNER) { 4635 return resolveInfos; 4636 } 4637 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 4638 ResolveInfo info = resolveInfos.get(i); 4639 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 4640 resolveInfos.remove(i); 4641 } 4642 } 4643 return resolveInfos; 4644 } 4645 4646 private static boolean hasWebURI(Intent intent) { 4647 if (intent.getData() == null) { 4648 return false; 4649 } 4650 final String scheme = intent.getScheme(); 4651 if (TextUtils.isEmpty(scheme)) { 4652 return false; 4653 } 4654 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4655 } 4656 4657 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 4658 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 4659 int userId) { 4660 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 4661 4662 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4663 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 4664 candidates.size()); 4665 } 4666 4667 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4668 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 4669 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4670 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4671 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4672 4673 synchronized (mPackages) { 4674 final int count = candidates.size(); 4675 // First, try to use linked apps. Partition the candidates into four lists: 4676 // one for the final results, one for the "do not use ever", one for "undefined status" 4677 // and finally one for "browser app type". 4678 for (int n=0; n<count; n++) { 4679 ResolveInfo info = candidates.get(n); 4680 String packageName = info.activityInfo.packageName; 4681 PackageSetting ps = mSettings.mPackages.get(packageName); 4682 if (ps != null) { 4683 // Add to the special match all list (Browser use case) 4684 if (info.handleAllWebDataURI) { 4685 matchAllList.add(info); 4686 continue; 4687 } 4688 // Try to get the status from User settings first 4689 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4690 int status = (int)(packedStatus >> 32); 4691 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 4692 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4693 if (DEBUG_DOMAIN_VERIFICATION) { 4694 Slog.i(TAG, " + always: " + info.activityInfo.packageName 4695 + " : linkgen=" + linkGeneration); 4696 } 4697 // Use link-enabled generation as preferredOrder, i.e. 4698 // prefer newly-enabled over earlier-enabled. 4699 info.preferredOrder = linkGeneration; 4700 alwaysList.add(info); 4701 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4702 if (DEBUG_DOMAIN_VERIFICATION) { 4703 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 4704 } 4705 neverList.add(info); 4706 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 4707 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 4708 if (DEBUG_DOMAIN_VERIFICATION) { 4709 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 4710 } 4711 undefinedList.add(info); 4712 } 4713 } 4714 } 4715 // First try to add the "always" resolution(s) for the current user, if any 4716 if (alwaysList.size() > 0) { 4717 result.addAll(alwaysList); 4718 // if there is an "always" for the parent user, add it. 4719 } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus 4720 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4721 result.add(xpDomainInfo.resolveInfo); 4722 } else { 4723 // Add all undefined Apps as we want them to appear in the Disambiguation dialog. 4724 result.addAll(undefinedList); 4725 if (xpDomainInfo != null && ( 4726 xpDomainInfo.bestDomainVerificationStatus 4727 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 4728 || xpDomainInfo.bestDomainVerificationStatus 4729 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) { 4730 result.add(xpDomainInfo.resolveInfo); 4731 } 4732 // Also add Browsers (all of them or only the default one) 4733 if ((matchFlags & MATCH_ALL) != 0) { 4734 result.addAll(matchAllList); 4735 } else { 4736 // Browser/generic handling case. If there's a default browser, go straight 4737 // to that (but only if there is no other higher-priority match). 4738 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 4739 int maxMatchPrio = 0; 4740 ResolveInfo defaultBrowserMatch = null; 4741 final int numCandidates = matchAllList.size(); 4742 for (int n = 0; n < numCandidates; n++) { 4743 ResolveInfo info = matchAllList.get(n); 4744 // track the highest overall match priority... 4745 if (info.priority > maxMatchPrio) { 4746 maxMatchPrio = info.priority; 4747 } 4748 // ...and the highest-priority default browser match 4749 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4750 if (defaultBrowserMatch == null 4751 || (defaultBrowserMatch.priority < info.priority)) { 4752 if (debug) { 4753 Slog.v(TAG, "Considering default browser match " + info); 4754 } 4755 defaultBrowserMatch = info; 4756 } 4757 } 4758 } 4759 if (defaultBrowserMatch != null 4760 && defaultBrowserMatch.priority >= maxMatchPrio 4761 && !TextUtils.isEmpty(defaultBrowserPackageName)) 4762 { 4763 if (debug) { 4764 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 4765 } 4766 result.add(defaultBrowserMatch); 4767 } else { 4768 result.addAll(matchAllList); 4769 } 4770 } 4771 4772 // If there is nothing selected, add all candidates and remove the ones that the user 4773 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 4774 if (result.size() == 0) { 4775 result.addAll(candidates); 4776 result.removeAll(neverList); 4777 } 4778 } 4779 } 4780 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4781 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 4782 result.size()); 4783 for (ResolveInfo info : result) { 4784 Slog.v(TAG, " + " + info.activityInfo); 4785 } 4786 } 4787 return result; 4788 } 4789 4790 // Returns a packed value as a long: 4791 // 4792 // high 'int'-sized word: link status: undefined/ask/never/always. 4793 // low 'int'-sized word: relative priority among 'always' results. 4794 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4795 long result = ps.getDomainVerificationStatusForUser(userId); 4796 // if none available, get the master status 4797 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4798 if (ps.getIntentFilterVerificationInfo() != null) { 4799 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 4800 } 4801 } 4802 return result; 4803 } 4804 4805 private ResolveInfo querySkipCurrentProfileIntents( 4806 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4807 int flags, int sourceUserId) { 4808 if (matchingFilters != null) { 4809 int size = matchingFilters.size(); 4810 for (int i = 0; i < size; i ++) { 4811 CrossProfileIntentFilter filter = matchingFilters.get(i); 4812 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4813 // Checking if there are activities in the target user that can handle the 4814 // intent. 4815 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4816 flags, sourceUserId); 4817 if (resolveInfo != null) { 4818 return resolveInfo; 4819 } 4820 } 4821 } 4822 } 4823 return null; 4824 } 4825 4826 // Return matching ResolveInfo if any for skip current profile intent filters. 4827 private ResolveInfo queryCrossProfileIntents( 4828 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4829 int flags, int sourceUserId) { 4830 if (matchingFilters != null) { 4831 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4832 // match the same intent. For performance reasons, it is better not to 4833 // run queryIntent twice for the same userId 4834 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4835 int size = matchingFilters.size(); 4836 for (int i = 0; i < size; i++) { 4837 CrossProfileIntentFilter filter = matchingFilters.get(i); 4838 int targetUserId = filter.getTargetUserId(); 4839 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4840 && !alreadyTriedUserIds.get(targetUserId)) { 4841 // Checking if there are activities in the target user that can handle the 4842 // intent. 4843 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4844 flags, sourceUserId); 4845 if (resolveInfo != null) return resolveInfo; 4846 alreadyTriedUserIds.put(targetUserId, true); 4847 } 4848 } 4849 } 4850 return null; 4851 } 4852 4853 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 4854 String resolvedType, int flags, int sourceUserId) { 4855 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4856 resolvedType, flags, filter.getTargetUserId()); 4857 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4858 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4859 } 4860 return null; 4861 } 4862 4863 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4864 int sourceUserId, int targetUserId) { 4865 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4866 String className; 4867 if (targetUserId == UserHandle.USER_OWNER) { 4868 className = FORWARD_INTENT_TO_USER_OWNER; 4869 } else { 4870 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4871 } 4872 ComponentName forwardingActivityComponentName = new ComponentName( 4873 mAndroidApplication.packageName, className); 4874 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4875 sourceUserId); 4876 if (targetUserId == UserHandle.USER_OWNER) { 4877 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 4878 forwardingResolveInfo.noResourceId = true; 4879 } 4880 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4881 forwardingResolveInfo.priority = 0; 4882 forwardingResolveInfo.preferredOrder = 0; 4883 forwardingResolveInfo.match = 0; 4884 forwardingResolveInfo.isDefault = true; 4885 forwardingResolveInfo.filter = filter; 4886 forwardingResolveInfo.targetUserId = targetUserId; 4887 return forwardingResolveInfo; 4888 } 4889 4890 @Override 4891 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4892 Intent[] specifics, String[] specificTypes, Intent intent, 4893 String resolvedType, int flags, int userId) { 4894 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4895 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4896 false, "query intent activity options"); 4897 final String resultsAction = intent.getAction(); 4898 4899 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4900 | PackageManager.GET_RESOLVED_FILTER, userId); 4901 4902 if (DEBUG_INTENT_MATCHING) { 4903 Log.v(TAG, "Query " + intent + ": " + results); 4904 } 4905 4906 int specificsPos = 0; 4907 int N; 4908 4909 // todo: note that the algorithm used here is O(N^2). This 4910 // isn't a problem in our current environment, but if we start running 4911 // into situations where we have more than 5 or 10 matches then this 4912 // should probably be changed to something smarter... 4913 4914 // First we go through and resolve each of the specific items 4915 // that were supplied, taking care of removing any corresponding 4916 // duplicate items in the generic resolve list. 4917 if (specifics != null) { 4918 for (int i=0; i<specifics.length; i++) { 4919 final Intent sintent = specifics[i]; 4920 if (sintent == null) { 4921 continue; 4922 } 4923 4924 if (DEBUG_INTENT_MATCHING) { 4925 Log.v(TAG, "Specific #" + i + ": " + sintent); 4926 } 4927 4928 String action = sintent.getAction(); 4929 if (resultsAction != null && resultsAction.equals(action)) { 4930 // If this action was explicitly requested, then don't 4931 // remove things that have it. 4932 action = null; 4933 } 4934 4935 ResolveInfo ri = null; 4936 ActivityInfo ai = null; 4937 4938 ComponentName comp = sintent.getComponent(); 4939 if (comp == null) { 4940 ri = resolveIntent( 4941 sintent, 4942 specificTypes != null ? specificTypes[i] : null, 4943 flags, userId); 4944 if (ri == null) { 4945 continue; 4946 } 4947 if (ri == mResolveInfo) { 4948 // ACK! Must do something better with this. 4949 } 4950 ai = ri.activityInfo; 4951 comp = new ComponentName(ai.applicationInfo.packageName, 4952 ai.name); 4953 } else { 4954 ai = getActivityInfo(comp, flags, userId); 4955 if (ai == null) { 4956 continue; 4957 } 4958 } 4959 4960 // Look for any generic query activities that are duplicates 4961 // of this specific one, and remove them from the results. 4962 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 4963 N = results.size(); 4964 int j; 4965 for (j=specificsPos; j<N; j++) { 4966 ResolveInfo sri = results.get(j); 4967 if ((sri.activityInfo.name.equals(comp.getClassName()) 4968 && sri.activityInfo.applicationInfo.packageName.equals( 4969 comp.getPackageName())) 4970 || (action != null && sri.filter.matchAction(action))) { 4971 results.remove(j); 4972 if (DEBUG_INTENT_MATCHING) Log.v( 4973 TAG, "Removing duplicate item from " + j 4974 + " due to specific " + specificsPos); 4975 if (ri == null) { 4976 ri = sri; 4977 } 4978 j--; 4979 N--; 4980 } 4981 } 4982 4983 // Add this specific item to its proper place. 4984 if (ri == null) { 4985 ri = new ResolveInfo(); 4986 ri.activityInfo = ai; 4987 } 4988 results.add(specificsPos, ri); 4989 ri.specificIndex = i; 4990 specificsPos++; 4991 } 4992 } 4993 4994 // Now we go through the remaining generic results and remove any 4995 // duplicate actions that are found here. 4996 N = results.size(); 4997 for (int i=specificsPos; i<N-1; i++) { 4998 final ResolveInfo rii = results.get(i); 4999 if (rii.filter == null) { 5000 continue; 5001 } 5002 5003 // Iterate over all of the actions of this result's intent 5004 // filter... typically this should be just one. 5005 final Iterator<String> it = rii.filter.actionsIterator(); 5006 if (it == null) { 5007 continue; 5008 } 5009 while (it.hasNext()) { 5010 final String action = it.next(); 5011 if (resultsAction != null && resultsAction.equals(action)) { 5012 // If this action was explicitly requested, then don't 5013 // remove things that have it. 5014 continue; 5015 } 5016 for (int j=i+1; j<N; j++) { 5017 final ResolveInfo rij = results.get(j); 5018 if (rij.filter != null && rij.filter.hasAction(action)) { 5019 results.remove(j); 5020 if (DEBUG_INTENT_MATCHING) Log.v( 5021 TAG, "Removing duplicate item from " + j 5022 + " due to action " + action + " at " + i); 5023 j--; 5024 N--; 5025 } 5026 } 5027 } 5028 5029 // If the caller didn't request filter information, drop it now 5030 // so we don't have to marshall/unmarshall it. 5031 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5032 rii.filter = null; 5033 } 5034 } 5035 5036 // Filter out the caller activity if so requested. 5037 if (caller != null) { 5038 N = results.size(); 5039 for (int i=0; i<N; i++) { 5040 ActivityInfo ainfo = results.get(i).activityInfo; 5041 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5042 && caller.getClassName().equals(ainfo.name)) { 5043 results.remove(i); 5044 break; 5045 } 5046 } 5047 } 5048 5049 // If the caller didn't request filter information, 5050 // drop them now so we don't have to 5051 // marshall/unmarshall it. 5052 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5053 N = results.size(); 5054 for (int i=0; i<N; i++) { 5055 results.get(i).filter = null; 5056 } 5057 } 5058 5059 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5060 return results; 5061 } 5062 5063 @Override 5064 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 5065 int userId) { 5066 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5067 ComponentName comp = intent.getComponent(); 5068 if (comp == null) { 5069 if (intent.getSelector() != null) { 5070 intent = intent.getSelector(); 5071 comp = intent.getComponent(); 5072 } 5073 } 5074 if (comp != null) { 5075 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5076 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5077 if (ai != null) { 5078 ResolveInfo ri = new ResolveInfo(); 5079 ri.activityInfo = ai; 5080 list.add(ri); 5081 } 5082 return list; 5083 } 5084 5085 // reader 5086 synchronized (mPackages) { 5087 String pkgName = intent.getPackage(); 5088 if (pkgName == null) { 5089 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5090 } 5091 final PackageParser.Package pkg = mPackages.get(pkgName); 5092 if (pkg != null) { 5093 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5094 userId); 5095 } 5096 return null; 5097 } 5098 } 5099 5100 @Override 5101 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5102 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 5103 if (!sUserManager.exists(userId)) return null; 5104 if (query != null) { 5105 if (query.size() >= 1) { 5106 // If there is more than one service with the same priority, 5107 // just arbitrarily pick the first one. 5108 return query.get(0); 5109 } 5110 } 5111 return null; 5112 } 5113 5114 @Override 5115 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 5116 int userId) { 5117 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5118 ComponentName comp = intent.getComponent(); 5119 if (comp == null) { 5120 if (intent.getSelector() != null) { 5121 intent = intent.getSelector(); 5122 comp = intent.getComponent(); 5123 } 5124 } 5125 if (comp != null) { 5126 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5127 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5128 if (si != null) { 5129 final ResolveInfo ri = new ResolveInfo(); 5130 ri.serviceInfo = si; 5131 list.add(ri); 5132 } 5133 return list; 5134 } 5135 5136 // reader 5137 synchronized (mPackages) { 5138 String pkgName = intent.getPackage(); 5139 if (pkgName == null) { 5140 return mServices.queryIntent(intent, resolvedType, flags, userId); 5141 } 5142 final PackageParser.Package pkg = mPackages.get(pkgName); 5143 if (pkg != null) { 5144 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5145 userId); 5146 } 5147 return null; 5148 } 5149 } 5150 5151 @Override 5152 public List<ResolveInfo> queryIntentContentProviders( 5153 Intent intent, String resolvedType, int flags, int userId) { 5154 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5155 ComponentName comp = intent.getComponent(); 5156 if (comp == null) { 5157 if (intent.getSelector() != null) { 5158 intent = intent.getSelector(); 5159 comp = intent.getComponent(); 5160 } 5161 } 5162 if (comp != null) { 5163 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5164 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5165 if (pi != null) { 5166 final ResolveInfo ri = new ResolveInfo(); 5167 ri.providerInfo = pi; 5168 list.add(ri); 5169 } 5170 return list; 5171 } 5172 5173 // reader 5174 synchronized (mPackages) { 5175 String pkgName = intent.getPackage(); 5176 if (pkgName == null) { 5177 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5178 } 5179 final PackageParser.Package pkg = mPackages.get(pkgName); 5180 if (pkg != null) { 5181 return mProviders.queryIntentForPackage( 5182 intent, resolvedType, flags, pkg.providers, userId); 5183 } 5184 return null; 5185 } 5186 } 5187 5188 @Override 5189 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5190 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5191 5192 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 5193 5194 // writer 5195 synchronized (mPackages) { 5196 ArrayList<PackageInfo> list; 5197 if (listUninstalled) { 5198 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5199 for (PackageSetting ps : mSettings.mPackages.values()) { 5200 PackageInfo pi; 5201 if (ps.pkg != null) { 5202 pi = generatePackageInfo(ps.pkg, flags, userId); 5203 } else { 5204 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5205 } 5206 if (pi != null) { 5207 list.add(pi); 5208 } 5209 } 5210 } else { 5211 list = new ArrayList<PackageInfo>(mPackages.size()); 5212 for (PackageParser.Package p : mPackages.values()) { 5213 PackageInfo pi = generatePackageInfo(p, flags, userId); 5214 if (pi != null) { 5215 list.add(pi); 5216 } 5217 } 5218 } 5219 5220 return new ParceledListSlice<PackageInfo>(list); 5221 } 5222 } 5223 5224 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5225 String[] permissions, boolean[] tmp, int flags, int userId) { 5226 int numMatch = 0; 5227 final PermissionsState permissionsState = ps.getPermissionsState(); 5228 for (int i=0; i<permissions.length; i++) { 5229 final String permission = permissions[i]; 5230 if (permissionsState.hasPermission(permission, userId)) { 5231 tmp[i] = true; 5232 numMatch++; 5233 } else { 5234 tmp[i] = false; 5235 } 5236 } 5237 if (numMatch == 0) { 5238 return; 5239 } 5240 PackageInfo pi; 5241 if (ps.pkg != null) { 5242 pi = generatePackageInfo(ps.pkg, flags, userId); 5243 } else { 5244 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5245 } 5246 // The above might return null in cases of uninstalled apps or install-state 5247 // skew across users/profiles. 5248 if (pi != null) { 5249 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5250 if (numMatch == permissions.length) { 5251 pi.requestedPermissions = permissions; 5252 } else { 5253 pi.requestedPermissions = new String[numMatch]; 5254 numMatch = 0; 5255 for (int i=0; i<permissions.length; i++) { 5256 if (tmp[i]) { 5257 pi.requestedPermissions[numMatch] = permissions[i]; 5258 numMatch++; 5259 } 5260 } 5261 } 5262 } 5263 list.add(pi); 5264 } 5265 } 5266 5267 @Override 5268 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5269 String[] permissions, int flags, int userId) { 5270 if (!sUserManager.exists(userId)) return null; 5271 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5272 5273 // writer 5274 synchronized (mPackages) { 5275 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5276 boolean[] tmpBools = new boolean[permissions.length]; 5277 if (listUninstalled) { 5278 for (PackageSetting ps : mSettings.mPackages.values()) { 5279 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5280 } 5281 } else { 5282 for (PackageParser.Package pkg : mPackages.values()) { 5283 PackageSetting ps = (PackageSetting)pkg.mExtras; 5284 if (ps != null) { 5285 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5286 userId); 5287 } 5288 } 5289 } 5290 5291 return new ParceledListSlice<PackageInfo>(list); 5292 } 5293 } 5294 5295 @Override 5296 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5297 if (!sUserManager.exists(userId)) return null; 5298 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5299 5300 // writer 5301 synchronized (mPackages) { 5302 ArrayList<ApplicationInfo> list; 5303 if (listUninstalled) { 5304 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5305 for (PackageSetting ps : mSettings.mPackages.values()) { 5306 ApplicationInfo ai; 5307 if (ps.pkg != null) { 5308 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5309 ps.readUserState(userId), userId); 5310 } else { 5311 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5312 } 5313 if (ai != null) { 5314 list.add(ai); 5315 } 5316 } 5317 } else { 5318 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5319 for (PackageParser.Package p : mPackages.values()) { 5320 if (p.mExtras != null) { 5321 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5322 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5323 if (ai != null) { 5324 list.add(ai); 5325 } 5326 } 5327 } 5328 } 5329 5330 return new ParceledListSlice<ApplicationInfo>(list); 5331 } 5332 } 5333 5334 public List<ApplicationInfo> getPersistentApplications(int flags) { 5335 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 5336 5337 // reader 5338 synchronized (mPackages) { 5339 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 5340 final int userId = UserHandle.getCallingUserId(); 5341 while (i.hasNext()) { 5342 final PackageParser.Package p = i.next(); 5343 if (p.applicationInfo != null 5344 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 5345 && (!mSafeMode || isSystemApp(p))) { 5346 PackageSetting ps = mSettings.mPackages.get(p.packageName); 5347 if (ps != null) { 5348 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5349 ps.readUserState(userId), userId); 5350 if (ai != null) { 5351 finalList.add(ai); 5352 } 5353 } 5354 } 5355 } 5356 } 5357 5358 return finalList; 5359 } 5360 5361 @Override 5362 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 5363 if (!sUserManager.exists(userId)) return null; 5364 // reader 5365 synchronized (mPackages) { 5366 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 5367 PackageSetting ps = provider != null 5368 ? mSettings.mPackages.get(provider.owner.packageName) 5369 : null; 5370 return ps != null 5371 && mSettings.isEnabledLPr(provider.info, flags, userId) 5372 && (!mSafeMode || (provider.info.applicationInfo.flags 5373 &ApplicationInfo.FLAG_SYSTEM) != 0) 5374 ? PackageParser.generateProviderInfo(provider, flags, 5375 ps.readUserState(userId), userId) 5376 : null; 5377 } 5378 } 5379 5380 /** 5381 * @deprecated 5382 */ 5383 @Deprecated 5384 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 5385 // reader 5386 synchronized (mPackages) { 5387 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 5388 .entrySet().iterator(); 5389 final int userId = UserHandle.getCallingUserId(); 5390 while (i.hasNext()) { 5391 Map.Entry<String, PackageParser.Provider> entry = i.next(); 5392 PackageParser.Provider p = entry.getValue(); 5393 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5394 5395 if (ps != null && p.syncable 5396 && (!mSafeMode || (p.info.applicationInfo.flags 5397 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 5398 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 5399 ps.readUserState(userId), userId); 5400 if (info != null) { 5401 outNames.add(entry.getKey()); 5402 outInfo.add(info); 5403 } 5404 } 5405 } 5406 } 5407 } 5408 5409 @Override 5410 public List<ProviderInfo> queryContentProviders(String processName, 5411 int uid, int flags) { 5412 ArrayList<ProviderInfo> finalList = null; 5413 // reader 5414 synchronized (mPackages) { 5415 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 5416 final int userId = processName != null ? 5417 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 5418 while (i.hasNext()) { 5419 final PackageParser.Provider p = i.next(); 5420 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5421 if (ps != null && p.info.authority != null 5422 && (processName == null 5423 || (p.info.processName.equals(processName) 5424 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 5425 && mSettings.isEnabledLPr(p.info, flags, userId) 5426 && (!mSafeMode 5427 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 5428 if (finalList == null) { 5429 finalList = new ArrayList<ProviderInfo>(3); 5430 } 5431 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 5432 ps.readUserState(userId), userId); 5433 if (info != null) { 5434 finalList.add(info); 5435 } 5436 } 5437 } 5438 } 5439 5440 if (finalList != null) { 5441 Collections.sort(finalList, mProviderInitOrderSorter); 5442 } 5443 5444 return finalList; 5445 } 5446 5447 @Override 5448 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 5449 int flags) { 5450 // reader 5451 synchronized (mPackages) { 5452 final PackageParser.Instrumentation i = mInstrumentation.get(name); 5453 return PackageParser.generateInstrumentationInfo(i, flags); 5454 } 5455 } 5456 5457 @Override 5458 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 5459 int flags) { 5460 ArrayList<InstrumentationInfo> finalList = 5461 new ArrayList<InstrumentationInfo>(); 5462 5463 // reader 5464 synchronized (mPackages) { 5465 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 5466 while (i.hasNext()) { 5467 final PackageParser.Instrumentation p = i.next(); 5468 if (targetPackage == null 5469 || targetPackage.equals(p.info.targetPackage)) { 5470 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 5471 flags); 5472 if (ii != null) { 5473 finalList.add(ii); 5474 } 5475 } 5476 } 5477 } 5478 5479 return finalList; 5480 } 5481 5482 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 5483 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 5484 if (overlays == null) { 5485 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 5486 return; 5487 } 5488 for (PackageParser.Package opkg : overlays.values()) { 5489 // Not much to do if idmap fails: we already logged the error 5490 // and we certainly don't want to abort installation of pkg simply 5491 // because an overlay didn't fit properly. For these reasons, 5492 // ignore the return value of createIdmapForPackagePairLI. 5493 createIdmapForPackagePairLI(pkg, opkg); 5494 } 5495 } 5496 5497 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 5498 PackageParser.Package opkg) { 5499 if (!opkg.mTrustedOverlay) { 5500 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 5501 opkg.baseCodePath + ": overlay not trusted"); 5502 return false; 5503 } 5504 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 5505 if (overlaySet == null) { 5506 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 5507 opkg.baseCodePath + " but target package has no known overlays"); 5508 return false; 5509 } 5510 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 5511 // TODO: generate idmap for split APKs 5512 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 5513 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 5514 + opkg.baseCodePath); 5515 return false; 5516 } 5517 PackageParser.Package[] overlayArray = 5518 overlaySet.values().toArray(new PackageParser.Package[0]); 5519 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 5520 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 5521 return p1.mOverlayPriority - p2.mOverlayPriority; 5522 } 5523 }; 5524 Arrays.sort(overlayArray, cmp); 5525 5526 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 5527 int i = 0; 5528 for (PackageParser.Package p : overlayArray) { 5529 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 5530 } 5531 return true; 5532 } 5533 5534 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5535 final File[] files = dir.listFiles(); 5536 if (ArrayUtils.isEmpty(files)) { 5537 Log.d(TAG, "No files in app dir " + dir); 5538 return; 5539 } 5540 5541 if (DEBUG_PACKAGE_SCANNING) { 5542 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 5543 + " flags=0x" + Integer.toHexString(parseFlags)); 5544 } 5545 5546 for (File file : files) { 5547 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 5548 && !PackageInstallerService.isStageName(file.getName()); 5549 if (!isPackage) { 5550 // Ignore entries which are not packages 5551 continue; 5552 } 5553 try { 5554 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 5555 scanFlags, currentTime, null); 5556 } catch (PackageManagerException e) { 5557 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 5558 5559 // Delete invalid userdata apps 5560 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 5561 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 5562 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 5563 if (file.isDirectory()) { 5564 mInstaller.rmPackageDir(file.getAbsolutePath()); 5565 } else { 5566 file.delete(); 5567 } 5568 } 5569 } 5570 } 5571 } 5572 5573 private static File getSettingsProblemFile() { 5574 File dataDir = Environment.getDataDirectory(); 5575 File systemDir = new File(dataDir, "system"); 5576 File fname = new File(systemDir, "uiderrors.txt"); 5577 return fname; 5578 } 5579 5580 static void reportSettingsProblem(int priority, String msg) { 5581 logCriticalInfo(priority, msg); 5582 } 5583 5584 static void logCriticalInfo(int priority, String msg) { 5585 Slog.println(priority, TAG, msg); 5586 EventLogTags.writePmCriticalInfo(msg); 5587 try { 5588 File fname = getSettingsProblemFile(); 5589 FileOutputStream out = new FileOutputStream(fname, true); 5590 PrintWriter pw = new FastPrintWriter(out); 5591 SimpleDateFormat formatter = new SimpleDateFormat(); 5592 String dateString = formatter.format(new Date(System.currentTimeMillis())); 5593 pw.println(dateString + ": " + msg); 5594 pw.close(); 5595 FileUtils.setPermissions( 5596 fname.toString(), 5597 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 5598 -1, -1); 5599 } catch (java.io.IOException e) { 5600 } 5601 } 5602 5603 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 5604 PackageParser.Package pkg, File srcFile, int parseFlags) 5605 throws PackageManagerException { 5606 if (ps != null 5607 && ps.codePath.equals(srcFile) 5608 && ps.timeStamp == srcFile.lastModified() 5609 && !isCompatSignatureUpdateNeeded(pkg) 5610 && !isRecoverSignatureUpdateNeeded(pkg)) { 5611 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 5612 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5613 ArraySet<PublicKey> signingKs; 5614 synchronized (mPackages) { 5615 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 5616 } 5617 if (ps.signatures.mSignatures != null 5618 && ps.signatures.mSignatures.length != 0 5619 && signingKs != null) { 5620 // Optimization: reuse the existing cached certificates 5621 // if the package appears to be unchanged. 5622 pkg.mSignatures = ps.signatures.mSignatures; 5623 pkg.mSigningKeys = signingKs; 5624 return; 5625 } 5626 5627 Slog.w(TAG, "PackageSetting for " + ps.name 5628 + " is missing signatures. Collecting certs again to recover them."); 5629 } else { 5630 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 5631 } 5632 5633 try { 5634 pp.collectCertificates(pkg, parseFlags); 5635 pp.collectManifestDigest(pkg); 5636 } catch (PackageParserException e) { 5637 throw PackageManagerException.from(e); 5638 } 5639 } 5640 5641 /* 5642 * Scan a package and return the newly parsed package. 5643 * Returns null in case of errors and the error code is stored in mLastScanError 5644 */ 5645 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 5646 long currentTime, UserHandle user) throws PackageManagerException { 5647 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 5648 parseFlags |= mDefParseFlags; 5649 PackageParser pp = new PackageParser(); 5650 pp.setSeparateProcesses(mSeparateProcesses); 5651 pp.setOnlyCoreApps(mOnlyCore); 5652 pp.setDisplayMetrics(mMetrics); 5653 5654 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 5655 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 5656 } 5657 5658 final PackageParser.Package pkg; 5659 try { 5660 pkg = pp.parsePackage(scanFile, parseFlags); 5661 } catch (PackageParserException e) { 5662 throw PackageManagerException.from(e); 5663 } 5664 5665 PackageSetting ps = null; 5666 PackageSetting updatedPkg; 5667 // reader 5668 synchronized (mPackages) { 5669 // Look to see if we already know about this package. 5670 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 5671 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 5672 // This package has been renamed to its original name. Let's 5673 // use that. 5674 ps = mSettings.peekPackageLPr(oldName); 5675 } 5676 // If there was no original package, see one for the real package name. 5677 if (ps == null) { 5678 ps = mSettings.peekPackageLPr(pkg.packageName); 5679 } 5680 // Check to see if this package could be hiding/updating a system 5681 // package. Must look for it either under the original or real 5682 // package name depending on our state. 5683 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 5684 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 5685 } 5686 boolean updatedPkgBetter = false; 5687 // First check if this is a system package that may involve an update 5688 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5689 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5690 // it needs to drop FLAG_PRIVILEGED. 5691 if (locationIsPrivileged(scanFile)) { 5692 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5693 } else { 5694 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5695 } 5696 5697 if (ps != null && !ps.codePath.equals(scanFile)) { 5698 // The path has changed from what was last scanned... check the 5699 // version of the new path against what we have stored to determine 5700 // what to do. 5701 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5702 if (pkg.mVersionCode <= ps.versionCode) { 5703 // The system package has been updated and the code path does not match 5704 // Ignore entry. Skip it. 5705 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5706 + " ignored: updated version " + ps.versionCode 5707 + " better than this " + pkg.mVersionCode); 5708 if (!updatedPkg.codePath.equals(scanFile)) { 5709 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5710 + ps.name + " changing from " + updatedPkg.codePathString 5711 + " to " + scanFile); 5712 updatedPkg.codePath = scanFile; 5713 updatedPkg.codePathString = scanFile.toString(); 5714 updatedPkg.resourcePath = scanFile; 5715 updatedPkg.resourcePathString = scanFile.toString(); 5716 } 5717 updatedPkg.pkg = pkg; 5718 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5719 "Package " + ps.name + " at " + scanFile 5720 + " ignored: updated version " + ps.versionCode 5721 + " better than this " + pkg.mVersionCode); 5722 } else { 5723 // The current app on the system partition is better than 5724 // what we have updated to on the data partition; switch 5725 // back to the system partition version. 5726 // At this point, its safely assumed that package installation for 5727 // apps in system partition will go through. If not there won't be a working 5728 // version of the app 5729 // writer 5730 synchronized (mPackages) { 5731 // Just remove the loaded entries from package lists. 5732 mPackages.remove(ps.name); 5733 } 5734 5735 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5736 + " reverting from " + ps.codePathString 5737 + ": new version " + pkg.mVersionCode 5738 + " better than installed " + ps.versionCode); 5739 5740 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5741 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5742 synchronized (mInstallLock) { 5743 args.cleanUpResourcesLI(); 5744 } 5745 synchronized (mPackages) { 5746 mSettings.enableSystemPackageLPw(ps.name); 5747 } 5748 updatedPkgBetter = true; 5749 } 5750 } 5751 } 5752 5753 if (updatedPkg != null) { 5754 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5755 // initially 5756 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5757 5758 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5759 // flag set initially 5760 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5761 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5762 } 5763 } 5764 5765 // Verify certificates against what was last scanned 5766 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5767 5768 /* 5769 * A new system app appeared, but we already had a non-system one of the 5770 * same name installed earlier. 5771 */ 5772 boolean shouldHideSystemApp = false; 5773 if (updatedPkg == null && ps != null 5774 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5775 /* 5776 * Check to make sure the signatures match first. If they don't, 5777 * wipe the installed application and its data. 5778 */ 5779 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5780 != PackageManager.SIGNATURE_MATCH) { 5781 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5782 + " signatures don't match existing userdata copy; removing"); 5783 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5784 ps = null; 5785 } else { 5786 /* 5787 * If the newly-added system app is an older version than the 5788 * already installed version, hide it. It will be scanned later 5789 * and re-added like an update. 5790 */ 5791 if (pkg.mVersionCode <= ps.versionCode) { 5792 shouldHideSystemApp = true; 5793 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5794 + " but new version " + pkg.mVersionCode + " better than installed " 5795 + ps.versionCode + "; hiding system"); 5796 } else { 5797 /* 5798 * The newly found system app is a newer version that the 5799 * one previously installed. Simply remove the 5800 * already-installed application and replace it with our own 5801 * while keeping the application data. 5802 */ 5803 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5804 + " reverting from " + ps.codePathString + ": new version " 5805 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5806 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5807 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5808 synchronized (mInstallLock) { 5809 args.cleanUpResourcesLI(); 5810 } 5811 } 5812 } 5813 } 5814 5815 // The apk is forward locked (not public) if its code and resources 5816 // are kept in different files. (except for app in either system or 5817 // vendor path). 5818 // TODO grab this value from PackageSettings 5819 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5820 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5821 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5822 } 5823 } 5824 5825 // TODO: extend to support forward-locked splits 5826 String resourcePath = null; 5827 String baseResourcePath = null; 5828 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5829 if (ps != null && ps.resourcePathString != null) { 5830 resourcePath = ps.resourcePathString; 5831 baseResourcePath = ps.resourcePathString; 5832 } else { 5833 // Should not happen at all. Just log an error. 5834 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5835 } 5836 } else { 5837 resourcePath = pkg.codePath; 5838 baseResourcePath = pkg.baseCodePath; 5839 } 5840 5841 // Set application objects path explicitly. 5842 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5843 pkg.applicationInfo.setCodePath(pkg.codePath); 5844 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5845 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5846 pkg.applicationInfo.setResourcePath(resourcePath); 5847 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5848 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5849 5850 // Note that we invoke the following method only if we are about to unpack an application 5851 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5852 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5853 5854 /* 5855 * If the system app should be overridden by a previously installed 5856 * data, hide the system app now and let the /data/app scan pick it up 5857 * again. 5858 */ 5859 if (shouldHideSystemApp) { 5860 synchronized (mPackages) { 5861 /* 5862 * We have to grant systems permissions before we hide, because 5863 * grantPermissions will assume the package update is trying to 5864 * expand its permissions. 5865 */ 5866 grantPermissionsLPw(pkg, true, pkg.packageName); 5867 mSettings.disableSystemPackageLPw(pkg.packageName); 5868 } 5869 } 5870 5871 return scannedPkg; 5872 } 5873 5874 private static String fixProcessName(String defProcessName, 5875 String processName, int uid) { 5876 if (processName == null) { 5877 return defProcessName; 5878 } 5879 return processName; 5880 } 5881 5882 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 5883 throws PackageManagerException { 5884 if (pkgSetting.signatures.mSignatures != null) { 5885 // Already existing package. Make sure signatures match 5886 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 5887 == PackageManager.SIGNATURE_MATCH; 5888 if (!match) { 5889 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 5890 == PackageManager.SIGNATURE_MATCH; 5891 } 5892 if (!match) { 5893 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 5894 == PackageManager.SIGNATURE_MATCH; 5895 } 5896 if (!match) { 5897 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5898 + pkg.packageName + " signatures do not match the " 5899 + "previously installed version; ignoring!"); 5900 } 5901 } 5902 5903 // Check for shared user signatures 5904 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 5905 // Already existing package. Make sure signatures match 5906 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5907 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 5908 if (!match) { 5909 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 5910 == PackageManager.SIGNATURE_MATCH; 5911 } 5912 if (!match) { 5913 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 5914 == PackageManager.SIGNATURE_MATCH; 5915 } 5916 if (!match) { 5917 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 5918 "Package " + pkg.packageName 5919 + " has no signatures that match those in shared user " 5920 + pkgSetting.sharedUser.name + "; ignoring!"); 5921 } 5922 } 5923 } 5924 5925 /** 5926 * Enforces that only the system UID or root's UID can call a method exposed 5927 * via Binder. 5928 * 5929 * @param message used as message if SecurityException is thrown 5930 * @throws SecurityException if the caller is not system or root 5931 */ 5932 private static final void enforceSystemOrRoot(String message) { 5933 final int uid = Binder.getCallingUid(); 5934 if (uid != Process.SYSTEM_UID && uid != 0) { 5935 throw new SecurityException(message); 5936 } 5937 } 5938 5939 @Override 5940 public void performBootDexOpt() { 5941 enforceSystemOrRoot("Only the system can request dexopt be performed"); 5942 5943 // Before everything else, see whether we need to fstrim. 5944 try { 5945 IMountService ms = PackageHelper.getMountService(); 5946 if (ms != null) { 5947 final boolean isUpgrade = isUpgrade(); 5948 boolean doTrim = isUpgrade; 5949 if (doTrim) { 5950 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 5951 } else { 5952 final long interval = android.provider.Settings.Global.getLong( 5953 mContext.getContentResolver(), 5954 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 5955 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 5956 if (interval > 0) { 5957 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 5958 if (timeSinceLast > interval) { 5959 doTrim = true; 5960 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 5961 + "; running immediately"); 5962 } 5963 } 5964 } 5965 if (doTrim) { 5966 if (!isFirstBoot()) { 5967 try { 5968 ActivityManagerNative.getDefault().showBootMessage( 5969 mContext.getResources().getString( 5970 R.string.android_upgrading_fstrim), true); 5971 } catch (RemoteException e) { 5972 } 5973 } 5974 ms.runMaintenance(); 5975 } 5976 } else { 5977 Slog.e(TAG, "Mount service unavailable!"); 5978 } 5979 } catch (RemoteException e) { 5980 // Can't happen; MountService is local 5981 } 5982 5983 final ArraySet<PackageParser.Package> pkgs; 5984 synchronized (mPackages) { 5985 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 5986 } 5987 5988 if (pkgs != null) { 5989 // Sort apps by importance for dexopt ordering. Important apps are given more priority 5990 // in case the device runs out of space. 5991 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 5992 // Give priority to core apps. 5993 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5994 PackageParser.Package pkg = it.next(); 5995 if (pkg.coreApp) { 5996 if (DEBUG_DEXOPT) { 5997 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 5998 } 5999 sortedPkgs.add(pkg); 6000 it.remove(); 6001 } 6002 } 6003 // Give priority to system apps that listen for pre boot complete. 6004 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 6005 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 6006 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6007 PackageParser.Package pkg = it.next(); 6008 if (pkgNames.contains(pkg.packageName)) { 6009 if (DEBUG_DEXOPT) { 6010 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 6011 } 6012 sortedPkgs.add(pkg); 6013 it.remove(); 6014 } 6015 } 6016 // Give priority to system apps. 6017 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6018 PackageParser.Package pkg = it.next(); 6019 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 6020 if (DEBUG_DEXOPT) { 6021 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 6022 } 6023 sortedPkgs.add(pkg); 6024 it.remove(); 6025 } 6026 } 6027 // Give priority to updated system apps. 6028 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6029 PackageParser.Package pkg = it.next(); 6030 if (pkg.isUpdatedSystemApp()) { 6031 if (DEBUG_DEXOPT) { 6032 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 6033 } 6034 sortedPkgs.add(pkg); 6035 it.remove(); 6036 } 6037 } 6038 // Give priority to apps that listen for boot complete. 6039 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 6040 pkgNames = getPackageNamesForIntent(intent); 6041 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6042 PackageParser.Package pkg = it.next(); 6043 if (pkgNames.contains(pkg.packageName)) { 6044 if (DEBUG_DEXOPT) { 6045 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 6046 } 6047 sortedPkgs.add(pkg); 6048 it.remove(); 6049 } 6050 } 6051 // Filter out packages that aren't recently used. 6052 filterRecentlyUsedApps(pkgs); 6053 // Add all remaining apps. 6054 for (PackageParser.Package pkg : pkgs) { 6055 if (DEBUG_DEXOPT) { 6056 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 6057 } 6058 sortedPkgs.add(pkg); 6059 } 6060 6061 // If we want to be lazy, filter everything that wasn't recently used. 6062 if (mLazyDexOpt) { 6063 filterRecentlyUsedApps(sortedPkgs); 6064 } 6065 6066 int i = 0; 6067 int total = sortedPkgs.size(); 6068 File dataDir = Environment.getDataDirectory(); 6069 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 6070 if (lowThreshold == 0) { 6071 throw new IllegalStateException("Invalid low memory threshold"); 6072 } 6073 for (PackageParser.Package pkg : sortedPkgs) { 6074 long usableSpace = dataDir.getUsableSpace(); 6075 if (usableSpace < lowThreshold) { 6076 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 6077 break; 6078 } 6079 performBootDexOpt(pkg, ++i, total); 6080 } 6081 } 6082 } 6083 6084 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 6085 // Filter out packages that aren't recently used. 6086 // 6087 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 6088 // should do a full dexopt. 6089 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 6090 int total = pkgs.size(); 6091 int skipped = 0; 6092 long now = System.currentTimeMillis(); 6093 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 6094 PackageParser.Package pkg = i.next(); 6095 long then = pkg.mLastPackageUsageTimeInMills; 6096 if (then + mDexOptLRUThresholdInMills < now) { 6097 if (DEBUG_DEXOPT) { 6098 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 6099 ((then == 0) ? "never" : new Date(then))); 6100 } 6101 i.remove(); 6102 skipped++; 6103 } 6104 } 6105 if (DEBUG_DEXOPT) { 6106 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 6107 } 6108 } 6109 } 6110 6111 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 6112 List<ResolveInfo> ris = null; 6113 try { 6114 ris = AppGlobals.getPackageManager().queryIntentReceivers( 6115 intent, null, 0, UserHandle.USER_OWNER); 6116 } catch (RemoteException e) { 6117 } 6118 ArraySet<String> pkgNames = new ArraySet<String>(); 6119 if (ris != null) { 6120 for (ResolveInfo ri : ris) { 6121 pkgNames.add(ri.activityInfo.packageName); 6122 } 6123 } 6124 return pkgNames; 6125 } 6126 6127 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 6128 if (DEBUG_DEXOPT) { 6129 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 6130 } 6131 if (!isFirstBoot()) { 6132 try { 6133 ActivityManagerNative.getDefault().showBootMessage( 6134 mContext.getResources().getString(R.string.android_upgrading_apk, 6135 curr, total), true); 6136 } catch (RemoteException e) { 6137 } 6138 } 6139 PackageParser.Package p = pkg; 6140 synchronized (mInstallLock) { 6141 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 6142 false /* force dex */, false /* defer */, true /* include dependencies */); 6143 } 6144 } 6145 6146 @Override 6147 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6148 return performDexOpt(packageName, instructionSet, false); 6149 } 6150 6151 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 6152 boolean dexopt = mLazyDexOpt || backgroundDexopt; 6153 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 6154 if (!dexopt && !updateUsage) { 6155 // We aren't going to dexopt or update usage, so bail early. 6156 return false; 6157 } 6158 PackageParser.Package p; 6159 final String targetInstructionSet; 6160 synchronized (mPackages) { 6161 p = mPackages.get(packageName); 6162 if (p == null) { 6163 return false; 6164 } 6165 if (updateUsage) { 6166 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6167 } 6168 mPackageUsage.write(false); 6169 if (!dexopt) { 6170 // We aren't going to dexopt, so bail early. 6171 return false; 6172 } 6173 6174 targetInstructionSet = instructionSet != null ? instructionSet : 6175 getPrimaryInstructionSet(p.applicationInfo); 6176 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 6177 return false; 6178 } 6179 } 6180 long callingId = Binder.clearCallingIdentity(); 6181 try { 6182 synchronized (mInstallLock) { 6183 final String[] instructionSets = new String[] { targetInstructionSet }; 6184 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 6185 false /* forceDex */, false /* defer */, true /* inclDependencies */); 6186 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6187 } 6188 } finally { 6189 Binder.restoreCallingIdentity(callingId); 6190 } 6191 } 6192 6193 public ArraySet<String> getPackagesThatNeedDexOpt() { 6194 ArraySet<String> pkgs = null; 6195 synchronized (mPackages) { 6196 for (PackageParser.Package p : mPackages.values()) { 6197 if (DEBUG_DEXOPT) { 6198 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 6199 } 6200 if (!p.mDexOptPerformed.isEmpty()) { 6201 continue; 6202 } 6203 if (pkgs == null) { 6204 pkgs = new ArraySet<String>(); 6205 } 6206 pkgs.add(p.packageName); 6207 } 6208 } 6209 return pkgs; 6210 } 6211 6212 public void shutdown() { 6213 mPackageUsage.write(true); 6214 } 6215 6216 @Override 6217 public void forceDexOpt(String packageName) { 6218 enforceSystemOrRoot("forceDexOpt"); 6219 6220 PackageParser.Package pkg; 6221 synchronized (mPackages) { 6222 pkg = mPackages.get(packageName); 6223 if (pkg == null) { 6224 throw new IllegalArgumentException("Missing package: " + packageName); 6225 } 6226 } 6227 6228 synchronized (mInstallLock) { 6229 final String[] instructionSets = new String[] { 6230 getPrimaryInstructionSet(pkg.applicationInfo) }; 6231 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 6232 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 6233 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 6234 throw new IllegalStateException("Failed to dexopt: " + res); 6235 } 6236 } 6237 } 6238 6239 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 6240 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 6241 Slog.w(TAG, "Unable to update from " + oldPkg.name 6242 + " to " + newPkg.packageName 6243 + ": old package not in system partition"); 6244 return false; 6245 } else if (mPackages.get(oldPkg.name) != null) { 6246 Slog.w(TAG, "Unable to update from " + oldPkg.name 6247 + " to " + newPkg.packageName 6248 + ": old package still exists"); 6249 return false; 6250 } 6251 return true; 6252 } 6253 6254 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 6255 int[] users = sUserManager.getUserIds(); 6256 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 6257 if (res < 0) { 6258 return res; 6259 } 6260 for (int user : users) { 6261 if (user != 0) { 6262 res = mInstaller.createUserData(volumeUuid, packageName, 6263 UserHandle.getUid(user, uid), user, seinfo); 6264 if (res < 0) { 6265 return res; 6266 } 6267 } 6268 } 6269 return res; 6270 } 6271 6272 private int removeDataDirsLI(String volumeUuid, String packageName) { 6273 int[] users = sUserManager.getUserIds(); 6274 int res = 0; 6275 for (int user : users) { 6276 int resInner = mInstaller.remove(volumeUuid, packageName, user); 6277 if (resInner < 0) { 6278 res = resInner; 6279 } 6280 } 6281 6282 return res; 6283 } 6284 6285 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 6286 int[] users = sUserManager.getUserIds(); 6287 int res = 0; 6288 for (int user : users) { 6289 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 6290 if (resInner < 0) { 6291 res = resInner; 6292 } 6293 } 6294 return res; 6295 } 6296 6297 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 6298 PackageParser.Package changingLib) { 6299 if (file.path != null) { 6300 usesLibraryFiles.add(file.path); 6301 return; 6302 } 6303 PackageParser.Package p = mPackages.get(file.apk); 6304 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 6305 // If we are doing this while in the middle of updating a library apk, 6306 // then we need to make sure to use that new apk for determining the 6307 // dependencies here. (We haven't yet finished committing the new apk 6308 // to the package manager state.) 6309 if (p == null || p.packageName.equals(changingLib.packageName)) { 6310 p = changingLib; 6311 } 6312 } 6313 if (p != null) { 6314 usesLibraryFiles.addAll(p.getAllCodePaths()); 6315 } 6316 } 6317 6318 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 6319 PackageParser.Package changingLib) throws PackageManagerException { 6320 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 6321 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 6322 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 6323 for (int i=0; i<N; i++) { 6324 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 6325 if (file == null) { 6326 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 6327 "Package " + pkg.packageName + " requires unavailable shared library " 6328 + pkg.usesLibraries.get(i) + "; failing!"); 6329 } 6330 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6331 } 6332 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 6333 for (int i=0; i<N; i++) { 6334 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 6335 if (file == null) { 6336 Slog.w(TAG, "Package " + pkg.packageName 6337 + " desires unavailable shared library " 6338 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 6339 } else { 6340 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6341 } 6342 } 6343 N = usesLibraryFiles.size(); 6344 if (N > 0) { 6345 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 6346 } else { 6347 pkg.usesLibraryFiles = null; 6348 } 6349 } 6350 } 6351 6352 private static boolean hasString(List<String> list, List<String> which) { 6353 if (list == null) { 6354 return false; 6355 } 6356 for (int i=list.size()-1; i>=0; i--) { 6357 for (int j=which.size()-1; j>=0; j--) { 6358 if (which.get(j).equals(list.get(i))) { 6359 return true; 6360 } 6361 } 6362 } 6363 return false; 6364 } 6365 6366 private void updateAllSharedLibrariesLPw() { 6367 for (PackageParser.Package pkg : mPackages.values()) { 6368 try { 6369 updateSharedLibrariesLPw(pkg, null); 6370 } catch (PackageManagerException e) { 6371 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6372 } 6373 } 6374 } 6375 6376 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 6377 PackageParser.Package changingPkg) { 6378 ArrayList<PackageParser.Package> res = null; 6379 for (PackageParser.Package pkg : mPackages.values()) { 6380 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 6381 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 6382 if (res == null) { 6383 res = new ArrayList<PackageParser.Package>(); 6384 } 6385 res.add(pkg); 6386 try { 6387 updateSharedLibrariesLPw(pkg, changingPkg); 6388 } catch (PackageManagerException e) { 6389 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6390 } 6391 } 6392 } 6393 return res; 6394 } 6395 6396 /** 6397 * Derive the value of the {@code cpuAbiOverride} based on the provided 6398 * value and an optional stored value from the package settings. 6399 */ 6400 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 6401 String cpuAbiOverride = null; 6402 6403 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 6404 cpuAbiOverride = null; 6405 } else if (abiOverride != null) { 6406 cpuAbiOverride = abiOverride; 6407 } else if (settings != null) { 6408 cpuAbiOverride = settings.cpuAbiOverrideString; 6409 } 6410 6411 return cpuAbiOverride; 6412 } 6413 6414 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 6415 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6416 boolean success = false; 6417 try { 6418 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 6419 currentTime, user); 6420 success = true; 6421 return res; 6422 } finally { 6423 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 6424 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 6425 } 6426 } 6427 } 6428 6429 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 6430 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6431 final File scanFile = new File(pkg.codePath); 6432 if (pkg.applicationInfo.getCodePath() == null || 6433 pkg.applicationInfo.getResourcePath() == null) { 6434 // Bail out. The resource and code paths haven't been set. 6435 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 6436 "Code and resource paths haven't been set correctly"); 6437 } 6438 6439 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 6440 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 6441 } else { 6442 // Only allow system apps to be flagged as core apps. 6443 pkg.coreApp = false; 6444 } 6445 6446 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 6447 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6448 } 6449 6450 if (mCustomResolverComponentName != null && 6451 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 6452 setUpCustomResolverActivity(pkg); 6453 } 6454 6455 if (pkg.packageName.equals("android")) { 6456 synchronized (mPackages) { 6457 if (mAndroidApplication != null) { 6458 Slog.w(TAG, "*************************************************"); 6459 Slog.w(TAG, "Core android package being redefined. Skipping."); 6460 Slog.w(TAG, " file=" + scanFile); 6461 Slog.w(TAG, "*************************************************"); 6462 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6463 "Core android package being redefined. Skipping."); 6464 } 6465 6466 // Set up information for our fall-back user intent resolution activity. 6467 mPlatformPackage = pkg; 6468 pkg.mVersionCode = mSdkVersion; 6469 mAndroidApplication = pkg.applicationInfo; 6470 6471 if (!mResolverReplaced) { 6472 mResolveActivity.applicationInfo = mAndroidApplication; 6473 mResolveActivity.name = ResolverActivity.class.getName(); 6474 mResolveActivity.packageName = mAndroidApplication.packageName; 6475 mResolveActivity.processName = "system:ui"; 6476 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6477 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 6478 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 6479 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 6480 mResolveActivity.exported = true; 6481 mResolveActivity.enabled = true; 6482 mResolveInfo.activityInfo = mResolveActivity; 6483 mResolveInfo.priority = 0; 6484 mResolveInfo.preferredOrder = 0; 6485 mResolveInfo.match = 0; 6486 mResolveComponentName = new ComponentName( 6487 mAndroidApplication.packageName, mResolveActivity.name); 6488 } 6489 } 6490 } 6491 6492 if (DEBUG_PACKAGE_SCANNING) { 6493 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6494 Log.d(TAG, "Scanning package " + pkg.packageName); 6495 } 6496 6497 if (mPackages.containsKey(pkg.packageName) 6498 || mSharedLibraries.containsKey(pkg.packageName)) { 6499 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6500 "Application package " + pkg.packageName 6501 + " already installed. Skipping duplicate."); 6502 } 6503 6504 // If we're only installing presumed-existing packages, require that the 6505 // scanned APK is both already known and at the path previously established 6506 // for it. Previously unknown packages we pick up normally, but if we have an 6507 // a priori expectation about this package's install presence, enforce it. 6508 // With a singular exception for new system packages. When an OTA contains 6509 // a new system package, we allow the codepath to change from a system location 6510 // to the user-installed location. If we don't allow this change, any newer, 6511 // user-installed version of the application will be ignored. 6512 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 6513 if (mExpectingBetter.containsKey(pkg.packageName)) { 6514 logCriticalInfo(Log.WARN, 6515 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 6516 } else { 6517 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 6518 if (known != null) { 6519 if (DEBUG_PACKAGE_SCANNING) { 6520 Log.d(TAG, "Examining " + pkg.codePath 6521 + " and requiring known paths " + known.codePathString 6522 + " & " + known.resourcePathString); 6523 } 6524 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6525 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6526 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6527 "Application package " + pkg.packageName 6528 + " found at " + pkg.applicationInfo.getCodePath() 6529 + " but expected at " + known.codePathString + "; ignoring."); 6530 } 6531 } 6532 } 6533 } 6534 6535 // Initialize package source and resource directories 6536 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6537 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6538 6539 SharedUserSetting suid = null; 6540 PackageSetting pkgSetting = null; 6541 6542 if (!isSystemApp(pkg)) { 6543 // Only system apps can use these features. 6544 pkg.mOriginalPackages = null; 6545 pkg.mRealPackage = null; 6546 pkg.mAdoptPermissions = null; 6547 } 6548 6549 // writer 6550 synchronized (mPackages) { 6551 if (pkg.mSharedUserId != null) { 6552 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 6553 if (suid == null) { 6554 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6555 "Creating application package " + pkg.packageName 6556 + " for shared user failed"); 6557 } 6558 if (DEBUG_PACKAGE_SCANNING) { 6559 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6560 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 6561 + "): packages=" + suid.packages); 6562 } 6563 } 6564 6565 // Check if we are renaming from an original package name. 6566 PackageSetting origPackage = null; 6567 String realName = null; 6568 if (pkg.mOriginalPackages != null) { 6569 // This package may need to be renamed to a previously 6570 // installed name. Let's check on that... 6571 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 6572 if (pkg.mOriginalPackages.contains(renamed)) { 6573 // This package had originally been installed as the 6574 // original name, and we have already taken care of 6575 // transitioning to the new one. Just update the new 6576 // one to continue using the old name. 6577 realName = pkg.mRealPackage; 6578 if (!pkg.packageName.equals(renamed)) { 6579 // Callers into this function may have already taken 6580 // care of renaming the package; only do it here if 6581 // it is not already done. 6582 pkg.setPackageName(renamed); 6583 } 6584 6585 } else { 6586 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 6587 if ((origPackage = mSettings.peekPackageLPr( 6588 pkg.mOriginalPackages.get(i))) != null) { 6589 // We do have the package already installed under its 6590 // original name... should we use it? 6591 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 6592 // New package is not compatible with original. 6593 origPackage = null; 6594 continue; 6595 } else if (origPackage.sharedUser != null) { 6596 // Make sure uid is compatible between packages. 6597 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 6598 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 6599 + " to " + pkg.packageName + ": old uid " 6600 + origPackage.sharedUser.name 6601 + " differs from " + pkg.mSharedUserId); 6602 origPackage = null; 6603 continue; 6604 } 6605 } else { 6606 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6607 + pkg.packageName + " to old name " + origPackage.name); 6608 } 6609 break; 6610 } 6611 } 6612 } 6613 } 6614 6615 if (mTransferedPackages.contains(pkg.packageName)) { 6616 Slog.w(TAG, "Package " + pkg.packageName 6617 + " was transferred to another, but its .apk remains"); 6618 } 6619 6620 // Just create the setting, don't add it yet. For already existing packages 6621 // the PkgSetting exists already and doesn't have to be created. 6622 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6623 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6624 pkg.applicationInfo.primaryCpuAbi, 6625 pkg.applicationInfo.secondaryCpuAbi, 6626 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6627 user, false); 6628 if (pkgSetting == null) { 6629 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6630 "Creating application package " + pkg.packageName + " failed"); 6631 } 6632 6633 if (pkgSetting.origPackage != null) { 6634 // If we are first transitioning from an original package, 6635 // fix up the new package's name now. We need to do this after 6636 // looking up the package under its new name, so getPackageLP 6637 // can take care of fiddling things correctly. 6638 pkg.setPackageName(origPackage.name); 6639 6640 // File a report about this. 6641 String msg = "New package " + pkgSetting.realName 6642 + " renamed to replace old package " + pkgSetting.name; 6643 reportSettingsProblem(Log.WARN, msg); 6644 6645 // Make a note of it. 6646 mTransferedPackages.add(origPackage.name); 6647 6648 // No longer need to retain this. 6649 pkgSetting.origPackage = null; 6650 } 6651 6652 if (realName != null) { 6653 // Make a note of it. 6654 mTransferedPackages.add(pkg.packageName); 6655 } 6656 6657 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6658 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6659 } 6660 6661 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6662 // Check all shared libraries and map to their actual file path. 6663 // We only do this here for apps not on a system dir, because those 6664 // are the only ones that can fail an install due to this. We 6665 // will take care of the system apps by updating all of their 6666 // library paths after the scan is done. 6667 updateSharedLibrariesLPw(pkg, null); 6668 } 6669 6670 if (mFoundPolicyFile) { 6671 SELinuxMMAC.assignSeinfoValue(pkg); 6672 } 6673 6674 pkg.applicationInfo.uid = pkgSetting.appId; 6675 pkg.mExtras = pkgSetting; 6676 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 6677 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 6678 // We just determined the app is signed correctly, so bring 6679 // over the latest parsed certs. 6680 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6681 } else { 6682 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6683 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6684 "Package " + pkg.packageName + " upgrade keys do not match the " 6685 + "previously installed version"); 6686 } else { 6687 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6688 String msg = "System package " + pkg.packageName 6689 + " signature changed; retaining data."; 6690 reportSettingsProblem(Log.WARN, msg); 6691 } 6692 } 6693 } else { 6694 try { 6695 verifySignaturesLP(pkgSetting, pkg); 6696 // We just determined the app is signed correctly, so bring 6697 // over the latest parsed certs. 6698 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6699 } catch (PackageManagerException e) { 6700 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6701 throw e; 6702 } 6703 // The signature has changed, but this package is in the system 6704 // image... let's recover! 6705 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6706 // However... if this package is part of a shared user, but it 6707 // doesn't match the signature of the shared user, let's fail. 6708 // What this means is that you can't change the signatures 6709 // associated with an overall shared user, which doesn't seem all 6710 // that unreasonable. 6711 if (pkgSetting.sharedUser != null) { 6712 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6713 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 6714 throw new PackageManagerException( 6715 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6716 "Signature mismatch for shared user : " 6717 + pkgSetting.sharedUser); 6718 } 6719 } 6720 // File a report about this. 6721 String msg = "System package " + pkg.packageName 6722 + " signature changed; retaining data."; 6723 reportSettingsProblem(Log.WARN, msg); 6724 } 6725 } 6726 // Verify that this new package doesn't have any content providers 6727 // that conflict with existing packages. Only do this if the 6728 // package isn't already installed, since we don't want to break 6729 // things that are installed. 6730 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6731 final int N = pkg.providers.size(); 6732 int i; 6733 for (i=0; i<N; i++) { 6734 PackageParser.Provider p = pkg.providers.get(i); 6735 if (p.info.authority != null) { 6736 String names[] = p.info.authority.split(";"); 6737 for (int j = 0; j < names.length; j++) { 6738 if (mProvidersByAuthority.containsKey(names[j])) { 6739 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6740 final String otherPackageName = 6741 ((other != null && other.getComponentName() != null) ? 6742 other.getComponentName().getPackageName() : "?"); 6743 throw new PackageManagerException( 6744 INSTALL_FAILED_CONFLICTING_PROVIDER, 6745 "Can't install because provider name " + names[j] 6746 + " (in package " + pkg.applicationInfo.packageName 6747 + ") is already used by " + otherPackageName); 6748 } 6749 } 6750 } 6751 } 6752 } 6753 6754 if (pkg.mAdoptPermissions != null) { 6755 // This package wants to adopt ownership of permissions from 6756 // another package. 6757 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6758 final String origName = pkg.mAdoptPermissions.get(i); 6759 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6760 if (orig != null) { 6761 if (verifyPackageUpdateLPr(orig, pkg)) { 6762 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6763 + pkg.packageName); 6764 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6765 } 6766 } 6767 } 6768 } 6769 } 6770 6771 final String pkgName = pkg.packageName; 6772 6773 final long scanFileTime = scanFile.lastModified(); 6774 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6775 pkg.applicationInfo.processName = fixProcessName( 6776 pkg.applicationInfo.packageName, 6777 pkg.applicationInfo.processName, 6778 pkg.applicationInfo.uid); 6779 6780 File dataPath; 6781 if (mPlatformPackage == pkg) { 6782 // The system package is special. 6783 dataPath = new File(Environment.getDataDirectory(), "system"); 6784 6785 pkg.applicationInfo.dataDir = dataPath.getPath(); 6786 6787 } else { 6788 // This is a normal package, need to make its data directory. 6789 dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid, 6790 UserHandle.USER_OWNER, pkg.packageName); 6791 6792 boolean uidError = false; 6793 if (dataPath.exists()) { 6794 int currentUid = 0; 6795 try { 6796 StructStat stat = Os.stat(dataPath.getPath()); 6797 currentUid = stat.st_uid; 6798 } catch (ErrnoException e) { 6799 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6800 } 6801 6802 // If we have mismatched owners for the data path, we have a problem. 6803 if (currentUid != pkg.applicationInfo.uid) { 6804 boolean recovered = false; 6805 if (currentUid == 0) { 6806 // The directory somehow became owned by root. Wow. 6807 // This is probably because the system was stopped while 6808 // installd was in the middle of messing with its libs 6809 // directory. Ask installd to fix that. 6810 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6811 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6812 if (ret >= 0) { 6813 recovered = true; 6814 String msg = "Package " + pkg.packageName 6815 + " unexpectedly changed to uid 0; recovered to " + 6816 + pkg.applicationInfo.uid; 6817 reportSettingsProblem(Log.WARN, msg); 6818 } 6819 } 6820 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6821 || (scanFlags&SCAN_BOOTING) != 0)) { 6822 // If this is a system app, we can at least delete its 6823 // current data so the application will still work. 6824 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6825 if (ret >= 0) { 6826 // TODO: Kill the processes first 6827 // Old data gone! 6828 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6829 ? "System package " : "Third party package "; 6830 String msg = prefix + pkg.packageName 6831 + " has changed from uid: " 6832 + currentUid + " to " 6833 + pkg.applicationInfo.uid + "; old data erased"; 6834 reportSettingsProblem(Log.WARN, msg); 6835 recovered = true; 6836 6837 // And now re-install the app. 6838 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6839 pkg.applicationInfo.seinfo); 6840 if (ret == -1) { 6841 // Ack should not happen! 6842 msg = prefix + pkg.packageName 6843 + " could not have data directory re-created after delete."; 6844 reportSettingsProblem(Log.WARN, msg); 6845 throw new PackageManagerException( 6846 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6847 } 6848 } 6849 if (!recovered) { 6850 mHasSystemUidErrors = true; 6851 } 6852 } else if (!recovered) { 6853 // If we allow this install to proceed, we will be broken. 6854 // Abort, abort! 6855 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6856 "scanPackageLI"); 6857 } 6858 if (!recovered) { 6859 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6860 + pkg.applicationInfo.uid + "/fs_" 6861 + currentUid; 6862 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6863 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6864 String msg = "Package " + pkg.packageName 6865 + " has mismatched uid: " 6866 + currentUid + " on disk, " 6867 + pkg.applicationInfo.uid + " in settings"; 6868 // writer 6869 synchronized (mPackages) { 6870 mSettings.mReadMessages.append(msg); 6871 mSettings.mReadMessages.append('\n'); 6872 uidError = true; 6873 if (!pkgSetting.uidError) { 6874 reportSettingsProblem(Log.ERROR, msg); 6875 } 6876 } 6877 } 6878 } 6879 pkg.applicationInfo.dataDir = dataPath.getPath(); 6880 if (mShouldRestoreconData) { 6881 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6882 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 6883 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 6884 } 6885 } else { 6886 if (DEBUG_PACKAGE_SCANNING) { 6887 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6888 Log.v(TAG, "Want this data dir: " + dataPath); 6889 } 6890 //invoke installer to do the actual installation 6891 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6892 pkg.applicationInfo.seinfo); 6893 if (ret < 0) { 6894 // Error from installer 6895 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6896 "Unable to create data dirs [errorCode=" + ret + "]"); 6897 } 6898 6899 if (dataPath.exists()) { 6900 pkg.applicationInfo.dataDir = dataPath.getPath(); 6901 } else { 6902 Slog.w(TAG, "Unable to create data directory: " + dataPath); 6903 pkg.applicationInfo.dataDir = null; 6904 } 6905 } 6906 6907 pkgSetting.uidError = uidError; 6908 } 6909 6910 final String path = scanFile.getPath(); 6911 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6912 6913 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 6914 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 6915 6916 // Some system apps still use directory structure for native libraries 6917 // in which case we might end up not detecting abi solely based on apk 6918 // structure. Try to detect abi based on directory structure. 6919 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 6920 pkg.applicationInfo.primaryCpuAbi == null) { 6921 setBundledAppAbisAndRoots(pkg, pkgSetting); 6922 setNativeLibraryPaths(pkg); 6923 } 6924 6925 } else { 6926 if ((scanFlags & SCAN_MOVE) != 0) { 6927 // We haven't run dex-opt for this move (since we've moved the compiled output too) 6928 // but we already have this packages package info in the PackageSetting. We just 6929 // use that and derive the native library path based on the new codepath. 6930 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 6931 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 6932 } 6933 6934 // Set native library paths again. For moves, the path will be updated based on the 6935 // ABIs we've determined above. For non-moves, the path will be updated based on the 6936 // ABIs we determined during compilation, but the path will depend on the final 6937 // package path (after the rename away from the stage path). 6938 setNativeLibraryPaths(pkg); 6939 } 6940 6941 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 6942 final int[] userIds = sUserManager.getUserIds(); 6943 synchronized (mInstallLock) { 6944 // Make sure all user data directories are ready to roll; we're okay 6945 // if they already exist 6946 if (!TextUtils.isEmpty(pkg.volumeUuid)) { 6947 for (int userId : userIds) { 6948 if (userId != 0) { 6949 mInstaller.createUserData(pkg.volumeUuid, pkg.packageName, 6950 UserHandle.getUid(userId, pkg.applicationInfo.uid), userId, 6951 pkg.applicationInfo.seinfo); 6952 } 6953 } 6954 } 6955 6956 // Create a native library symlink only if we have native libraries 6957 // and if the native libraries are 32 bit libraries. We do not provide 6958 // this symlink for 64 bit libraries. 6959 if (pkg.applicationInfo.primaryCpuAbi != null && 6960 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 6961 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 6962 for (int userId : userIds) { 6963 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 6964 nativeLibPath, userId) < 0) { 6965 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6966 "Failed linking native library dir (user=" + userId + ")"); 6967 } 6968 } 6969 } 6970 } 6971 6972 // This is a special case for the "system" package, where the ABI is 6973 // dictated by the zygote configuration (and init.rc). We should keep track 6974 // of this ABI so that we can deal with "normal" applications that run under 6975 // the same UID correctly. 6976 if (mPlatformPackage == pkg) { 6977 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 6978 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 6979 } 6980 6981 // If there's a mismatch between the abi-override in the package setting 6982 // and the abiOverride specified for the install. Warn about this because we 6983 // would've already compiled the app without taking the package setting into 6984 // account. 6985 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 6986 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 6987 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 6988 " for package: " + pkg.packageName); 6989 } 6990 } 6991 6992 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6993 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6994 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 6995 6996 // Copy the derived override back to the parsed package, so that we can 6997 // update the package settings accordingly. 6998 pkg.cpuAbiOverride = cpuAbiOverride; 6999 7000 if (DEBUG_ABI_SELECTION) { 7001 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 7002 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 7003 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 7004 } 7005 7006 // Push the derived path down into PackageSettings so we know what to 7007 // clean up at uninstall time. 7008 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 7009 7010 if (DEBUG_ABI_SELECTION) { 7011 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 7012 " primary=" + pkg.applicationInfo.primaryCpuAbi + 7013 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 7014 } 7015 7016 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 7017 // We don't do this here during boot because we can do it all 7018 // at once after scanning all existing packages. 7019 // 7020 // We also do this *before* we perform dexopt on this package, so that 7021 // we can avoid redundant dexopts, and also to make sure we've got the 7022 // code and package path correct. 7023 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 7024 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 7025 } 7026 7027 if ((scanFlags & SCAN_NO_DEX) == 0) { 7028 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 7029 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 7030 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7031 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 7032 } 7033 } 7034 if (mFactoryTest && pkg.requestedPermissions.contains( 7035 android.Manifest.permission.FACTORY_TEST)) { 7036 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 7037 } 7038 7039 ArrayList<PackageParser.Package> clientLibPkgs = null; 7040 7041 // writer 7042 synchronized (mPackages) { 7043 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7044 // Only system apps can add new shared libraries. 7045 if (pkg.libraryNames != null) { 7046 for (int i=0; i<pkg.libraryNames.size(); i++) { 7047 String name = pkg.libraryNames.get(i); 7048 boolean allowed = false; 7049 if (pkg.isUpdatedSystemApp()) { 7050 // New library entries can only be added through the 7051 // system image. This is important to get rid of a lot 7052 // of nasty edge cases: for example if we allowed a non- 7053 // system update of the app to add a library, then uninstalling 7054 // the update would make the library go away, and assumptions 7055 // we made such as through app install filtering would now 7056 // have allowed apps on the device which aren't compatible 7057 // with it. Better to just have the restriction here, be 7058 // conservative, and create many fewer cases that can negatively 7059 // impact the user experience. 7060 final PackageSetting sysPs = mSettings 7061 .getDisabledSystemPkgLPr(pkg.packageName); 7062 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 7063 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 7064 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 7065 allowed = true; 7066 allowed = true; 7067 break; 7068 } 7069 } 7070 } 7071 } else { 7072 allowed = true; 7073 } 7074 if (allowed) { 7075 if (!mSharedLibraries.containsKey(name)) { 7076 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 7077 } else if (!name.equals(pkg.packageName)) { 7078 Slog.w(TAG, "Package " + pkg.packageName + " library " 7079 + name + " already exists; skipping"); 7080 } 7081 } else { 7082 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 7083 + name + " that is not declared on system image; skipping"); 7084 } 7085 } 7086 if ((scanFlags&SCAN_BOOTING) == 0) { 7087 // If we are not booting, we need to update any applications 7088 // that are clients of our shared library. If we are booting, 7089 // this will all be done once the scan is complete. 7090 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 7091 } 7092 } 7093 } 7094 } 7095 7096 // We also need to dexopt any apps that are dependent on this library. Note that 7097 // if these fail, we should abort the install since installing the library will 7098 // result in some apps being broken. 7099 if (clientLibPkgs != null) { 7100 if ((scanFlags & SCAN_NO_DEX) == 0) { 7101 for (int i = 0; i < clientLibPkgs.size(); i++) { 7102 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7103 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 7104 null /* instruction sets */, forceDex, 7105 (scanFlags & SCAN_DEFER_DEX) != 0, false); 7106 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7107 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 7108 "scanPackageLI failed to dexopt clientLibPkgs"); 7109 } 7110 } 7111 } 7112 } 7113 7114 // Also need to kill any apps that are dependent on the library. 7115 if (clientLibPkgs != null) { 7116 for (int i=0; i<clientLibPkgs.size(); i++) { 7117 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7118 killApplication(clientPkg.applicationInfo.packageName, 7119 clientPkg.applicationInfo.uid, "update lib"); 7120 } 7121 } 7122 7123 // Make sure we're not adding any bogus keyset info 7124 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7125 ksms.assertScannedPackageValid(pkg); 7126 7127 // writer 7128 synchronized (mPackages) { 7129 // We don't expect installation to fail beyond this point 7130 7131 // Add the new setting to mSettings 7132 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 7133 // Add the new setting to mPackages 7134 mPackages.put(pkg.applicationInfo.packageName, pkg); 7135 // Make sure we don't accidentally delete its data. 7136 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 7137 while (iter.hasNext()) { 7138 PackageCleanItem item = iter.next(); 7139 if (pkgName.equals(item.packageName)) { 7140 iter.remove(); 7141 } 7142 } 7143 7144 // Take care of first install / last update times. 7145 if (currentTime != 0) { 7146 if (pkgSetting.firstInstallTime == 0) { 7147 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7148 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7149 pkgSetting.lastUpdateTime = currentTime; 7150 } 7151 } else if (pkgSetting.firstInstallTime == 0) { 7152 // We need *something*. Take time time stamp of the file. 7153 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7154 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7155 if (scanFileTime != pkgSetting.timeStamp) { 7156 // A package on the system image has changed; consider this 7157 // to be an update. 7158 pkgSetting.lastUpdateTime = scanFileTime; 7159 } 7160 } 7161 7162 // Add the package's KeySets to the global KeySetManagerService 7163 ksms.addScannedPackageLPw(pkg); 7164 7165 int N = pkg.providers.size(); 7166 StringBuilder r = null; 7167 int i; 7168 for (i=0; i<N; i++) { 7169 PackageParser.Provider p = pkg.providers.get(i); 7170 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7171 p.info.processName, pkg.applicationInfo.uid); 7172 mProviders.addProvider(p); 7173 p.syncable = p.info.isSyncable; 7174 if (p.info.authority != null) { 7175 String names[] = p.info.authority.split(";"); 7176 p.info.authority = null; 7177 for (int j = 0; j < names.length; j++) { 7178 if (j == 1 && p.syncable) { 7179 // We only want the first authority for a provider to possibly be 7180 // syncable, so if we already added this provider using a different 7181 // authority clear the syncable flag. We copy the provider before 7182 // changing it because the mProviders object contains a reference 7183 // to a provider that we don't want to change. 7184 // Only do this for the second authority since the resulting provider 7185 // object can be the same for all future authorities for this provider. 7186 p = new PackageParser.Provider(p); 7187 p.syncable = false; 7188 } 7189 if (!mProvidersByAuthority.containsKey(names[j])) { 7190 mProvidersByAuthority.put(names[j], p); 7191 if (p.info.authority == null) { 7192 p.info.authority = names[j]; 7193 } else { 7194 p.info.authority = p.info.authority + ";" + names[j]; 7195 } 7196 if (DEBUG_PACKAGE_SCANNING) { 7197 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7198 Log.d(TAG, "Registered content provider: " + names[j] 7199 + ", className = " + p.info.name + ", isSyncable = " 7200 + p.info.isSyncable); 7201 } 7202 } else { 7203 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7204 Slog.w(TAG, "Skipping provider name " + names[j] + 7205 " (in package " + pkg.applicationInfo.packageName + 7206 "): name already used by " 7207 + ((other != null && other.getComponentName() != null) 7208 ? other.getComponentName().getPackageName() : "?")); 7209 } 7210 } 7211 } 7212 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7213 if (r == null) { 7214 r = new StringBuilder(256); 7215 } else { 7216 r.append(' '); 7217 } 7218 r.append(p.info.name); 7219 } 7220 } 7221 if (r != null) { 7222 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7223 } 7224 7225 N = pkg.services.size(); 7226 r = null; 7227 for (i=0; i<N; i++) { 7228 PackageParser.Service s = pkg.services.get(i); 7229 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 7230 s.info.processName, pkg.applicationInfo.uid); 7231 mServices.addService(s); 7232 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7233 if (r == null) { 7234 r = new StringBuilder(256); 7235 } else { 7236 r.append(' '); 7237 } 7238 r.append(s.info.name); 7239 } 7240 } 7241 if (r != null) { 7242 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 7243 } 7244 7245 N = pkg.receivers.size(); 7246 r = null; 7247 for (i=0; i<N; i++) { 7248 PackageParser.Activity a = pkg.receivers.get(i); 7249 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7250 a.info.processName, pkg.applicationInfo.uid); 7251 mReceivers.addActivity(a, "receiver"); 7252 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7253 if (r == null) { 7254 r = new StringBuilder(256); 7255 } else { 7256 r.append(' '); 7257 } 7258 r.append(a.info.name); 7259 } 7260 } 7261 if (r != null) { 7262 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 7263 } 7264 7265 N = pkg.activities.size(); 7266 r = null; 7267 for (i=0; i<N; i++) { 7268 PackageParser.Activity a = pkg.activities.get(i); 7269 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7270 a.info.processName, pkg.applicationInfo.uid); 7271 mActivities.addActivity(a, "activity"); 7272 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7273 if (r == null) { 7274 r = new StringBuilder(256); 7275 } else { 7276 r.append(' '); 7277 } 7278 r.append(a.info.name); 7279 } 7280 } 7281 if (r != null) { 7282 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 7283 } 7284 7285 N = pkg.permissionGroups.size(); 7286 r = null; 7287 for (i=0; i<N; i++) { 7288 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 7289 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 7290 if (cur == null) { 7291 mPermissionGroups.put(pg.info.name, pg); 7292 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7293 if (r == null) { 7294 r = new StringBuilder(256); 7295 } else { 7296 r.append(' '); 7297 } 7298 r.append(pg.info.name); 7299 } 7300 } else { 7301 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 7302 + pg.info.packageName + " ignored: original from " 7303 + cur.info.packageName); 7304 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7305 if (r == null) { 7306 r = new StringBuilder(256); 7307 } else { 7308 r.append(' '); 7309 } 7310 r.append("DUP:"); 7311 r.append(pg.info.name); 7312 } 7313 } 7314 } 7315 if (r != null) { 7316 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 7317 } 7318 7319 N = pkg.permissions.size(); 7320 r = null; 7321 for (i=0; i<N; i++) { 7322 PackageParser.Permission p = pkg.permissions.get(i); 7323 7324 // Now that permission groups have a special meaning, we ignore permission 7325 // groups for legacy apps to prevent unexpected behavior. In particular, 7326 // permissions for one app being granted to someone just becuase they happen 7327 // to be in a group defined by another app (before this had no implications). 7328 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 7329 p.group = mPermissionGroups.get(p.info.group); 7330 // Warn for a permission in an unknown group. 7331 if (p.info.group != null && p.group == null) { 7332 Slog.w(TAG, "Permission " + p.info.name + " from package " 7333 + p.info.packageName + " in an unknown group " + p.info.group); 7334 } 7335 } 7336 7337 ArrayMap<String, BasePermission> permissionMap = 7338 p.tree ? mSettings.mPermissionTrees 7339 : mSettings.mPermissions; 7340 BasePermission bp = permissionMap.get(p.info.name); 7341 7342 // Allow system apps to redefine non-system permissions 7343 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 7344 final boolean currentOwnerIsSystem = (bp.perm != null 7345 && isSystemApp(bp.perm.owner)); 7346 if (isSystemApp(p.owner)) { 7347 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 7348 // It's a built-in permission and no owner, take ownership now 7349 bp.packageSetting = pkgSetting; 7350 bp.perm = p; 7351 bp.uid = pkg.applicationInfo.uid; 7352 bp.sourcePackage = p.info.packageName; 7353 } else if (!currentOwnerIsSystem) { 7354 String msg = "New decl " + p.owner + " of permission " 7355 + p.info.name + " is system; overriding " + bp.sourcePackage; 7356 reportSettingsProblem(Log.WARN, msg); 7357 bp = null; 7358 } 7359 } 7360 } 7361 7362 if (bp == null) { 7363 bp = new BasePermission(p.info.name, p.info.packageName, 7364 BasePermission.TYPE_NORMAL); 7365 permissionMap.put(p.info.name, bp); 7366 } 7367 7368 if (bp.perm == null) { 7369 if (bp.sourcePackage == null 7370 || bp.sourcePackage.equals(p.info.packageName)) { 7371 BasePermission tree = findPermissionTreeLP(p.info.name); 7372 if (tree == null 7373 || tree.sourcePackage.equals(p.info.packageName)) { 7374 bp.packageSetting = pkgSetting; 7375 bp.perm = p; 7376 bp.uid = pkg.applicationInfo.uid; 7377 bp.sourcePackage = p.info.packageName; 7378 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7379 if (r == null) { 7380 r = new StringBuilder(256); 7381 } else { 7382 r.append(' '); 7383 } 7384 r.append(p.info.name); 7385 } 7386 } else { 7387 Slog.w(TAG, "Permission " + p.info.name + " from package " 7388 + p.info.packageName + " ignored: base tree " 7389 + tree.name + " is from package " 7390 + tree.sourcePackage); 7391 } 7392 } else { 7393 Slog.w(TAG, "Permission " + p.info.name + " from package " 7394 + p.info.packageName + " ignored: original from " 7395 + bp.sourcePackage); 7396 } 7397 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7398 if (r == null) { 7399 r = new StringBuilder(256); 7400 } else { 7401 r.append(' '); 7402 } 7403 r.append("DUP:"); 7404 r.append(p.info.name); 7405 } 7406 if (bp.perm == p) { 7407 bp.protectionLevel = p.info.protectionLevel; 7408 } 7409 } 7410 7411 if (r != null) { 7412 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 7413 } 7414 7415 N = pkg.instrumentation.size(); 7416 r = null; 7417 for (i=0; i<N; i++) { 7418 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7419 a.info.packageName = pkg.applicationInfo.packageName; 7420 a.info.sourceDir = pkg.applicationInfo.sourceDir; 7421 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 7422 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 7423 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 7424 a.info.dataDir = pkg.applicationInfo.dataDir; 7425 7426 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 7427 // need other information about the application, like the ABI and what not ? 7428 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 7429 mInstrumentation.put(a.getComponentName(), a); 7430 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7431 if (r == null) { 7432 r = new StringBuilder(256); 7433 } else { 7434 r.append(' '); 7435 } 7436 r.append(a.info.name); 7437 } 7438 } 7439 if (r != null) { 7440 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 7441 } 7442 7443 if (pkg.protectedBroadcasts != null) { 7444 N = pkg.protectedBroadcasts.size(); 7445 for (i=0; i<N; i++) { 7446 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 7447 } 7448 } 7449 7450 pkgSetting.setTimeStamp(scanFileTime); 7451 7452 // Create idmap files for pairs of (packages, overlay packages). 7453 // Note: "android", ie framework-res.apk, is handled by native layers. 7454 if (pkg.mOverlayTarget != null) { 7455 // This is an overlay package. 7456 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 7457 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 7458 mOverlays.put(pkg.mOverlayTarget, 7459 new ArrayMap<String, PackageParser.Package>()); 7460 } 7461 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 7462 map.put(pkg.packageName, pkg); 7463 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 7464 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 7465 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7466 "scanPackageLI failed to createIdmap"); 7467 } 7468 } 7469 } else if (mOverlays.containsKey(pkg.packageName) && 7470 !pkg.packageName.equals("android")) { 7471 // This is a regular package, with one or more known overlay packages. 7472 createIdmapsForPackageLI(pkg); 7473 } 7474 } 7475 7476 return pkg; 7477 } 7478 7479 /** 7480 * Derive the ABI of a non-system package located at {@code scanFile}. This information 7481 * is derived purely on the basis of the contents of {@code scanFile} and 7482 * {@code cpuAbiOverride}. 7483 * 7484 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 7485 */ 7486 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 7487 String cpuAbiOverride, boolean extractLibs) 7488 throws PackageManagerException { 7489 // TODO: We can probably be smarter about this stuff. For installed apps, 7490 // we can calculate this information at install time once and for all. For 7491 // system apps, we can probably assume that this information doesn't change 7492 // after the first boot scan. As things stand, we do lots of unnecessary work. 7493 7494 // Give ourselves some initial paths; we'll come back for another 7495 // pass once we've determined ABI below. 7496 setNativeLibraryPaths(pkg); 7497 7498 // We would never need to extract libs for forward-locked and external packages, 7499 // since the container service will do it for us. We shouldn't attempt to 7500 // extract libs from system app when it was not updated. 7501 if (pkg.isForwardLocked() || isExternal(pkg) || 7502 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) { 7503 extractLibs = false; 7504 } 7505 7506 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7507 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7508 7509 NativeLibraryHelper.Handle handle = null; 7510 try { 7511 handle = NativeLibraryHelper.Handle.create(scanFile); 7512 // TODO(multiArch): This can be null for apps that didn't go through the 7513 // usual installation process. We can calculate it again, like we 7514 // do during install time. 7515 // 7516 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7517 // unnecessary. 7518 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7519 7520 // Null out the abis so that they can be recalculated. 7521 pkg.applicationInfo.primaryCpuAbi = null; 7522 pkg.applicationInfo.secondaryCpuAbi = null; 7523 if (isMultiArch(pkg.applicationInfo)) { 7524 // Warn if we've set an abiOverride for multi-lib packages.. 7525 // By definition, we need to copy both 32 and 64 bit libraries for 7526 // such packages. 7527 if (pkg.cpuAbiOverride != null 7528 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7529 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7530 } 7531 7532 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7533 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7534 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7535 if (extractLibs) { 7536 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7537 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7538 useIsaSpecificSubdirs); 7539 } else { 7540 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7541 } 7542 } 7543 7544 maybeThrowExceptionForMultiArchCopy( 7545 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7546 7547 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7548 if (extractLibs) { 7549 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7550 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7551 useIsaSpecificSubdirs); 7552 } else { 7553 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7554 } 7555 } 7556 7557 maybeThrowExceptionForMultiArchCopy( 7558 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7559 7560 if (abi64 >= 0) { 7561 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7562 } 7563 7564 if (abi32 >= 0) { 7565 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7566 if (abi64 >= 0) { 7567 pkg.applicationInfo.secondaryCpuAbi = abi; 7568 } else { 7569 pkg.applicationInfo.primaryCpuAbi = abi; 7570 } 7571 } 7572 } else { 7573 String[] abiList = (cpuAbiOverride != null) ? 7574 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7575 7576 // Enable gross and lame hacks for apps that are built with old 7577 // SDK tools. We must scan their APKs for renderscript bitcode and 7578 // not launch them if it's present. Don't bother checking on devices 7579 // that don't have 64 bit support. 7580 boolean needsRenderScriptOverride = false; 7581 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7582 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7583 abiList = Build.SUPPORTED_32_BIT_ABIS; 7584 needsRenderScriptOverride = true; 7585 } 7586 7587 final int copyRet; 7588 if (extractLibs) { 7589 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7590 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7591 } else { 7592 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7593 } 7594 7595 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7596 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7597 "Error unpackaging native libs for app, errorCode=" + copyRet); 7598 } 7599 7600 if (copyRet >= 0) { 7601 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7602 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7603 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7604 } else if (needsRenderScriptOverride) { 7605 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7606 } 7607 } 7608 } catch (IOException ioe) { 7609 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7610 } finally { 7611 IoUtils.closeQuietly(handle); 7612 } 7613 7614 // Now that we've calculated the ABIs and determined if it's an internal app, 7615 // we will go ahead and populate the nativeLibraryPath. 7616 setNativeLibraryPaths(pkg); 7617 } 7618 7619 /** 7620 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7621 * i.e, so that all packages can be run inside a single process if required. 7622 * 7623 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7624 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7625 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7626 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7627 * updating a package that belongs to a shared user. 7628 * 7629 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7630 * adds unnecessary complexity. 7631 */ 7632 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7633 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 7634 String requiredInstructionSet = null; 7635 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7636 requiredInstructionSet = VMRuntime.getInstructionSet( 7637 scannedPackage.applicationInfo.primaryCpuAbi); 7638 } 7639 7640 PackageSetting requirer = null; 7641 for (PackageSetting ps : packagesForUser) { 7642 // If packagesForUser contains scannedPackage, we skip it. This will happen 7643 // when scannedPackage is an update of an existing package. Without this check, 7644 // we will never be able to change the ABI of any package belonging to a shared 7645 // user, even if it's compatible with other packages. 7646 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7647 if (ps.primaryCpuAbiString == null) { 7648 continue; 7649 } 7650 7651 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7652 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7653 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7654 // this but there's not much we can do. 7655 String errorMessage = "Instruction set mismatch, " 7656 + ((requirer == null) ? "[caller]" : requirer) 7657 + " requires " + requiredInstructionSet + " whereas " + ps 7658 + " requires " + instructionSet; 7659 Slog.w(TAG, errorMessage); 7660 } 7661 7662 if (requiredInstructionSet == null) { 7663 requiredInstructionSet = instructionSet; 7664 requirer = ps; 7665 } 7666 } 7667 } 7668 7669 if (requiredInstructionSet != null) { 7670 String adjustedAbi; 7671 if (requirer != null) { 7672 // requirer != null implies that either scannedPackage was null or that scannedPackage 7673 // did not require an ABI, in which case we have to adjust scannedPackage to match 7674 // the ABI of the set (which is the same as requirer's ABI) 7675 adjustedAbi = requirer.primaryCpuAbiString; 7676 if (scannedPackage != null) { 7677 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7678 } 7679 } else { 7680 // requirer == null implies that we're updating all ABIs in the set to 7681 // match scannedPackage. 7682 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7683 } 7684 7685 for (PackageSetting ps : packagesForUser) { 7686 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7687 if (ps.primaryCpuAbiString != null) { 7688 continue; 7689 } 7690 7691 ps.primaryCpuAbiString = adjustedAbi; 7692 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7693 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7694 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7695 7696 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 7697 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 7698 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7699 ps.primaryCpuAbiString = null; 7700 ps.pkg.applicationInfo.primaryCpuAbi = null; 7701 return; 7702 } else { 7703 mInstaller.rmdex(ps.codePathString, 7704 getDexCodeInstructionSet(getPreferredInstructionSet())); 7705 } 7706 } 7707 } 7708 } 7709 } 7710 } 7711 7712 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7713 synchronized (mPackages) { 7714 mResolverReplaced = true; 7715 // Set up information for custom user intent resolution activity. 7716 mResolveActivity.applicationInfo = pkg.applicationInfo; 7717 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7718 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7719 mResolveActivity.processName = pkg.applicationInfo.packageName; 7720 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7721 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7722 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7723 mResolveActivity.theme = 0; 7724 mResolveActivity.exported = true; 7725 mResolveActivity.enabled = true; 7726 mResolveInfo.activityInfo = mResolveActivity; 7727 mResolveInfo.priority = 0; 7728 mResolveInfo.preferredOrder = 0; 7729 mResolveInfo.match = 0; 7730 mResolveComponentName = mCustomResolverComponentName; 7731 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7732 mResolveComponentName); 7733 } 7734 } 7735 7736 private static String calculateBundledApkRoot(final String codePathString) { 7737 final File codePath = new File(codePathString); 7738 final File codeRoot; 7739 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 7740 codeRoot = Environment.getRootDirectory(); 7741 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7742 codeRoot = Environment.getOemDirectory(); 7743 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7744 codeRoot = Environment.getVendorDirectory(); 7745 } else { 7746 // Unrecognized code path; take its top real segment as the apk root: 7747 // e.g. /something/app/blah.apk => /something 7748 try { 7749 File f = codePath.getCanonicalFile(); 7750 File parent = f.getParentFile(); // non-null because codePath is a file 7751 File tmp; 7752 while ((tmp = parent.getParentFile()) != null) { 7753 f = parent; 7754 parent = tmp; 7755 } 7756 codeRoot = f; 7757 Slog.w(TAG, "Unrecognized code path " 7758 + codePath + " - using " + codeRoot); 7759 } catch (IOException e) { 7760 // Can't canonicalize the code path -- shenanigans? 7761 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7762 return Environment.getRootDirectory().getPath(); 7763 } 7764 } 7765 return codeRoot.getPath(); 7766 } 7767 7768 /** 7769 * Derive and set the location of native libraries for the given package, 7770 * which varies depending on where and how the package was installed. 7771 */ 7772 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7773 final ApplicationInfo info = pkg.applicationInfo; 7774 final String codePath = pkg.codePath; 7775 final File codeFile = new File(codePath); 7776 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7777 final boolean asecApp = info.isForwardLocked() || isExternal(info); 7778 7779 info.nativeLibraryRootDir = null; 7780 info.nativeLibraryRootRequiresIsa = false; 7781 info.nativeLibraryDir = null; 7782 info.secondaryNativeLibraryDir = null; 7783 7784 if (isApkFile(codeFile)) { 7785 // Monolithic install 7786 if (bundledApp) { 7787 // If "/system/lib64/apkname" exists, assume that is the per-package 7788 // native library directory to use; otherwise use "/system/lib/apkname". 7789 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7790 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7791 getPrimaryInstructionSet(info)); 7792 7793 // This is a bundled system app so choose the path based on the ABI. 7794 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7795 // is just the default path. 7796 final String apkName = deriveCodePathName(codePath); 7797 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7798 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7799 apkName).getAbsolutePath(); 7800 7801 if (info.secondaryCpuAbi != null) { 7802 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7803 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7804 secondaryLibDir, apkName).getAbsolutePath(); 7805 } 7806 } else if (asecApp) { 7807 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 7808 .getAbsolutePath(); 7809 } else { 7810 final String apkName = deriveCodePathName(codePath); 7811 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 7812 .getAbsolutePath(); 7813 } 7814 7815 info.nativeLibraryRootRequiresIsa = false; 7816 info.nativeLibraryDir = info.nativeLibraryRootDir; 7817 } else { 7818 // Cluster install 7819 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 7820 info.nativeLibraryRootRequiresIsa = true; 7821 7822 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 7823 getPrimaryInstructionSet(info)).getAbsolutePath(); 7824 7825 if (info.secondaryCpuAbi != null) { 7826 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 7827 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 7828 } 7829 } 7830 } 7831 7832 /** 7833 * Calculate the abis and roots for a bundled app. These can uniquely 7834 * be determined from the contents of the system partition, i.e whether 7835 * it contains 64 or 32 bit shared libraries etc. We do not validate any 7836 * of this information, and instead assume that the system was built 7837 * sensibly. 7838 */ 7839 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 7840 PackageSetting pkgSetting) { 7841 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 7842 7843 // If "/system/lib64/apkname" exists, assume that is the per-package 7844 // native library directory to use; otherwise use "/system/lib/apkname". 7845 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 7846 setBundledAppAbi(pkg, apkRoot, apkName); 7847 // pkgSetting might be null during rescan following uninstall of updates 7848 // to a bundled app, so accommodate that possibility. The settings in 7849 // that case will be established later from the parsed package. 7850 // 7851 // If the settings aren't null, sync them up with what we've just derived. 7852 // note that apkRoot isn't stored in the package settings. 7853 if (pkgSetting != null) { 7854 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7855 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7856 } 7857 } 7858 7859 /** 7860 * Deduces the ABI of a bundled app and sets the relevant fields on the 7861 * parsed pkg object. 7862 * 7863 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 7864 * under which system libraries are installed. 7865 * @param apkName the name of the installed package. 7866 */ 7867 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 7868 final File codeFile = new File(pkg.codePath); 7869 7870 final boolean has64BitLibs; 7871 final boolean has32BitLibs; 7872 if (isApkFile(codeFile)) { 7873 // Monolithic install 7874 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 7875 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7876 } else { 7877 // Cluster install 7878 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7879 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7880 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7881 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7882 has64BitLibs = (new File(rootDir, isa)).exists(); 7883 } else { 7884 has64BitLibs = false; 7885 } 7886 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7887 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 7888 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 7889 has32BitLibs = (new File(rootDir, isa)).exists(); 7890 } else { 7891 has32BitLibs = false; 7892 } 7893 } 7894 7895 if (has64BitLibs && !has32BitLibs) { 7896 // The package has 64 bit libs, but not 32 bit libs. Its primary 7897 // ABI should be 64 bit. We can safely assume here that the bundled 7898 // native libraries correspond to the most preferred ABI in the list. 7899 7900 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7901 pkg.applicationInfo.secondaryCpuAbi = null; 7902 } else if (has32BitLibs && !has64BitLibs) { 7903 // The package has 32 bit libs but not 64 bit libs. Its primary 7904 // ABI should be 32 bit. 7905 7906 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7907 pkg.applicationInfo.secondaryCpuAbi = null; 7908 } else if (has32BitLibs && has64BitLibs) { 7909 // The application has both 64 and 32 bit bundled libraries. We check 7910 // here that the app declares multiArch support, and warn if it doesn't. 7911 // 7912 // We will be lenient here and record both ABIs. The primary will be the 7913 // ABI that's higher on the list, i.e, a device that's configured to prefer 7914 // 64 bit apps will see a 64 bit primary ABI, 7915 7916 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 7917 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 7918 } 7919 7920 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 7921 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7922 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7923 } else { 7924 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7925 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7926 } 7927 } else { 7928 pkg.applicationInfo.primaryCpuAbi = null; 7929 pkg.applicationInfo.secondaryCpuAbi = null; 7930 } 7931 } 7932 7933 private void killApplication(String pkgName, int appId, String reason) { 7934 // Request the ActivityManager to kill the process(only for existing packages) 7935 // so that we do not end up in a confused state while the user is still using the older 7936 // version of the application while the new one gets installed. 7937 IActivityManager am = ActivityManagerNative.getDefault(); 7938 if (am != null) { 7939 try { 7940 am.killApplicationWithAppId(pkgName, appId, reason); 7941 } catch (RemoteException e) { 7942 } 7943 } 7944 } 7945 7946 void removePackageLI(PackageSetting ps, boolean chatty) { 7947 if (DEBUG_INSTALL) { 7948 if (chatty) 7949 Log.d(TAG, "Removing package " + ps.name); 7950 } 7951 7952 // writer 7953 synchronized (mPackages) { 7954 mPackages.remove(ps.name); 7955 final PackageParser.Package pkg = ps.pkg; 7956 if (pkg != null) { 7957 cleanPackageDataStructuresLILPw(pkg, chatty); 7958 } 7959 } 7960 } 7961 7962 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 7963 if (DEBUG_INSTALL) { 7964 if (chatty) 7965 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 7966 } 7967 7968 // writer 7969 synchronized (mPackages) { 7970 mPackages.remove(pkg.applicationInfo.packageName); 7971 cleanPackageDataStructuresLILPw(pkg, chatty); 7972 } 7973 } 7974 7975 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 7976 int N = pkg.providers.size(); 7977 StringBuilder r = null; 7978 int i; 7979 for (i=0; i<N; i++) { 7980 PackageParser.Provider p = pkg.providers.get(i); 7981 mProviders.removeProvider(p); 7982 if (p.info.authority == null) { 7983 7984 /* There was another ContentProvider with this authority when 7985 * this app was installed so this authority is null, 7986 * Ignore it as we don't have to unregister the provider. 7987 */ 7988 continue; 7989 } 7990 String names[] = p.info.authority.split(";"); 7991 for (int j = 0; j < names.length; j++) { 7992 if (mProvidersByAuthority.get(names[j]) == p) { 7993 mProvidersByAuthority.remove(names[j]); 7994 if (DEBUG_REMOVE) { 7995 if (chatty) 7996 Log.d(TAG, "Unregistered content provider: " + names[j] 7997 + ", className = " + p.info.name + ", isSyncable = " 7998 + p.info.isSyncable); 7999 } 8000 } 8001 } 8002 if (DEBUG_REMOVE && chatty) { 8003 if (r == null) { 8004 r = new StringBuilder(256); 8005 } else { 8006 r.append(' '); 8007 } 8008 r.append(p.info.name); 8009 } 8010 } 8011 if (r != null) { 8012 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 8013 } 8014 8015 N = pkg.services.size(); 8016 r = null; 8017 for (i=0; i<N; i++) { 8018 PackageParser.Service s = pkg.services.get(i); 8019 mServices.removeService(s); 8020 if (chatty) { 8021 if (r == null) { 8022 r = new StringBuilder(256); 8023 } else { 8024 r.append(' '); 8025 } 8026 r.append(s.info.name); 8027 } 8028 } 8029 if (r != null) { 8030 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 8031 } 8032 8033 N = pkg.receivers.size(); 8034 r = null; 8035 for (i=0; i<N; i++) { 8036 PackageParser.Activity a = pkg.receivers.get(i); 8037 mReceivers.removeActivity(a, "receiver"); 8038 if (DEBUG_REMOVE && chatty) { 8039 if (r == null) { 8040 r = new StringBuilder(256); 8041 } else { 8042 r.append(' '); 8043 } 8044 r.append(a.info.name); 8045 } 8046 } 8047 if (r != null) { 8048 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 8049 } 8050 8051 N = pkg.activities.size(); 8052 r = null; 8053 for (i=0; i<N; i++) { 8054 PackageParser.Activity a = pkg.activities.get(i); 8055 mActivities.removeActivity(a, "activity"); 8056 if (DEBUG_REMOVE && chatty) { 8057 if (r == null) { 8058 r = new StringBuilder(256); 8059 } else { 8060 r.append(' '); 8061 } 8062 r.append(a.info.name); 8063 } 8064 } 8065 if (r != null) { 8066 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 8067 } 8068 8069 N = pkg.permissions.size(); 8070 r = null; 8071 for (i=0; i<N; i++) { 8072 PackageParser.Permission p = pkg.permissions.get(i); 8073 BasePermission bp = mSettings.mPermissions.get(p.info.name); 8074 if (bp == null) { 8075 bp = mSettings.mPermissionTrees.get(p.info.name); 8076 } 8077 if (bp != null && bp.perm == p) { 8078 bp.perm = null; 8079 if (DEBUG_REMOVE && chatty) { 8080 if (r == null) { 8081 r = new StringBuilder(256); 8082 } else { 8083 r.append(' '); 8084 } 8085 r.append(p.info.name); 8086 } 8087 } 8088 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8089 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 8090 if (appOpPerms != null) { 8091 appOpPerms.remove(pkg.packageName); 8092 } 8093 } 8094 } 8095 if (r != null) { 8096 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8097 } 8098 8099 N = pkg.requestedPermissions.size(); 8100 r = null; 8101 for (i=0; i<N; i++) { 8102 String perm = pkg.requestedPermissions.get(i); 8103 BasePermission bp = mSettings.mPermissions.get(perm); 8104 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8105 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 8106 if (appOpPerms != null) { 8107 appOpPerms.remove(pkg.packageName); 8108 if (appOpPerms.isEmpty()) { 8109 mAppOpPermissionPackages.remove(perm); 8110 } 8111 } 8112 } 8113 } 8114 if (r != null) { 8115 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8116 } 8117 8118 N = pkg.instrumentation.size(); 8119 r = null; 8120 for (i=0; i<N; i++) { 8121 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8122 mInstrumentation.remove(a.getComponentName()); 8123 if (DEBUG_REMOVE && chatty) { 8124 if (r == null) { 8125 r = new StringBuilder(256); 8126 } else { 8127 r.append(' '); 8128 } 8129 r.append(a.info.name); 8130 } 8131 } 8132 if (r != null) { 8133 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 8134 } 8135 8136 r = null; 8137 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8138 // Only system apps can hold shared libraries. 8139 if (pkg.libraryNames != null) { 8140 for (i=0; i<pkg.libraryNames.size(); i++) { 8141 String name = pkg.libraryNames.get(i); 8142 SharedLibraryEntry cur = mSharedLibraries.get(name); 8143 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 8144 mSharedLibraries.remove(name); 8145 if (DEBUG_REMOVE && chatty) { 8146 if (r == null) { 8147 r = new StringBuilder(256); 8148 } else { 8149 r.append(' '); 8150 } 8151 r.append(name); 8152 } 8153 } 8154 } 8155 } 8156 } 8157 if (r != null) { 8158 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 8159 } 8160 } 8161 8162 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 8163 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 8164 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 8165 return true; 8166 } 8167 } 8168 return false; 8169 } 8170 8171 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 8172 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 8173 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 8174 8175 private void updatePermissionsLPw(String changingPkg, 8176 PackageParser.Package pkgInfo, int flags) { 8177 // Make sure there are no dangling permission trees. 8178 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 8179 while (it.hasNext()) { 8180 final BasePermission bp = it.next(); 8181 if (bp.packageSetting == null) { 8182 // We may not yet have parsed the package, so just see if 8183 // we still know about its settings. 8184 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8185 } 8186 if (bp.packageSetting == null) { 8187 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 8188 + " from package " + bp.sourcePackage); 8189 it.remove(); 8190 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8191 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8192 Slog.i(TAG, "Removing old permission tree: " + bp.name 8193 + " from package " + bp.sourcePackage); 8194 flags |= UPDATE_PERMISSIONS_ALL; 8195 it.remove(); 8196 } 8197 } 8198 } 8199 8200 // Make sure all dynamic permissions have been assigned to a package, 8201 // and make sure there are no dangling permissions. 8202 it = mSettings.mPermissions.values().iterator(); 8203 while (it.hasNext()) { 8204 final BasePermission bp = it.next(); 8205 if (bp.type == BasePermission.TYPE_DYNAMIC) { 8206 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 8207 + bp.name + " pkg=" + bp.sourcePackage 8208 + " info=" + bp.pendingInfo); 8209 if (bp.packageSetting == null && bp.pendingInfo != null) { 8210 final BasePermission tree = findPermissionTreeLP(bp.name); 8211 if (tree != null && tree.perm != null) { 8212 bp.packageSetting = tree.packageSetting; 8213 bp.perm = new PackageParser.Permission(tree.perm.owner, 8214 new PermissionInfo(bp.pendingInfo)); 8215 bp.perm.info.packageName = tree.perm.info.packageName; 8216 bp.perm.info.name = bp.name; 8217 bp.uid = tree.uid; 8218 } 8219 } 8220 } 8221 if (bp.packageSetting == null) { 8222 // We may not yet have parsed the package, so just see if 8223 // we still know about its settings. 8224 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8225 } 8226 if (bp.packageSetting == null) { 8227 Slog.w(TAG, "Removing dangling permission: " + bp.name 8228 + " from package " + bp.sourcePackage); 8229 it.remove(); 8230 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8231 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8232 Slog.i(TAG, "Removing old permission: " + bp.name 8233 + " from package " + bp.sourcePackage); 8234 flags |= UPDATE_PERMISSIONS_ALL; 8235 it.remove(); 8236 } 8237 } 8238 } 8239 8240 // Now update the permissions for all packages, in particular 8241 // replace the granted permissions of the system packages. 8242 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 8243 for (PackageParser.Package pkg : mPackages.values()) { 8244 if (pkg != pkgInfo) { 8245 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 8246 changingPkg); 8247 } 8248 } 8249 } 8250 8251 if (pkgInfo != null) { 8252 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 8253 } 8254 } 8255 8256 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 8257 String packageOfInterest) { 8258 // IMPORTANT: There are two types of permissions: install and runtime. 8259 // Install time permissions are granted when the app is installed to 8260 // all device users and users added in the future. Runtime permissions 8261 // are granted at runtime explicitly to specific users. Normal and signature 8262 // protected permissions are install time permissions. Dangerous permissions 8263 // are install permissions if the app's target SDK is Lollipop MR1 or older, 8264 // otherwise they are runtime permissions. This function does not manage 8265 // runtime permissions except for the case an app targeting Lollipop MR1 8266 // being upgraded to target a newer SDK, in which case dangerous permissions 8267 // are transformed from install time to runtime ones. 8268 8269 final PackageSetting ps = (PackageSetting) pkg.mExtras; 8270 if (ps == null) { 8271 return; 8272 } 8273 8274 PermissionsState permissionsState = ps.getPermissionsState(); 8275 PermissionsState origPermissions = permissionsState; 8276 8277 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 8278 8279 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 8280 8281 boolean changedInstallPermission = false; 8282 8283 if (replace) { 8284 ps.installPermissionsFixed = false; 8285 if (!ps.isSharedUser()) { 8286 origPermissions = new PermissionsState(permissionsState); 8287 permissionsState.reset(); 8288 } 8289 } 8290 8291 permissionsState.setGlobalGids(mGlobalGids); 8292 8293 final int N = pkg.requestedPermissions.size(); 8294 for (int i=0; i<N; i++) { 8295 final String name = pkg.requestedPermissions.get(i); 8296 final BasePermission bp = mSettings.mPermissions.get(name); 8297 8298 if (DEBUG_INSTALL) { 8299 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 8300 } 8301 8302 if (bp == null || bp.packageSetting == null) { 8303 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8304 Slog.w(TAG, "Unknown permission " + name 8305 + " in package " + pkg.packageName); 8306 } 8307 continue; 8308 } 8309 8310 final String perm = bp.name; 8311 boolean allowedSig = false; 8312 int grant = GRANT_DENIED; 8313 8314 // Keep track of app op permissions. 8315 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8316 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 8317 if (pkgs == null) { 8318 pkgs = new ArraySet<>(); 8319 mAppOpPermissionPackages.put(bp.name, pkgs); 8320 } 8321 pkgs.add(pkg.packageName); 8322 } 8323 8324 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 8325 switch (level) { 8326 case PermissionInfo.PROTECTION_NORMAL: { 8327 // For all apps normal permissions are install time ones. 8328 grant = GRANT_INSTALL; 8329 } break; 8330 8331 case PermissionInfo.PROTECTION_DANGEROUS: { 8332 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 8333 // For legacy apps dangerous permissions are install time ones. 8334 grant = GRANT_INSTALL_LEGACY; 8335 } else if (origPermissions.hasInstallPermission(bp.name)) { 8336 // For legacy apps that became modern, install becomes runtime. 8337 grant = GRANT_UPGRADE; 8338 } else { 8339 // For modern apps keep runtime permissions unchanged. 8340 grant = GRANT_RUNTIME; 8341 } 8342 } break; 8343 8344 case PermissionInfo.PROTECTION_SIGNATURE: { 8345 // For all apps signature permissions are install time ones. 8346 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 8347 if (allowedSig) { 8348 grant = GRANT_INSTALL; 8349 } 8350 } break; 8351 } 8352 8353 if (DEBUG_INSTALL) { 8354 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 8355 } 8356 8357 if (grant != GRANT_DENIED) { 8358 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 8359 // If this is an existing, non-system package, then 8360 // we can't add any new permissions to it. 8361 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 8362 // Except... if this is a permission that was added 8363 // to the platform (note: need to only do this when 8364 // updating the platform). 8365 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 8366 grant = GRANT_DENIED; 8367 } 8368 } 8369 } 8370 8371 switch (grant) { 8372 case GRANT_INSTALL: { 8373 // Revoke this as runtime permission to handle the case of 8374 // a runtime permission being downgraded to an install one. 8375 for (int userId : UserManagerService.getInstance().getUserIds()) { 8376 if (origPermissions.getRuntimePermissionState( 8377 bp.name, userId) != null) { 8378 // Revoke the runtime permission and clear the flags. 8379 origPermissions.revokeRuntimePermission(bp, userId); 8380 origPermissions.updatePermissionFlags(bp, userId, 8381 PackageManager.MASK_PERMISSION_FLAGS, 0); 8382 // If we revoked a permission permission, we have to write. 8383 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8384 changedRuntimePermissionUserIds, userId); 8385 } 8386 } 8387 // Grant an install permission. 8388 if (permissionsState.grantInstallPermission(bp) != 8389 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8390 changedInstallPermission = true; 8391 } 8392 } break; 8393 8394 case GRANT_INSTALL_LEGACY: { 8395 // Grant an install permission. 8396 if (permissionsState.grantInstallPermission(bp) != 8397 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8398 changedInstallPermission = true; 8399 } 8400 } break; 8401 8402 case GRANT_RUNTIME: { 8403 // Grant previously granted runtime permissions. 8404 for (int userId : UserManagerService.getInstance().getUserIds()) { 8405 PermissionState permissionState = origPermissions 8406 .getRuntimePermissionState(bp.name, userId); 8407 final int flags = permissionState != null 8408 ? permissionState.getFlags() : 0; 8409 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8410 if (permissionsState.grantRuntimePermission(bp, userId) == 8411 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8412 // If we cannot put the permission as it was, we have to write. 8413 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8414 changedRuntimePermissionUserIds, userId); 8415 } 8416 } 8417 // Propagate the permission flags. 8418 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 8419 } 8420 } break; 8421 8422 case GRANT_UPGRADE: { 8423 // Grant runtime permissions for a previously held install permission. 8424 PermissionState permissionState = origPermissions 8425 .getInstallPermissionState(bp.name); 8426 final int flags = permissionState != null ? permissionState.getFlags() : 0; 8427 8428 if (origPermissions.revokeInstallPermission(bp) 8429 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 8430 // We will be transferring the permission flags, so clear them. 8431 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 8432 PackageManager.MASK_PERMISSION_FLAGS, 0); 8433 changedInstallPermission = true; 8434 } 8435 8436 // If the permission is not to be promoted to runtime we ignore it and 8437 // also its other flags as they are not applicable to install permissions. 8438 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 8439 for (int userId : currentUserIds) { 8440 if (permissionsState.grantRuntimePermission(bp, userId) != 8441 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8442 // Transfer the permission flags. 8443 permissionsState.updatePermissionFlags(bp, userId, 8444 flags, flags); 8445 // If we granted the permission, we have to write. 8446 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8447 changedRuntimePermissionUserIds, userId); 8448 } 8449 } 8450 } 8451 } break; 8452 8453 default: { 8454 if (packageOfInterest == null 8455 || packageOfInterest.equals(pkg.packageName)) { 8456 Slog.w(TAG, "Not granting permission " + perm 8457 + " to package " + pkg.packageName 8458 + " because it was previously installed without"); 8459 } 8460 } break; 8461 } 8462 } else { 8463 if (permissionsState.revokeInstallPermission(bp) != 8464 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8465 // Also drop the permission flags. 8466 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 8467 PackageManager.MASK_PERMISSION_FLAGS, 0); 8468 changedInstallPermission = true; 8469 Slog.i(TAG, "Un-granting permission " + perm 8470 + " from package " + pkg.packageName 8471 + " (protectionLevel=" + bp.protectionLevel 8472 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8473 + ")"); 8474 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 8475 // Don't print warning for app op permissions, since it is fine for them 8476 // not to be granted, there is a UI for the user to decide. 8477 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8478 Slog.w(TAG, "Not granting permission " + perm 8479 + " to package " + pkg.packageName 8480 + " (protectionLevel=" + bp.protectionLevel 8481 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8482 + ")"); 8483 } 8484 } 8485 } 8486 } 8487 8488 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 8489 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 8490 // This is the first that we have heard about this package, so the 8491 // permissions we have now selected are fixed until explicitly 8492 // changed. 8493 ps.installPermissionsFixed = true; 8494 } 8495 8496 // Persist the runtime permissions state for users with changes. 8497 for (int userId : changedRuntimePermissionUserIds) { 8498 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 8499 } 8500 } 8501 8502 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8503 boolean allowed = false; 8504 final int NP = PackageParser.NEW_PERMISSIONS.length; 8505 for (int ip=0; ip<NP; ip++) { 8506 final PackageParser.NewPermissionInfo npi 8507 = PackageParser.NEW_PERMISSIONS[ip]; 8508 if (npi.name.equals(perm) 8509 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8510 allowed = true; 8511 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8512 + pkg.packageName); 8513 break; 8514 } 8515 } 8516 return allowed; 8517 } 8518 8519 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 8520 BasePermission bp, PermissionsState origPermissions) { 8521 boolean allowed; 8522 allowed = (compareSignatures( 8523 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 8524 == PackageManager.SIGNATURE_MATCH) 8525 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 8526 == PackageManager.SIGNATURE_MATCH); 8527 if (!allowed && (bp.protectionLevel 8528 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 8529 if (isSystemApp(pkg)) { 8530 // For updated system applications, a system permission 8531 // is granted only if it had been defined by the original application. 8532 if (pkg.isUpdatedSystemApp()) { 8533 final PackageSetting sysPs = mSettings 8534 .getDisabledSystemPkgLPr(pkg.packageName); 8535 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 8536 // If the original was granted this permission, we take 8537 // that grant decision as read and propagate it to the 8538 // update. 8539 if (sysPs.isPrivileged()) { 8540 allowed = true; 8541 } 8542 } else { 8543 // The system apk may have been updated with an older 8544 // version of the one on the data partition, but which 8545 // granted a new system permission that it didn't have 8546 // before. In this case we do want to allow the app to 8547 // now get the new permission if the ancestral apk is 8548 // privileged to get it. 8549 if (sysPs.pkg != null && sysPs.isPrivileged()) { 8550 for (int j=0; 8551 j<sysPs.pkg.requestedPermissions.size(); j++) { 8552 if (perm.equals( 8553 sysPs.pkg.requestedPermissions.get(j))) { 8554 allowed = true; 8555 break; 8556 } 8557 } 8558 } 8559 } 8560 } else { 8561 allowed = isPrivilegedApp(pkg); 8562 } 8563 } 8564 } 8565 if (!allowed) { 8566 if (!allowed && (bp.protectionLevel 8567 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 8568 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.MNC) { 8569 // If this was a previously normal/dangerous permission that got moved 8570 // to a system permission as part of the runtime permission redesign, then 8571 // we still want to blindly grant it to old apps. 8572 allowed = true; 8573 } 8574 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 8575 && pkg.packageName.equals(mRequiredInstallerPackage)) { 8576 // If this permission is to be granted to the system installer and 8577 // this app is an installer, then it gets the permission. 8578 allowed = true; 8579 } 8580 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 8581 && pkg.packageName.equals(mRequiredVerifierPackage)) { 8582 // If this permission is to be granted to the system verifier and 8583 // this app is a verifier, then it gets the permission. 8584 allowed = true; 8585 } 8586 if (!allowed && (bp.protectionLevel 8587 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 8588 && isSystemApp(pkg)) { 8589 // Any pre-installed system app is allowed to get this permission. 8590 allowed = true; 8591 } 8592 if (!allowed && (bp.protectionLevel 8593 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 8594 // For development permissions, a development permission 8595 // is granted only if it was already granted. 8596 allowed = origPermissions.hasInstallPermission(perm); 8597 } 8598 } 8599 return allowed; 8600 } 8601 8602 final class ActivityIntentResolver 8603 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 8604 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8605 boolean defaultOnly, int userId) { 8606 if (!sUserManager.exists(userId)) return null; 8607 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8608 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8609 } 8610 8611 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8612 int userId) { 8613 if (!sUserManager.exists(userId)) return null; 8614 mFlags = flags; 8615 return super.queryIntent(intent, resolvedType, 8616 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8617 } 8618 8619 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8620 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 8621 if (!sUserManager.exists(userId)) return null; 8622 if (packageActivities == null) { 8623 return null; 8624 } 8625 mFlags = flags; 8626 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8627 final int N = packageActivities.size(); 8628 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 8629 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 8630 8631 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 8632 for (int i = 0; i < N; ++i) { 8633 intentFilters = packageActivities.get(i).intents; 8634 if (intentFilters != null && intentFilters.size() > 0) { 8635 PackageParser.ActivityIntentInfo[] array = 8636 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 8637 intentFilters.toArray(array); 8638 listCut.add(array); 8639 } 8640 } 8641 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8642 } 8643 8644 public final void addActivity(PackageParser.Activity a, String type) { 8645 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 8646 mActivities.put(a.getComponentName(), a); 8647 if (DEBUG_SHOW_INFO) 8648 Log.v( 8649 TAG, " " + type + " " + 8650 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 8651 if (DEBUG_SHOW_INFO) 8652 Log.v(TAG, " Class=" + a.info.name); 8653 final int NI = a.intents.size(); 8654 for (int j=0; j<NI; j++) { 8655 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8656 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 8657 intent.setPriority(0); 8658 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 8659 + a.className + " with priority > 0, forcing to 0"); 8660 } 8661 if (DEBUG_SHOW_INFO) { 8662 Log.v(TAG, " IntentFilter:"); 8663 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8664 } 8665 if (!intent.debugCheck()) { 8666 Log.w(TAG, "==> For Activity " + a.info.name); 8667 } 8668 addFilter(intent); 8669 } 8670 } 8671 8672 public final void removeActivity(PackageParser.Activity a, String type) { 8673 mActivities.remove(a.getComponentName()); 8674 if (DEBUG_SHOW_INFO) { 8675 Log.v(TAG, " " + type + " " 8676 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 8677 : a.info.name) + ":"); 8678 Log.v(TAG, " Class=" + a.info.name); 8679 } 8680 final int NI = a.intents.size(); 8681 for (int j=0; j<NI; j++) { 8682 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8683 if (DEBUG_SHOW_INFO) { 8684 Log.v(TAG, " IntentFilter:"); 8685 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8686 } 8687 removeFilter(intent); 8688 } 8689 } 8690 8691 @Override 8692 protected boolean allowFilterResult( 8693 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 8694 ActivityInfo filterAi = filter.activity.info; 8695 for (int i=dest.size()-1; i>=0; i--) { 8696 ActivityInfo destAi = dest.get(i).activityInfo; 8697 if (destAi.name == filterAi.name 8698 && destAi.packageName == filterAi.packageName) { 8699 return false; 8700 } 8701 } 8702 return true; 8703 } 8704 8705 @Override 8706 protected ActivityIntentInfo[] newArray(int size) { 8707 return new ActivityIntentInfo[size]; 8708 } 8709 8710 @Override 8711 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 8712 if (!sUserManager.exists(userId)) return true; 8713 PackageParser.Package p = filter.activity.owner; 8714 if (p != null) { 8715 PackageSetting ps = (PackageSetting)p.mExtras; 8716 if (ps != null) { 8717 // System apps are never considered stopped for purposes of 8718 // filtering, because there may be no way for the user to 8719 // actually re-launch them. 8720 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 8721 && ps.getStopped(userId); 8722 } 8723 } 8724 return false; 8725 } 8726 8727 @Override 8728 protected boolean isPackageForFilter(String packageName, 8729 PackageParser.ActivityIntentInfo info) { 8730 return packageName.equals(info.activity.owner.packageName); 8731 } 8732 8733 @Override 8734 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 8735 int match, int userId) { 8736 if (!sUserManager.exists(userId)) return null; 8737 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 8738 return null; 8739 } 8740 final PackageParser.Activity activity = info.activity; 8741 if (mSafeMode && (activity.info.applicationInfo.flags 8742 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8743 return null; 8744 } 8745 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 8746 if (ps == null) { 8747 return null; 8748 } 8749 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 8750 ps.readUserState(userId), userId); 8751 if (ai == null) { 8752 return null; 8753 } 8754 final ResolveInfo res = new ResolveInfo(); 8755 res.activityInfo = ai; 8756 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8757 res.filter = info; 8758 } 8759 if (info != null) { 8760 res.handleAllWebDataURI = info.handleAllWebDataURI(); 8761 } 8762 res.priority = info.getPriority(); 8763 res.preferredOrder = activity.owner.mPreferredOrder; 8764 //System.out.println("Result: " + res.activityInfo.className + 8765 // " = " + res.priority); 8766 res.match = match; 8767 res.isDefault = info.hasDefault; 8768 res.labelRes = info.labelRes; 8769 res.nonLocalizedLabel = info.nonLocalizedLabel; 8770 if (userNeedsBadging(userId)) { 8771 res.noResourceId = true; 8772 } else { 8773 res.icon = info.icon; 8774 } 8775 res.iconResourceId = info.icon; 8776 res.system = res.activityInfo.applicationInfo.isSystemApp(); 8777 return res; 8778 } 8779 8780 @Override 8781 protected void sortResults(List<ResolveInfo> results) { 8782 Collections.sort(results, mResolvePrioritySorter); 8783 } 8784 8785 @Override 8786 protected void dumpFilter(PrintWriter out, String prefix, 8787 PackageParser.ActivityIntentInfo filter) { 8788 out.print(prefix); out.print( 8789 Integer.toHexString(System.identityHashCode(filter.activity))); 8790 out.print(' '); 8791 filter.activity.printComponentShortName(out); 8792 out.print(" filter "); 8793 out.println(Integer.toHexString(System.identityHashCode(filter))); 8794 } 8795 8796 @Override 8797 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 8798 return filter.activity; 8799 } 8800 8801 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8802 PackageParser.Activity activity = (PackageParser.Activity)label; 8803 out.print(prefix); out.print( 8804 Integer.toHexString(System.identityHashCode(activity))); 8805 out.print(' '); 8806 activity.printComponentShortName(out); 8807 if (count > 1) { 8808 out.print(" ("); out.print(count); out.print(" filters)"); 8809 } 8810 out.println(); 8811 } 8812 8813// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8814// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8815// final List<ResolveInfo> retList = Lists.newArrayList(); 8816// while (i.hasNext()) { 8817// final ResolveInfo resolveInfo = i.next(); 8818// if (isEnabledLP(resolveInfo.activityInfo)) { 8819// retList.add(resolveInfo); 8820// } 8821// } 8822// return retList; 8823// } 8824 8825 // Keys are String (activity class name), values are Activity. 8826 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 8827 = new ArrayMap<ComponentName, PackageParser.Activity>(); 8828 private int mFlags; 8829 } 8830 8831 private final class ServiceIntentResolver 8832 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 8833 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8834 boolean defaultOnly, int userId) { 8835 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8836 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8837 } 8838 8839 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8840 int userId) { 8841 if (!sUserManager.exists(userId)) return null; 8842 mFlags = flags; 8843 return super.queryIntent(intent, resolvedType, 8844 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8845 } 8846 8847 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8848 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 8849 if (!sUserManager.exists(userId)) return null; 8850 if (packageServices == null) { 8851 return null; 8852 } 8853 mFlags = flags; 8854 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8855 final int N = packageServices.size(); 8856 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 8857 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 8858 8859 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 8860 for (int i = 0; i < N; ++i) { 8861 intentFilters = packageServices.get(i).intents; 8862 if (intentFilters != null && intentFilters.size() > 0) { 8863 PackageParser.ServiceIntentInfo[] array = 8864 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 8865 intentFilters.toArray(array); 8866 listCut.add(array); 8867 } 8868 } 8869 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8870 } 8871 8872 public final void addService(PackageParser.Service s) { 8873 mServices.put(s.getComponentName(), s); 8874 if (DEBUG_SHOW_INFO) { 8875 Log.v(TAG, " " 8876 + (s.info.nonLocalizedLabel != null 8877 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8878 Log.v(TAG, " Class=" + s.info.name); 8879 } 8880 final int NI = s.intents.size(); 8881 int j; 8882 for (j=0; j<NI; j++) { 8883 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8884 if (DEBUG_SHOW_INFO) { 8885 Log.v(TAG, " IntentFilter:"); 8886 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8887 } 8888 if (!intent.debugCheck()) { 8889 Log.w(TAG, "==> For Service " + s.info.name); 8890 } 8891 addFilter(intent); 8892 } 8893 } 8894 8895 public final void removeService(PackageParser.Service s) { 8896 mServices.remove(s.getComponentName()); 8897 if (DEBUG_SHOW_INFO) { 8898 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 8899 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8900 Log.v(TAG, " Class=" + s.info.name); 8901 } 8902 final int NI = s.intents.size(); 8903 int j; 8904 for (j=0; j<NI; j++) { 8905 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8906 if (DEBUG_SHOW_INFO) { 8907 Log.v(TAG, " IntentFilter:"); 8908 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8909 } 8910 removeFilter(intent); 8911 } 8912 } 8913 8914 @Override 8915 protected boolean allowFilterResult( 8916 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 8917 ServiceInfo filterSi = filter.service.info; 8918 for (int i=dest.size()-1; i>=0; i--) { 8919 ServiceInfo destAi = dest.get(i).serviceInfo; 8920 if (destAi.name == filterSi.name 8921 && destAi.packageName == filterSi.packageName) { 8922 return false; 8923 } 8924 } 8925 return true; 8926 } 8927 8928 @Override 8929 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 8930 return new PackageParser.ServiceIntentInfo[size]; 8931 } 8932 8933 @Override 8934 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 8935 if (!sUserManager.exists(userId)) return true; 8936 PackageParser.Package p = filter.service.owner; 8937 if (p != null) { 8938 PackageSetting ps = (PackageSetting)p.mExtras; 8939 if (ps != null) { 8940 // System apps are never considered stopped for purposes of 8941 // filtering, because there may be no way for the user to 8942 // actually re-launch them. 8943 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8944 && ps.getStopped(userId); 8945 } 8946 } 8947 return false; 8948 } 8949 8950 @Override 8951 protected boolean isPackageForFilter(String packageName, 8952 PackageParser.ServiceIntentInfo info) { 8953 return packageName.equals(info.service.owner.packageName); 8954 } 8955 8956 @Override 8957 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 8958 int match, int userId) { 8959 if (!sUserManager.exists(userId)) return null; 8960 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 8961 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 8962 return null; 8963 } 8964 final PackageParser.Service service = info.service; 8965 if (mSafeMode && (service.info.applicationInfo.flags 8966 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8967 return null; 8968 } 8969 PackageSetting ps = (PackageSetting) service.owner.mExtras; 8970 if (ps == null) { 8971 return null; 8972 } 8973 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 8974 ps.readUserState(userId), userId); 8975 if (si == null) { 8976 return null; 8977 } 8978 final ResolveInfo res = new ResolveInfo(); 8979 res.serviceInfo = si; 8980 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8981 res.filter = filter; 8982 } 8983 res.priority = info.getPriority(); 8984 res.preferredOrder = service.owner.mPreferredOrder; 8985 res.match = match; 8986 res.isDefault = info.hasDefault; 8987 res.labelRes = info.labelRes; 8988 res.nonLocalizedLabel = info.nonLocalizedLabel; 8989 res.icon = info.icon; 8990 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 8991 return res; 8992 } 8993 8994 @Override 8995 protected void sortResults(List<ResolveInfo> results) { 8996 Collections.sort(results, mResolvePrioritySorter); 8997 } 8998 8999 @Override 9000 protected void dumpFilter(PrintWriter out, String prefix, 9001 PackageParser.ServiceIntentInfo filter) { 9002 out.print(prefix); out.print( 9003 Integer.toHexString(System.identityHashCode(filter.service))); 9004 out.print(' '); 9005 filter.service.printComponentShortName(out); 9006 out.print(" filter "); 9007 out.println(Integer.toHexString(System.identityHashCode(filter))); 9008 } 9009 9010 @Override 9011 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 9012 return filter.service; 9013 } 9014 9015 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9016 PackageParser.Service service = (PackageParser.Service)label; 9017 out.print(prefix); out.print( 9018 Integer.toHexString(System.identityHashCode(service))); 9019 out.print(' '); 9020 service.printComponentShortName(out); 9021 if (count > 1) { 9022 out.print(" ("); out.print(count); out.print(" filters)"); 9023 } 9024 out.println(); 9025 } 9026 9027// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9028// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9029// final List<ResolveInfo> retList = Lists.newArrayList(); 9030// while (i.hasNext()) { 9031// final ResolveInfo resolveInfo = (ResolveInfo) i; 9032// if (isEnabledLP(resolveInfo.serviceInfo)) { 9033// retList.add(resolveInfo); 9034// } 9035// } 9036// return retList; 9037// } 9038 9039 // Keys are String (activity class name), values are Activity. 9040 private final ArrayMap<ComponentName, PackageParser.Service> mServices 9041 = new ArrayMap<ComponentName, PackageParser.Service>(); 9042 private int mFlags; 9043 }; 9044 9045 private final class ProviderIntentResolver 9046 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 9047 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9048 boolean defaultOnly, int userId) { 9049 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9050 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9051 } 9052 9053 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9054 int userId) { 9055 if (!sUserManager.exists(userId)) 9056 return null; 9057 mFlags = flags; 9058 return super.queryIntent(intent, resolvedType, 9059 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9060 } 9061 9062 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9063 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 9064 if (!sUserManager.exists(userId)) 9065 return null; 9066 if (packageProviders == null) { 9067 return null; 9068 } 9069 mFlags = flags; 9070 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 9071 final int N = packageProviders.size(); 9072 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 9073 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 9074 9075 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 9076 for (int i = 0; i < N; ++i) { 9077 intentFilters = packageProviders.get(i).intents; 9078 if (intentFilters != null && intentFilters.size() > 0) { 9079 PackageParser.ProviderIntentInfo[] array = 9080 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 9081 intentFilters.toArray(array); 9082 listCut.add(array); 9083 } 9084 } 9085 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9086 } 9087 9088 public final void addProvider(PackageParser.Provider p) { 9089 if (mProviders.containsKey(p.getComponentName())) { 9090 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 9091 return; 9092 } 9093 9094 mProviders.put(p.getComponentName(), p); 9095 if (DEBUG_SHOW_INFO) { 9096 Log.v(TAG, " " 9097 + (p.info.nonLocalizedLabel != null 9098 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9099 Log.v(TAG, " Class=" + p.info.name); 9100 } 9101 final int NI = p.intents.size(); 9102 int j; 9103 for (j = 0; j < NI; j++) { 9104 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9105 if (DEBUG_SHOW_INFO) { 9106 Log.v(TAG, " IntentFilter:"); 9107 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9108 } 9109 if (!intent.debugCheck()) { 9110 Log.w(TAG, "==> For Provider " + p.info.name); 9111 } 9112 addFilter(intent); 9113 } 9114 } 9115 9116 public final void removeProvider(PackageParser.Provider p) { 9117 mProviders.remove(p.getComponentName()); 9118 if (DEBUG_SHOW_INFO) { 9119 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 9120 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9121 Log.v(TAG, " Class=" + p.info.name); 9122 } 9123 final int NI = p.intents.size(); 9124 int j; 9125 for (j = 0; j < NI; j++) { 9126 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9127 if (DEBUG_SHOW_INFO) { 9128 Log.v(TAG, " IntentFilter:"); 9129 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9130 } 9131 removeFilter(intent); 9132 } 9133 } 9134 9135 @Override 9136 protected boolean allowFilterResult( 9137 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 9138 ProviderInfo filterPi = filter.provider.info; 9139 for (int i = dest.size() - 1; i >= 0; i--) { 9140 ProviderInfo destPi = dest.get(i).providerInfo; 9141 if (destPi.name == filterPi.name 9142 && destPi.packageName == filterPi.packageName) { 9143 return false; 9144 } 9145 } 9146 return true; 9147 } 9148 9149 @Override 9150 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 9151 return new PackageParser.ProviderIntentInfo[size]; 9152 } 9153 9154 @Override 9155 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 9156 if (!sUserManager.exists(userId)) 9157 return true; 9158 PackageParser.Package p = filter.provider.owner; 9159 if (p != null) { 9160 PackageSetting ps = (PackageSetting) p.mExtras; 9161 if (ps != null) { 9162 // System apps are never considered stopped for purposes of 9163 // filtering, because there may be no way for the user to 9164 // actually re-launch them. 9165 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9166 && ps.getStopped(userId); 9167 } 9168 } 9169 return false; 9170 } 9171 9172 @Override 9173 protected boolean isPackageForFilter(String packageName, 9174 PackageParser.ProviderIntentInfo info) { 9175 return packageName.equals(info.provider.owner.packageName); 9176 } 9177 9178 @Override 9179 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 9180 int match, int userId) { 9181 if (!sUserManager.exists(userId)) 9182 return null; 9183 final PackageParser.ProviderIntentInfo info = filter; 9184 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 9185 return null; 9186 } 9187 final PackageParser.Provider provider = info.provider; 9188 if (mSafeMode && (provider.info.applicationInfo.flags 9189 & ApplicationInfo.FLAG_SYSTEM) == 0) { 9190 return null; 9191 } 9192 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 9193 if (ps == null) { 9194 return null; 9195 } 9196 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 9197 ps.readUserState(userId), userId); 9198 if (pi == null) { 9199 return null; 9200 } 9201 final ResolveInfo res = new ResolveInfo(); 9202 res.providerInfo = pi; 9203 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 9204 res.filter = filter; 9205 } 9206 res.priority = info.getPriority(); 9207 res.preferredOrder = provider.owner.mPreferredOrder; 9208 res.match = match; 9209 res.isDefault = info.hasDefault; 9210 res.labelRes = info.labelRes; 9211 res.nonLocalizedLabel = info.nonLocalizedLabel; 9212 res.icon = info.icon; 9213 res.system = res.providerInfo.applicationInfo.isSystemApp(); 9214 return res; 9215 } 9216 9217 @Override 9218 protected void sortResults(List<ResolveInfo> results) { 9219 Collections.sort(results, mResolvePrioritySorter); 9220 } 9221 9222 @Override 9223 protected void dumpFilter(PrintWriter out, String prefix, 9224 PackageParser.ProviderIntentInfo filter) { 9225 out.print(prefix); 9226 out.print( 9227 Integer.toHexString(System.identityHashCode(filter.provider))); 9228 out.print(' '); 9229 filter.provider.printComponentShortName(out); 9230 out.print(" filter "); 9231 out.println(Integer.toHexString(System.identityHashCode(filter))); 9232 } 9233 9234 @Override 9235 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 9236 return filter.provider; 9237 } 9238 9239 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9240 PackageParser.Provider provider = (PackageParser.Provider)label; 9241 out.print(prefix); out.print( 9242 Integer.toHexString(System.identityHashCode(provider))); 9243 out.print(' '); 9244 provider.printComponentShortName(out); 9245 if (count > 1) { 9246 out.print(" ("); out.print(count); out.print(" filters)"); 9247 } 9248 out.println(); 9249 } 9250 9251 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 9252 = new ArrayMap<ComponentName, PackageParser.Provider>(); 9253 private int mFlags; 9254 }; 9255 9256 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 9257 new Comparator<ResolveInfo>() { 9258 public int compare(ResolveInfo r1, ResolveInfo r2) { 9259 int v1 = r1.priority; 9260 int v2 = r2.priority; 9261 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 9262 if (v1 != v2) { 9263 return (v1 > v2) ? -1 : 1; 9264 } 9265 v1 = r1.preferredOrder; 9266 v2 = r2.preferredOrder; 9267 if (v1 != v2) { 9268 return (v1 > v2) ? -1 : 1; 9269 } 9270 if (r1.isDefault != r2.isDefault) { 9271 return r1.isDefault ? -1 : 1; 9272 } 9273 v1 = r1.match; 9274 v2 = r2.match; 9275 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 9276 if (v1 != v2) { 9277 return (v1 > v2) ? -1 : 1; 9278 } 9279 if (r1.system != r2.system) { 9280 return r1.system ? -1 : 1; 9281 } 9282 return 0; 9283 } 9284 }; 9285 9286 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 9287 new Comparator<ProviderInfo>() { 9288 public int compare(ProviderInfo p1, ProviderInfo p2) { 9289 final int v1 = p1.initOrder; 9290 final int v2 = p2.initOrder; 9291 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 9292 } 9293 }; 9294 9295 final void sendPackageBroadcast(final String action, final String pkg, 9296 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 9297 final int[] userIds) { 9298 mHandler.post(new Runnable() { 9299 @Override 9300 public void run() { 9301 try { 9302 final IActivityManager am = ActivityManagerNative.getDefault(); 9303 if (am == null) return; 9304 final int[] resolvedUserIds; 9305 if (userIds == null) { 9306 resolvedUserIds = am.getRunningUserIds(); 9307 } else { 9308 resolvedUserIds = userIds; 9309 } 9310 for (int id : resolvedUserIds) { 9311 final Intent intent = new Intent(action, 9312 pkg != null ? Uri.fromParts("package", pkg, null) : null); 9313 if (extras != null) { 9314 intent.putExtras(extras); 9315 } 9316 if (targetPkg != null) { 9317 intent.setPackage(targetPkg); 9318 } 9319 // Modify the UID when posting to other users 9320 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 9321 if (uid > 0 && UserHandle.getUserId(uid) != id) { 9322 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 9323 intent.putExtra(Intent.EXTRA_UID, uid); 9324 } 9325 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 9326 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 9327 if (DEBUG_BROADCASTS) { 9328 RuntimeException here = new RuntimeException("here"); 9329 here.fillInStackTrace(); 9330 Slog.d(TAG, "Sending to user " + id + ": " 9331 + intent.toShortString(false, true, false, false) 9332 + " " + intent.getExtras(), here); 9333 } 9334 am.broadcastIntent(null, intent, null, finishedReceiver, 9335 0, null, null, null, android.app.AppOpsManager.OP_NONE, 9336 null, finishedReceiver != null, false, id); 9337 } 9338 } catch (RemoteException ex) { 9339 } 9340 } 9341 }); 9342 } 9343 9344 /** 9345 * Check if the external storage media is available. This is true if there 9346 * is a mounted external storage medium or if the external storage is 9347 * emulated. 9348 */ 9349 private boolean isExternalMediaAvailable() { 9350 return mMediaMounted || Environment.isExternalStorageEmulated(); 9351 } 9352 9353 @Override 9354 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 9355 // writer 9356 synchronized (mPackages) { 9357 if (!isExternalMediaAvailable()) { 9358 // If the external storage is no longer mounted at this point, 9359 // the caller may not have been able to delete all of this 9360 // packages files and can not delete any more. Bail. 9361 return null; 9362 } 9363 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 9364 if (lastPackage != null) { 9365 pkgs.remove(lastPackage); 9366 } 9367 if (pkgs.size() > 0) { 9368 return pkgs.get(0); 9369 } 9370 } 9371 return null; 9372 } 9373 9374 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 9375 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 9376 userId, andCode ? 1 : 0, packageName); 9377 if (mSystemReady) { 9378 msg.sendToTarget(); 9379 } else { 9380 if (mPostSystemReadyMessages == null) { 9381 mPostSystemReadyMessages = new ArrayList<>(); 9382 } 9383 mPostSystemReadyMessages.add(msg); 9384 } 9385 } 9386 9387 void startCleaningPackages() { 9388 // reader 9389 synchronized (mPackages) { 9390 if (!isExternalMediaAvailable()) { 9391 return; 9392 } 9393 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 9394 return; 9395 } 9396 } 9397 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 9398 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 9399 IActivityManager am = ActivityManagerNative.getDefault(); 9400 if (am != null) { 9401 try { 9402 am.startService(null, intent, null, mContext.getOpPackageName(), 9403 UserHandle.USER_OWNER); 9404 } catch (RemoteException e) { 9405 } 9406 } 9407 } 9408 9409 @Override 9410 public void installPackage(String originPath, IPackageInstallObserver2 observer, 9411 int installFlags, String installerPackageName, VerificationParams verificationParams, 9412 String packageAbiOverride) { 9413 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 9414 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 9415 } 9416 9417 @Override 9418 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 9419 int installFlags, String installerPackageName, VerificationParams verificationParams, 9420 String packageAbiOverride, int userId) { 9421 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 9422 9423 final int callingUid = Binder.getCallingUid(); 9424 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 9425 9426 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9427 try { 9428 if (observer != null) { 9429 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 9430 } 9431 } catch (RemoteException re) { 9432 } 9433 return; 9434 } 9435 9436 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 9437 installFlags |= PackageManager.INSTALL_FROM_ADB; 9438 9439 } else { 9440 // Caller holds INSTALL_PACKAGES permission, so we're less strict 9441 // about installerPackageName. 9442 9443 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 9444 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 9445 } 9446 9447 UserHandle user; 9448 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 9449 user = UserHandle.ALL; 9450 } else { 9451 user = new UserHandle(userId); 9452 } 9453 9454 // Only system components can circumvent runtime permissions when installing. 9455 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 9456 && mContext.checkCallingOrSelfPermission(Manifest.permission 9457 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 9458 throw new SecurityException("You need the " 9459 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 9460 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 9461 } 9462 9463 verificationParams.setInstallerUid(callingUid); 9464 9465 final File originFile = new File(originPath); 9466 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 9467 9468 final Message msg = mHandler.obtainMessage(INIT_COPY); 9469 msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName, 9470 null, verificationParams, user, packageAbiOverride, null); 9471 mHandler.sendMessage(msg); 9472 } 9473 9474 void installStage(String packageName, File stagedDir, String stagedCid, 9475 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 9476 String installerPackageName, int installerUid, UserHandle user) { 9477 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 9478 params.referrerUri, installerUid, null); 9479 verifParams.setInstallerUid(installerUid); 9480 9481 final OriginInfo origin; 9482 if (stagedDir != null) { 9483 origin = OriginInfo.fromStagedFile(stagedDir); 9484 } else { 9485 origin = OriginInfo.fromStagedContainer(stagedCid); 9486 } 9487 9488 final Message msg = mHandler.obtainMessage(INIT_COPY); 9489 msg.obj = new InstallParams(origin, null, observer, params.installFlags, 9490 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride, 9491 params.grantedRuntimePermissions); 9492 mHandler.sendMessage(msg); 9493 } 9494 9495 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 9496 Bundle extras = new Bundle(1); 9497 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 9498 9499 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 9500 packageName, extras, null, null, new int[] {userId}); 9501 try { 9502 IActivityManager am = ActivityManagerNative.getDefault(); 9503 final boolean isSystem = 9504 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 9505 if (isSystem && am.isUserRunning(userId, false)) { 9506 // The just-installed/enabled app is bundled on the system, so presumed 9507 // to be able to run automatically without needing an explicit launch. 9508 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 9509 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 9510 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 9511 .setPackage(packageName); 9512 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 9513 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 9514 } 9515 } catch (RemoteException e) { 9516 // shouldn't happen 9517 Slog.w(TAG, "Unable to bootstrap installed package", e); 9518 } 9519 } 9520 9521 @Override 9522 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 9523 int userId) { 9524 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9525 PackageSetting pkgSetting; 9526 final int uid = Binder.getCallingUid(); 9527 enforceCrossUserPermission(uid, userId, true, true, 9528 "setApplicationHiddenSetting for user " + userId); 9529 9530 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 9531 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 9532 return false; 9533 } 9534 9535 long callingId = Binder.clearCallingIdentity(); 9536 try { 9537 boolean sendAdded = false; 9538 boolean sendRemoved = false; 9539 // writer 9540 synchronized (mPackages) { 9541 pkgSetting = mSettings.mPackages.get(packageName); 9542 if (pkgSetting == null) { 9543 return false; 9544 } 9545 if (pkgSetting.getHidden(userId) != hidden) { 9546 pkgSetting.setHidden(hidden, userId); 9547 mSettings.writePackageRestrictionsLPr(userId); 9548 if (hidden) { 9549 sendRemoved = true; 9550 } else { 9551 sendAdded = true; 9552 } 9553 } 9554 } 9555 if (sendAdded) { 9556 sendPackageAddedForUser(packageName, pkgSetting, userId); 9557 return true; 9558 } 9559 if (sendRemoved) { 9560 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 9561 "hiding pkg"); 9562 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 9563 } 9564 } finally { 9565 Binder.restoreCallingIdentity(callingId); 9566 } 9567 return false; 9568 } 9569 9570 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 9571 int userId) { 9572 final PackageRemovedInfo info = new PackageRemovedInfo(); 9573 info.removedPackage = packageName; 9574 info.removedUsers = new int[] {userId}; 9575 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 9576 info.sendBroadcast(false, false, false); 9577 } 9578 9579 /** 9580 * Returns true if application is not found or there was an error. Otherwise it returns 9581 * the hidden state of the package for the given user. 9582 */ 9583 @Override 9584 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 9585 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9586 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 9587 false, "getApplicationHidden for user " + userId); 9588 PackageSetting pkgSetting; 9589 long callingId = Binder.clearCallingIdentity(); 9590 try { 9591 // writer 9592 synchronized (mPackages) { 9593 pkgSetting = mSettings.mPackages.get(packageName); 9594 if (pkgSetting == null) { 9595 return true; 9596 } 9597 return pkgSetting.getHidden(userId); 9598 } 9599 } finally { 9600 Binder.restoreCallingIdentity(callingId); 9601 } 9602 } 9603 9604 /** 9605 * @hide 9606 */ 9607 @Override 9608 public int installExistingPackageAsUser(String packageName, int userId) { 9609 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 9610 null); 9611 PackageSetting pkgSetting; 9612 final int uid = Binder.getCallingUid(); 9613 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 9614 + userId); 9615 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9616 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 9617 } 9618 9619 long callingId = Binder.clearCallingIdentity(); 9620 try { 9621 boolean sendAdded = false; 9622 9623 // writer 9624 synchronized (mPackages) { 9625 pkgSetting = mSettings.mPackages.get(packageName); 9626 if (pkgSetting == null) { 9627 return PackageManager.INSTALL_FAILED_INVALID_URI; 9628 } 9629 if (!pkgSetting.getInstalled(userId)) { 9630 pkgSetting.setInstalled(true, userId); 9631 pkgSetting.setHidden(false, userId); 9632 mSettings.writePackageRestrictionsLPr(userId); 9633 sendAdded = true; 9634 } 9635 } 9636 9637 if (sendAdded) { 9638 sendPackageAddedForUser(packageName, pkgSetting, userId); 9639 } 9640 } finally { 9641 Binder.restoreCallingIdentity(callingId); 9642 } 9643 9644 return PackageManager.INSTALL_SUCCEEDED; 9645 } 9646 9647 boolean isUserRestricted(int userId, String restrictionKey) { 9648 Bundle restrictions = sUserManager.getUserRestrictions(userId); 9649 if (restrictions.getBoolean(restrictionKey, false)) { 9650 Log.w(TAG, "User is restricted: " + restrictionKey); 9651 return true; 9652 } 9653 return false; 9654 } 9655 9656 @Override 9657 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 9658 mContext.enforceCallingOrSelfPermission( 9659 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9660 "Only package verification agents can verify applications"); 9661 9662 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9663 final PackageVerificationResponse response = new PackageVerificationResponse( 9664 verificationCode, Binder.getCallingUid()); 9665 msg.arg1 = id; 9666 msg.obj = response; 9667 mHandler.sendMessage(msg); 9668 } 9669 9670 @Override 9671 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 9672 long millisecondsToDelay) { 9673 mContext.enforceCallingOrSelfPermission( 9674 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9675 "Only package verification agents can extend verification timeouts"); 9676 9677 final PackageVerificationState state = mPendingVerification.get(id); 9678 final PackageVerificationResponse response = new PackageVerificationResponse( 9679 verificationCodeAtTimeout, Binder.getCallingUid()); 9680 9681 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 9682 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 9683 } 9684 if (millisecondsToDelay < 0) { 9685 millisecondsToDelay = 0; 9686 } 9687 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 9688 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 9689 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 9690 } 9691 9692 if ((state != null) && !state.timeoutExtended()) { 9693 state.extendTimeout(); 9694 9695 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9696 msg.arg1 = id; 9697 msg.obj = response; 9698 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 9699 } 9700 } 9701 9702 private void broadcastPackageVerified(int verificationId, Uri packageUri, 9703 int verificationCode, UserHandle user) { 9704 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 9705 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 9706 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9707 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9708 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 9709 9710 mContext.sendBroadcastAsUser(intent, user, 9711 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 9712 } 9713 9714 private ComponentName matchComponentForVerifier(String packageName, 9715 List<ResolveInfo> receivers) { 9716 ActivityInfo targetReceiver = null; 9717 9718 final int NR = receivers.size(); 9719 for (int i = 0; i < NR; i++) { 9720 final ResolveInfo info = receivers.get(i); 9721 if (info.activityInfo == null) { 9722 continue; 9723 } 9724 9725 if (packageName.equals(info.activityInfo.packageName)) { 9726 targetReceiver = info.activityInfo; 9727 break; 9728 } 9729 } 9730 9731 if (targetReceiver == null) { 9732 return null; 9733 } 9734 9735 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 9736 } 9737 9738 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 9739 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 9740 if (pkgInfo.verifiers.length == 0) { 9741 return null; 9742 } 9743 9744 final int N = pkgInfo.verifiers.length; 9745 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 9746 for (int i = 0; i < N; i++) { 9747 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 9748 9749 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 9750 receivers); 9751 if (comp == null) { 9752 continue; 9753 } 9754 9755 final int verifierUid = getUidForVerifier(verifierInfo); 9756 if (verifierUid == -1) { 9757 continue; 9758 } 9759 9760 if (DEBUG_VERIFY) { 9761 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 9762 + " with the correct signature"); 9763 } 9764 sufficientVerifiers.add(comp); 9765 verificationState.addSufficientVerifier(verifierUid); 9766 } 9767 9768 return sufficientVerifiers; 9769 } 9770 9771 private int getUidForVerifier(VerifierInfo verifierInfo) { 9772 synchronized (mPackages) { 9773 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 9774 if (pkg == null) { 9775 return -1; 9776 } else if (pkg.mSignatures.length != 1) { 9777 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9778 + " has more than one signature; ignoring"); 9779 return -1; 9780 } 9781 9782 /* 9783 * If the public key of the package's signature does not match 9784 * our expected public key, then this is a different package and 9785 * we should skip. 9786 */ 9787 9788 final byte[] expectedPublicKey; 9789 try { 9790 final Signature verifierSig = pkg.mSignatures[0]; 9791 final PublicKey publicKey = verifierSig.getPublicKey(); 9792 expectedPublicKey = publicKey.getEncoded(); 9793 } catch (CertificateException e) { 9794 return -1; 9795 } 9796 9797 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 9798 9799 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 9800 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9801 + " does not have the expected public key; ignoring"); 9802 return -1; 9803 } 9804 9805 return pkg.applicationInfo.uid; 9806 } 9807 } 9808 9809 @Override 9810 public void finishPackageInstall(int token) { 9811 enforceSystemOrRoot("Only the system is allowed to finish installs"); 9812 9813 if (DEBUG_INSTALL) { 9814 Slog.v(TAG, "BM finishing package install for " + token); 9815 } 9816 9817 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9818 mHandler.sendMessage(msg); 9819 } 9820 9821 /** 9822 * Get the verification agent timeout. 9823 * 9824 * @return verification timeout in milliseconds 9825 */ 9826 private long getVerificationTimeout() { 9827 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 9828 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 9829 DEFAULT_VERIFICATION_TIMEOUT); 9830 } 9831 9832 /** 9833 * Get the default verification agent response code. 9834 * 9835 * @return default verification response code 9836 */ 9837 private int getDefaultVerificationResponse() { 9838 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9839 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 9840 DEFAULT_VERIFICATION_RESPONSE); 9841 } 9842 9843 /** 9844 * Check whether or not package verification has been enabled. 9845 * 9846 * @return true if verification should be performed 9847 */ 9848 private boolean isVerificationEnabled(int userId, int installFlags) { 9849 if (!DEFAULT_VERIFY_ENABLE) { 9850 return false; 9851 } 9852 9853 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 9854 9855 // Check if installing from ADB 9856 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 9857 // Do not run verification in a test harness environment 9858 if (ActivityManager.isRunningInTestHarness()) { 9859 return false; 9860 } 9861 if (ensureVerifyAppsEnabled) { 9862 return true; 9863 } 9864 // Check if the developer does not want package verification for ADB installs 9865 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9866 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 9867 return false; 9868 } 9869 } 9870 9871 if (ensureVerifyAppsEnabled) { 9872 return true; 9873 } 9874 9875 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9876 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 9877 } 9878 9879 @Override 9880 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 9881 throws RemoteException { 9882 mContext.enforceCallingOrSelfPermission( 9883 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 9884 "Only intentfilter verification agents can verify applications"); 9885 9886 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 9887 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 9888 Binder.getCallingUid(), verificationCode, failedDomains); 9889 msg.arg1 = id; 9890 msg.obj = response; 9891 mHandler.sendMessage(msg); 9892 } 9893 9894 @Override 9895 public int getIntentVerificationStatus(String packageName, int userId) { 9896 synchronized (mPackages) { 9897 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 9898 } 9899 } 9900 9901 @Override 9902 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 9903 mContext.enforceCallingOrSelfPermission( 9904 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 9905 9906 boolean result = false; 9907 synchronized (mPackages) { 9908 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 9909 } 9910 if (result) { 9911 scheduleWritePackageRestrictionsLocked(userId); 9912 } 9913 return result; 9914 } 9915 9916 @Override 9917 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 9918 synchronized (mPackages) { 9919 return mSettings.getIntentFilterVerificationsLPr(packageName); 9920 } 9921 } 9922 9923 @Override 9924 public List<IntentFilter> getAllIntentFilters(String packageName) { 9925 if (TextUtils.isEmpty(packageName)) { 9926 return Collections.<IntentFilter>emptyList(); 9927 } 9928 synchronized (mPackages) { 9929 PackageParser.Package pkg = mPackages.get(packageName); 9930 if (pkg == null || pkg.activities == null) { 9931 return Collections.<IntentFilter>emptyList(); 9932 } 9933 final int count = pkg.activities.size(); 9934 ArrayList<IntentFilter> result = new ArrayList<>(); 9935 for (int n=0; n<count; n++) { 9936 PackageParser.Activity activity = pkg.activities.get(n); 9937 if (activity.intents != null || activity.intents.size() > 0) { 9938 result.addAll(activity.intents); 9939 } 9940 } 9941 return result; 9942 } 9943 } 9944 9945 @Override 9946 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 9947 mContext.enforceCallingOrSelfPermission( 9948 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 9949 9950 synchronized (mPackages) { 9951 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 9952 if (packageName != null) { 9953 result |= updateIntentVerificationStatus(packageName, 9954 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 9955 userId); 9956 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 9957 packageName, userId); 9958 } 9959 return result; 9960 } 9961 } 9962 9963 @Override 9964 public String getDefaultBrowserPackageName(int userId) { 9965 synchronized (mPackages) { 9966 return mSettings.getDefaultBrowserPackageNameLPw(userId); 9967 } 9968 } 9969 9970 /** 9971 * Get the "allow unknown sources" setting. 9972 * 9973 * @return the current "allow unknown sources" setting 9974 */ 9975 private int getUnknownSourcesSettings() { 9976 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9977 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 9978 -1); 9979 } 9980 9981 @Override 9982 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 9983 final int uid = Binder.getCallingUid(); 9984 // writer 9985 synchronized (mPackages) { 9986 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 9987 if (targetPackageSetting == null) { 9988 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 9989 } 9990 9991 PackageSetting installerPackageSetting; 9992 if (installerPackageName != null) { 9993 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 9994 if (installerPackageSetting == null) { 9995 throw new IllegalArgumentException("Unknown installer package: " 9996 + installerPackageName); 9997 } 9998 } else { 9999 installerPackageSetting = null; 10000 } 10001 10002 Signature[] callerSignature; 10003 Object obj = mSettings.getUserIdLPr(uid); 10004 if (obj != null) { 10005 if (obj instanceof SharedUserSetting) { 10006 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 10007 } else if (obj instanceof PackageSetting) { 10008 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 10009 } else { 10010 throw new SecurityException("Bad object " + obj + " for uid " + uid); 10011 } 10012 } else { 10013 throw new SecurityException("Unknown calling uid " + uid); 10014 } 10015 10016 // Verify: can't set installerPackageName to a package that is 10017 // not signed with the same cert as the caller. 10018 if (installerPackageSetting != null) { 10019 if (compareSignatures(callerSignature, 10020 installerPackageSetting.signatures.mSignatures) 10021 != PackageManager.SIGNATURE_MATCH) { 10022 throw new SecurityException( 10023 "Caller does not have same cert as new installer package " 10024 + installerPackageName); 10025 } 10026 } 10027 10028 // Verify: if target already has an installer package, it must 10029 // be signed with the same cert as the caller. 10030 if (targetPackageSetting.installerPackageName != null) { 10031 PackageSetting setting = mSettings.mPackages.get( 10032 targetPackageSetting.installerPackageName); 10033 // If the currently set package isn't valid, then it's always 10034 // okay to change it. 10035 if (setting != null) { 10036 if (compareSignatures(callerSignature, 10037 setting.signatures.mSignatures) 10038 != PackageManager.SIGNATURE_MATCH) { 10039 throw new SecurityException( 10040 "Caller does not have same cert as old installer package " 10041 + targetPackageSetting.installerPackageName); 10042 } 10043 } 10044 } 10045 10046 // Okay! 10047 targetPackageSetting.installerPackageName = installerPackageName; 10048 scheduleWriteSettingsLocked(); 10049 } 10050 } 10051 10052 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 10053 // Queue up an async operation since the package installation may take a little while. 10054 mHandler.post(new Runnable() { 10055 public void run() { 10056 mHandler.removeCallbacks(this); 10057 // Result object to be returned 10058 PackageInstalledInfo res = new PackageInstalledInfo(); 10059 res.returnCode = currentStatus; 10060 res.uid = -1; 10061 res.pkg = null; 10062 res.removedInfo = new PackageRemovedInfo(); 10063 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10064 args.doPreInstall(res.returnCode); 10065 synchronized (mInstallLock) { 10066 installPackageLI(args, res); 10067 } 10068 args.doPostInstall(res.returnCode, res.uid); 10069 } 10070 10071 // A restore should be performed at this point if (a) the install 10072 // succeeded, (b) the operation is not an update, and (c) the new 10073 // package has not opted out of backup participation. 10074 final boolean update = res.removedInfo.removedPackage != null; 10075 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 10076 boolean doRestore = !update 10077 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 10078 10079 // Set up the post-install work request bookkeeping. This will be used 10080 // and cleaned up by the post-install event handling regardless of whether 10081 // there's a restore pass performed. Token values are >= 1. 10082 int token; 10083 if (mNextInstallToken < 0) mNextInstallToken = 1; 10084 token = mNextInstallToken++; 10085 10086 PostInstallData data = new PostInstallData(args, res); 10087 mRunningInstalls.put(token, data); 10088 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 10089 10090 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 10091 // Pass responsibility to the Backup Manager. It will perform a 10092 // restore if appropriate, then pass responsibility back to the 10093 // Package Manager to run the post-install observer callbacks 10094 // and broadcasts. 10095 IBackupManager bm = IBackupManager.Stub.asInterface( 10096 ServiceManager.getService(Context.BACKUP_SERVICE)); 10097 if (bm != null) { 10098 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 10099 + " to BM for possible restore"); 10100 try { 10101 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 10102 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 10103 } else { 10104 doRestore = false; 10105 } 10106 } catch (RemoteException e) { 10107 // can't happen; the backup manager is local 10108 } catch (Exception e) { 10109 Slog.e(TAG, "Exception trying to enqueue restore", e); 10110 doRestore = false; 10111 } 10112 } else { 10113 Slog.e(TAG, "Backup Manager not found!"); 10114 doRestore = false; 10115 } 10116 } 10117 10118 if (!doRestore) { 10119 // No restore possible, or the Backup Manager was mysteriously not 10120 // available -- just fire the post-install work request directly. 10121 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 10122 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10123 mHandler.sendMessage(msg); 10124 } 10125 } 10126 }); 10127 } 10128 10129 private abstract class HandlerParams { 10130 private static final int MAX_RETRIES = 4; 10131 10132 /** 10133 * Number of times startCopy() has been attempted and had a non-fatal 10134 * error. 10135 */ 10136 private int mRetries = 0; 10137 10138 /** User handle for the user requesting the information or installation. */ 10139 private final UserHandle mUser; 10140 10141 HandlerParams(UserHandle user) { 10142 mUser = user; 10143 } 10144 10145 UserHandle getUser() { 10146 return mUser; 10147 } 10148 10149 final boolean startCopy() { 10150 boolean res; 10151 try { 10152 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 10153 10154 if (++mRetries > MAX_RETRIES) { 10155 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 10156 mHandler.sendEmptyMessage(MCS_GIVE_UP); 10157 handleServiceError(); 10158 return false; 10159 } else { 10160 handleStartCopy(); 10161 res = true; 10162 } 10163 } catch (RemoteException e) { 10164 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 10165 mHandler.sendEmptyMessage(MCS_RECONNECT); 10166 res = false; 10167 } 10168 handleReturnCode(); 10169 return res; 10170 } 10171 10172 final void serviceError() { 10173 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 10174 handleServiceError(); 10175 handleReturnCode(); 10176 } 10177 10178 abstract void handleStartCopy() throws RemoteException; 10179 abstract void handleServiceError(); 10180 abstract void handleReturnCode(); 10181 } 10182 10183 class MeasureParams extends HandlerParams { 10184 private final PackageStats mStats; 10185 private boolean mSuccess; 10186 10187 private final IPackageStatsObserver mObserver; 10188 10189 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 10190 super(new UserHandle(stats.userHandle)); 10191 mObserver = observer; 10192 mStats = stats; 10193 } 10194 10195 @Override 10196 public String toString() { 10197 return "MeasureParams{" 10198 + Integer.toHexString(System.identityHashCode(this)) 10199 + " " + mStats.packageName + "}"; 10200 } 10201 10202 @Override 10203 void handleStartCopy() throws RemoteException { 10204 synchronized (mInstallLock) { 10205 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 10206 } 10207 10208 if (mSuccess) { 10209 final boolean mounted; 10210 if (Environment.isExternalStorageEmulated()) { 10211 mounted = true; 10212 } else { 10213 final String status = Environment.getExternalStorageState(); 10214 mounted = (Environment.MEDIA_MOUNTED.equals(status) 10215 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 10216 } 10217 10218 if (mounted) { 10219 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 10220 10221 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 10222 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 10223 10224 mStats.externalDataSize = calculateDirectorySize(mContainerService, 10225 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 10226 10227 // Always subtract cache size, since it's a subdirectory 10228 mStats.externalDataSize -= mStats.externalCacheSize; 10229 10230 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 10231 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 10232 10233 mStats.externalObbSize = calculateDirectorySize(mContainerService, 10234 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 10235 } 10236 } 10237 } 10238 10239 @Override 10240 void handleReturnCode() { 10241 if (mObserver != null) { 10242 try { 10243 mObserver.onGetStatsCompleted(mStats, mSuccess); 10244 } catch (RemoteException e) { 10245 Slog.i(TAG, "Observer no longer exists."); 10246 } 10247 } 10248 } 10249 10250 @Override 10251 void handleServiceError() { 10252 Slog.e(TAG, "Could not measure application " + mStats.packageName 10253 + " external storage"); 10254 } 10255 } 10256 10257 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 10258 throws RemoteException { 10259 long result = 0; 10260 for (File path : paths) { 10261 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 10262 } 10263 return result; 10264 } 10265 10266 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 10267 for (File path : paths) { 10268 try { 10269 mcs.clearDirectory(path.getAbsolutePath()); 10270 } catch (RemoteException e) { 10271 } 10272 } 10273 } 10274 10275 static class OriginInfo { 10276 /** 10277 * Location where install is coming from, before it has been 10278 * copied/renamed into place. This could be a single monolithic APK 10279 * file, or a cluster directory. This location may be untrusted. 10280 */ 10281 final File file; 10282 final String cid; 10283 10284 /** 10285 * Flag indicating that {@link #file} or {@link #cid} has already been 10286 * staged, meaning downstream users don't need to defensively copy the 10287 * contents. 10288 */ 10289 final boolean staged; 10290 10291 /** 10292 * Flag indicating that {@link #file} or {@link #cid} is an already 10293 * installed app that is being moved. 10294 */ 10295 final boolean existing; 10296 10297 final String resolvedPath; 10298 final File resolvedFile; 10299 10300 static OriginInfo fromNothing() { 10301 return new OriginInfo(null, null, false, false); 10302 } 10303 10304 static OriginInfo fromUntrustedFile(File file) { 10305 return new OriginInfo(file, null, false, false); 10306 } 10307 10308 static OriginInfo fromExistingFile(File file) { 10309 return new OriginInfo(file, null, false, true); 10310 } 10311 10312 static OriginInfo fromStagedFile(File file) { 10313 return new OriginInfo(file, null, true, false); 10314 } 10315 10316 static OriginInfo fromStagedContainer(String cid) { 10317 return new OriginInfo(null, cid, true, false); 10318 } 10319 10320 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 10321 this.file = file; 10322 this.cid = cid; 10323 this.staged = staged; 10324 this.existing = existing; 10325 10326 if (cid != null) { 10327 resolvedPath = PackageHelper.getSdDir(cid); 10328 resolvedFile = new File(resolvedPath); 10329 } else if (file != null) { 10330 resolvedPath = file.getAbsolutePath(); 10331 resolvedFile = file; 10332 } else { 10333 resolvedPath = null; 10334 resolvedFile = null; 10335 } 10336 } 10337 } 10338 10339 class MoveInfo { 10340 final int moveId; 10341 final String fromUuid; 10342 final String toUuid; 10343 final String packageName; 10344 final String dataAppName; 10345 final int appId; 10346 final String seinfo; 10347 10348 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 10349 String dataAppName, int appId, String seinfo) { 10350 this.moveId = moveId; 10351 this.fromUuid = fromUuid; 10352 this.toUuid = toUuid; 10353 this.packageName = packageName; 10354 this.dataAppName = dataAppName; 10355 this.appId = appId; 10356 this.seinfo = seinfo; 10357 } 10358 } 10359 10360 class InstallParams extends HandlerParams { 10361 final OriginInfo origin; 10362 final MoveInfo move; 10363 final IPackageInstallObserver2 observer; 10364 int installFlags; 10365 final String installerPackageName; 10366 final String volumeUuid; 10367 final VerificationParams verificationParams; 10368 private InstallArgs mArgs; 10369 private int mRet; 10370 final String packageAbiOverride; 10371 final String[] grantedRuntimePermissions; 10372 10373 10374 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10375 int installFlags, String installerPackageName, String volumeUuid, 10376 VerificationParams verificationParams, UserHandle user, String packageAbiOverride, 10377 String[] grantedPermissions) { 10378 super(user); 10379 this.origin = origin; 10380 this.move = move; 10381 this.observer = observer; 10382 this.installFlags = installFlags; 10383 this.installerPackageName = installerPackageName; 10384 this.volumeUuid = volumeUuid; 10385 this.verificationParams = verificationParams; 10386 this.packageAbiOverride = packageAbiOverride; 10387 this.grantedRuntimePermissions = grantedPermissions; 10388 } 10389 10390 @Override 10391 public String toString() { 10392 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 10393 + " file=" + origin.file + " cid=" + origin.cid + "}"; 10394 } 10395 10396 public ManifestDigest getManifestDigest() { 10397 if (verificationParams == null) { 10398 return null; 10399 } 10400 return verificationParams.getManifestDigest(); 10401 } 10402 10403 private int installLocationPolicy(PackageInfoLite pkgLite) { 10404 String packageName = pkgLite.packageName; 10405 int installLocation = pkgLite.installLocation; 10406 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10407 // reader 10408 synchronized (mPackages) { 10409 PackageParser.Package pkg = mPackages.get(packageName); 10410 if (pkg != null) { 10411 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10412 // Check for downgrading. 10413 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 10414 try { 10415 checkDowngrade(pkg, pkgLite); 10416 } catch (PackageManagerException e) { 10417 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 10418 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 10419 } 10420 } 10421 // Check for updated system application. 10422 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10423 if (onSd) { 10424 Slog.w(TAG, "Cannot install update to system app on sdcard"); 10425 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 10426 } 10427 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10428 } else { 10429 if (onSd) { 10430 // Install flag overrides everything. 10431 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10432 } 10433 // If current upgrade specifies particular preference 10434 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 10435 // Application explicitly specified internal. 10436 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10437 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 10438 // App explictly prefers external. Let policy decide 10439 } else { 10440 // Prefer previous location 10441 if (isExternal(pkg)) { 10442 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10443 } 10444 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10445 } 10446 } 10447 } else { 10448 // Invalid install. Return error code 10449 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 10450 } 10451 } 10452 } 10453 // All the special cases have been taken care of. 10454 // Return result based on recommended install location. 10455 if (onSd) { 10456 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10457 } 10458 return pkgLite.recommendedInstallLocation; 10459 } 10460 10461 /* 10462 * Invoke remote method to get package information and install 10463 * location values. Override install location based on default 10464 * policy if needed and then create install arguments based 10465 * on the install location. 10466 */ 10467 public void handleStartCopy() throws RemoteException { 10468 int ret = PackageManager.INSTALL_SUCCEEDED; 10469 10470 // If we're already staged, we've firmly committed to an install location 10471 if (origin.staged) { 10472 if (origin.file != null) { 10473 installFlags |= PackageManager.INSTALL_INTERNAL; 10474 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10475 } else if (origin.cid != null) { 10476 installFlags |= PackageManager.INSTALL_EXTERNAL; 10477 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10478 } else { 10479 throw new IllegalStateException("Invalid stage location"); 10480 } 10481 } 10482 10483 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10484 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 10485 10486 PackageInfoLite pkgLite = null; 10487 10488 if (onInt && onSd) { 10489 // Check if both bits are set. 10490 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 10491 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10492 } else { 10493 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 10494 packageAbiOverride); 10495 10496 /* 10497 * If we have too little free space, try to free cache 10498 * before giving up. 10499 */ 10500 if (!origin.staged && pkgLite.recommendedInstallLocation 10501 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10502 // TODO: focus freeing disk space on the target device 10503 final StorageManager storage = StorageManager.from(mContext); 10504 final long lowThreshold = storage.getStorageLowBytes( 10505 Environment.getDataDirectory()); 10506 10507 final long sizeBytes = mContainerService.calculateInstalledSize( 10508 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 10509 10510 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 10511 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 10512 installFlags, packageAbiOverride); 10513 } 10514 10515 /* 10516 * The cache free must have deleted the file we 10517 * downloaded to install. 10518 * 10519 * TODO: fix the "freeCache" call to not delete 10520 * the file we care about. 10521 */ 10522 if (pkgLite.recommendedInstallLocation 10523 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10524 pkgLite.recommendedInstallLocation 10525 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 10526 } 10527 } 10528 } 10529 10530 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10531 int loc = pkgLite.recommendedInstallLocation; 10532 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 10533 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10534 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 10535 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 10536 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10537 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10538 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 10539 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 10540 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10541 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 10542 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 10543 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 10544 } else { 10545 // Override with defaults if needed. 10546 loc = installLocationPolicy(pkgLite); 10547 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 10548 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 10549 } else if (!onSd && !onInt) { 10550 // Override install location with flags 10551 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 10552 // Set the flag to install on external media. 10553 installFlags |= PackageManager.INSTALL_EXTERNAL; 10554 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10555 } else { 10556 // Make sure the flag for installing on external 10557 // media is unset 10558 installFlags |= PackageManager.INSTALL_INTERNAL; 10559 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10560 } 10561 } 10562 } 10563 } 10564 10565 final InstallArgs args = createInstallArgs(this); 10566 mArgs = args; 10567 10568 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10569 /* 10570 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 10571 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 10572 */ 10573 int userIdentifier = getUser().getIdentifier(); 10574 if (userIdentifier == UserHandle.USER_ALL 10575 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 10576 userIdentifier = UserHandle.USER_OWNER; 10577 } 10578 10579 /* 10580 * Determine if we have any installed package verifiers. If we 10581 * do, then we'll defer to them to verify the packages. 10582 */ 10583 final int requiredUid = mRequiredVerifierPackage == null ? -1 10584 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 10585 if (!origin.existing && requiredUid != -1 10586 && isVerificationEnabled(userIdentifier, installFlags)) { 10587 final Intent verification = new Intent( 10588 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 10589 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 10590 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 10591 PACKAGE_MIME_TYPE); 10592 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10593 10594 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 10595 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 10596 0 /* TODO: Which userId? */); 10597 10598 if (DEBUG_VERIFY) { 10599 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 10600 + verification.toString() + " with " + pkgLite.verifiers.length 10601 + " optional verifiers"); 10602 } 10603 10604 final int verificationId = mPendingVerificationToken++; 10605 10606 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10607 10608 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 10609 installerPackageName); 10610 10611 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 10612 installFlags); 10613 10614 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 10615 pkgLite.packageName); 10616 10617 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 10618 pkgLite.versionCode); 10619 10620 if (verificationParams != null) { 10621 if (verificationParams.getVerificationURI() != null) { 10622 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 10623 verificationParams.getVerificationURI()); 10624 } 10625 if (verificationParams.getOriginatingURI() != null) { 10626 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 10627 verificationParams.getOriginatingURI()); 10628 } 10629 if (verificationParams.getReferrer() != null) { 10630 verification.putExtra(Intent.EXTRA_REFERRER, 10631 verificationParams.getReferrer()); 10632 } 10633 if (verificationParams.getOriginatingUid() >= 0) { 10634 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 10635 verificationParams.getOriginatingUid()); 10636 } 10637 if (verificationParams.getInstallerUid() >= 0) { 10638 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 10639 verificationParams.getInstallerUid()); 10640 } 10641 } 10642 10643 final PackageVerificationState verificationState = new PackageVerificationState( 10644 requiredUid, args); 10645 10646 mPendingVerification.append(verificationId, verificationState); 10647 10648 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 10649 receivers, verificationState); 10650 10651 // Apps installed for "all" users use the device owner to verify the app 10652 UserHandle verifierUser = getUser(); 10653 if (verifierUser == UserHandle.ALL) { 10654 verifierUser = UserHandle.OWNER; 10655 } 10656 10657 /* 10658 * If any sufficient verifiers were listed in the package 10659 * manifest, attempt to ask them. 10660 */ 10661 if (sufficientVerifiers != null) { 10662 final int N = sufficientVerifiers.size(); 10663 if (N == 0) { 10664 Slog.i(TAG, "Additional verifiers required, but none installed."); 10665 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 10666 } else { 10667 for (int i = 0; i < N; i++) { 10668 final ComponentName verifierComponent = sufficientVerifiers.get(i); 10669 10670 final Intent sufficientIntent = new Intent(verification); 10671 sufficientIntent.setComponent(verifierComponent); 10672 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 10673 } 10674 } 10675 } 10676 10677 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 10678 mRequiredVerifierPackage, receivers); 10679 if (ret == PackageManager.INSTALL_SUCCEEDED 10680 && mRequiredVerifierPackage != null) { 10681 /* 10682 * Send the intent to the required verification agent, 10683 * but only start the verification timeout after the 10684 * target BroadcastReceivers have run. 10685 */ 10686 verification.setComponent(requiredVerifierComponent); 10687 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 10688 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10689 new BroadcastReceiver() { 10690 @Override 10691 public void onReceive(Context context, Intent intent) { 10692 final Message msg = mHandler 10693 .obtainMessage(CHECK_PENDING_VERIFICATION); 10694 msg.arg1 = verificationId; 10695 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 10696 } 10697 }, null, 0, null, null); 10698 10699 /* 10700 * We don't want the copy to proceed until verification 10701 * succeeds, so null out this field. 10702 */ 10703 mArgs = null; 10704 } 10705 } else { 10706 /* 10707 * No package verification is enabled, so immediately start 10708 * the remote call to initiate copy using temporary file. 10709 */ 10710 ret = args.copyApk(mContainerService, true); 10711 } 10712 } 10713 10714 mRet = ret; 10715 } 10716 10717 @Override 10718 void handleReturnCode() { 10719 // If mArgs is null, then MCS couldn't be reached. When it 10720 // reconnects, it will try again to install. At that point, this 10721 // will succeed. 10722 if (mArgs != null) { 10723 processPendingInstall(mArgs, mRet); 10724 } 10725 } 10726 10727 @Override 10728 void handleServiceError() { 10729 mArgs = createInstallArgs(this); 10730 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10731 } 10732 10733 public boolean isForwardLocked() { 10734 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10735 } 10736 } 10737 10738 /** 10739 * Used during creation of InstallArgs 10740 * 10741 * @param installFlags package installation flags 10742 * @return true if should be installed on external storage 10743 */ 10744 private static boolean installOnExternalAsec(int installFlags) { 10745 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 10746 return false; 10747 } 10748 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 10749 return true; 10750 } 10751 return false; 10752 } 10753 10754 /** 10755 * Used during creation of InstallArgs 10756 * 10757 * @param installFlags package installation flags 10758 * @return true if should be installed as forward locked 10759 */ 10760 private static boolean installForwardLocked(int installFlags) { 10761 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10762 } 10763 10764 private InstallArgs createInstallArgs(InstallParams params) { 10765 if (params.move != null) { 10766 return new MoveInstallArgs(params); 10767 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 10768 return new AsecInstallArgs(params); 10769 } else { 10770 return new FileInstallArgs(params); 10771 } 10772 } 10773 10774 /** 10775 * Create args that describe an existing installed package. Typically used 10776 * when cleaning up old installs, or used as a move source. 10777 */ 10778 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 10779 String resourcePath, String[] instructionSets) { 10780 final boolean isInAsec; 10781 if (installOnExternalAsec(installFlags)) { 10782 /* Apps on SD card are always in ASEC containers. */ 10783 isInAsec = true; 10784 } else if (installForwardLocked(installFlags) 10785 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 10786 /* 10787 * Forward-locked apps are only in ASEC containers if they're the 10788 * new style 10789 */ 10790 isInAsec = true; 10791 } else { 10792 isInAsec = false; 10793 } 10794 10795 if (isInAsec) { 10796 return new AsecInstallArgs(codePath, instructionSets, 10797 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 10798 } else { 10799 return new FileInstallArgs(codePath, resourcePath, instructionSets); 10800 } 10801 } 10802 10803 static abstract class InstallArgs { 10804 /** @see InstallParams#origin */ 10805 final OriginInfo origin; 10806 /** @see InstallParams#move */ 10807 final MoveInfo move; 10808 10809 final IPackageInstallObserver2 observer; 10810 // Always refers to PackageManager flags only 10811 final int installFlags; 10812 final String installerPackageName; 10813 final String volumeUuid; 10814 final ManifestDigest manifestDigest; 10815 final UserHandle user; 10816 final String abiOverride; 10817 final String[] installGrantPermissions; 10818 10819 // The list of instruction sets supported by this app. This is currently 10820 // only used during the rmdex() phase to clean up resources. We can get rid of this 10821 // if we move dex files under the common app path. 10822 /* nullable */ String[] instructionSets; 10823 10824 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10825 int installFlags, String installerPackageName, String volumeUuid, 10826 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 10827 String abiOverride, String[] installGrantPermissions) { 10828 this.origin = origin; 10829 this.move = move; 10830 this.installFlags = installFlags; 10831 this.observer = observer; 10832 this.installerPackageName = installerPackageName; 10833 this.volumeUuid = volumeUuid; 10834 this.manifestDigest = manifestDigest; 10835 this.user = user; 10836 this.instructionSets = instructionSets; 10837 this.abiOverride = abiOverride; 10838 this.installGrantPermissions = installGrantPermissions; 10839 } 10840 10841 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 10842 abstract int doPreInstall(int status); 10843 10844 /** 10845 * Rename package into final resting place. All paths on the given 10846 * scanned package should be updated to reflect the rename. 10847 */ 10848 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 10849 abstract int doPostInstall(int status, int uid); 10850 10851 /** @see PackageSettingBase#codePathString */ 10852 abstract String getCodePath(); 10853 /** @see PackageSettingBase#resourcePathString */ 10854 abstract String getResourcePath(); 10855 10856 // Need installer lock especially for dex file removal. 10857 abstract void cleanUpResourcesLI(); 10858 abstract boolean doPostDeleteLI(boolean delete); 10859 10860 /** 10861 * Called before the source arguments are copied. This is used mostly 10862 * for MoveParams when it needs to read the source file to put it in the 10863 * destination. 10864 */ 10865 int doPreCopy() { 10866 return PackageManager.INSTALL_SUCCEEDED; 10867 } 10868 10869 /** 10870 * Called after the source arguments are copied. This is used mostly for 10871 * MoveParams when it needs to read the source file to put it in the 10872 * destination. 10873 * 10874 * @return 10875 */ 10876 int doPostCopy(int uid) { 10877 return PackageManager.INSTALL_SUCCEEDED; 10878 } 10879 10880 protected boolean isFwdLocked() { 10881 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10882 } 10883 10884 protected boolean isExternalAsec() { 10885 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10886 } 10887 10888 UserHandle getUser() { 10889 return user; 10890 } 10891 } 10892 10893 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 10894 if (!allCodePaths.isEmpty()) { 10895 if (instructionSets == null) { 10896 throw new IllegalStateException("instructionSet == null"); 10897 } 10898 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 10899 for (String codePath : allCodePaths) { 10900 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 10901 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 10902 if (retCode < 0) { 10903 Slog.w(TAG, "Couldn't remove dex file for package: " 10904 + " at location " + codePath + ", retcode=" + retCode); 10905 // we don't consider this to be a failure of the core package deletion 10906 } 10907 } 10908 } 10909 } 10910 } 10911 10912 /** 10913 * Logic to handle installation of non-ASEC applications, including copying 10914 * and renaming logic. 10915 */ 10916 class FileInstallArgs extends InstallArgs { 10917 private File codeFile; 10918 private File resourceFile; 10919 10920 // Example topology: 10921 // /data/app/com.example/base.apk 10922 // /data/app/com.example/split_foo.apk 10923 // /data/app/com.example/lib/arm/libfoo.so 10924 // /data/app/com.example/lib/arm64/libfoo.so 10925 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 10926 10927 /** New install */ 10928 FileInstallArgs(InstallParams params) { 10929 super(params.origin, params.move, params.observer, params.installFlags, 10930 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10931 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 10932 params.grantedRuntimePermissions); 10933 if (isFwdLocked()) { 10934 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 10935 } 10936 } 10937 10938 /** Existing install */ 10939 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 10940 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 10941 null, null); 10942 this.codeFile = (codePath != null) ? new File(codePath) : null; 10943 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 10944 } 10945 10946 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10947 if (origin.staged) { 10948 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 10949 codeFile = origin.file; 10950 resourceFile = origin.file; 10951 return PackageManager.INSTALL_SUCCEEDED; 10952 } 10953 10954 try { 10955 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 10956 codeFile = tempDir; 10957 resourceFile = tempDir; 10958 } catch (IOException e) { 10959 Slog.w(TAG, "Failed to create copy file: " + e); 10960 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10961 } 10962 10963 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 10964 @Override 10965 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 10966 if (!FileUtils.isValidExtFilename(name)) { 10967 throw new IllegalArgumentException("Invalid filename: " + name); 10968 } 10969 try { 10970 final File file = new File(codeFile, name); 10971 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 10972 O_RDWR | O_CREAT, 0644); 10973 Os.chmod(file.getAbsolutePath(), 0644); 10974 return new ParcelFileDescriptor(fd); 10975 } catch (ErrnoException e) { 10976 throw new RemoteException("Failed to open: " + e.getMessage()); 10977 } 10978 } 10979 }; 10980 10981 int ret = PackageManager.INSTALL_SUCCEEDED; 10982 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 10983 if (ret != PackageManager.INSTALL_SUCCEEDED) { 10984 Slog.e(TAG, "Failed to copy package"); 10985 return ret; 10986 } 10987 10988 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 10989 NativeLibraryHelper.Handle handle = null; 10990 try { 10991 handle = NativeLibraryHelper.Handle.create(codeFile); 10992 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 10993 abiOverride); 10994 } catch (IOException e) { 10995 Slog.e(TAG, "Copying native libraries failed", e); 10996 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10997 } finally { 10998 IoUtils.closeQuietly(handle); 10999 } 11000 11001 return ret; 11002 } 11003 11004 int doPreInstall(int status) { 11005 if (status != PackageManager.INSTALL_SUCCEEDED) { 11006 cleanUp(); 11007 } 11008 return status; 11009 } 11010 11011 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11012 if (status != PackageManager.INSTALL_SUCCEEDED) { 11013 cleanUp(); 11014 return false; 11015 } 11016 11017 final File targetDir = codeFile.getParentFile(); 11018 final File beforeCodeFile = codeFile; 11019 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 11020 11021 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 11022 try { 11023 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 11024 } catch (ErrnoException e) { 11025 Slog.w(TAG, "Failed to rename", e); 11026 return false; 11027 } 11028 11029 if (!SELinux.restoreconRecursive(afterCodeFile)) { 11030 Slog.w(TAG, "Failed to restorecon"); 11031 return false; 11032 } 11033 11034 // Reflect the rename internally 11035 codeFile = afterCodeFile; 11036 resourceFile = afterCodeFile; 11037 11038 // Reflect the rename in scanned details 11039 pkg.codePath = afterCodeFile.getAbsolutePath(); 11040 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11041 pkg.baseCodePath); 11042 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11043 pkg.splitCodePaths); 11044 11045 // Reflect the rename in app info 11046 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11047 pkg.applicationInfo.setCodePath(pkg.codePath); 11048 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11049 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11050 pkg.applicationInfo.setResourcePath(pkg.codePath); 11051 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11052 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11053 11054 return true; 11055 } 11056 11057 int doPostInstall(int status, int uid) { 11058 if (status != PackageManager.INSTALL_SUCCEEDED) { 11059 cleanUp(); 11060 } 11061 return status; 11062 } 11063 11064 @Override 11065 String getCodePath() { 11066 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11067 } 11068 11069 @Override 11070 String getResourcePath() { 11071 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11072 } 11073 11074 private boolean cleanUp() { 11075 if (codeFile == null || !codeFile.exists()) { 11076 return false; 11077 } 11078 11079 if (codeFile.isDirectory()) { 11080 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11081 } else { 11082 codeFile.delete(); 11083 } 11084 11085 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 11086 resourceFile.delete(); 11087 } 11088 11089 return true; 11090 } 11091 11092 void cleanUpResourcesLI() { 11093 // Try enumerating all code paths before deleting 11094 List<String> allCodePaths = Collections.EMPTY_LIST; 11095 if (codeFile != null && codeFile.exists()) { 11096 try { 11097 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11098 allCodePaths = pkg.getAllCodePaths(); 11099 } catch (PackageParserException e) { 11100 // Ignored; we tried our best 11101 } 11102 } 11103 11104 cleanUp(); 11105 removeDexFiles(allCodePaths, instructionSets); 11106 } 11107 11108 boolean doPostDeleteLI(boolean delete) { 11109 // XXX err, shouldn't we respect the delete flag? 11110 cleanUpResourcesLI(); 11111 return true; 11112 } 11113 } 11114 11115 private boolean isAsecExternal(String cid) { 11116 final String asecPath = PackageHelper.getSdFilesystem(cid); 11117 return !asecPath.startsWith(mAsecInternalPath); 11118 } 11119 11120 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 11121 PackageManagerException { 11122 if (copyRet < 0) { 11123 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 11124 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 11125 throw new PackageManagerException(copyRet, message); 11126 } 11127 } 11128 } 11129 11130 /** 11131 * Extract the MountService "container ID" from the full code path of an 11132 * .apk. 11133 */ 11134 static String cidFromCodePath(String fullCodePath) { 11135 int eidx = fullCodePath.lastIndexOf("/"); 11136 String subStr1 = fullCodePath.substring(0, eidx); 11137 int sidx = subStr1.lastIndexOf("/"); 11138 return subStr1.substring(sidx+1, eidx); 11139 } 11140 11141 /** 11142 * Logic to handle installation of ASEC applications, including copying and 11143 * renaming logic. 11144 */ 11145 class AsecInstallArgs extends InstallArgs { 11146 static final String RES_FILE_NAME = "pkg.apk"; 11147 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 11148 11149 String cid; 11150 String packagePath; 11151 String resourcePath; 11152 11153 /** New install */ 11154 AsecInstallArgs(InstallParams params) { 11155 super(params.origin, params.move, params.observer, params.installFlags, 11156 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11157 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11158 params.grantedRuntimePermissions); 11159 } 11160 11161 /** Existing install */ 11162 AsecInstallArgs(String fullCodePath, String[] instructionSets, 11163 boolean isExternal, boolean isForwardLocked) { 11164 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 11165 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11166 instructionSets, null, null); 11167 // Hackily pretend we're still looking at a full code path 11168 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 11169 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 11170 } 11171 11172 // Extract cid from fullCodePath 11173 int eidx = fullCodePath.lastIndexOf("/"); 11174 String subStr1 = fullCodePath.substring(0, eidx); 11175 int sidx = subStr1.lastIndexOf("/"); 11176 cid = subStr1.substring(sidx+1, eidx); 11177 setMountPath(subStr1); 11178 } 11179 11180 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 11181 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 11182 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11183 instructionSets, null, null); 11184 this.cid = cid; 11185 setMountPath(PackageHelper.getSdDir(cid)); 11186 } 11187 11188 void createCopyFile() { 11189 cid = mInstallerService.allocateExternalStageCidLegacy(); 11190 } 11191 11192 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11193 if (origin.staged) { 11194 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 11195 cid = origin.cid; 11196 setMountPath(PackageHelper.getSdDir(cid)); 11197 return PackageManager.INSTALL_SUCCEEDED; 11198 } 11199 11200 if (temp) { 11201 createCopyFile(); 11202 } else { 11203 /* 11204 * Pre-emptively destroy the container since it's destroyed if 11205 * copying fails due to it existing anyway. 11206 */ 11207 PackageHelper.destroySdDir(cid); 11208 } 11209 11210 final String newMountPath = imcs.copyPackageToContainer( 11211 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 11212 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 11213 11214 if (newMountPath != null) { 11215 setMountPath(newMountPath); 11216 return PackageManager.INSTALL_SUCCEEDED; 11217 } else { 11218 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11219 } 11220 } 11221 11222 @Override 11223 String getCodePath() { 11224 return packagePath; 11225 } 11226 11227 @Override 11228 String getResourcePath() { 11229 return resourcePath; 11230 } 11231 11232 int doPreInstall(int status) { 11233 if (status != PackageManager.INSTALL_SUCCEEDED) { 11234 // Destroy container 11235 PackageHelper.destroySdDir(cid); 11236 } else { 11237 boolean mounted = PackageHelper.isContainerMounted(cid); 11238 if (!mounted) { 11239 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 11240 Process.SYSTEM_UID); 11241 if (newMountPath != null) { 11242 setMountPath(newMountPath); 11243 } else { 11244 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11245 } 11246 } 11247 } 11248 return status; 11249 } 11250 11251 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11252 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 11253 String newMountPath = null; 11254 if (PackageHelper.isContainerMounted(cid)) { 11255 // Unmount the container 11256 if (!PackageHelper.unMountSdDir(cid)) { 11257 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 11258 return false; 11259 } 11260 } 11261 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11262 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 11263 " which might be stale. Will try to clean up."); 11264 // Clean up the stale container and proceed to recreate. 11265 if (!PackageHelper.destroySdDir(newCacheId)) { 11266 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 11267 return false; 11268 } 11269 // Successfully cleaned up stale container. Try to rename again. 11270 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11271 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 11272 + " inspite of cleaning it up."); 11273 return false; 11274 } 11275 } 11276 if (!PackageHelper.isContainerMounted(newCacheId)) { 11277 Slog.w(TAG, "Mounting container " + newCacheId); 11278 newMountPath = PackageHelper.mountSdDir(newCacheId, 11279 getEncryptKey(), Process.SYSTEM_UID); 11280 } else { 11281 newMountPath = PackageHelper.getSdDir(newCacheId); 11282 } 11283 if (newMountPath == null) { 11284 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 11285 return false; 11286 } 11287 Log.i(TAG, "Succesfully renamed " + cid + 11288 " to " + newCacheId + 11289 " at new path: " + newMountPath); 11290 cid = newCacheId; 11291 11292 final File beforeCodeFile = new File(packagePath); 11293 setMountPath(newMountPath); 11294 final File afterCodeFile = new File(packagePath); 11295 11296 // Reflect the rename in scanned details 11297 pkg.codePath = afterCodeFile.getAbsolutePath(); 11298 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11299 pkg.baseCodePath); 11300 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11301 pkg.splitCodePaths); 11302 11303 // Reflect the rename in app info 11304 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11305 pkg.applicationInfo.setCodePath(pkg.codePath); 11306 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11307 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11308 pkg.applicationInfo.setResourcePath(pkg.codePath); 11309 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11310 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11311 11312 return true; 11313 } 11314 11315 private void setMountPath(String mountPath) { 11316 final File mountFile = new File(mountPath); 11317 11318 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 11319 if (monolithicFile.exists()) { 11320 packagePath = monolithicFile.getAbsolutePath(); 11321 if (isFwdLocked()) { 11322 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 11323 } else { 11324 resourcePath = packagePath; 11325 } 11326 } else { 11327 packagePath = mountFile.getAbsolutePath(); 11328 resourcePath = packagePath; 11329 } 11330 } 11331 11332 int doPostInstall(int status, int uid) { 11333 if (status != PackageManager.INSTALL_SUCCEEDED) { 11334 cleanUp(); 11335 } else { 11336 final int groupOwner; 11337 final String protectedFile; 11338 if (isFwdLocked()) { 11339 groupOwner = UserHandle.getSharedAppGid(uid); 11340 protectedFile = RES_FILE_NAME; 11341 } else { 11342 groupOwner = -1; 11343 protectedFile = null; 11344 } 11345 11346 if (uid < Process.FIRST_APPLICATION_UID 11347 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 11348 Slog.e(TAG, "Failed to finalize " + cid); 11349 PackageHelper.destroySdDir(cid); 11350 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11351 } 11352 11353 boolean mounted = PackageHelper.isContainerMounted(cid); 11354 if (!mounted) { 11355 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 11356 } 11357 } 11358 return status; 11359 } 11360 11361 private void cleanUp() { 11362 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 11363 11364 // Destroy secure container 11365 PackageHelper.destroySdDir(cid); 11366 } 11367 11368 private List<String> getAllCodePaths() { 11369 final File codeFile = new File(getCodePath()); 11370 if (codeFile != null && codeFile.exists()) { 11371 try { 11372 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11373 return pkg.getAllCodePaths(); 11374 } catch (PackageParserException e) { 11375 // Ignored; we tried our best 11376 } 11377 } 11378 return Collections.EMPTY_LIST; 11379 } 11380 11381 void cleanUpResourcesLI() { 11382 // Enumerate all code paths before deleting 11383 cleanUpResourcesLI(getAllCodePaths()); 11384 } 11385 11386 private void cleanUpResourcesLI(List<String> allCodePaths) { 11387 cleanUp(); 11388 removeDexFiles(allCodePaths, instructionSets); 11389 } 11390 11391 String getPackageName() { 11392 return getAsecPackageName(cid); 11393 } 11394 11395 boolean doPostDeleteLI(boolean delete) { 11396 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 11397 final List<String> allCodePaths = getAllCodePaths(); 11398 boolean mounted = PackageHelper.isContainerMounted(cid); 11399 if (mounted) { 11400 // Unmount first 11401 if (PackageHelper.unMountSdDir(cid)) { 11402 mounted = false; 11403 } 11404 } 11405 if (!mounted && delete) { 11406 cleanUpResourcesLI(allCodePaths); 11407 } 11408 return !mounted; 11409 } 11410 11411 @Override 11412 int doPreCopy() { 11413 if (isFwdLocked()) { 11414 if (!PackageHelper.fixSdPermissions(cid, 11415 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 11416 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11417 } 11418 } 11419 11420 return PackageManager.INSTALL_SUCCEEDED; 11421 } 11422 11423 @Override 11424 int doPostCopy(int uid) { 11425 if (isFwdLocked()) { 11426 if (uid < Process.FIRST_APPLICATION_UID 11427 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 11428 RES_FILE_NAME)) { 11429 Slog.e(TAG, "Failed to finalize " + cid); 11430 PackageHelper.destroySdDir(cid); 11431 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11432 } 11433 } 11434 11435 return PackageManager.INSTALL_SUCCEEDED; 11436 } 11437 } 11438 11439 /** 11440 * Logic to handle movement of existing installed applications. 11441 */ 11442 class MoveInstallArgs extends InstallArgs { 11443 private File codeFile; 11444 private File resourceFile; 11445 11446 /** New install */ 11447 MoveInstallArgs(InstallParams params) { 11448 super(params.origin, params.move, params.observer, params.installFlags, 11449 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11450 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11451 params.grantedRuntimePermissions); 11452 } 11453 11454 int copyApk(IMediaContainerService imcs, boolean temp) { 11455 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 11456 + move.fromUuid + " to " + move.toUuid); 11457 synchronized (mInstaller) { 11458 if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName, 11459 move.dataAppName, move.appId, move.seinfo) != 0) { 11460 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11461 } 11462 } 11463 11464 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 11465 resourceFile = codeFile; 11466 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 11467 11468 return PackageManager.INSTALL_SUCCEEDED; 11469 } 11470 11471 int doPreInstall(int status) { 11472 if (status != PackageManager.INSTALL_SUCCEEDED) { 11473 cleanUp(move.toUuid); 11474 } 11475 return status; 11476 } 11477 11478 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11479 if (status != PackageManager.INSTALL_SUCCEEDED) { 11480 cleanUp(move.toUuid); 11481 return false; 11482 } 11483 11484 // Reflect the move in app info 11485 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11486 pkg.applicationInfo.setCodePath(pkg.codePath); 11487 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11488 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11489 pkg.applicationInfo.setResourcePath(pkg.codePath); 11490 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11491 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11492 11493 return true; 11494 } 11495 11496 int doPostInstall(int status, int uid) { 11497 if (status == PackageManager.INSTALL_SUCCEEDED) { 11498 cleanUp(move.fromUuid); 11499 } else { 11500 cleanUp(move.toUuid); 11501 } 11502 return status; 11503 } 11504 11505 @Override 11506 String getCodePath() { 11507 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11508 } 11509 11510 @Override 11511 String getResourcePath() { 11512 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11513 } 11514 11515 private boolean cleanUp(String volumeUuid) { 11516 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 11517 move.dataAppName); 11518 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 11519 synchronized (mInstallLock) { 11520 // Clean up both app data and code 11521 removeDataDirsLI(volumeUuid, move.packageName); 11522 if (codeFile.isDirectory()) { 11523 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11524 } else { 11525 codeFile.delete(); 11526 } 11527 } 11528 return true; 11529 } 11530 11531 void cleanUpResourcesLI() { 11532 throw new UnsupportedOperationException(); 11533 } 11534 11535 boolean doPostDeleteLI(boolean delete) { 11536 throw new UnsupportedOperationException(); 11537 } 11538 } 11539 11540 static String getAsecPackageName(String packageCid) { 11541 int idx = packageCid.lastIndexOf("-"); 11542 if (idx == -1) { 11543 return packageCid; 11544 } 11545 return packageCid.substring(0, idx); 11546 } 11547 11548 // Utility method used to create code paths based on package name and available index. 11549 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 11550 String idxStr = ""; 11551 int idx = 1; 11552 // Fall back to default value of idx=1 if prefix is not 11553 // part of oldCodePath 11554 if (oldCodePath != null) { 11555 String subStr = oldCodePath; 11556 // Drop the suffix right away 11557 if (suffix != null && subStr.endsWith(suffix)) { 11558 subStr = subStr.substring(0, subStr.length() - suffix.length()); 11559 } 11560 // If oldCodePath already contains prefix find out the 11561 // ending index to either increment or decrement. 11562 int sidx = subStr.lastIndexOf(prefix); 11563 if (sidx != -1) { 11564 subStr = subStr.substring(sidx + prefix.length()); 11565 if (subStr != null) { 11566 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 11567 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 11568 } 11569 try { 11570 idx = Integer.parseInt(subStr); 11571 if (idx <= 1) { 11572 idx++; 11573 } else { 11574 idx--; 11575 } 11576 } catch(NumberFormatException e) { 11577 } 11578 } 11579 } 11580 } 11581 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 11582 return prefix + idxStr; 11583 } 11584 11585 private File getNextCodePath(File targetDir, String packageName) { 11586 int suffix = 1; 11587 File result; 11588 do { 11589 result = new File(targetDir, packageName + "-" + suffix); 11590 suffix++; 11591 } while (result.exists()); 11592 return result; 11593 } 11594 11595 // Utility method that returns the relative package path with respect 11596 // to the installation directory. Like say for /data/data/com.test-1.apk 11597 // string com.test-1 is returned. 11598 static String deriveCodePathName(String codePath) { 11599 if (codePath == null) { 11600 return null; 11601 } 11602 final File codeFile = new File(codePath); 11603 final String name = codeFile.getName(); 11604 if (codeFile.isDirectory()) { 11605 return name; 11606 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 11607 final int lastDot = name.lastIndexOf('.'); 11608 return name.substring(0, lastDot); 11609 } else { 11610 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 11611 return null; 11612 } 11613 } 11614 11615 class PackageInstalledInfo { 11616 String name; 11617 int uid; 11618 // The set of users that originally had this package installed. 11619 int[] origUsers; 11620 // The set of users that now have this package installed. 11621 int[] newUsers; 11622 PackageParser.Package pkg; 11623 int returnCode; 11624 String returnMsg; 11625 PackageRemovedInfo removedInfo; 11626 11627 public void setError(int code, String msg) { 11628 returnCode = code; 11629 returnMsg = msg; 11630 Slog.w(TAG, msg); 11631 } 11632 11633 public void setError(String msg, PackageParserException e) { 11634 returnCode = e.error; 11635 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11636 Slog.w(TAG, msg, e); 11637 } 11638 11639 public void setError(String msg, PackageManagerException e) { 11640 returnCode = e.error; 11641 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11642 Slog.w(TAG, msg, e); 11643 } 11644 11645 // In some error cases we want to convey more info back to the observer 11646 String origPackage; 11647 String origPermission; 11648 } 11649 11650 /* 11651 * Install a non-existing package. 11652 */ 11653 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11654 UserHandle user, String installerPackageName, String volumeUuid, 11655 PackageInstalledInfo res) { 11656 // Remember this for later, in case we need to rollback this install 11657 String pkgName = pkg.packageName; 11658 11659 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 11660 final boolean dataDirExists = Environment 11661 .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists(); 11662 synchronized(mPackages) { 11663 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 11664 // A package with the same name is already installed, though 11665 // it has been renamed to an older name. The package we 11666 // are trying to install should be installed as an update to 11667 // the existing one, but that has not been requested, so bail. 11668 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11669 + " without first uninstalling package running as " 11670 + mSettings.mRenamedPackages.get(pkgName)); 11671 return; 11672 } 11673 if (mPackages.containsKey(pkgName)) { 11674 // Don't allow installation over an existing package with the same name. 11675 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11676 + " without first uninstalling."); 11677 return; 11678 } 11679 } 11680 11681 try { 11682 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 11683 System.currentTimeMillis(), user); 11684 11685 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 11686 // delete the partially installed application. the data directory will have to be 11687 // restored if it was already existing 11688 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11689 // remove package from internal structures. Note that we want deletePackageX to 11690 // delete the package data and cache directories that it created in 11691 // scanPackageLocked, unless those directories existed before we even tried to 11692 // install. 11693 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 11694 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 11695 res.removedInfo, true); 11696 } 11697 11698 } catch (PackageManagerException e) { 11699 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11700 } 11701 } 11702 11703 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 11704 // Can't rotate keys during boot or if sharedUser. 11705 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 11706 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 11707 return false; 11708 } 11709 // app is using upgradeKeySets; make sure all are valid 11710 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11711 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 11712 for (int i = 0; i < upgradeKeySets.length; i++) { 11713 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 11714 Slog.wtf(TAG, "Package " 11715 + (oldPs.name != null ? oldPs.name : "<null>") 11716 + " contains upgrade-key-set reference to unknown key-set: " 11717 + upgradeKeySets[i] 11718 + " reverting to signatures check."); 11719 return false; 11720 } 11721 } 11722 return true; 11723 } 11724 11725 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 11726 // Upgrade keysets are being used. Determine if new package has a superset of the 11727 // required keys. 11728 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 11729 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11730 for (int i = 0; i < upgradeKeySets.length; i++) { 11731 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 11732 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 11733 return true; 11734 } 11735 } 11736 return false; 11737 } 11738 11739 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11740 UserHandle user, String installerPackageName, String volumeUuid, 11741 PackageInstalledInfo res) { 11742 final PackageParser.Package oldPackage; 11743 final String pkgName = pkg.packageName; 11744 final int[] allUsers; 11745 final boolean[] perUserInstalled; 11746 final boolean weFroze; 11747 11748 // First find the old package info and check signatures 11749 synchronized(mPackages) { 11750 oldPackage = mPackages.get(pkgName); 11751 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 11752 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11753 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 11754 if(!checkUpgradeKeySetLP(ps, pkg)) { 11755 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11756 "New package not signed by keys specified by upgrade-keysets: " 11757 + pkgName); 11758 return; 11759 } 11760 } else { 11761 // default to original signature matching 11762 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 11763 != PackageManager.SIGNATURE_MATCH) { 11764 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11765 "New package has a different signature: " + pkgName); 11766 return; 11767 } 11768 } 11769 11770 // In case of rollback, remember per-user/profile install state 11771 allUsers = sUserManager.getUserIds(); 11772 perUserInstalled = new boolean[allUsers.length]; 11773 for (int i = 0; i < allUsers.length; i++) { 11774 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11775 } 11776 11777 // Mark the app as frozen to prevent launching during the upgrade 11778 // process, and then kill all running instances 11779 if (!ps.frozen) { 11780 ps.frozen = true; 11781 weFroze = true; 11782 } else { 11783 weFroze = false; 11784 } 11785 } 11786 11787 // Now that we're guarded by frozen state, kill app during upgrade 11788 killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg"); 11789 11790 try { 11791 boolean sysPkg = (isSystemApp(oldPackage)); 11792 if (sysPkg) { 11793 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11794 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11795 } else { 11796 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11797 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11798 } 11799 } finally { 11800 // Regardless of success or failure of upgrade steps above, always 11801 // unfreeze the package if we froze it 11802 if (weFroze) { 11803 unfreezePackage(pkgName); 11804 } 11805 } 11806 } 11807 11808 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 11809 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11810 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11811 String volumeUuid, PackageInstalledInfo res) { 11812 String pkgName = deletedPackage.packageName; 11813 boolean deletedPkg = true; 11814 boolean updatedSettings = false; 11815 11816 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 11817 + deletedPackage); 11818 long origUpdateTime; 11819 if (pkg.mExtras != null) { 11820 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 11821 } else { 11822 origUpdateTime = 0; 11823 } 11824 11825 // First delete the existing package while retaining the data directory 11826 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 11827 res.removedInfo, true)) { 11828 // If the existing package wasn't successfully deleted 11829 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 11830 deletedPkg = false; 11831 } else { 11832 // Successfully deleted the old package; proceed with replace. 11833 11834 // If deleted package lived in a container, give users a chance to 11835 // relinquish resources before killing. 11836 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 11837 if (DEBUG_INSTALL) { 11838 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 11839 } 11840 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 11841 final ArrayList<String> pkgList = new ArrayList<String>(1); 11842 pkgList.add(deletedPackage.applicationInfo.packageName); 11843 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 11844 } 11845 11846 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 11847 try { 11848 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 11849 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 11850 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11851 perUserInstalled, res, user); 11852 updatedSettings = true; 11853 } catch (PackageManagerException e) { 11854 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11855 } 11856 } 11857 11858 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11859 // remove package from internal structures. Note that we want deletePackageX to 11860 // delete the package data and cache directories that it created in 11861 // scanPackageLocked, unless those directories existed before we even tried to 11862 // install. 11863 if(updatedSettings) { 11864 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 11865 deletePackageLI( 11866 pkgName, null, true, allUsers, perUserInstalled, 11867 PackageManager.DELETE_KEEP_DATA, 11868 res.removedInfo, true); 11869 } 11870 // Since we failed to install the new package we need to restore the old 11871 // package that we deleted. 11872 if (deletedPkg) { 11873 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 11874 File restoreFile = new File(deletedPackage.codePath); 11875 // Parse old package 11876 boolean oldExternal = isExternal(deletedPackage); 11877 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 11878 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 11879 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11880 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 11881 try { 11882 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 11883 } catch (PackageManagerException e) { 11884 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 11885 + e.getMessage()); 11886 return; 11887 } 11888 // Restore of old package succeeded. Update permissions. 11889 // writer 11890 synchronized (mPackages) { 11891 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 11892 UPDATE_PERMISSIONS_ALL); 11893 // can downgrade to reader 11894 mSettings.writeLPr(); 11895 } 11896 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 11897 } 11898 } 11899 } 11900 11901 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 11902 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11903 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11904 String volumeUuid, PackageInstalledInfo res) { 11905 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 11906 + ", old=" + deletedPackage); 11907 boolean disabledSystem = false; 11908 boolean updatedSettings = false; 11909 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 11910 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 11911 != 0) { 11912 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11913 } 11914 String packageName = deletedPackage.packageName; 11915 if (packageName == null) { 11916 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11917 "Attempt to delete null packageName."); 11918 return; 11919 } 11920 PackageParser.Package oldPkg; 11921 PackageSetting oldPkgSetting; 11922 // reader 11923 synchronized (mPackages) { 11924 oldPkg = mPackages.get(packageName); 11925 oldPkgSetting = mSettings.mPackages.get(packageName); 11926 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 11927 (oldPkgSetting == null)) { 11928 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11929 "Couldn't find package:" + packageName + " information"); 11930 return; 11931 } 11932 } 11933 11934 res.removedInfo.uid = oldPkg.applicationInfo.uid; 11935 res.removedInfo.removedPackage = packageName; 11936 // Remove existing system package 11937 removePackageLI(oldPkgSetting, true); 11938 // writer 11939 synchronized (mPackages) { 11940 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 11941 if (!disabledSystem && deletedPackage != null) { 11942 // We didn't need to disable the .apk as a current system package, 11943 // which means we are replacing another update that is already 11944 // installed. We need to make sure to delete the older one's .apk. 11945 res.removedInfo.args = createInstallArgsForExisting(0, 11946 deletedPackage.applicationInfo.getCodePath(), 11947 deletedPackage.applicationInfo.getResourcePath(), 11948 getAppDexInstructionSets(deletedPackage.applicationInfo)); 11949 } else { 11950 res.removedInfo.args = null; 11951 } 11952 } 11953 11954 // Successfully disabled the old package. Now proceed with re-installation 11955 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 11956 11957 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11958 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 11959 11960 PackageParser.Package newPackage = null; 11961 try { 11962 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 11963 if (newPackage.mExtras != null) { 11964 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 11965 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 11966 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 11967 11968 // is the update attempting to change shared user? that isn't going to work... 11969 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 11970 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 11971 "Forbidding shared user change from " + oldPkgSetting.sharedUser 11972 + " to " + newPkgSetting.sharedUser); 11973 updatedSettings = true; 11974 } 11975 } 11976 11977 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11978 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11979 perUserInstalled, res, user); 11980 updatedSettings = true; 11981 } 11982 11983 } catch (PackageManagerException e) { 11984 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11985 } 11986 11987 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11988 // Re installation failed. Restore old information 11989 // Remove new pkg information 11990 if (newPackage != null) { 11991 removeInstalledPackageLI(newPackage, true); 11992 } 11993 // Add back the old system package 11994 try { 11995 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 11996 } catch (PackageManagerException e) { 11997 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 11998 } 11999 // Restore the old system information in Settings 12000 synchronized (mPackages) { 12001 if (disabledSystem) { 12002 mSettings.enableSystemPackageLPw(packageName); 12003 } 12004 if (updatedSettings) { 12005 mSettings.setInstallerPackageName(packageName, 12006 oldPkgSetting.installerPackageName); 12007 } 12008 mSettings.writeLPr(); 12009 } 12010 } 12011 } 12012 12013 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 12014 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 12015 UserHandle user) { 12016 String pkgName = newPackage.packageName; 12017 synchronized (mPackages) { 12018 //write settings. the installStatus will be incomplete at this stage. 12019 //note that the new package setting would have already been 12020 //added to mPackages. It hasn't been persisted yet. 12021 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 12022 mSettings.writeLPr(); 12023 } 12024 12025 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 12026 12027 synchronized (mPackages) { 12028 updatePermissionsLPw(newPackage.packageName, newPackage, 12029 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 12030 ? UPDATE_PERMISSIONS_ALL : 0)); 12031 // For system-bundled packages, we assume that installing an upgraded version 12032 // of the package implies that the user actually wants to run that new code, 12033 // so we enable the package. 12034 PackageSetting ps = mSettings.mPackages.get(pkgName); 12035 if (ps != null) { 12036 if (isSystemApp(newPackage)) { 12037 // NB: implicit assumption that system package upgrades apply to all users 12038 if (DEBUG_INSTALL) { 12039 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 12040 } 12041 if (res.origUsers != null) { 12042 for (int userHandle : res.origUsers) { 12043 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 12044 userHandle, installerPackageName); 12045 } 12046 } 12047 // Also convey the prior install/uninstall state 12048 if (allUsers != null && perUserInstalled != null) { 12049 for (int i = 0; i < allUsers.length; i++) { 12050 if (DEBUG_INSTALL) { 12051 Slog.d(TAG, " user " + allUsers[i] 12052 + " => " + perUserInstalled[i]); 12053 } 12054 ps.setInstalled(perUserInstalled[i], allUsers[i]); 12055 } 12056 // these install state changes will be persisted in the 12057 // upcoming call to mSettings.writeLPr(). 12058 } 12059 } 12060 // It's implied that when a user requests installation, they want the app to be 12061 // installed and enabled. 12062 int userId = user.getIdentifier(); 12063 if (userId != UserHandle.USER_ALL) { 12064 ps.setInstalled(true, userId); 12065 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 12066 } 12067 } 12068 res.name = pkgName; 12069 res.uid = newPackage.applicationInfo.uid; 12070 res.pkg = newPackage; 12071 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 12072 mSettings.setInstallerPackageName(pkgName, installerPackageName); 12073 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12074 //to update install status 12075 mSettings.writeLPr(); 12076 } 12077 } 12078 12079 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 12080 final int installFlags = args.installFlags; 12081 final String installerPackageName = args.installerPackageName; 12082 final String volumeUuid = args.volumeUuid; 12083 final File tmpPackageFile = new File(args.getCodePath()); 12084 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 12085 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 12086 || (args.volumeUuid != null)); 12087 boolean replace = false; 12088 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 12089 if (args.move != null) { 12090 // moving a complete application; perfom an initial scan on the new install location 12091 scanFlags |= SCAN_INITIAL; 12092 } 12093 // Result object to be returned 12094 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12095 12096 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 12097 // Retrieve PackageSettings and parse package 12098 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 12099 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 12100 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 12101 PackageParser pp = new PackageParser(); 12102 pp.setSeparateProcesses(mSeparateProcesses); 12103 pp.setDisplayMetrics(mMetrics); 12104 12105 final PackageParser.Package pkg; 12106 try { 12107 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 12108 } catch (PackageParserException e) { 12109 res.setError("Failed parse during installPackageLI", e); 12110 return; 12111 } 12112 12113 // Mark that we have an install time CPU ABI override. 12114 pkg.cpuAbiOverride = args.abiOverride; 12115 12116 String pkgName = res.name = pkg.packageName; 12117 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 12118 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 12119 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 12120 return; 12121 } 12122 } 12123 12124 try { 12125 pp.collectCertificates(pkg, parseFlags); 12126 pp.collectManifestDigest(pkg); 12127 } catch (PackageParserException e) { 12128 res.setError("Failed collect during installPackageLI", e); 12129 return; 12130 } 12131 12132 /* If the installer passed in a manifest digest, compare it now. */ 12133 if (args.manifestDigest != null) { 12134 if (DEBUG_INSTALL) { 12135 final String parsedManifest = pkg.manifestDigest == null ? "null" 12136 : pkg.manifestDigest.toString(); 12137 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 12138 + parsedManifest); 12139 } 12140 12141 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 12142 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 12143 return; 12144 } 12145 } else if (DEBUG_INSTALL) { 12146 final String parsedManifest = pkg.manifestDigest == null 12147 ? "null" : pkg.manifestDigest.toString(); 12148 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 12149 } 12150 12151 // Get rid of all references to package scan path via parser. 12152 pp = null; 12153 String oldCodePath = null; 12154 boolean systemApp = false; 12155 synchronized (mPackages) { 12156 // Check if installing already existing package 12157 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12158 String oldName = mSettings.mRenamedPackages.get(pkgName); 12159 if (pkg.mOriginalPackages != null 12160 && pkg.mOriginalPackages.contains(oldName) 12161 && mPackages.containsKey(oldName)) { 12162 // This package is derived from an original package, 12163 // and this device has been updating from that original 12164 // name. We must continue using the original name, so 12165 // rename the new package here. 12166 pkg.setPackageName(oldName); 12167 pkgName = pkg.packageName; 12168 replace = true; 12169 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 12170 + oldName + " pkgName=" + pkgName); 12171 } else if (mPackages.containsKey(pkgName)) { 12172 // This package, under its official name, already exists 12173 // on the device; we should replace it. 12174 replace = true; 12175 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 12176 } 12177 12178 // Prevent apps opting out from runtime permissions 12179 if (replace) { 12180 PackageParser.Package oldPackage = mPackages.get(pkgName); 12181 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 12182 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 12183 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 12184 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 12185 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 12186 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 12187 + " doesn't support runtime permissions but the old" 12188 + " target SDK " + oldTargetSdk + " does."); 12189 return; 12190 } 12191 } 12192 } 12193 12194 PackageSetting ps = mSettings.mPackages.get(pkgName); 12195 if (ps != null) { 12196 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 12197 12198 // Quick sanity check that we're signed correctly if updating; 12199 // we'll check this again later when scanning, but we want to 12200 // bail early here before tripping over redefined permissions. 12201 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12202 if (!checkUpgradeKeySetLP(ps, pkg)) { 12203 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 12204 + pkg.packageName + " upgrade keys do not match the " 12205 + "previously installed version"); 12206 return; 12207 } 12208 } else { 12209 try { 12210 verifySignaturesLP(ps, pkg); 12211 } catch (PackageManagerException e) { 12212 res.setError(e.error, e.getMessage()); 12213 return; 12214 } 12215 } 12216 12217 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 12218 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 12219 systemApp = (ps.pkg.applicationInfo.flags & 12220 ApplicationInfo.FLAG_SYSTEM) != 0; 12221 } 12222 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12223 } 12224 12225 // Check whether the newly-scanned package wants to define an already-defined perm 12226 int N = pkg.permissions.size(); 12227 for (int i = N-1; i >= 0; i--) { 12228 PackageParser.Permission perm = pkg.permissions.get(i); 12229 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 12230 if (bp != null) { 12231 // If the defining package is signed with our cert, it's okay. This 12232 // also includes the "updating the same package" case, of course. 12233 // "updating same package" could also involve key-rotation. 12234 final boolean sigsOk; 12235 if (bp.sourcePackage.equals(pkg.packageName) 12236 && (bp.packageSetting instanceof PackageSetting) 12237 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 12238 scanFlags))) { 12239 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 12240 } else { 12241 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 12242 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 12243 } 12244 if (!sigsOk) { 12245 // If the owning package is the system itself, we log but allow 12246 // install to proceed; we fail the install on all other permission 12247 // redefinitions. 12248 if (!bp.sourcePackage.equals("android")) { 12249 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 12250 + pkg.packageName + " attempting to redeclare permission " 12251 + perm.info.name + " already owned by " + bp.sourcePackage); 12252 res.origPermission = perm.info.name; 12253 res.origPackage = bp.sourcePackage; 12254 return; 12255 } else { 12256 Slog.w(TAG, "Package " + pkg.packageName 12257 + " attempting to redeclare system permission " 12258 + perm.info.name + "; ignoring new declaration"); 12259 pkg.permissions.remove(i); 12260 } 12261 } 12262 } 12263 } 12264 12265 } 12266 12267 if (systemApp && onExternal) { 12268 // Disable updates to system apps on sdcard 12269 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 12270 "Cannot install updates to system apps on sdcard"); 12271 return; 12272 } 12273 12274 if (args.move != null) { 12275 // We did an in-place move, so dex is ready to roll 12276 scanFlags |= SCAN_NO_DEX; 12277 scanFlags |= SCAN_MOVE; 12278 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 12279 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 12280 scanFlags |= SCAN_NO_DEX; 12281 12282 try { 12283 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 12284 true /* extract libs */); 12285 } catch (PackageManagerException pme) { 12286 Slog.e(TAG, "Error deriving application ABI", pme); 12287 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 12288 return; 12289 } 12290 12291 // Run dexopt before old package gets removed, to minimize time when app is unavailable 12292 int result = mPackageDexOptimizer 12293 .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */, 12294 false /* defer */, false /* inclDependencies */); 12295 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 12296 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 12297 return; 12298 } 12299 } 12300 12301 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 12302 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 12303 return; 12304 } 12305 12306 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 12307 12308 if (replace) { 12309 replacePackageLI(pkg, parseFlags, scanFlags, args.user, 12310 installerPackageName, volumeUuid, res); 12311 } else { 12312 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 12313 args.user, installerPackageName, volumeUuid, res); 12314 } 12315 synchronized (mPackages) { 12316 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12317 if (ps != null) { 12318 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12319 } 12320 } 12321 } 12322 12323 private void startIntentFilterVerifications(int userId, boolean replacing, 12324 PackageParser.Package pkg) { 12325 if (mIntentFilterVerifierComponent == null) { 12326 Slog.w(TAG, "No IntentFilter verification will not be done as " 12327 + "there is no IntentFilterVerifier available!"); 12328 return; 12329 } 12330 12331 final int verifierUid = getPackageUid( 12332 mIntentFilterVerifierComponent.getPackageName(), 12333 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 12334 12335 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 12336 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 12337 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 12338 mHandler.sendMessage(msg); 12339 } 12340 12341 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 12342 PackageParser.Package pkg) { 12343 int size = pkg.activities.size(); 12344 if (size == 0) { 12345 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12346 "No activity, so no need to verify any IntentFilter!"); 12347 return; 12348 } 12349 12350 final boolean hasDomainURLs = hasDomainURLs(pkg); 12351 if (!hasDomainURLs) { 12352 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12353 "No domain URLs, so no need to verify any IntentFilter!"); 12354 return; 12355 } 12356 12357 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 12358 + " if any IntentFilter from the " + size 12359 + " Activities needs verification ..."); 12360 12361 int count = 0; 12362 final String packageName = pkg.packageName; 12363 12364 synchronized (mPackages) { 12365 // If this is a new install and we see that we've already run verification for this 12366 // package, we have nothing to do: it means the state was restored from backup. 12367 if (!replacing) { 12368 IntentFilterVerificationInfo ivi = 12369 mSettings.getIntentFilterVerificationLPr(packageName); 12370 if (ivi != null) { 12371 if (DEBUG_DOMAIN_VERIFICATION) { 12372 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 12373 + ivi.getStatusString()); 12374 } 12375 return; 12376 } 12377 } 12378 12379 // If any filters need to be verified, then all need to be. 12380 boolean needToVerify = false; 12381 for (PackageParser.Activity a : pkg.activities) { 12382 for (ActivityIntentInfo filter : a.intents) { 12383 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 12384 if (DEBUG_DOMAIN_VERIFICATION) { 12385 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 12386 } 12387 needToVerify = true; 12388 break; 12389 } 12390 } 12391 } 12392 12393 if (needToVerify) { 12394 final int verificationId = mIntentFilterVerificationToken++; 12395 for (PackageParser.Activity a : pkg.activities) { 12396 for (ActivityIntentInfo filter : a.intents) { 12397 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 12398 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12399 "Verification needed for IntentFilter:" + filter.toString()); 12400 mIntentFilterVerifier.addOneIntentFilterVerification( 12401 verifierUid, userId, verificationId, filter, packageName); 12402 count++; 12403 } 12404 } 12405 } 12406 } 12407 } 12408 12409 if (count > 0) { 12410 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 12411 + " IntentFilter verification" + (count > 1 ? "s" : "") 12412 + " for userId:" + userId); 12413 mIntentFilterVerifier.startVerifications(userId); 12414 } else { 12415 if (DEBUG_DOMAIN_VERIFICATION) { 12416 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 12417 } 12418 } 12419 } 12420 12421 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 12422 final ComponentName cn = filter.activity.getComponentName(); 12423 final String packageName = cn.getPackageName(); 12424 12425 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 12426 packageName); 12427 if (ivi == null) { 12428 return true; 12429 } 12430 int status = ivi.getStatus(); 12431 switch (status) { 12432 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 12433 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 12434 return true; 12435 12436 default: 12437 // Nothing to do 12438 return false; 12439 } 12440 } 12441 12442 private static boolean isMultiArch(PackageSetting ps) { 12443 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12444 } 12445 12446 private static boolean isMultiArch(ApplicationInfo info) { 12447 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12448 } 12449 12450 private static boolean isExternal(PackageParser.Package pkg) { 12451 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12452 } 12453 12454 private static boolean isExternal(PackageSetting ps) { 12455 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12456 } 12457 12458 private static boolean isExternal(ApplicationInfo info) { 12459 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12460 } 12461 12462 private static boolean isSystemApp(PackageParser.Package pkg) { 12463 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 12464 } 12465 12466 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 12467 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 12468 } 12469 12470 private static boolean hasDomainURLs(PackageParser.Package pkg) { 12471 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 12472 } 12473 12474 private static boolean isSystemApp(PackageSetting ps) { 12475 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 12476 } 12477 12478 private static boolean isUpdatedSystemApp(PackageSetting ps) { 12479 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 12480 } 12481 12482 private int packageFlagsToInstallFlags(PackageSetting ps) { 12483 int installFlags = 0; 12484 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 12485 // This existing package was an external ASEC install when we have 12486 // the external flag without a UUID 12487 installFlags |= PackageManager.INSTALL_EXTERNAL; 12488 } 12489 if (ps.isForwardLocked()) { 12490 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12491 } 12492 return installFlags; 12493 } 12494 12495 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 12496 if (isExternal(pkg)) { 12497 if (TextUtils.isEmpty(pkg.volumeUuid)) { 12498 return mSettings.getExternalVersion(); 12499 } else { 12500 return mSettings.findOrCreateVersion(pkg.volumeUuid); 12501 } 12502 } else { 12503 return mSettings.getInternalVersion(); 12504 } 12505 } 12506 12507 private void deleteTempPackageFiles() { 12508 final FilenameFilter filter = new FilenameFilter() { 12509 public boolean accept(File dir, String name) { 12510 return name.startsWith("vmdl") && name.endsWith(".tmp"); 12511 } 12512 }; 12513 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 12514 file.delete(); 12515 } 12516 } 12517 12518 @Override 12519 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 12520 int flags) { 12521 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 12522 flags); 12523 } 12524 12525 @Override 12526 public void deletePackage(final String packageName, 12527 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 12528 mContext.enforceCallingOrSelfPermission( 12529 android.Manifest.permission.DELETE_PACKAGES, null); 12530 Preconditions.checkNotNull(packageName); 12531 Preconditions.checkNotNull(observer); 12532 final int uid = Binder.getCallingUid(); 12533 if (UserHandle.getUserId(uid) != userId) { 12534 mContext.enforceCallingPermission( 12535 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 12536 "deletePackage for user " + userId); 12537 } 12538 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 12539 try { 12540 observer.onPackageDeleted(packageName, 12541 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 12542 } catch (RemoteException re) { 12543 } 12544 return; 12545 } 12546 12547 boolean uninstallBlocked = false; 12548 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 12549 int[] users = sUserManager.getUserIds(); 12550 for (int i = 0; i < users.length; ++i) { 12551 if (getBlockUninstallForUser(packageName, users[i])) { 12552 uninstallBlocked = true; 12553 break; 12554 } 12555 } 12556 } else { 12557 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 12558 } 12559 if (uninstallBlocked) { 12560 try { 12561 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 12562 null); 12563 } catch (RemoteException re) { 12564 } 12565 return; 12566 } 12567 12568 if (DEBUG_REMOVE) { 12569 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 12570 } 12571 // Queue up an async operation since the package deletion may take a little while. 12572 mHandler.post(new Runnable() { 12573 public void run() { 12574 mHandler.removeCallbacks(this); 12575 final int returnCode = deletePackageX(packageName, userId, flags); 12576 if (observer != null) { 12577 try { 12578 observer.onPackageDeleted(packageName, returnCode, null); 12579 } catch (RemoteException e) { 12580 Log.i(TAG, "Observer no longer exists."); 12581 } //end catch 12582 } //end if 12583 } //end run 12584 }); 12585 } 12586 12587 private boolean isPackageDeviceAdmin(String packageName, int userId) { 12588 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 12589 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 12590 try { 12591 if (dpm != null) { 12592 if (dpm.isDeviceOwner(packageName)) { 12593 return true; 12594 } 12595 int[] users; 12596 if (userId == UserHandle.USER_ALL) { 12597 users = sUserManager.getUserIds(); 12598 } else { 12599 users = new int[]{userId}; 12600 } 12601 for (int i = 0; i < users.length; ++i) { 12602 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 12603 return true; 12604 } 12605 } 12606 } 12607 } catch (RemoteException e) { 12608 } 12609 return false; 12610 } 12611 12612 /** 12613 * This method is an internal method that could be get invoked either 12614 * to delete an installed package or to clean up a failed installation. 12615 * After deleting an installed package, a broadcast is sent to notify any 12616 * listeners that the package has been installed. For cleaning up a failed 12617 * installation, the broadcast is not necessary since the package's 12618 * installation wouldn't have sent the initial broadcast either 12619 * The key steps in deleting a package are 12620 * deleting the package information in internal structures like mPackages, 12621 * deleting the packages base directories through installd 12622 * updating mSettings to reflect current status 12623 * persisting settings for later use 12624 * sending a broadcast if necessary 12625 */ 12626 private int deletePackageX(String packageName, int userId, int flags) { 12627 final PackageRemovedInfo info = new PackageRemovedInfo(); 12628 final boolean res; 12629 12630 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 12631 ? UserHandle.ALL : new UserHandle(userId); 12632 12633 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 12634 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 12635 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 12636 } 12637 12638 boolean removedForAllUsers = false; 12639 boolean systemUpdate = false; 12640 12641 // for the uninstall-updates case and restricted profiles, remember the per- 12642 // userhandle installed state 12643 int[] allUsers; 12644 boolean[] perUserInstalled; 12645 synchronized (mPackages) { 12646 PackageSetting ps = mSettings.mPackages.get(packageName); 12647 allUsers = sUserManager.getUserIds(); 12648 perUserInstalled = new boolean[allUsers.length]; 12649 for (int i = 0; i < allUsers.length; i++) { 12650 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12651 } 12652 } 12653 12654 synchronized (mInstallLock) { 12655 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 12656 res = deletePackageLI(packageName, removeForUser, 12657 true, allUsers, perUserInstalled, 12658 flags | REMOVE_CHATTY, info, true); 12659 systemUpdate = info.isRemovedPackageSystemUpdate; 12660 if (res && !systemUpdate && mPackages.get(packageName) == null) { 12661 removedForAllUsers = true; 12662 } 12663 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 12664 + " removedForAllUsers=" + removedForAllUsers); 12665 } 12666 12667 if (res) { 12668 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 12669 12670 // If the removed package was a system update, the old system package 12671 // was re-enabled; we need to broadcast this information 12672 if (systemUpdate) { 12673 Bundle extras = new Bundle(1); 12674 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 12675 ? info.removedAppId : info.uid); 12676 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12677 12678 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 12679 extras, null, null, null); 12680 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 12681 extras, null, null, null); 12682 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 12683 null, packageName, null, null); 12684 } 12685 } 12686 // Force a gc here. 12687 Runtime.getRuntime().gc(); 12688 // Delete the resources here after sending the broadcast to let 12689 // other processes clean up before deleting resources. 12690 if (info.args != null) { 12691 synchronized (mInstallLock) { 12692 info.args.doPostDeleteLI(true); 12693 } 12694 } 12695 12696 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 12697 } 12698 12699 class PackageRemovedInfo { 12700 String removedPackage; 12701 int uid = -1; 12702 int removedAppId = -1; 12703 int[] removedUsers = null; 12704 boolean isRemovedPackageSystemUpdate = false; 12705 // Clean up resources deleted packages. 12706 InstallArgs args = null; 12707 12708 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 12709 Bundle extras = new Bundle(1); 12710 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 12711 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 12712 if (replacing) { 12713 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12714 } 12715 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 12716 if (removedPackage != null) { 12717 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 12718 extras, null, null, removedUsers); 12719 if (fullRemove && !replacing) { 12720 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 12721 extras, null, null, removedUsers); 12722 } 12723 } 12724 if (removedAppId >= 0) { 12725 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 12726 removedUsers); 12727 } 12728 } 12729 } 12730 12731 /* 12732 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 12733 * flag is not set, the data directory is removed as well. 12734 * make sure this flag is set for partially installed apps. If not its meaningless to 12735 * delete a partially installed application. 12736 */ 12737 private void removePackageDataLI(PackageSetting ps, 12738 int[] allUserHandles, boolean[] perUserInstalled, 12739 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 12740 String packageName = ps.name; 12741 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 12742 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 12743 // Retrieve object to delete permissions for shared user later on 12744 final PackageSetting deletedPs; 12745 // reader 12746 synchronized (mPackages) { 12747 deletedPs = mSettings.mPackages.get(packageName); 12748 if (outInfo != null) { 12749 outInfo.removedPackage = packageName; 12750 outInfo.removedUsers = deletedPs != null 12751 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 12752 : null; 12753 } 12754 } 12755 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12756 removeDataDirsLI(ps.volumeUuid, packageName); 12757 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 12758 } 12759 // writer 12760 synchronized (mPackages) { 12761 if (deletedPs != null) { 12762 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12763 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 12764 clearDefaultBrowserIfNeeded(packageName); 12765 if (outInfo != null) { 12766 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 12767 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 12768 } 12769 updatePermissionsLPw(deletedPs.name, null, 0); 12770 if (deletedPs.sharedUser != null) { 12771 // Remove permissions associated with package. Since runtime 12772 // permissions are per user we have to kill the removed package 12773 // or packages running under the shared user of the removed 12774 // package if revoking the permissions requested only by the removed 12775 // package is successful and this causes a change in gids. 12776 for (int userId : UserManagerService.getInstance().getUserIds()) { 12777 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 12778 userId); 12779 if (userIdToKill == UserHandle.USER_ALL 12780 || userIdToKill >= UserHandle.USER_OWNER) { 12781 // If gids changed for this user, kill all affected packages. 12782 mHandler.post(new Runnable() { 12783 @Override 12784 public void run() { 12785 // This has to happen with no lock held. 12786 killSettingPackagesForUser(deletedPs, userIdToKill, 12787 KILL_APP_REASON_GIDS_CHANGED); 12788 } 12789 }); 12790 break; 12791 } 12792 } 12793 } 12794 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 12795 } 12796 // make sure to preserve per-user disabled state if this removal was just 12797 // a downgrade of a system app to the factory package 12798 if (allUserHandles != null && perUserInstalled != null) { 12799 if (DEBUG_REMOVE) { 12800 Slog.d(TAG, "Propagating install state across downgrade"); 12801 } 12802 for (int i = 0; i < allUserHandles.length; i++) { 12803 if (DEBUG_REMOVE) { 12804 Slog.d(TAG, " user " + allUserHandles[i] 12805 + " => " + perUserInstalled[i]); 12806 } 12807 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12808 } 12809 } 12810 } 12811 // can downgrade to reader 12812 if (writeSettings) { 12813 // Save settings now 12814 mSettings.writeLPr(); 12815 } 12816 } 12817 if (outInfo != null) { 12818 // A user ID was deleted here. Go through all users and remove it 12819 // from KeyStore. 12820 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 12821 } 12822 } 12823 12824 static boolean locationIsPrivileged(File path) { 12825 try { 12826 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 12827 .getCanonicalPath(); 12828 return path.getCanonicalPath().startsWith(privilegedAppDir); 12829 } catch (IOException e) { 12830 Slog.e(TAG, "Unable to access code path " + path); 12831 } 12832 return false; 12833 } 12834 12835 /* 12836 * Tries to delete system package. 12837 */ 12838 private boolean deleteSystemPackageLI(PackageSetting newPs, 12839 int[] allUserHandles, boolean[] perUserInstalled, 12840 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 12841 final boolean applyUserRestrictions 12842 = (allUserHandles != null) && (perUserInstalled != null); 12843 PackageSetting disabledPs = null; 12844 // Confirm if the system package has been updated 12845 // An updated system app can be deleted. This will also have to restore 12846 // the system pkg from system partition 12847 // reader 12848 synchronized (mPackages) { 12849 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 12850 } 12851 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 12852 + " disabledPs=" + disabledPs); 12853 if (disabledPs == null) { 12854 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 12855 return false; 12856 } else if (DEBUG_REMOVE) { 12857 Slog.d(TAG, "Deleting system pkg from data partition"); 12858 } 12859 if (DEBUG_REMOVE) { 12860 if (applyUserRestrictions) { 12861 Slog.d(TAG, "Remembering install states:"); 12862 for (int i = 0; i < allUserHandles.length; i++) { 12863 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 12864 } 12865 } 12866 } 12867 // Delete the updated package 12868 outInfo.isRemovedPackageSystemUpdate = true; 12869 if (disabledPs.versionCode < newPs.versionCode) { 12870 // Delete data for downgrades 12871 flags &= ~PackageManager.DELETE_KEEP_DATA; 12872 } else { 12873 // Preserve data by setting flag 12874 flags |= PackageManager.DELETE_KEEP_DATA; 12875 } 12876 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 12877 allUserHandles, perUserInstalled, outInfo, writeSettings); 12878 if (!ret) { 12879 return false; 12880 } 12881 // writer 12882 synchronized (mPackages) { 12883 // Reinstate the old system package 12884 mSettings.enableSystemPackageLPw(newPs.name); 12885 // Remove any native libraries from the upgraded package. 12886 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 12887 } 12888 // Install the system package 12889 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 12890 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 12891 if (locationIsPrivileged(disabledPs.codePath)) { 12892 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12893 } 12894 12895 final PackageParser.Package newPkg; 12896 try { 12897 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 12898 } catch (PackageManagerException e) { 12899 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 12900 return false; 12901 } 12902 12903 // writer 12904 synchronized (mPackages) { 12905 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 12906 12907 // Propagate the permissions state as we do want to drop on the floor 12908 // runtime permissions. The update permissions method below will take 12909 // care of removing obsolete permissions and grant install permissions. 12910 ps.getPermissionsState().copyFrom(disabledPs.getPermissionsState()); 12911 updatePermissionsLPw(newPkg.packageName, newPkg, 12912 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 12913 12914 if (applyUserRestrictions) { 12915 if (DEBUG_REMOVE) { 12916 Slog.d(TAG, "Propagating install state across reinstall"); 12917 } 12918 for (int i = 0; i < allUserHandles.length; i++) { 12919 if (DEBUG_REMOVE) { 12920 Slog.d(TAG, " user " + allUserHandles[i] 12921 + " => " + perUserInstalled[i]); 12922 } 12923 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12924 } 12925 // Regardless of writeSettings we need to ensure that this restriction 12926 // state propagation is persisted 12927 mSettings.writeAllUsersPackageRestrictionsLPr(); 12928 } 12929 // can downgrade to reader here 12930 if (writeSettings) { 12931 mSettings.writeLPr(); 12932 } 12933 } 12934 return true; 12935 } 12936 12937 private boolean deleteInstalledPackageLI(PackageSetting ps, 12938 boolean deleteCodeAndResources, int flags, 12939 int[] allUserHandles, boolean[] perUserInstalled, 12940 PackageRemovedInfo outInfo, boolean writeSettings) { 12941 if (outInfo != null) { 12942 outInfo.uid = ps.appId; 12943 } 12944 12945 // Delete package data from internal structures and also remove data if flag is set 12946 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 12947 12948 // Delete application code and resources 12949 if (deleteCodeAndResources && (outInfo != null)) { 12950 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 12951 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 12952 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 12953 } 12954 return true; 12955 } 12956 12957 @Override 12958 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 12959 int userId) { 12960 mContext.enforceCallingOrSelfPermission( 12961 android.Manifest.permission.DELETE_PACKAGES, null); 12962 synchronized (mPackages) { 12963 PackageSetting ps = mSettings.mPackages.get(packageName); 12964 if (ps == null) { 12965 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 12966 return false; 12967 } 12968 if (!ps.getInstalled(userId)) { 12969 // Can't block uninstall for an app that is not installed or enabled. 12970 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 12971 return false; 12972 } 12973 ps.setBlockUninstall(blockUninstall, userId); 12974 mSettings.writePackageRestrictionsLPr(userId); 12975 } 12976 return true; 12977 } 12978 12979 @Override 12980 public boolean getBlockUninstallForUser(String packageName, int userId) { 12981 synchronized (mPackages) { 12982 PackageSetting ps = mSettings.mPackages.get(packageName); 12983 if (ps == null) { 12984 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 12985 return false; 12986 } 12987 return ps.getBlockUninstall(userId); 12988 } 12989 } 12990 12991 /* 12992 * This method handles package deletion in general 12993 */ 12994 private boolean deletePackageLI(String packageName, UserHandle user, 12995 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 12996 int flags, PackageRemovedInfo outInfo, 12997 boolean writeSettings) { 12998 if (packageName == null) { 12999 Slog.w(TAG, "Attempt to delete null packageName."); 13000 return false; 13001 } 13002 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 13003 PackageSetting ps; 13004 boolean dataOnly = false; 13005 int removeUser = -1; 13006 int appId = -1; 13007 synchronized (mPackages) { 13008 ps = mSettings.mPackages.get(packageName); 13009 if (ps == null) { 13010 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13011 return false; 13012 } 13013 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 13014 && user.getIdentifier() != UserHandle.USER_ALL) { 13015 // The caller is asking that the package only be deleted for a single 13016 // user. To do this, we just mark its uninstalled state and delete 13017 // its data. If this is a system app, we only allow this to happen if 13018 // they have set the special DELETE_SYSTEM_APP which requests different 13019 // semantics than normal for uninstalling system apps. 13020 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 13021 ps.setUserState(user.getIdentifier(), 13022 COMPONENT_ENABLED_STATE_DEFAULT, 13023 false, //installed 13024 true, //stopped 13025 true, //notLaunched 13026 false, //hidden 13027 null, null, null, 13028 false, // blockUninstall 13029 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED, 0); 13030 if (!isSystemApp(ps)) { 13031 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 13032 // Other user still have this package installed, so all 13033 // we need to do is clear this user's data and save that 13034 // it is uninstalled. 13035 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 13036 removeUser = user.getIdentifier(); 13037 appId = ps.appId; 13038 scheduleWritePackageRestrictionsLocked(removeUser); 13039 } else { 13040 // We need to set it back to 'installed' so the uninstall 13041 // broadcasts will be sent correctly. 13042 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 13043 ps.setInstalled(true, user.getIdentifier()); 13044 } 13045 } else { 13046 // This is a system app, so we assume that the 13047 // other users still have this package installed, so all 13048 // we need to do is clear this user's data and save that 13049 // it is uninstalled. 13050 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 13051 removeUser = user.getIdentifier(); 13052 appId = ps.appId; 13053 scheduleWritePackageRestrictionsLocked(removeUser); 13054 } 13055 } 13056 } 13057 13058 if (removeUser >= 0) { 13059 // From above, we determined that we are deleting this only 13060 // for a single user. Continue the work here. 13061 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 13062 if (outInfo != null) { 13063 outInfo.removedPackage = packageName; 13064 outInfo.removedAppId = appId; 13065 outInfo.removedUsers = new int[] {removeUser}; 13066 } 13067 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 13068 removeKeystoreDataIfNeeded(removeUser, appId); 13069 schedulePackageCleaning(packageName, removeUser, false); 13070 synchronized (mPackages) { 13071 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 13072 scheduleWritePackageRestrictionsLocked(removeUser); 13073 } 13074 resetUserChangesToRuntimePermissionsAndFlagsLocked(ps, removeUser); 13075 } 13076 return true; 13077 } 13078 13079 if (dataOnly) { 13080 // Delete application data first 13081 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 13082 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 13083 return true; 13084 } 13085 13086 boolean ret = false; 13087 if (isSystemApp(ps)) { 13088 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 13089 // When an updated system application is deleted we delete the existing resources as well and 13090 // fall back to existing code in system partition 13091 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 13092 flags, outInfo, writeSettings); 13093 } else { 13094 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 13095 // Kill application pre-emptively especially for apps on sd. 13096 killApplication(packageName, ps.appId, "uninstall pkg"); 13097 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 13098 allUserHandles, perUserInstalled, 13099 outInfo, writeSettings); 13100 } 13101 13102 return ret; 13103 } 13104 13105 private final class ClearStorageConnection implements ServiceConnection { 13106 IMediaContainerService mContainerService; 13107 13108 @Override 13109 public void onServiceConnected(ComponentName name, IBinder service) { 13110 synchronized (this) { 13111 mContainerService = IMediaContainerService.Stub.asInterface(service); 13112 notifyAll(); 13113 } 13114 } 13115 13116 @Override 13117 public void onServiceDisconnected(ComponentName name) { 13118 } 13119 } 13120 13121 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 13122 final boolean mounted; 13123 if (Environment.isExternalStorageEmulated()) { 13124 mounted = true; 13125 } else { 13126 final String status = Environment.getExternalStorageState(); 13127 13128 mounted = status.equals(Environment.MEDIA_MOUNTED) 13129 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 13130 } 13131 13132 if (!mounted) { 13133 return; 13134 } 13135 13136 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 13137 int[] users; 13138 if (userId == UserHandle.USER_ALL) { 13139 users = sUserManager.getUserIds(); 13140 } else { 13141 users = new int[] { userId }; 13142 } 13143 final ClearStorageConnection conn = new ClearStorageConnection(); 13144 if (mContext.bindServiceAsUser( 13145 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 13146 try { 13147 for (int curUser : users) { 13148 long timeout = SystemClock.uptimeMillis() + 5000; 13149 synchronized (conn) { 13150 long now = SystemClock.uptimeMillis(); 13151 while (conn.mContainerService == null && now < timeout) { 13152 try { 13153 conn.wait(timeout - now); 13154 } catch (InterruptedException e) { 13155 } 13156 } 13157 } 13158 if (conn.mContainerService == null) { 13159 return; 13160 } 13161 13162 final UserEnvironment userEnv = new UserEnvironment(curUser); 13163 clearDirectory(conn.mContainerService, 13164 userEnv.buildExternalStorageAppCacheDirs(packageName)); 13165 if (allData) { 13166 clearDirectory(conn.mContainerService, 13167 userEnv.buildExternalStorageAppDataDirs(packageName)); 13168 clearDirectory(conn.mContainerService, 13169 userEnv.buildExternalStorageAppMediaDirs(packageName)); 13170 } 13171 } 13172 } finally { 13173 mContext.unbindService(conn); 13174 } 13175 } 13176 } 13177 13178 @Override 13179 public void clearApplicationUserData(final String packageName, 13180 final IPackageDataObserver observer, final int userId) { 13181 mContext.enforceCallingOrSelfPermission( 13182 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 13183 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 13184 // Queue up an async operation since the package deletion may take a little while. 13185 mHandler.post(new Runnable() { 13186 public void run() { 13187 mHandler.removeCallbacks(this); 13188 final boolean succeeded; 13189 synchronized (mInstallLock) { 13190 succeeded = clearApplicationUserDataLI(packageName, userId); 13191 } 13192 clearExternalStorageDataSync(packageName, userId, true); 13193 if (succeeded) { 13194 // invoke DeviceStorageMonitor's update method to clear any notifications 13195 DeviceStorageMonitorInternal 13196 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13197 if (dsm != null) { 13198 dsm.checkMemory(); 13199 } 13200 } 13201 if(observer != null) { 13202 try { 13203 observer.onRemoveCompleted(packageName, succeeded); 13204 } catch (RemoteException e) { 13205 Log.i(TAG, "Observer no longer exists."); 13206 } 13207 } //end if observer 13208 } //end run 13209 }); 13210 } 13211 13212 private boolean clearApplicationUserDataLI(String packageName, int userId) { 13213 if (packageName == null) { 13214 Slog.w(TAG, "Attempt to delete null packageName."); 13215 return false; 13216 } 13217 13218 // Try finding details about the requested package 13219 PackageParser.Package pkg; 13220 synchronized (mPackages) { 13221 pkg = mPackages.get(packageName); 13222 if (pkg == null) { 13223 final PackageSetting ps = mSettings.mPackages.get(packageName); 13224 if (ps != null) { 13225 pkg = ps.pkg; 13226 } 13227 } 13228 13229 if (pkg == null) { 13230 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13231 return false; 13232 } 13233 13234 PackageSetting ps = (PackageSetting) pkg.mExtras; 13235 resetUserChangesToRuntimePermissionsAndFlagsLocked(ps, userId); 13236 } 13237 13238 // Always delete data directories for package, even if we found no other 13239 // record of app. This helps users recover from UID mismatches without 13240 // resorting to a full data wipe. 13241 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 13242 if (retCode < 0) { 13243 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 13244 return false; 13245 } 13246 13247 final int appId = pkg.applicationInfo.uid; 13248 removeKeystoreDataIfNeeded(userId, appId); 13249 13250 // Create a native library symlink only if we have native libraries 13251 // and if the native libraries are 32 bit libraries. We do not provide 13252 // this symlink for 64 bit libraries. 13253 if (pkg.applicationInfo.primaryCpuAbi != null && 13254 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 13255 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 13256 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 13257 nativeLibPath, userId) < 0) { 13258 Slog.w(TAG, "Failed linking native library dir"); 13259 return false; 13260 } 13261 } 13262 13263 return true; 13264 } 13265 13266 /** 13267 * Reverts user permission state changes (permissions and flags). 13268 * 13269 * @param ps The package for which to reset. 13270 * @param userId The device user for which to do a reset. 13271 */ 13272 private void resetUserChangesToRuntimePermissionsAndFlagsLocked( 13273 final PackageSetting ps, final int userId) { 13274 if (ps.pkg == null) { 13275 return; 13276 } 13277 13278 final int userSettableFlags = FLAG_PERMISSION_USER_SET 13279 | FLAG_PERMISSION_USER_FIXED 13280 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 13281 13282 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 13283 | FLAG_PERMISSION_POLICY_FIXED; 13284 13285 boolean writeInstallPermissions = false; 13286 boolean writeRuntimePermissions = false; 13287 13288 final int permissionCount = ps.pkg.requestedPermissions.size(); 13289 for (int i = 0; i < permissionCount; i++) { 13290 String permission = ps.pkg.requestedPermissions.get(i); 13291 13292 BasePermission bp = mSettings.mPermissions.get(permission); 13293 if (bp == null) { 13294 continue; 13295 } 13296 13297 // If shared user we just reset the state to which only this app contributed. 13298 if (ps.sharedUser != null) { 13299 boolean used = false; 13300 final int packageCount = ps.sharedUser.packages.size(); 13301 for (int j = 0; j < packageCount; j++) { 13302 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 13303 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 13304 && pkg.pkg.requestedPermissions.contains(permission)) { 13305 used = true; 13306 break; 13307 } 13308 } 13309 if (used) { 13310 continue; 13311 } 13312 } 13313 13314 PermissionsState permissionsState = ps.getPermissionsState(); 13315 13316 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 13317 13318 // Always clear the user settable flags. 13319 final boolean hasInstallState = permissionsState.getInstallPermissionState( 13320 bp.name) != null; 13321 if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) { 13322 if (hasInstallState) { 13323 writeInstallPermissions = true; 13324 } else { 13325 writeRuntimePermissions = true; 13326 } 13327 } 13328 13329 // Below is only runtime permission handling. 13330 if (!bp.isRuntime()) { 13331 continue; 13332 } 13333 13334 // Never clobber system or policy. 13335 if ((oldFlags & policyOrSystemFlags) != 0) { 13336 continue; 13337 } 13338 13339 // If this permission was granted by default, make sure it is. 13340 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 13341 if (permissionsState.grantRuntimePermission(bp, userId) 13342 != PERMISSION_OPERATION_FAILURE) { 13343 writeRuntimePermissions = true; 13344 } 13345 } else { 13346 // Otherwise, reset the permission. 13347 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 13348 switch (revokeResult) { 13349 case PERMISSION_OPERATION_SUCCESS: { 13350 writeRuntimePermissions = true; 13351 } break; 13352 13353 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 13354 writeRuntimePermissions = true; 13355 // If gids changed for this user, kill all affected packages. 13356 mHandler.post(new Runnable() { 13357 @Override 13358 public void run() { 13359 // This has to happen with no lock held. 13360 killSettingPackagesForUser(ps, userId, 13361 KILL_APP_REASON_GIDS_CHANGED); 13362 } 13363 }); 13364 } break; 13365 } 13366 } 13367 } 13368 13369 // Synchronously write as we are taking permissions away. 13370 if (writeRuntimePermissions) { 13371 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 13372 } 13373 13374 // Synchronously write as we are taking permissions away. 13375 if (writeInstallPermissions) { 13376 mSettings.writeLPr(); 13377 } 13378 } 13379 13380 /** 13381 * Remove entries from the keystore daemon. Will only remove it if the 13382 * {@code appId} is valid. 13383 */ 13384 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 13385 if (appId < 0) { 13386 return; 13387 } 13388 13389 final KeyStore keyStore = KeyStore.getInstance(); 13390 if (keyStore != null) { 13391 if (userId == UserHandle.USER_ALL) { 13392 for (final int individual : sUserManager.getUserIds()) { 13393 keyStore.clearUid(UserHandle.getUid(individual, appId)); 13394 } 13395 } else { 13396 keyStore.clearUid(UserHandle.getUid(userId, appId)); 13397 } 13398 } else { 13399 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 13400 } 13401 } 13402 13403 @Override 13404 public void deleteApplicationCacheFiles(final String packageName, 13405 final IPackageDataObserver observer) { 13406 mContext.enforceCallingOrSelfPermission( 13407 android.Manifest.permission.DELETE_CACHE_FILES, null); 13408 // Queue up an async operation since the package deletion may take a little while. 13409 final int userId = UserHandle.getCallingUserId(); 13410 mHandler.post(new Runnable() { 13411 public void run() { 13412 mHandler.removeCallbacks(this); 13413 final boolean succeded; 13414 synchronized (mInstallLock) { 13415 succeded = deleteApplicationCacheFilesLI(packageName, userId); 13416 } 13417 clearExternalStorageDataSync(packageName, userId, false); 13418 if (observer != null) { 13419 try { 13420 observer.onRemoveCompleted(packageName, succeded); 13421 } catch (RemoteException e) { 13422 Log.i(TAG, "Observer no longer exists."); 13423 } 13424 } //end if observer 13425 } //end run 13426 }); 13427 } 13428 13429 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 13430 if (packageName == null) { 13431 Slog.w(TAG, "Attempt to delete null packageName."); 13432 return false; 13433 } 13434 PackageParser.Package p; 13435 synchronized (mPackages) { 13436 p = mPackages.get(packageName); 13437 } 13438 if (p == null) { 13439 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13440 return false; 13441 } 13442 final ApplicationInfo applicationInfo = p.applicationInfo; 13443 if (applicationInfo == null) { 13444 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13445 return false; 13446 } 13447 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 13448 if (retCode < 0) { 13449 Slog.w(TAG, "Couldn't remove cache files for package: " 13450 + packageName + " u" + userId); 13451 return false; 13452 } 13453 return true; 13454 } 13455 13456 @Override 13457 public void getPackageSizeInfo(final String packageName, int userHandle, 13458 final IPackageStatsObserver observer) { 13459 mContext.enforceCallingOrSelfPermission( 13460 android.Manifest.permission.GET_PACKAGE_SIZE, null); 13461 if (packageName == null) { 13462 throw new IllegalArgumentException("Attempt to get size of null packageName"); 13463 } 13464 13465 PackageStats stats = new PackageStats(packageName, userHandle); 13466 13467 /* 13468 * Queue up an async operation since the package measurement may take a 13469 * little while. 13470 */ 13471 Message msg = mHandler.obtainMessage(INIT_COPY); 13472 msg.obj = new MeasureParams(stats, observer); 13473 mHandler.sendMessage(msg); 13474 } 13475 13476 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 13477 PackageStats pStats) { 13478 if (packageName == null) { 13479 Slog.w(TAG, "Attempt to get size of null packageName."); 13480 return false; 13481 } 13482 PackageParser.Package p; 13483 boolean dataOnly = false; 13484 String libDirRoot = null; 13485 String asecPath = null; 13486 PackageSetting ps = null; 13487 synchronized (mPackages) { 13488 p = mPackages.get(packageName); 13489 ps = mSettings.mPackages.get(packageName); 13490 if(p == null) { 13491 dataOnly = true; 13492 if((ps == null) || (ps.pkg == null)) { 13493 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13494 return false; 13495 } 13496 p = ps.pkg; 13497 } 13498 if (ps != null) { 13499 libDirRoot = ps.legacyNativeLibraryPathString; 13500 } 13501 if (p != null && (isExternal(p) || p.isForwardLocked())) { 13502 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 13503 if (secureContainerId != null) { 13504 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 13505 } 13506 } 13507 } 13508 String publicSrcDir = null; 13509 if(!dataOnly) { 13510 final ApplicationInfo applicationInfo = p.applicationInfo; 13511 if (applicationInfo == null) { 13512 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13513 return false; 13514 } 13515 if (p.isForwardLocked()) { 13516 publicSrcDir = applicationInfo.getBaseResourcePath(); 13517 } 13518 } 13519 // TODO: extend to measure size of split APKs 13520 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 13521 // not just the first level. 13522 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 13523 // just the primary. 13524 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 13525 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath, 13526 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 13527 if (res < 0) { 13528 return false; 13529 } 13530 13531 // Fix-up for forward-locked applications in ASEC containers. 13532 if (!isExternal(p)) { 13533 pStats.codeSize += pStats.externalCodeSize; 13534 pStats.externalCodeSize = 0L; 13535 } 13536 13537 return true; 13538 } 13539 13540 13541 @Override 13542 public void addPackageToPreferred(String packageName) { 13543 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 13544 } 13545 13546 @Override 13547 public void removePackageFromPreferred(String packageName) { 13548 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 13549 } 13550 13551 @Override 13552 public List<PackageInfo> getPreferredPackages(int flags) { 13553 return new ArrayList<PackageInfo>(); 13554 } 13555 13556 private int getUidTargetSdkVersionLockedLPr(int uid) { 13557 Object obj = mSettings.getUserIdLPr(uid); 13558 if (obj instanceof SharedUserSetting) { 13559 final SharedUserSetting sus = (SharedUserSetting) obj; 13560 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 13561 final Iterator<PackageSetting> it = sus.packages.iterator(); 13562 while (it.hasNext()) { 13563 final PackageSetting ps = it.next(); 13564 if (ps.pkg != null) { 13565 int v = ps.pkg.applicationInfo.targetSdkVersion; 13566 if (v < vers) vers = v; 13567 } 13568 } 13569 return vers; 13570 } else if (obj instanceof PackageSetting) { 13571 final PackageSetting ps = (PackageSetting) obj; 13572 if (ps.pkg != null) { 13573 return ps.pkg.applicationInfo.targetSdkVersion; 13574 } 13575 } 13576 return Build.VERSION_CODES.CUR_DEVELOPMENT; 13577 } 13578 13579 @Override 13580 public void addPreferredActivity(IntentFilter filter, int match, 13581 ComponentName[] set, ComponentName activity, int userId) { 13582 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13583 "Adding preferred"); 13584 } 13585 13586 private void addPreferredActivityInternal(IntentFilter filter, int match, 13587 ComponentName[] set, ComponentName activity, boolean always, int userId, 13588 String opname) { 13589 // writer 13590 int callingUid = Binder.getCallingUid(); 13591 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 13592 if (filter.countActions() == 0) { 13593 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13594 return; 13595 } 13596 synchronized (mPackages) { 13597 if (mContext.checkCallingOrSelfPermission( 13598 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13599 != PackageManager.PERMISSION_GRANTED) { 13600 if (getUidTargetSdkVersionLockedLPr(callingUid) 13601 < Build.VERSION_CODES.FROYO) { 13602 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 13603 + callingUid); 13604 return; 13605 } 13606 mContext.enforceCallingOrSelfPermission( 13607 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13608 } 13609 13610 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 13611 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 13612 + userId + ":"); 13613 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13614 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 13615 scheduleWritePackageRestrictionsLocked(userId); 13616 } 13617 } 13618 13619 @Override 13620 public void replacePreferredActivity(IntentFilter filter, int match, 13621 ComponentName[] set, ComponentName activity, int userId) { 13622 if (filter.countActions() != 1) { 13623 throw new IllegalArgumentException( 13624 "replacePreferredActivity expects filter to have only 1 action."); 13625 } 13626 if (filter.countDataAuthorities() != 0 13627 || filter.countDataPaths() != 0 13628 || filter.countDataSchemes() > 1 13629 || filter.countDataTypes() != 0) { 13630 throw new IllegalArgumentException( 13631 "replacePreferredActivity expects filter to have no data authorities, " + 13632 "paths, or types; and at most one scheme."); 13633 } 13634 13635 final int callingUid = Binder.getCallingUid(); 13636 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 13637 synchronized (mPackages) { 13638 if (mContext.checkCallingOrSelfPermission( 13639 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13640 != PackageManager.PERMISSION_GRANTED) { 13641 if (getUidTargetSdkVersionLockedLPr(callingUid) 13642 < Build.VERSION_CODES.FROYO) { 13643 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 13644 + Binder.getCallingUid()); 13645 return; 13646 } 13647 mContext.enforceCallingOrSelfPermission( 13648 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13649 } 13650 13651 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13652 if (pir != null) { 13653 // Get all of the existing entries that exactly match this filter. 13654 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 13655 if (existing != null && existing.size() == 1) { 13656 PreferredActivity cur = existing.get(0); 13657 if (DEBUG_PREFERRED) { 13658 Slog.i(TAG, "Checking replace of preferred:"); 13659 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13660 if (!cur.mPref.mAlways) { 13661 Slog.i(TAG, " -- CUR; not mAlways!"); 13662 } else { 13663 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 13664 Slog.i(TAG, " -- CUR: mSet=" 13665 + Arrays.toString(cur.mPref.mSetComponents)); 13666 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 13667 Slog.i(TAG, " -- NEW: mMatch=" 13668 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 13669 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 13670 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 13671 } 13672 } 13673 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 13674 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 13675 && cur.mPref.sameSet(set)) { 13676 // Setting the preferred activity to what it happens to be already 13677 if (DEBUG_PREFERRED) { 13678 Slog.i(TAG, "Replacing with same preferred activity " 13679 + cur.mPref.mShortComponent + " for user " 13680 + userId + ":"); 13681 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13682 } 13683 return; 13684 } 13685 } 13686 13687 if (existing != null) { 13688 if (DEBUG_PREFERRED) { 13689 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 13690 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13691 } 13692 for (int i = 0; i < existing.size(); i++) { 13693 PreferredActivity pa = existing.get(i); 13694 if (DEBUG_PREFERRED) { 13695 Slog.i(TAG, "Removing existing preferred activity " 13696 + pa.mPref.mComponent + ":"); 13697 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 13698 } 13699 pir.removeFilter(pa); 13700 } 13701 } 13702 } 13703 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13704 "Replacing preferred"); 13705 } 13706 } 13707 13708 @Override 13709 public void clearPackagePreferredActivities(String packageName) { 13710 final int uid = Binder.getCallingUid(); 13711 // writer 13712 synchronized (mPackages) { 13713 PackageParser.Package pkg = mPackages.get(packageName); 13714 if (pkg == null || pkg.applicationInfo.uid != uid) { 13715 if (mContext.checkCallingOrSelfPermission( 13716 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13717 != PackageManager.PERMISSION_GRANTED) { 13718 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 13719 < Build.VERSION_CODES.FROYO) { 13720 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 13721 + Binder.getCallingUid()); 13722 return; 13723 } 13724 mContext.enforceCallingOrSelfPermission( 13725 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13726 } 13727 } 13728 13729 int user = UserHandle.getCallingUserId(); 13730 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 13731 scheduleWritePackageRestrictionsLocked(user); 13732 } 13733 } 13734 } 13735 13736 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13737 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 13738 ArrayList<PreferredActivity> removed = null; 13739 boolean changed = false; 13740 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13741 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 13742 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13743 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 13744 continue; 13745 } 13746 Iterator<PreferredActivity> it = pir.filterIterator(); 13747 while (it.hasNext()) { 13748 PreferredActivity pa = it.next(); 13749 // Mark entry for removal only if it matches the package name 13750 // and the entry is of type "always". 13751 if (packageName == null || 13752 (pa.mPref.mComponent.getPackageName().equals(packageName) 13753 && pa.mPref.mAlways)) { 13754 if (removed == null) { 13755 removed = new ArrayList<PreferredActivity>(); 13756 } 13757 removed.add(pa); 13758 } 13759 } 13760 if (removed != null) { 13761 for (int j=0; j<removed.size(); j++) { 13762 PreferredActivity pa = removed.get(j); 13763 pir.removeFilter(pa); 13764 } 13765 changed = true; 13766 } 13767 } 13768 return changed; 13769 } 13770 13771 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13772 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 13773 if (userId == UserHandle.USER_ALL) { 13774 if (mSettings.removeIntentFilterVerificationLPw(packageName, 13775 sUserManager.getUserIds())) { 13776 for (int oneUserId : sUserManager.getUserIds()) { 13777 scheduleWritePackageRestrictionsLocked(oneUserId); 13778 } 13779 } 13780 } else { 13781 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 13782 scheduleWritePackageRestrictionsLocked(userId); 13783 } 13784 } 13785 } 13786 13787 13788 void clearDefaultBrowserIfNeeded(String packageName) { 13789 for (int oneUserId : sUserManager.getUserIds()) { 13790 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 13791 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 13792 if (packageName.equals(defaultBrowserPackageName)) { 13793 setDefaultBrowserPackageName(null, oneUserId); 13794 } 13795 } 13796 } 13797 13798 @Override 13799 public void resetPreferredActivities(int userId) { 13800 mContext.enforceCallingOrSelfPermission( 13801 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13802 // writer 13803 synchronized (mPackages) { 13804 clearPackagePreferredActivitiesLPw(null, userId); 13805 mSettings.applyDefaultPreferredAppsLPw(this, userId); 13806 applyFactoryDefaultBrowserLPw(userId); 13807 primeDomainVerificationsLPw(userId); 13808 13809 scheduleWritePackageRestrictionsLocked(userId); 13810 } 13811 } 13812 13813 @Override 13814 public int getPreferredActivities(List<IntentFilter> outFilters, 13815 List<ComponentName> outActivities, String packageName) { 13816 13817 int num = 0; 13818 final int userId = UserHandle.getCallingUserId(); 13819 // reader 13820 synchronized (mPackages) { 13821 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13822 if (pir != null) { 13823 final Iterator<PreferredActivity> it = pir.filterIterator(); 13824 while (it.hasNext()) { 13825 final PreferredActivity pa = it.next(); 13826 if (packageName == null 13827 || (pa.mPref.mComponent.getPackageName().equals(packageName) 13828 && pa.mPref.mAlways)) { 13829 if (outFilters != null) { 13830 outFilters.add(new IntentFilter(pa)); 13831 } 13832 if (outActivities != null) { 13833 outActivities.add(pa.mPref.mComponent); 13834 } 13835 } 13836 } 13837 } 13838 } 13839 13840 return num; 13841 } 13842 13843 @Override 13844 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 13845 int userId) { 13846 int callingUid = Binder.getCallingUid(); 13847 if (callingUid != Process.SYSTEM_UID) { 13848 throw new SecurityException( 13849 "addPersistentPreferredActivity can only be run by the system"); 13850 } 13851 if (filter.countActions() == 0) { 13852 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13853 return; 13854 } 13855 synchronized (mPackages) { 13856 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 13857 " :"); 13858 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13859 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 13860 new PersistentPreferredActivity(filter, activity)); 13861 scheduleWritePackageRestrictionsLocked(userId); 13862 } 13863 } 13864 13865 @Override 13866 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 13867 int callingUid = Binder.getCallingUid(); 13868 if (callingUid != Process.SYSTEM_UID) { 13869 throw new SecurityException( 13870 "clearPackagePersistentPreferredActivities can only be run by the system"); 13871 } 13872 ArrayList<PersistentPreferredActivity> removed = null; 13873 boolean changed = false; 13874 synchronized (mPackages) { 13875 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 13876 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 13877 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 13878 .valueAt(i); 13879 if (userId != thisUserId) { 13880 continue; 13881 } 13882 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 13883 while (it.hasNext()) { 13884 PersistentPreferredActivity ppa = it.next(); 13885 // Mark entry for removal only if it matches the package name. 13886 if (ppa.mComponent.getPackageName().equals(packageName)) { 13887 if (removed == null) { 13888 removed = new ArrayList<PersistentPreferredActivity>(); 13889 } 13890 removed.add(ppa); 13891 } 13892 } 13893 if (removed != null) { 13894 for (int j=0; j<removed.size(); j++) { 13895 PersistentPreferredActivity ppa = removed.get(j); 13896 ppir.removeFilter(ppa); 13897 } 13898 changed = true; 13899 } 13900 } 13901 13902 if (changed) { 13903 scheduleWritePackageRestrictionsLocked(userId); 13904 } 13905 } 13906 } 13907 13908 /** 13909 * Common machinery for picking apart a restored XML blob and passing 13910 * it to a caller-supplied functor to be applied to the running system. 13911 */ 13912 private void restoreFromXml(XmlPullParser parser, int userId, 13913 String expectedStartTag, BlobXmlRestorer functor) 13914 throws IOException, XmlPullParserException { 13915 int type; 13916 while ((type = parser.next()) != XmlPullParser.START_TAG 13917 && type != XmlPullParser.END_DOCUMENT) { 13918 } 13919 if (type != XmlPullParser.START_TAG) { 13920 // oops didn't find a start tag?! 13921 if (DEBUG_BACKUP) { 13922 Slog.e(TAG, "Didn't find start tag during restore"); 13923 } 13924 return; 13925 } 13926 13927 // this is supposed to be TAG_PREFERRED_BACKUP 13928 if (!expectedStartTag.equals(parser.getName())) { 13929 if (DEBUG_BACKUP) { 13930 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 13931 } 13932 return; 13933 } 13934 13935 // skip interfering stuff, then we're aligned with the backing implementation 13936 while ((type = parser.next()) == XmlPullParser.TEXT) { } 13937 functor.apply(parser, userId); 13938 } 13939 13940 private interface BlobXmlRestorer { 13941 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 13942 } 13943 13944 /** 13945 * Non-Binder method, support for the backup/restore mechanism: write the 13946 * full set of preferred activities in its canonical XML format. Returns the 13947 * XML output as a byte array, or null if there is none. 13948 */ 13949 @Override 13950 public byte[] getPreferredActivityBackup(int userId) { 13951 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13952 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 13953 } 13954 13955 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13956 try { 13957 final XmlSerializer serializer = new FastXmlSerializer(); 13958 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13959 serializer.startDocument(null, true); 13960 serializer.startTag(null, TAG_PREFERRED_BACKUP); 13961 13962 synchronized (mPackages) { 13963 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 13964 } 13965 13966 serializer.endTag(null, TAG_PREFERRED_BACKUP); 13967 serializer.endDocument(); 13968 serializer.flush(); 13969 } catch (Exception e) { 13970 if (DEBUG_BACKUP) { 13971 Slog.e(TAG, "Unable to write preferred activities for backup", e); 13972 } 13973 return null; 13974 } 13975 13976 return dataStream.toByteArray(); 13977 } 13978 13979 @Override 13980 public void restorePreferredActivities(byte[] backup, int userId) { 13981 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13982 throw new SecurityException("Only the system may call restorePreferredActivities()"); 13983 } 13984 13985 try { 13986 final XmlPullParser parser = Xml.newPullParser(); 13987 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13988 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 13989 new BlobXmlRestorer() { 13990 @Override 13991 public void apply(XmlPullParser parser, int userId) 13992 throws XmlPullParserException, IOException { 13993 synchronized (mPackages) { 13994 mSettings.readPreferredActivitiesLPw(parser, userId); 13995 } 13996 } 13997 } ); 13998 } catch (Exception e) { 13999 if (DEBUG_BACKUP) { 14000 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14001 } 14002 } 14003 } 14004 14005 /** 14006 * Non-Binder method, support for the backup/restore mechanism: write the 14007 * default browser (etc) settings in its canonical XML format. Returns the default 14008 * browser XML representation as a byte array, or null if there is none. 14009 */ 14010 @Override 14011 public byte[] getDefaultAppsBackup(int userId) { 14012 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14013 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 14014 } 14015 14016 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14017 try { 14018 final XmlSerializer serializer = new FastXmlSerializer(); 14019 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14020 serializer.startDocument(null, true); 14021 serializer.startTag(null, TAG_DEFAULT_APPS); 14022 14023 synchronized (mPackages) { 14024 mSettings.writeDefaultAppsLPr(serializer, userId); 14025 } 14026 14027 serializer.endTag(null, TAG_DEFAULT_APPS); 14028 serializer.endDocument(); 14029 serializer.flush(); 14030 } catch (Exception e) { 14031 if (DEBUG_BACKUP) { 14032 Slog.e(TAG, "Unable to write default apps for backup", e); 14033 } 14034 return null; 14035 } 14036 14037 return dataStream.toByteArray(); 14038 } 14039 14040 @Override 14041 public void restoreDefaultApps(byte[] backup, int userId) { 14042 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14043 throw new SecurityException("Only the system may call restoreDefaultApps()"); 14044 } 14045 14046 try { 14047 final XmlPullParser parser = Xml.newPullParser(); 14048 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14049 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 14050 new BlobXmlRestorer() { 14051 @Override 14052 public void apply(XmlPullParser parser, int userId) 14053 throws XmlPullParserException, IOException { 14054 synchronized (mPackages) { 14055 mSettings.readDefaultAppsLPw(parser, userId); 14056 } 14057 } 14058 } ); 14059 } catch (Exception e) { 14060 if (DEBUG_BACKUP) { 14061 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 14062 } 14063 } 14064 } 14065 14066 @Override 14067 public byte[] getIntentFilterVerificationBackup(int userId) { 14068 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14069 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 14070 } 14071 14072 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14073 try { 14074 final XmlSerializer serializer = new FastXmlSerializer(); 14075 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14076 serializer.startDocument(null, true); 14077 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 14078 14079 synchronized (mPackages) { 14080 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 14081 } 14082 14083 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 14084 serializer.endDocument(); 14085 serializer.flush(); 14086 } catch (Exception e) { 14087 if (DEBUG_BACKUP) { 14088 Slog.e(TAG, "Unable to write default apps for backup", e); 14089 } 14090 return null; 14091 } 14092 14093 return dataStream.toByteArray(); 14094 } 14095 14096 @Override 14097 public void restoreIntentFilterVerification(byte[] backup, int userId) { 14098 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14099 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14100 } 14101 14102 try { 14103 final XmlPullParser parser = Xml.newPullParser(); 14104 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14105 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 14106 new BlobXmlRestorer() { 14107 @Override 14108 public void apply(XmlPullParser parser, int userId) 14109 throws XmlPullParserException, IOException { 14110 synchronized (mPackages) { 14111 mSettings.readAllDomainVerificationsLPr(parser, userId); 14112 mSettings.writeLPr(); 14113 } 14114 } 14115 } ); 14116 } catch (Exception e) { 14117 if (DEBUG_BACKUP) { 14118 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14119 } 14120 } 14121 } 14122 14123 @Override 14124 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 14125 int sourceUserId, int targetUserId, int flags) { 14126 mContext.enforceCallingOrSelfPermission( 14127 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14128 int callingUid = Binder.getCallingUid(); 14129 enforceOwnerRights(ownerPackage, callingUid); 14130 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14131 if (intentFilter.countActions() == 0) { 14132 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 14133 return; 14134 } 14135 synchronized (mPackages) { 14136 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 14137 ownerPackage, targetUserId, flags); 14138 CrossProfileIntentResolver resolver = 14139 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14140 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 14141 // We have all those whose filter is equal. Now checking if the rest is equal as well. 14142 if (existing != null) { 14143 int size = existing.size(); 14144 for (int i = 0; i < size; i++) { 14145 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 14146 return; 14147 } 14148 } 14149 } 14150 resolver.addFilter(newFilter); 14151 scheduleWritePackageRestrictionsLocked(sourceUserId); 14152 } 14153 } 14154 14155 @Override 14156 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 14157 mContext.enforceCallingOrSelfPermission( 14158 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14159 int callingUid = Binder.getCallingUid(); 14160 enforceOwnerRights(ownerPackage, callingUid); 14161 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14162 synchronized (mPackages) { 14163 CrossProfileIntentResolver resolver = 14164 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14165 ArraySet<CrossProfileIntentFilter> set = 14166 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 14167 for (CrossProfileIntentFilter filter : set) { 14168 if (filter.getOwnerPackage().equals(ownerPackage)) { 14169 resolver.removeFilter(filter); 14170 } 14171 } 14172 scheduleWritePackageRestrictionsLocked(sourceUserId); 14173 } 14174 } 14175 14176 // Enforcing that callingUid is owning pkg on userId 14177 private void enforceOwnerRights(String pkg, int callingUid) { 14178 // The system owns everything. 14179 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 14180 return; 14181 } 14182 int callingUserId = UserHandle.getUserId(callingUid); 14183 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 14184 if (pi == null) { 14185 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 14186 + callingUserId); 14187 } 14188 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 14189 throw new SecurityException("Calling uid " + callingUid 14190 + " does not own package " + pkg); 14191 } 14192 } 14193 14194 @Override 14195 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 14196 Intent intent = new Intent(Intent.ACTION_MAIN); 14197 intent.addCategory(Intent.CATEGORY_HOME); 14198 14199 final int callingUserId = UserHandle.getCallingUserId(); 14200 List<ResolveInfo> list = queryIntentActivities(intent, null, 14201 PackageManager.GET_META_DATA, callingUserId); 14202 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 14203 true, false, false, callingUserId); 14204 14205 allHomeCandidates.clear(); 14206 if (list != null) { 14207 for (ResolveInfo ri : list) { 14208 allHomeCandidates.add(ri); 14209 } 14210 } 14211 return (preferred == null || preferred.activityInfo == null) 14212 ? null 14213 : new ComponentName(preferred.activityInfo.packageName, 14214 preferred.activityInfo.name); 14215 } 14216 14217 @Override 14218 public void setApplicationEnabledSetting(String appPackageName, 14219 int newState, int flags, int userId, String callingPackage) { 14220 if (!sUserManager.exists(userId)) return; 14221 if (callingPackage == null) { 14222 callingPackage = Integer.toString(Binder.getCallingUid()); 14223 } 14224 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 14225 } 14226 14227 @Override 14228 public void setComponentEnabledSetting(ComponentName componentName, 14229 int newState, int flags, int userId) { 14230 if (!sUserManager.exists(userId)) return; 14231 setEnabledSetting(componentName.getPackageName(), 14232 componentName.getClassName(), newState, flags, userId, null); 14233 } 14234 14235 private void setEnabledSetting(final String packageName, String className, int newState, 14236 final int flags, int userId, String callingPackage) { 14237 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 14238 || newState == COMPONENT_ENABLED_STATE_ENABLED 14239 || newState == COMPONENT_ENABLED_STATE_DISABLED 14240 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 14241 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 14242 throw new IllegalArgumentException("Invalid new component state: " 14243 + newState); 14244 } 14245 PackageSetting pkgSetting; 14246 final int uid = Binder.getCallingUid(); 14247 final int permission = mContext.checkCallingOrSelfPermission( 14248 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14249 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 14250 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14251 boolean sendNow = false; 14252 boolean isApp = (className == null); 14253 String componentName = isApp ? packageName : className; 14254 int packageUid = -1; 14255 ArrayList<String> components; 14256 14257 // writer 14258 synchronized (mPackages) { 14259 pkgSetting = mSettings.mPackages.get(packageName); 14260 if (pkgSetting == null) { 14261 if (className == null) { 14262 throw new IllegalArgumentException( 14263 "Unknown package: " + packageName); 14264 } 14265 throw new IllegalArgumentException( 14266 "Unknown component: " + packageName 14267 + "/" + className); 14268 } 14269 // Allow root and verify that userId is not being specified by a different user 14270 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 14271 throw new SecurityException( 14272 "Permission Denial: attempt to change component state from pid=" 14273 + Binder.getCallingPid() 14274 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 14275 } 14276 if (className == null) { 14277 // We're dealing with an application/package level state change 14278 if (pkgSetting.getEnabled(userId) == newState) { 14279 // Nothing to do 14280 return; 14281 } 14282 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 14283 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 14284 // Don't care about who enables an app. 14285 callingPackage = null; 14286 } 14287 pkgSetting.setEnabled(newState, userId, callingPackage); 14288 // pkgSetting.pkg.mSetEnabled = newState; 14289 } else { 14290 // We're dealing with a component level state change 14291 // First, verify that this is a valid class name. 14292 PackageParser.Package pkg = pkgSetting.pkg; 14293 if (pkg == null || !pkg.hasComponentClassName(className)) { 14294 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 14295 throw new IllegalArgumentException("Component class " + className 14296 + " does not exist in " + packageName); 14297 } else { 14298 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 14299 + className + " does not exist in " + packageName); 14300 } 14301 } 14302 switch (newState) { 14303 case COMPONENT_ENABLED_STATE_ENABLED: 14304 if (!pkgSetting.enableComponentLPw(className, userId)) { 14305 return; 14306 } 14307 break; 14308 case COMPONENT_ENABLED_STATE_DISABLED: 14309 if (!pkgSetting.disableComponentLPw(className, userId)) { 14310 return; 14311 } 14312 break; 14313 case COMPONENT_ENABLED_STATE_DEFAULT: 14314 if (!pkgSetting.restoreComponentLPw(className, userId)) { 14315 return; 14316 } 14317 break; 14318 default: 14319 Slog.e(TAG, "Invalid new component state: " + newState); 14320 return; 14321 } 14322 } 14323 scheduleWritePackageRestrictionsLocked(userId); 14324 components = mPendingBroadcasts.get(userId, packageName); 14325 final boolean newPackage = components == null; 14326 if (newPackage) { 14327 components = new ArrayList<String>(); 14328 } 14329 if (!components.contains(componentName)) { 14330 components.add(componentName); 14331 } 14332 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 14333 sendNow = true; 14334 // Purge entry from pending broadcast list if another one exists already 14335 // since we are sending one right away. 14336 mPendingBroadcasts.remove(userId, packageName); 14337 } else { 14338 if (newPackage) { 14339 mPendingBroadcasts.put(userId, packageName, components); 14340 } 14341 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 14342 // Schedule a message 14343 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 14344 } 14345 } 14346 } 14347 14348 long callingId = Binder.clearCallingIdentity(); 14349 try { 14350 if (sendNow) { 14351 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 14352 sendPackageChangedBroadcast(packageName, 14353 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 14354 } 14355 } finally { 14356 Binder.restoreCallingIdentity(callingId); 14357 } 14358 } 14359 14360 private void sendPackageChangedBroadcast(String packageName, 14361 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 14362 if (DEBUG_INSTALL) 14363 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 14364 + componentNames); 14365 Bundle extras = new Bundle(4); 14366 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 14367 String nameList[] = new String[componentNames.size()]; 14368 componentNames.toArray(nameList); 14369 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 14370 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 14371 extras.putInt(Intent.EXTRA_UID, packageUid); 14372 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 14373 new int[] {UserHandle.getUserId(packageUid)}); 14374 } 14375 14376 @Override 14377 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 14378 if (!sUserManager.exists(userId)) return; 14379 final int uid = Binder.getCallingUid(); 14380 final int permission = mContext.checkCallingOrSelfPermission( 14381 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14382 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14383 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 14384 // writer 14385 synchronized (mPackages) { 14386 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 14387 allowedByPermission, uid, userId)) { 14388 scheduleWritePackageRestrictionsLocked(userId); 14389 } 14390 } 14391 } 14392 14393 @Override 14394 public String getInstallerPackageName(String packageName) { 14395 // reader 14396 synchronized (mPackages) { 14397 return mSettings.getInstallerPackageNameLPr(packageName); 14398 } 14399 } 14400 14401 @Override 14402 public int getApplicationEnabledSetting(String packageName, int userId) { 14403 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14404 int uid = Binder.getCallingUid(); 14405 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 14406 // reader 14407 synchronized (mPackages) { 14408 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 14409 } 14410 } 14411 14412 @Override 14413 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 14414 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14415 int uid = Binder.getCallingUid(); 14416 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 14417 // reader 14418 synchronized (mPackages) { 14419 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 14420 } 14421 } 14422 14423 @Override 14424 public void enterSafeMode() { 14425 enforceSystemOrRoot("Only the system can request entering safe mode"); 14426 14427 if (!mSystemReady) { 14428 mSafeMode = true; 14429 } 14430 } 14431 14432 @Override 14433 public void systemReady() { 14434 mSystemReady = true; 14435 14436 // Read the compatibilty setting when the system is ready. 14437 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 14438 mContext.getContentResolver(), 14439 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 14440 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 14441 if (DEBUG_SETTINGS) { 14442 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 14443 } 14444 14445 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 14446 14447 synchronized (mPackages) { 14448 // Verify that all of the preferred activity components actually 14449 // exist. It is possible for applications to be updated and at 14450 // that point remove a previously declared activity component that 14451 // had been set as a preferred activity. We try to clean this up 14452 // the next time we encounter that preferred activity, but it is 14453 // possible for the user flow to never be able to return to that 14454 // situation so here we do a sanity check to make sure we haven't 14455 // left any junk around. 14456 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 14457 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14458 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14459 removed.clear(); 14460 for (PreferredActivity pa : pir.filterSet()) { 14461 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 14462 removed.add(pa); 14463 } 14464 } 14465 if (removed.size() > 0) { 14466 for (int r=0; r<removed.size(); r++) { 14467 PreferredActivity pa = removed.get(r); 14468 Slog.w(TAG, "Removing dangling preferred activity: " 14469 + pa.mPref.mComponent); 14470 pir.removeFilter(pa); 14471 } 14472 mSettings.writePackageRestrictionsLPr( 14473 mSettings.mPreferredActivities.keyAt(i)); 14474 } 14475 } 14476 14477 for (int userId : UserManagerService.getInstance().getUserIds()) { 14478 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 14479 grantPermissionsUserIds = ArrayUtils.appendInt( 14480 grantPermissionsUserIds, userId); 14481 } 14482 } 14483 } 14484 sUserManager.systemReady(); 14485 14486 // If we upgraded grant all default permissions before kicking off. 14487 for (int userId : grantPermissionsUserIds) { 14488 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 14489 } 14490 14491 // Kick off any messages waiting for system ready 14492 if (mPostSystemReadyMessages != null) { 14493 for (Message msg : mPostSystemReadyMessages) { 14494 msg.sendToTarget(); 14495 } 14496 mPostSystemReadyMessages = null; 14497 } 14498 14499 // Watch for external volumes that come and go over time 14500 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14501 storage.registerListener(mStorageListener); 14502 14503 mInstallerService.systemReady(); 14504 mPackageDexOptimizer.systemReady(); 14505 14506 MountServiceInternal mountServiceInternal = LocalServices.getService( 14507 MountServiceInternal.class); 14508 mountServiceInternal.addExternalStoragePolicy( 14509 new MountServiceInternal.ExternalStorageMountPolicy() { 14510 @Override 14511 public int getMountMode(int uid, String packageName) { 14512 if (Process.isIsolated(uid)) { 14513 return Zygote.MOUNT_EXTERNAL_NONE; 14514 } 14515 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 14516 return Zygote.MOUNT_EXTERNAL_DEFAULT; 14517 } 14518 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 14519 return Zygote.MOUNT_EXTERNAL_DEFAULT; 14520 } 14521 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 14522 return Zygote.MOUNT_EXTERNAL_READ; 14523 } 14524 return Zygote.MOUNT_EXTERNAL_WRITE; 14525 } 14526 14527 @Override 14528 public boolean hasExternalStorage(int uid, String packageName) { 14529 return true; 14530 } 14531 }); 14532 } 14533 14534 @Override 14535 public boolean isSafeMode() { 14536 return mSafeMode; 14537 } 14538 14539 @Override 14540 public boolean hasSystemUidErrors() { 14541 return mHasSystemUidErrors; 14542 } 14543 14544 static String arrayToString(int[] array) { 14545 StringBuffer buf = new StringBuffer(128); 14546 buf.append('['); 14547 if (array != null) { 14548 for (int i=0; i<array.length; i++) { 14549 if (i > 0) buf.append(", "); 14550 buf.append(array[i]); 14551 } 14552 } 14553 buf.append(']'); 14554 return buf.toString(); 14555 } 14556 14557 static class DumpState { 14558 public static final int DUMP_LIBS = 1 << 0; 14559 public static final int DUMP_FEATURES = 1 << 1; 14560 public static final int DUMP_RESOLVERS = 1 << 2; 14561 public static final int DUMP_PERMISSIONS = 1 << 3; 14562 public static final int DUMP_PACKAGES = 1 << 4; 14563 public static final int DUMP_SHARED_USERS = 1 << 5; 14564 public static final int DUMP_MESSAGES = 1 << 6; 14565 public static final int DUMP_PROVIDERS = 1 << 7; 14566 public static final int DUMP_VERIFIERS = 1 << 8; 14567 public static final int DUMP_PREFERRED = 1 << 9; 14568 public static final int DUMP_PREFERRED_XML = 1 << 10; 14569 public static final int DUMP_KEYSETS = 1 << 11; 14570 public static final int DUMP_VERSION = 1 << 12; 14571 public static final int DUMP_INSTALLS = 1 << 13; 14572 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 14573 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 14574 14575 public static final int OPTION_SHOW_FILTERS = 1 << 0; 14576 14577 private int mTypes; 14578 14579 private int mOptions; 14580 14581 private boolean mTitlePrinted; 14582 14583 private SharedUserSetting mSharedUser; 14584 14585 public boolean isDumping(int type) { 14586 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 14587 return true; 14588 } 14589 14590 return (mTypes & type) != 0; 14591 } 14592 14593 public void setDump(int type) { 14594 mTypes |= type; 14595 } 14596 14597 public boolean isOptionEnabled(int option) { 14598 return (mOptions & option) != 0; 14599 } 14600 14601 public void setOptionEnabled(int option) { 14602 mOptions |= option; 14603 } 14604 14605 public boolean onTitlePrinted() { 14606 final boolean printed = mTitlePrinted; 14607 mTitlePrinted = true; 14608 return printed; 14609 } 14610 14611 public boolean getTitlePrinted() { 14612 return mTitlePrinted; 14613 } 14614 14615 public void setTitlePrinted(boolean enabled) { 14616 mTitlePrinted = enabled; 14617 } 14618 14619 public SharedUserSetting getSharedUser() { 14620 return mSharedUser; 14621 } 14622 14623 public void setSharedUser(SharedUserSetting user) { 14624 mSharedUser = user; 14625 } 14626 } 14627 14628 @Override 14629 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 14630 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 14631 != PackageManager.PERMISSION_GRANTED) { 14632 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 14633 + Binder.getCallingPid() 14634 + ", uid=" + Binder.getCallingUid() 14635 + " without permission " 14636 + android.Manifest.permission.DUMP); 14637 return; 14638 } 14639 14640 DumpState dumpState = new DumpState(); 14641 boolean fullPreferred = false; 14642 boolean checkin = false; 14643 14644 String packageName = null; 14645 ArraySet<String> permissionNames = null; 14646 14647 int opti = 0; 14648 while (opti < args.length) { 14649 String opt = args[opti]; 14650 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 14651 break; 14652 } 14653 opti++; 14654 14655 if ("-a".equals(opt)) { 14656 // Right now we only know how to print all. 14657 } else if ("-h".equals(opt)) { 14658 pw.println("Package manager dump options:"); 14659 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 14660 pw.println(" --checkin: dump for a checkin"); 14661 pw.println(" -f: print details of intent filters"); 14662 pw.println(" -h: print this help"); 14663 pw.println(" cmd may be one of:"); 14664 pw.println(" l[ibraries]: list known shared libraries"); 14665 pw.println(" f[ibraries]: list device features"); 14666 pw.println(" k[eysets]: print known keysets"); 14667 pw.println(" r[esolvers]: dump intent resolvers"); 14668 pw.println(" perm[issions]: dump permissions"); 14669 pw.println(" permission [name ...]: dump declaration and use of given permission"); 14670 pw.println(" pref[erred]: print preferred package settings"); 14671 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 14672 pw.println(" prov[iders]: dump content providers"); 14673 pw.println(" p[ackages]: dump installed packages"); 14674 pw.println(" s[hared-users]: dump shared user IDs"); 14675 pw.println(" m[essages]: print collected runtime messages"); 14676 pw.println(" v[erifiers]: print package verifier info"); 14677 pw.println(" version: print database version info"); 14678 pw.println(" write: write current settings now"); 14679 pw.println(" <package.name>: info about given package"); 14680 pw.println(" installs: details about install sessions"); 14681 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 14682 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 14683 return; 14684 } else if ("--checkin".equals(opt)) { 14685 checkin = true; 14686 } else if ("-f".equals(opt)) { 14687 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14688 } else { 14689 pw.println("Unknown argument: " + opt + "; use -h for help"); 14690 } 14691 } 14692 14693 // Is the caller requesting to dump a particular piece of data? 14694 if (opti < args.length) { 14695 String cmd = args[opti]; 14696 opti++; 14697 // Is this a package name? 14698 if ("android".equals(cmd) || cmd.contains(".")) { 14699 packageName = cmd; 14700 // When dumping a single package, we always dump all of its 14701 // filter information since the amount of data will be reasonable. 14702 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14703 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 14704 dumpState.setDump(DumpState.DUMP_LIBS); 14705 } else if ("f".equals(cmd) || "features".equals(cmd)) { 14706 dumpState.setDump(DumpState.DUMP_FEATURES); 14707 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 14708 dumpState.setDump(DumpState.DUMP_RESOLVERS); 14709 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 14710 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 14711 } else if ("permission".equals(cmd)) { 14712 if (opti >= args.length) { 14713 pw.println("Error: permission requires permission name"); 14714 return; 14715 } 14716 permissionNames = new ArraySet<>(); 14717 while (opti < args.length) { 14718 permissionNames.add(args[opti]); 14719 opti++; 14720 } 14721 dumpState.setDump(DumpState.DUMP_PERMISSIONS 14722 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 14723 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 14724 dumpState.setDump(DumpState.DUMP_PREFERRED); 14725 } else if ("preferred-xml".equals(cmd)) { 14726 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 14727 if (opti < args.length && "--full".equals(args[opti])) { 14728 fullPreferred = true; 14729 opti++; 14730 } 14731 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 14732 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 14733 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 14734 dumpState.setDump(DumpState.DUMP_PACKAGES); 14735 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 14736 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 14737 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 14738 dumpState.setDump(DumpState.DUMP_PROVIDERS); 14739 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 14740 dumpState.setDump(DumpState.DUMP_MESSAGES); 14741 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 14742 dumpState.setDump(DumpState.DUMP_VERIFIERS); 14743 } else if ("i".equals(cmd) || "ifv".equals(cmd) 14744 || "intent-filter-verifiers".equals(cmd)) { 14745 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 14746 } else if ("version".equals(cmd)) { 14747 dumpState.setDump(DumpState.DUMP_VERSION); 14748 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 14749 dumpState.setDump(DumpState.DUMP_KEYSETS); 14750 } else if ("installs".equals(cmd)) { 14751 dumpState.setDump(DumpState.DUMP_INSTALLS); 14752 } else if ("write".equals(cmd)) { 14753 synchronized (mPackages) { 14754 mSettings.writeLPr(); 14755 pw.println("Settings written."); 14756 return; 14757 } 14758 } 14759 } 14760 14761 if (checkin) { 14762 pw.println("vers,1"); 14763 } 14764 14765 // reader 14766 synchronized (mPackages) { 14767 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 14768 if (!checkin) { 14769 if (dumpState.onTitlePrinted()) 14770 pw.println(); 14771 pw.println("Database versions:"); 14772 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 14773 } 14774 } 14775 14776 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 14777 if (!checkin) { 14778 if (dumpState.onTitlePrinted()) 14779 pw.println(); 14780 pw.println("Verifiers:"); 14781 pw.print(" Required: "); 14782 pw.print(mRequiredVerifierPackage); 14783 pw.print(" (uid="); 14784 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 14785 pw.println(")"); 14786 } else if (mRequiredVerifierPackage != null) { 14787 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 14788 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 14789 } 14790 } 14791 14792 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 14793 packageName == null) { 14794 if (mIntentFilterVerifierComponent != null) { 14795 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 14796 if (!checkin) { 14797 if (dumpState.onTitlePrinted()) 14798 pw.println(); 14799 pw.println("Intent Filter Verifier:"); 14800 pw.print(" Using: "); 14801 pw.print(verifierPackageName); 14802 pw.print(" (uid="); 14803 pw.print(getPackageUid(verifierPackageName, 0)); 14804 pw.println(")"); 14805 } else if (verifierPackageName != null) { 14806 pw.print("ifv,"); pw.print(verifierPackageName); 14807 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 14808 } 14809 } else { 14810 pw.println(); 14811 pw.println("No Intent Filter Verifier available!"); 14812 } 14813 } 14814 14815 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 14816 boolean printedHeader = false; 14817 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 14818 while (it.hasNext()) { 14819 String name = it.next(); 14820 SharedLibraryEntry ent = mSharedLibraries.get(name); 14821 if (!checkin) { 14822 if (!printedHeader) { 14823 if (dumpState.onTitlePrinted()) 14824 pw.println(); 14825 pw.println("Libraries:"); 14826 printedHeader = true; 14827 } 14828 pw.print(" "); 14829 } else { 14830 pw.print("lib,"); 14831 } 14832 pw.print(name); 14833 if (!checkin) { 14834 pw.print(" -> "); 14835 } 14836 if (ent.path != null) { 14837 if (!checkin) { 14838 pw.print("(jar) "); 14839 pw.print(ent.path); 14840 } else { 14841 pw.print(",jar,"); 14842 pw.print(ent.path); 14843 } 14844 } else { 14845 if (!checkin) { 14846 pw.print("(apk) "); 14847 pw.print(ent.apk); 14848 } else { 14849 pw.print(",apk,"); 14850 pw.print(ent.apk); 14851 } 14852 } 14853 pw.println(); 14854 } 14855 } 14856 14857 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 14858 if (dumpState.onTitlePrinted()) 14859 pw.println(); 14860 if (!checkin) { 14861 pw.println("Features:"); 14862 } 14863 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 14864 while (it.hasNext()) { 14865 String name = it.next(); 14866 if (!checkin) { 14867 pw.print(" "); 14868 } else { 14869 pw.print("feat,"); 14870 } 14871 pw.println(name); 14872 } 14873 } 14874 14875 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 14876 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 14877 : "Activity Resolver Table:", " ", packageName, 14878 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14879 dumpState.setTitlePrinted(true); 14880 } 14881 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 14882 : "Receiver Resolver Table:", " ", packageName, 14883 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14884 dumpState.setTitlePrinted(true); 14885 } 14886 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 14887 : "Service Resolver Table:", " ", packageName, 14888 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14889 dumpState.setTitlePrinted(true); 14890 } 14891 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 14892 : "Provider Resolver Table:", " ", packageName, 14893 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14894 dumpState.setTitlePrinted(true); 14895 } 14896 } 14897 14898 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 14899 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14900 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14901 int user = mSettings.mPreferredActivities.keyAt(i); 14902 if (pir.dump(pw, 14903 dumpState.getTitlePrinted() 14904 ? "\nPreferred Activities User " + user + ":" 14905 : "Preferred Activities User " + user + ":", " ", 14906 packageName, true, false)) { 14907 dumpState.setTitlePrinted(true); 14908 } 14909 } 14910 } 14911 14912 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 14913 pw.flush(); 14914 FileOutputStream fout = new FileOutputStream(fd); 14915 BufferedOutputStream str = new BufferedOutputStream(fout); 14916 XmlSerializer serializer = new FastXmlSerializer(); 14917 try { 14918 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 14919 serializer.startDocument(null, true); 14920 serializer.setFeature( 14921 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 14922 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 14923 serializer.endDocument(); 14924 serializer.flush(); 14925 } catch (IllegalArgumentException e) { 14926 pw.println("Failed writing: " + e); 14927 } catch (IllegalStateException e) { 14928 pw.println("Failed writing: " + e); 14929 } catch (IOException e) { 14930 pw.println("Failed writing: " + e); 14931 } 14932 } 14933 14934 if (!checkin 14935 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 14936 && packageName == null) { 14937 pw.println(); 14938 int count = mSettings.mPackages.size(); 14939 if (count == 0) { 14940 pw.println("No applications!"); 14941 pw.println(); 14942 } else { 14943 final String prefix = " "; 14944 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 14945 if (allPackageSettings.size() == 0) { 14946 pw.println("No domain preferred apps!"); 14947 pw.println(); 14948 } else { 14949 pw.println("App verification status:"); 14950 pw.println(); 14951 count = 0; 14952 for (PackageSetting ps : allPackageSettings) { 14953 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 14954 if (ivi == null || ivi.getPackageName() == null) continue; 14955 pw.println(prefix + "Package: " + ivi.getPackageName()); 14956 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 14957 pw.println(prefix + "Status: " + ivi.getStatusString()); 14958 pw.println(); 14959 count++; 14960 } 14961 if (count == 0) { 14962 pw.println(prefix + "No app verification established."); 14963 pw.println(); 14964 } 14965 for (int userId : sUserManager.getUserIds()) { 14966 pw.println("App linkages for user " + userId + ":"); 14967 pw.println(); 14968 count = 0; 14969 for (PackageSetting ps : allPackageSettings) { 14970 final long status = ps.getDomainVerificationStatusForUser(userId); 14971 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 14972 continue; 14973 } 14974 pw.println(prefix + "Package: " + ps.name); 14975 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 14976 String statusStr = IntentFilterVerificationInfo. 14977 getStatusStringFromValue(status); 14978 pw.println(prefix + "Status: " + statusStr); 14979 pw.println(); 14980 count++; 14981 } 14982 if (count == 0) { 14983 pw.println(prefix + "No configured app linkages."); 14984 pw.println(); 14985 } 14986 } 14987 } 14988 } 14989 } 14990 14991 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 14992 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 14993 if (packageName == null && permissionNames == null) { 14994 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 14995 if (iperm == 0) { 14996 if (dumpState.onTitlePrinted()) 14997 pw.println(); 14998 pw.println("AppOp Permissions:"); 14999 } 15000 pw.print(" AppOp Permission "); 15001 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 15002 pw.println(":"); 15003 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 15004 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 15005 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 15006 } 15007 } 15008 } 15009 } 15010 15011 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 15012 boolean printedSomething = false; 15013 for (PackageParser.Provider p : mProviders.mProviders.values()) { 15014 if (packageName != null && !packageName.equals(p.info.packageName)) { 15015 continue; 15016 } 15017 if (!printedSomething) { 15018 if (dumpState.onTitlePrinted()) 15019 pw.println(); 15020 pw.println("Registered ContentProviders:"); 15021 printedSomething = true; 15022 } 15023 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 15024 pw.print(" "); pw.println(p.toString()); 15025 } 15026 printedSomething = false; 15027 for (Map.Entry<String, PackageParser.Provider> entry : 15028 mProvidersByAuthority.entrySet()) { 15029 PackageParser.Provider p = entry.getValue(); 15030 if (packageName != null && !packageName.equals(p.info.packageName)) { 15031 continue; 15032 } 15033 if (!printedSomething) { 15034 if (dumpState.onTitlePrinted()) 15035 pw.println(); 15036 pw.println("ContentProvider Authorities:"); 15037 printedSomething = true; 15038 } 15039 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 15040 pw.print(" "); pw.println(p.toString()); 15041 if (p.info != null && p.info.applicationInfo != null) { 15042 final String appInfo = p.info.applicationInfo.toString(); 15043 pw.print(" applicationInfo="); pw.println(appInfo); 15044 } 15045 } 15046 } 15047 15048 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 15049 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 15050 } 15051 15052 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 15053 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 15054 } 15055 15056 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 15057 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 15058 } 15059 15060 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 15061 // XXX should handle packageName != null by dumping only install data that 15062 // the given package is involved with. 15063 if (dumpState.onTitlePrinted()) pw.println(); 15064 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 15065 } 15066 15067 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 15068 if (dumpState.onTitlePrinted()) pw.println(); 15069 mSettings.dumpReadMessagesLPr(pw, dumpState); 15070 15071 pw.println(); 15072 pw.println("Package warning messages:"); 15073 BufferedReader in = null; 15074 String line = null; 15075 try { 15076 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15077 while ((line = in.readLine()) != null) { 15078 if (line.contains("ignored: updated version")) continue; 15079 pw.println(line); 15080 } 15081 } catch (IOException ignored) { 15082 } finally { 15083 IoUtils.closeQuietly(in); 15084 } 15085 } 15086 15087 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 15088 BufferedReader in = null; 15089 String line = null; 15090 try { 15091 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15092 while ((line = in.readLine()) != null) { 15093 if (line.contains("ignored: updated version")) continue; 15094 pw.print("msg,"); 15095 pw.println(line); 15096 } 15097 } catch (IOException ignored) { 15098 } finally { 15099 IoUtils.closeQuietly(in); 15100 } 15101 } 15102 } 15103 } 15104 15105 private String dumpDomainString(String packageName) { 15106 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName); 15107 List<IntentFilter> filters = getAllIntentFilters(packageName); 15108 15109 ArraySet<String> result = new ArraySet<>(); 15110 if (iviList.size() > 0) { 15111 for (IntentFilterVerificationInfo ivi : iviList) { 15112 for (String host : ivi.getDomains()) { 15113 result.add(host); 15114 } 15115 } 15116 } 15117 if (filters != null && filters.size() > 0) { 15118 for (IntentFilter filter : filters) { 15119 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 15120 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 15121 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 15122 result.addAll(filter.getHostsList()); 15123 } 15124 } 15125 } 15126 15127 StringBuilder sb = new StringBuilder(result.size() * 16); 15128 for (String domain : result) { 15129 if (sb.length() > 0) sb.append(" "); 15130 sb.append(domain); 15131 } 15132 return sb.toString(); 15133 } 15134 15135 // ------- apps on sdcard specific code ------- 15136 static final boolean DEBUG_SD_INSTALL = false; 15137 15138 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 15139 15140 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 15141 15142 private boolean mMediaMounted = false; 15143 15144 static String getEncryptKey() { 15145 try { 15146 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 15147 SD_ENCRYPTION_KEYSTORE_NAME); 15148 if (sdEncKey == null) { 15149 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 15150 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 15151 if (sdEncKey == null) { 15152 Slog.e(TAG, "Failed to create encryption keys"); 15153 return null; 15154 } 15155 } 15156 return sdEncKey; 15157 } catch (NoSuchAlgorithmException nsae) { 15158 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 15159 return null; 15160 } catch (IOException ioe) { 15161 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 15162 return null; 15163 } 15164 } 15165 15166 /* 15167 * Update media status on PackageManager. 15168 */ 15169 @Override 15170 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 15171 int callingUid = Binder.getCallingUid(); 15172 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 15173 throw new SecurityException("Media status can only be updated by the system"); 15174 } 15175 // reader; this apparently protects mMediaMounted, but should probably 15176 // be a different lock in that case. 15177 synchronized (mPackages) { 15178 Log.i(TAG, "Updating external media status from " 15179 + (mMediaMounted ? "mounted" : "unmounted") + " to " 15180 + (mediaStatus ? "mounted" : "unmounted")); 15181 if (DEBUG_SD_INSTALL) 15182 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 15183 + ", mMediaMounted=" + mMediaMounted); 15184 if (mediaStatus == mMediaMounted) { 15185 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 15186 : 0, -1); 15187 mHandler.sendMessage(msg); 15188 return; 15189 } 15190 mMediaMounted = mediaStatus; 15191 } 15192 // Queue up an async operation since the package installation may take a 15193 // little while. 15194 mHandler.post(new Runnable() { 15195 public void run() { 15196 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 15197 } 15198 }); 15199 } 15200 15201 /** 15202 * Called by MountService when the initial ASECs to scan are available. 15203 * Should block until all the ASEC containers are finished being scanned. 15204 */ 15205 public void scanAvailableAsecs() { 15206 updateExternalMediaStatusInner(true, false, false); 15207 if (mShouldRestoreconData) { 15208 SELinuxMMAC.setRestoreconDone(); 15209 mShouldRestoreconData = false; 15210 } 15211 } 15212 15213 /* 15214 * Collect information of applications on external media, map them against 15215 * existing containers and update information based on current mount status. 15216 * Please note that we always have to report status if reportStatus has been 15217 * set to true especially when unloading packages. 15218 */ 15219 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 15220 boolean externalStorage) { 15221 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 15222 int[] uidArr = EmptyArray.INT; 15223 15224 final String[] list = PackageHelper.getSecureContainerList(); 15225 if (ArrayUtils.isEmpty(list)) { 15226 Log.i(TAG, "No secure containers found"); 15227 } else { 15228 // Process list of secure containers and categorize them 15229 // as active or stale based on their package internal state. 15230 15231 // reader 15232 synchronized (mPackages) { 15233 for (String cid : list) { 15234 // Leave stages untouched for now; installer service owns them 15235 if (PackageInstallerService.isStageName(cid)) continue; 15236 15237 if (DEBUG_SD_INSTALL) 15238 Log.i(TAG, "Processing container " + cid); 15239 String pkgName = getAsecPackageName(cid); 15240 if (pkgName == null) { 15241 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 15242 continue; 15243 } 15244 if (DEBUG_SD_INSTALL) 15245 Log.i(TAG, "Looking for pkg : " + pkgName); 15246 15247 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15248 if (ps == null) { 15249 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 15250 continue; 15251 } 15252 15253 /* 15254 * Skip packages that are not external if we're unmounting 15255 * external storage. 15256 */ 15257 if (externalStorage && !isMounted && !isExternal(ps)) { 15258 continue; 15259 } 15260 15261 final AsecInstallArgs args = new AsecInstallArgs(cid, 15262 getAppDexInstructionSets(ps), ps.isForwardLocked()); 15263 // The package status is changed only if the code path 15264 // matches between settings and the container id. 15265 if (ps.codePathString != null 15266 && ps.codePathString.startsWith(args.getCodePath())) { 15267 if (DEBUG_SD_INSTALL) { 15268 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 15269 + " at code path: " + ps.codePathString); 15270 } 15271 15272 // We do have a valid package installed on sdcard 15273 processCids.put(args, ps.codePathString); 15274 final int uid = ps.appId; 15275 if (uid != -1) { 15276 uidArr = ArrayUtils.appendInt(uidArr, uid); 15277 } 15278 } else { 15279 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 15280 + ps.codePathString); 15281 } 15282 } 15283 } 15284 15285 Arrays.sort(uidArr); 15286 } 15287 15288 // Process packages with valid entries. 15289 if (isMounted) { 15290 if (DEBUG_SD_INSTALL) 15291 Log.i(TAG, "Loading packages"); 15292 loadMediaPackages(processCids, uidArr); 15293 startCleaningPackages(); 15294 mInstallerService.onSecureContainersAvailable(); 15295 } else { 15296 if (DEBUG_SD_INSTALL) 15297 Log.i(TAG, "Unloading packages"); 15298 unloadMediaPackages(processCids, uidArr, reportStatus); 15299 } 15300 } 15301 15302 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15303 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 15304 final int size = infos.size(); 15305 final String[] packageNames = new String[size]; 15306 final int[] packageUids = new int[size]; 15307 for (int i = 0; i < size; i++) { 15308 final ApplicationInfo info = infos.get(i); 15309 packageNames[i] = info.packageName; 15310 packageUids[i] = info.uid; 15311 } 15312 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 15313 finishedReceiver); 15314 } 15315 15316 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15317 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15318 sendResourcesChangedBroadcast(mediaStatus, replacing, 15319 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 15320 } 15321 15322 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15323 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15324 int size = pkgList.length; 15325 if (size > 0) { 15326 // Send broadcasts here 15327 Bundle extras = new Bundle(); 15328 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 15329 if (uidArr != null) { 15330 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 15331 } 15332 if (replacing) { 15333 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 15334 } 15335 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 15336 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 15337 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 15338 } 15339 } 15340 15341 /* 15342 * Look at potentially valid container ids from processCids If package 15343 * information doesn't match the one on record or package scanning fails, 15344 * the cid is added to list of removeCids. We currently don't delete stale 15345 * containers. 15346 */ 15347 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 15348 ArrayList<String> pkgList = new ArrayList<String>(); 15349 Set<AsecInstallArgs> keys = processCids.keySet(); 15350 15351 for (AsecInstallArgs args : keys) { 15352 String codePath = processCids.get(args); 15353 if (DEBUG_SD_INSTALL) 15354 Log.i(TAG, "Loading container : " + args.cid); 15355 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15356 try { 15357 // Make sure there are no container errors first. 15358 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 15359 Slog.e(TAG, "Failed to mount cid : " + args.cid 15360 + " when installing from sdcard"); 15361 continue; 15362 } 15363 // Check code path here. 15364 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 15365 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 15366 + " does not match one in settings " + codePath); 15367 continue; 15368 } 15369 // Parse package 15370 int parseFlags = mDefParseFlags; 15371 if (args.isExternalAsec()) { 15372 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 15373 } 15374 if (args.isFwdLocked()) { 15375 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 15376 } 15377 15378 synchronized (mInstallLock) { 15379 PackageParser.Package pkg = null; 15380 try { 15381 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 15382 } catch (PackageManagerException e) { 15383 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 15384 } 15385 // Scan the package 15386 if (pkg != null) { 15387 /* 15388 * TODO why is the lock being held? doPostInstall is 15389 * called in other places without the lock. This needs 15390 * to be straightened out. 15391 */ 15392 // writer 15393 synchronized (mPackages) { 15394 retCode = PackageManager.INSTALL_SUCCEEDED; 15395 pkgList.add(pkg.packageName); 15396 // Post process args 15397 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 15398 pkg.applicationInfo.uid); 15399 } 15400 } else { 15401 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 15402 } 15403 } 15404 15405 } finally { 15406 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 15407 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 15408 } 15409 } 15410 } 15411 // writer 15412 synchronized (mPackages) { 15413 // If the platform SDK has changed since the last time we booted, 15414 // we need to re-grant app permission to catch any new ones that 15415 // appear. This is really a hack, and means that apps can in some 15416 // cases get permissions that the user didn't initially explicitly 15417 // allow... it would be nice to have some better way to handle 15418 // this situation. 15419 final VersionInfo ver = mSettings.getExternalVersion(); 15420 15421 int updateFlags = UPDATE_PERMISSIONS_ALL; 15422 if (ver.sdkVersion != mSdkVersion) { 15423 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 15424 + mSdkVersion + "; regranting permissions for external"); 15425 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 15426 } 15427 updatePermissionsLPw(null, null, updateFlags); 15428 15429 // Yay, everything is now upgraded 15430 ver.forceCurrent(); 15431 15432 // can downgrade to reader 15433 // Persist settings 15434 mSettings.writeLPr(); 15435 } 15436 // Send a broadcast to let everyone know we are done processing 15437 if (pkgList.size() > 0) { 15438 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 15439 } 15440 } 15441 15442 /* 15443 * Utility method to unload a list of specified containers 15444 */ 15445 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 15446 // Just unmount all valid containers. 15447 for (AsecInstallArgs arg : cidArgs) { 15448 synchronized (mInstallLock) { 15449 arg.doPostDeleteLI(false); 15450 } 15451 } 15452 } 15453 15454 /* 15455 * Unload packages mounted on external media. This involves deleting package 15456 * data from internal structures, sending broadcasts about diabled packages, 15457 * gc'ing to free up references, unmounting all secure containers 15458 * corresponding to packages on external media, and posting a 15459 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 15460 * that we always have to post this message if status has been requested no 15461 * matter what. 15462 */ 15463 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 15464 final boolean reportStatus) { 15465 if (DEBUG_SD_INSTALL) 15466 Log.i(TAG, "unloading media packages"); 15467 ArrayList<String> pkgList = new ArrayList<String>(); 15468 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 15469 final Set<AsecInstallArgs> keys = processCids.keySet(); 15470 for (AsecInstallArgs args : keys) { 15471 String pkgName = args.getPackageName(); 15472 if (DEBUG_SD_INSTALL) 15473 Log.i(TAG, "Trying to unload pkg : " + pkgName); 15474 // Delete package internally 15475 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15476 synchronized (mInstallLock) { 15477 boolean res = deletePackageLI(pkgName, null, false, null, null, 15478 PackageManager.DELETE_KEEP_DATA, outInfo, false); 15479 if (res) { 15480 pkgList.add(pkgName); 15481 } else { 15482 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 15483 failedList.add(args); 15484 } 15485 } 15486 } 15487 15488 // reader 15489 synchronized (mPackages) { 15490 // We didn't update the settings after removing each package; 15491 // write them now for all packages. 15492 mSettings.writeLPr(); 15493 } 15494 15495 // We have to absolutely send UPDATED_MEDIA_STATUS only 15496 // after confirming that all the receivers processed the ordered 15497 // broadcast when packages get disabled, force a gc to clean things up. 15498 // and unload all the containers. 15499 if (pkgList.size() > 0) { 15500 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 15501 new IIntentReceiver.Stub() { 15502 public void performReceive(Intent intent, int resultCode, String data, 15503 Bundle extras, boolean ordered, boolean sticky, 15504 int sendingUser) throws RemoteException { 15505 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 15506 reportStatus ? 1 : 0, 1, keys); 15507 mHandler.sendMessage(msg); 15508 } 15509 }); 15510 } else { 15511 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 15512 keys); 15513 mHandler.sendMessage(msg); 15514 } 15515 } 15516 15517 private void loadPrivatePackages(VolumeInfo vol) { 15518 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 15519 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 15520 synchronized (mInstallLock) { 15521 synchronized (mPackages) { 15522 final VersionInfo ver = mSettings.findOrCreateVersion(vol.fsUuid); 15523 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15524 for (PackageSetting ps : packages) { 15525 final PackageParser.Package pkg; 15526 try { 15527 pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null); 15528 loaded.add(pkg.applicationInfo); 15529 } catch (PackageManagerException e) { 15530 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 15531 } 15532 15533 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 15534 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 15535 } 15536 } 15537 15538 int updateFlags = UPDATE_PERMISSIONS_ALL; 15539 if (ver.sdkVersion != mSdkVersion) { 15540 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 15541 + mSdkVersion + "; regranting permissions for " + vol.fsUuid); 15542 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 15543 } 15544 updatePermissionsLPw(null, null, updateFlags); 15545 15546 // Yay, everything is now upgraded 15547 ver.forceCurrent(); 15548 15549 mSettings.writeLPr(); 15550 } 15551 } 15552 15553 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 15554 sendResourcesChangedBroadcast(true, false, loaded, null); 15555 } 15556 15557 private void unloadPrivatePackages(VolumeInfo vol) { 15558 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 15559 synchronized (mInstallLock) { 15560 synchronized (mPackages) { 15561 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15562 for (PackageSetting ps : packages) { 15563 if (ps.pkg == null) continue; 15564 15565 final ApplicationInfo info = ps.pkg.applicationInfo; 15566 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15567 if (deletePackageLI(ps.name, null, false, null, null, 15568 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 15569 unloaded.add(info); 15570 } else { 15571 Slog.w(TAG, "Failed to unload " + ps.codePath); 15572 } 15573 } 15574 15575 mSettings.writeLPr(); 15576 } 15577 } 15578 15579 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 15580 sendResourcesChangedBroadcast(false, false, unloaded, null); 15581 } 15582 15583 /** 15584 * Examine all users present on given mounted volume, and destroy data 15585 * belonging to users that are no longer valid, or whose user ID has been 15586 * recycled. 15587 */ 15588 private void reconcileUsers(String volumeUuid) { 15589 final File[] files = Environment.getDataUserDirectory(volumeUuid).listFiles(); 15590 if (ArrayUtils.isEmpty(files)) { 15591 Slog.d(TAG, "No users found on " + volumeUuid); 15592 return; 15593 } 15594 15595 for (File file : files) { 15596 if (!file.isDirectory()) continue; 15597 15598 final int userId; 15599 final UserInfo info; 15600 try { 15601 userId = Integer.parseInt(file.getName()); 15602 info = sUserManager.getUserInfo(userId); 15603 } catch (NumberFormatException e) { 15604 Slog.w(TAG, "Invalid user directory " + file); 15605 continue; 15606 } 15607 15608 boolean destroyUser = false; 15609 if (info == null) { 15610 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15611 + " because no matching user was found"); 15612 destroyUser = true; 15613 } else { 15614 try { 15615 UserManagerService.enforceSerialNumber(file, info.serialNumber); 15616 } catch (IOException e) { 15617 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15618 + " because we failed to enforce serial number: " + e); 15619 destroyUser = true; 15620 } 15621 } 15622 15623 if (destroyUser) { 15624 synchronized (mInstallLock) { 15625 mInstaller.removeUserDataDirs(volumeUuid, userId); 15626 } 15627 } 15628 } 15629 15630 final UserManager um = mContext.getSystemService(UserManager.class); 15631 for (UserInfo user : um.getUsers()) { 15632 final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id); 15633 if (userDir.exists()) continue; 15634 15635 try { 15636 UserManagerService.prepareUserDirectory(mContext, volumeUuid, user.id); 15637 UserManagerService.enforceSerialNumber(userDir, user.serialNumber); 15638 } catch (IOException e) { 15639 Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e); 15640 } 15641 } 15642 } 15643 15644 /** 15645 * Examine all apps present on given mounted volume, and destroy apps that 15646 * aren't expected, either due to uninstallation or reinstallation on 15647 * another volume. 15648 */ 15649 private void reconcileApps(String volumeUuid) { 15650 final File[] files = Environment.getDataAppDirectory(volumeUuid).listFiles(); 15651 if (ArrayUtils.isEmpty(files)) { 15652 Slog.d(TAG, "No apps found on " + volumeUuid); 15653 return; 15654 } 15655 15656 for (File file : files) { 15657 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 15658 && !PackageInstallerService.isStageName(file.getName()); 15659 if (!isPackage) { 15660 // Ignore entries which are not packages 15661 continue; 15662 } 15663 15664 boolean destroyApp = false; 15665 String packageName = null; 15666 try { 15667 final PackageLite pkg = PackageParser.parsePackageLite(file, 15668 PackageParser.PARSE_MUST_BE_APK); 15669 packageName = pkg.packageName; 15670 15671 synchronized (mPackages) { 15672 final PackageSetting ps = mSettings.mPackages.get(packageName); 15673 if (ps == null) { 15674 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + " 15675 + volumeUuid + " because we found no install record"); 15676 destroyApp = true; 15677 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 15678 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on " 15679 + volumeUuid + " because we expected it on " + ps.volumeUuid); 15680 destroyApp = true; 15681 } 15682 } 15683 15684 } catch (PackageParserException e) { 15685 logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e); 15686 destroyApp = true; 15687 } 15688 15689 if (destroyApp) { 15690 synchronized (mInstallLock) { 15691 if (packageName != null) { 15692 removeDataDirsLI(volumeUuid, packageName); 15693 } 15694 if (file.isDirectory()) { 15695 mInstaller.rmPackageDir(file.getAbsolutePath()); 15696 } else { 15697 file.delete(); 15698 } 15699 } 15700 } 15701 } 15702 } 15703 15704 private void unfreezePackage(String packageName) { 15705 synchronized (mPackages) { 15706 final PackageSetting ps = mSettings.mPackages.get(packageName); 15707 if (ps != null) { 15708 ps.frozen = false; 15709 } 15710 } 15711 } 15712 15713 @Override 15714 public int movePackage(final String packageName, final String volumeUuid) { 15715 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15716 15717 final int moveId = mNextMoveId.getAndIncrement(); 15718 try { 15719 movePackageInternal(packageName, volumeUuid, moveId); 15720 } catch (PackageManagerException e) { 15721 Slog.w(TAG, "Failed to move " + packageName, e); 15722 mMoveCallbacks.notifyStatusChanged(moveId, 15723 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15724 } 15725 return moveId; 15726 } 15727 15728 private void movePackageInternal(final String packageName, final String volumeUuid, 15729 final int moveId) throws PackageManagerException { 15730 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 15731 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15732 final PackageManager pm = mContext.getPackageManager(); 15733 15734 final boolean currentAsec; 15735 final String currentVolumeUuid; 15736 final File codeFile; 15737 final String installerPackageName; 15738 final String packageAbiOverride; 15739 final int appId; 15740 final String seinfo; 15741 final String label; 15742 15743 // reader 15744 synchronized (mPackages) { 15745 final PackageParser.Package pkg = mPackages.get(packageName); 15746 final PackageSetting ps = mSettings.mPackages.get(packageName); 15747 if (pkg == null || ps == null) { 15748 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 15749 } 15750 15751 if (pkg.applicationInfo.isSystemApp()) { 15752 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 15753 "Cannot move system application"); 15754 } 15755 15756 if (Objects.equals(ps.volumeUuid, volumeUuid)) { 15757 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15758 "Package already moved to " + volumeUuid); 15759 } 15760 15761 final File probe = new File(pkg.codePath); 15762 final File probeOat = new File(probe, "oat"); 15763 if (!probe.isDirectory() || !probeOat.isDirectory()) { 15764 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15765 "Move only supported for modern cluster style installs"); 15766 } 15767 15768 if (ps.frozen) { 15769 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 15770 "Failed to move already frozen package"); 15771 } 15772 ps.frozen = true; 15773 15774 currentAsec = pkg.applicationInfo.isForwardLocked() 15775 || pkg.applicationInfo.isExternalAsec(); 15776 currentVolumeUuid = ps.volumeUuid; 15777 codeFile = new File(pkg.codePath); 15778 installerPackageName = ps.installerPackageName; 15779 packageAbiOverride = ps.cpuAbiOverrideString; 15780 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 15781 seinfo = pkg.applicationInfo.seinfo; 15782 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 15783 } 15784 15785 // Now that we're guarded by frozen state, kill app during move 15786 killApplication(packageName, appId, "move pkg"); 15787 15788 final Bundle extras = new Bundle(); 15789 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 15790 extras.putString(Intent.EXTRA_TITLE, label); 15791 mMoveCallbacks.notifyCreated(moveId, extras); 15792 15793 int installFlags; 15794 final boolean moveCompleteApp; 15795 final File measurePath; 15796 15797 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 15798 installFlags = INSTALL_INTERNAL; 15799 moveCompleteApp = !currentAsec; 15800 measurePath = Environment.getDataAppDirectory(volumeUuid); 15801 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 15802 installFlags = INSTALL_EXTERNAL; 15803 moveCompleteApp = false; 15804 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 15805 } else { 15806 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 15807 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 15808 || !volume.isMountedWritable()) { 15809 unfreezePackage(packageName); 15810 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15811 "Move location not mounted private volume"); 15812 } 15813 15814 Preconditions.checkState(!currentAsec); 15815 15816 installFlags = INSTALL_INTERNAL; 15817 moveCompleteApp = true; 15818 measurePath = Environment.getDataAppDirectory(volumeUuid); 15819 } 15820 15821 final PackageStats stats = new PackageStats(null, -1); 15822 synchronized (mInstaller) { 15823 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 15824 unfreezePackage(packageName); 15825 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15826 "Failed to measure package size"); 15827 } 15828 } 15829 15830 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 15831 + stats.dataSize); 15832 15833 final long startFreeBytes = measurePath.getFreeSpace(); 15834 final long sizeBytes; 15835 if (moveCompleteApp) { 15836 sizeBytes = stats.codeSize + stats.dataSize; 15837 } else { 15838 sizeBytes = stats.codeSize; 15839 } 15840 15841 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 15842 unfreezePackage(packageName); 15843 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15844 "Not enough free space to move"); 15845 } 15846 15847 mMoveCallbacks.notifyStatusChanged(moveId, 10); 15848 15849 final CountDownLatch installedLatch = new CountDownLatch(1); 15850 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 15851 @Override 15852 public void onUserActionRequired(Intent intent) throws RemoteException { 15853 throw new IllegalStateException(); 15854 } 15855 15856 @Override 15857 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 15858 Bundle extras) throws RemoteException { 15859 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 15860 + PackageManager.installStatusToString(returnCode, msg)); 15861 15862 installedLatch.countDown(); 15863 15864 // Regardless of success or failure of the move operation, 15865 // always unfreeze the package 15866 unfreezePackage(packageName); 15867 15868 final int status = PackageManager.installStatusToPublicStatus(returnCode); 15869 switch (status) { 15870 case PackageInstaller.STATUS_SUCCESS: 15871 mMoveCallbacks.notifyStatusChanged(moveId, 15872 PackageManager.MOVE_SUCCEEDED); 15873 break; 15874 case PackageInstaller.STATUS_FAILURE_STORAGE: 15875 mMoveCallbacks.notifyStatusChanged(moveId, 15876 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 15877 break; 15878 default: 15879 mMoveCallbacks.notifyStatusChanged(moveId, 15880 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15881 break; 15882 } 15883 } 15884 }; 15885 15886 final MoveInfo move; 15887 if (moveCompleteApp) { 15888 // Kick off a thread to report progress estimates 15889 new Thread() { 15890 @Override 15891 public void run() { 15892 while (true) { 15893 try { 15894 if (installedLatch.await(1, TimeUnit.SECONDS)) { 15895 break; 15896 } 15897 } catch (InterruptedException ignored) { 15898 } 15899 15900 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 15901 final int progress = 10 + (int) MathUtils.constrain( 15902 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 15903 mMoveCallbacks.notifyStatusChanged(moveId, progress); 15904 } 15905 } 15906 }.start(); 15907 15908 final String dataAppName = codeFile.getName(); 15909 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 15910 dataAppName, appId, seinfo); 15911 } else { 15912 move = null; 15913 } 15914 15915 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 15916 15917 final Message msg = mHandler.obtainMessage(INIT_COPY); 15918 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 15919 msg.obj = new InstallParams(origin, move, installObserver, installFlags, 15920 installerPackageName, volumeUuid, null, user, packageAbiOverride, null); 15921 mHandler.sendMessage(msg); 15922 } 15923 15924 @Override 15925 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 15926 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15927 15928 final int realMoveId = mNextMoveId.getAndIncrement(); 15929 final Bundle extras = new Bundle(); 15930 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 15931 mMoveCallbacks.notifyCreated(realMoveId, extras); 15932 15933 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 15934 @Override 15935 public void onCreated(int moveId, Bundle extras) { 15936 // Ignored 15937 } 15938 15939 @Override 15940 public void onStatusChanged(int moveId, int status, long estMillis) { 15941 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 15942 } 15943 }; 15944 15945 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15946 storage.setPrimaryStorageUuid(volumeUuid, callback); 15947 return realMoveId; 15948 } 15949 15950 @Override 15951 public int getMoveStatus(int moveId) { 15952 mContext.enforceCallingOrSelfPermission( 15953 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15954 return mMoveCallbacks.mLastStatus.get(moveId); 15955 } 15956 15957 @Override 15958 public void registerMoveCallback(IPackageMoveObserver callback) { 15959 mContext.enforceCallingOrSelfPermission( 15960 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15961 mMoveCallbacks.register(callback); 15962 } 15963 15964 @Override 15965 public void unregisterMoveCallback(IPackageMoveObserver callback) { 15966 mContext.enforceCallingOrSelfPermission( 15967 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15968 mMoveCallbacks.unregister(callback); 15969 } 15970 15971 @Override 15972 public boolean setInstallLocation(int loc) { 15973 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 15974 null); 15975 if (getInstallLocation() == loc) { 15976 return true; 15977 } 15978 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 15979 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 15980 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 15981 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 15982 return true; 15983 } 15984 return false; 15985 } 15986 15987 @Override 15988 public int getInstallLocation() { 15989 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 15990 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 15991 PackageHelper.APP_INSTALL_AUTO); 15992 } 15993 15994 /** Called by UserManagerService */ 15995 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 15996 mDirtyUsers.remove(userHandle); 15997 mSettings.removeUserLPw(userHandle); 15998 mPendingBroadcasts.remove(userHandle); 15999 if (mInstaller != null) { 16000 // Technically, we shouldn't be doing this with the package lock 16001 // held. However, this is very rare, and there is already so much 16002 // other disk I/O going on, that we'll let it slide for now. 16003 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16004 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 16005 final String volumeUuid = vol.getFsUuid(); 16006 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 16007 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 16008 } 16009 } 16010 mUserNeedsBadging.delete(userHandle); 16011 removeUnusedPackagesLILPw(userManager, userHandle); 16012 } 16013 16014 /** 16015 * We're removing userHandle and would like to remove any downloaded packages 16016 * that are no longer in use by any other user. 16017 * @param userHandle the user being removed 16018 */ 16019 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 16020 final boolean DEBUG_CLEAN_APKS = false; 16021 int [] users = userManager.getUserIdsLPr(); 16022 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 16023 while (psit.hasNext()) { 16024 PackageSetting ps = psit.next(); 16025 if (ps.pkg == null) { 16026 continue; 16027 } 16028 final String packageName = ps.pkg.packageName; 16029 // Skip over if system app 16030 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 16031 continue; 16032 } 16033 if (DEBUG_CLEAN_APKS) { 16034 Slog.i(TAG, "Checking package " + packageName); 16035 } 16036 boolean keep = false; 16037 for (int i = 0; i < users.length; i++) { 16038 if (users[i] != userHandle && ps.getInstalled(users[i])) { 16039 keep = true; 16040 if (DEBUG_CLEAN_APKS) { 16041 Slog.i(TAG, " Keeping package " + packageName + " for user " 16042 + users[i]); 16043 } 16044 break; 16045 } 16046 } 16047 if (!keep) { 16048 if (DEBUG_CLEAN_APKS) { 16049 Slog.i(TAG, " Removing package " + packageName); 16050 } 16051 mHandler.post(new Runnable() { 16052 public void run() { 16053 deletePackageX(packageName, userHandle, 0); 16054 } //end run 16055 }); 16056 } 16057 } 16058 } 16059 16060 /** Called by UserManagerService */ 16061 void createNewUserLILPw(int userHandle) { 16062 if (mInstaller != null) { 16063 mInstaller.createUserConfig(userHandle); 16064 mSettings.createNewUserLILPw(this, mInstaller, userHandle); 16065 applyFactoryDefaultBrowserLPw(userHandle); 16066 primeDomainVerificationsLPw(userHandle); 16067 } 16068 } 16069 16070 void newUserCreated(final int userHandle) { 16071 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 16072 } 16073 16074 @Override 16075 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 16076 mContext.enforceCallingOrSelfPermission( 16077 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 16078 "Only package verification agents can read the verifier device identity"); 16079 16080 synchronized (mPackages) { 16081 return mSettings.getVerifierDeviceIdentityLPw(); 16082 } 16083 } 16084 16085 @Override 16086 public void setPermissionEnforced(String permission, boolean enforced) { 16087 // TODO: Now that we no longer change GID for storage, this should to away. 16088 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 16089 "setPermissionEnforced"); 16090 if (READ_EXTERNAL_STORAGE.equals(permission)) { 16091 synchronized (mPackages) { 16092 if (mSettings.mReadExternalStorageEnforced == null 16093 || mSettings.mReadExternalStorageEnforced != enforced) { 16094 mSettings.mReadExternalStorageEnforced = enforced; 16095 mSettings.writeLPr(); 16096 } 16097 } 16098 // kill any non-foreground processes so we restart them and 16099 // grant/revoke the GID. 16100 final IActivityManager am = ActivityManagerNative.getDefault(); 16101 if (am != null) { 16102 final long token = Binder.clearCallingIdentity(); 16103 try { 16104 am.killProcessesBelowForeground("setPermissionEnforcement"); 16105 } catch (RemoteException e) { 16106 } finally { 16107 Binder.restoreCallingIdentity(token); 16108 } 16109 } 16110 } else { 16111 throw new IllegalArgumentException("No selective enforcement for " + permission); 16112 } 16113 } 16114 16115 @Override 16116 @Deprecated 16117 public boolean isPermissionEnforced(String permission) { 16118 return true; 16119 } 16120 16121 @Override 16122 public boolean isStorageLow() { 16123 final long token = Binder.clearCallingIdentity(); 16124 try { 16125 final DeviceStorageMonitorInternal 16126 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 16127 if (dsm != null) { 16128 return dsm.isMemoryLow(); 16129 } else { 16130 return false; 16131 } 16132 } finally { 16133 Binder.restoreCallingIdentity(token); 16134 } 16135 } 16136 16137 @Override 16138 public IPackageInstaller getPackageInstaller() { 16139 return mInstallerService; 16140 } 16141 16142 private boolean userNeedsBadging(int userId) { 16143 int index = mUserNeedsBadging.indexOfKey(userId); 16144 if (index < 0) { 16145 final UserInfo userInfo; 16146 final long token = Binder.clearCallingIdentity(); 16147 try { 16148 userInfo = sUserManager.getUserInfo(userId); 16149 } finally { 16150 Binder.restoreCallingIdentity(token); 16151 } 16152 final boolean b; 16153 if (userInfo != null && userInfo.isManagedProfile()) { 16154 b = true; 16155 } else { 16156 b = false; 16157 } 16158 mUserNeedsBadging.put(userId, b); 16159 return b; 16160 } 16161 return mUserNeedsBadging.valueAt(index); 16162 } 16163 16164 @Override 16165 public KeySet getKeySetByAlias(String packageName, String alias) { 16166 if (packageName == null || alias == 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 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16176 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 16177 } 16178 } 16179 16180 @Override 16181 public KeySet getSigningKeySet(String packageName) { 16182 if (packageName == null) { 16183 return null; 16184 } 16185 synchronized(mPackages) { 16186 final PackageParser.Package pkg = mPackages.get(packageName); 16187 if (pkg == null) { 16188 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16189 throw new IllegalArgumentException("Unknown package: " + packageName); 16190 } 16191 if (pkg.applicationInfo.uid != Binder.getCallingUid() 16192 && Process.SYSTEM_UID != Binder.getCallingUid()) { 16193 throw new SecurityException("May not access signing KeySet of other apps."); 16194 } 16195 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16196 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 16197 } 16198 } 16199 16200 @Override 16201 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 16202 if (packageName == null || ks == null) { 16203 return false; 16204 } 16205 synchronized(mPackages) { 16206 final PackageParser.Package pkg = mPackages.get(packageName); 16207 if (pkg == null) { 16208 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16209 throw new IllegalArgumentException("Unknown package: " + packageName); 16210 } 16211 IBinder ksh = ks.getToken(); 16212 if (ksh instanceof KeySetHandle) { 16213 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16214 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 16215 } 16216 return false; 16217 } 16218 } 16219 16220 @Override 16221 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 16222 if (packageName == null || ks == null) { 16223 return false; 16224 } 16225 synchronized(mPackages) { 16226 final PackageParser.Package pkg = mPackages.get(packageName); 16227 if (pkg == null) { 16228 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16229 throw new IllegalArgumentException("Unknown package: " + packageName); 16230 } 16231 IBinder ksh = ks.getToken(); 16232 if (ksh instanceof KeySetHandle) { 16233 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16234 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 16235 } 16236 return false; 16237 } 16238 } 16239 16240 public void getUsageStatsIfNoPackageUsageInfo() { 16241 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 16242 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 16243 if (usm == null) { 16244 throw new IllegalStateException("UsageStatsManager must be initialized"); 16245 } 16246 long now = System.currentTimeMillis(); 16247 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 16248 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 16249 String packageName = entry.getKey(); 16250 PackageParser.Package pkg = mPackages.get(packageName); 16251 if (pkg == null) { 16252 continue; 16253 } 16254 UsageStats usage = entry.getValue(); 16255 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 16256 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 16257 } 16258 } 16259 } 16260 16261 /** 16262 * Check and throw if the given before/after packages would be considered a 16263 * downgrade. 16264 */ 16265 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 16266 throws PackageManagerException { 16267 if (after.versionCode < before.mVersionCode) { 16268 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16269 "Update version code " + after.versionCode + " is older than current " 16270 + before.mVersionCode); 16271 } else if (after.versionCode == before.mVersionCode) { 16272 if (after.baseRevisionCode < before.baseRevisionCode) { 16273 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16274 "Update base revision code " + after.baseRevisionCode 16275 + " is older than current " + before.baseRevisionCode); 16276 } 16277 16278 if (!ArrayUtils.isEmpty(after.splitNames)) { 16279 for (int i = 0; i < after.splitNames.length; i++) { 16280 final String splitName = after.splitNames[i]; 16281 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 16282 if (j != -1) { 16283 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 16284 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16285 "Update split " + splitName + " revision code " 16286 + after.splitRevisionCodes[i] + " is older than current " 16287 + before.splitRevisionCodes[j]); 16288 } 16289 } 16290 } 16291 } 16292 } 16293 } 16294 16295 private static class MoveCallbacks extends Handler { 16296 private static final int MSG_CREATED = 1; 16297 private static final int MSG_STATUS_CHANGED = 2; 16298 16299 private final RemoteCallbackList<IPackageMoveObserver> 16300 mCallbacks = new RemoteCallbackList<>(); 16301 16302 private final SparseIntArray mLastStatus = new SparseIntArray(); 16303 16304 public MoveCallbacks(Looper looper) { 16305 super(looper); 16306 } 16307 16308 public void register(IPackageMoveObserver callback) { 16309 mCallbacks.register(callback); 16310 } 16311 16312 public void unregister(IPackageMoveObserver callback) { 16313 mCallbacks.unregister(callback); 16314 } 16315 16316 @Override 16317 public void handleMessage(Message msg) { 16318 final SomeArgs args = (SomeArgs) msg.obj; 16319 final int n = mCallbacks.beginBroadcast(); 16320 for (int i = 0; i < n; i++) { 16321 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 16322 try { 16323 invokeCallback(callback, msg.what, args); 16324 } catch (RemoteException ignored) { 16325 } 16326 } 16327 mCallbacks.finishBroadcast(); 16328 args.recycle(); 16329 } 16330 16331 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 16332 throws RemoteException { 16333 switch (what) { 16334 case MSG_CREATED: { 16335 callback.onCreated(args.argi1, (Bundle) args.arg2); 16336 break; 16337 } 16338 case MSG_STATUS_CHANGED: { 16339 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 16340 break; 16341 } 16342 } 16343 } 16344 16345 private void notifyCreated(int moveId, Bundle extras) { 16346 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 16347 16348 final SomeArgs args = SomeArgs.obtain(); 16349 args.argi1 = moveId; 16350 args.arg2 = extras; 16351 obtainMessage(MSG_CREATED, args).sendToTarget(); 16352 } 16353 16354 private void notifyStatusChanged(int moveId, int status) { 16355 notifyStatusChanged(moveId, status, -1); 16356 } 16357 16358 private void notifyStatusChanged(int moveId, int status, long estMillis) { 16359 Slog.v(TAG, "Move " + moveId + " status " + status); 16360 16361 final SomeArgs args = SomeArgs.obtain(); 16362 args.argi1 = moveId; 16363 args.argi2 = status; 16364 args.arg3 = estMillis; 16365 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 16366 16367 synchronized (mLastStatus) { 16368 mLastStatus.put(moveId, status); 16369 } 16370 } 16371 } 16372 16373 private final class OnPermissionChangeListeners extends Handler { 16374 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 16375 16376 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 16377 new RemoteCallbackList<>(); 16378 16379 public OnPermissionChangeListeners(Looper looper) { 16380 super(looper); 16381 } 16382 16383 @Override 16384 public void handleMessage(Message msg) { 16385 switch (msg.what) { 16386 case MSG_ON_PERMISSIONS_CHANGED: { 16387 final int uid = msg.arg1; 16388 handleOnPermissionsChanged(uid); 16389 } break; 16390 } 16391 } 16392 16393 public void addListenerLocked(IOnPermissionsChangeListener listener) { 16394 mPermissionListeners.register(listener); 16395 16396 } 16397 16398 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 16399 mPermissionListeners.unregister(listener); 16400 } 16401 16402 public void onPermissionsChanged(int uid) { 16403 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 16404 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 16405 } 16406 } 16407 16408 private void handleOnPermissionsChanged(int uid) { 16409 final int count = mPermissionListeners.beginBroadcast(); 16410 try { 16411 for (int i = 0; i < count; i++) { 16412 IOnPermissionsChangeListener callback = mPermissionListeners 16413 .getBroadcastItem(i); 16414 try { 16415 callback.onPermissionsChanged(uid); 16416 } catch (RemoteException e) { 16417 Log.e(TAG, "Permission listener is dead", e); 16418 } 16419 } 16420 } finally { 16421 mPermissionListeners.finishBroadcast(); 16422 } 16423 } 16424 } 16425 16426 private class PackageManagerInternalImpl extends PackageManagerInternal { 16427 @Override 16428 public void setLocationPackagesProvider(PackagesProvider provider) { 16429 synchronized (mPackages) { 16430 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 16431 } 16432 } 16433 16434 @Override 16435 public void setImePackagesProvider(PackagesProvider provider) { 16436 synchronized (mPackages) { 16437 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 16438 } 16439 } 16440 16441 @Override 16442 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 16443 synchronized (mPackages) { 16444 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 16445 } 16446 } 16447 16448 @Override 16449 public void setSmsAppPackagesProvider(PackagesProvider provider) { 16450 synchronized (mPackages) { 16451 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 16452 } 16453 } 16454 16455 @Override 16456 public void setDialerAppPackagesProvider(PackagesProvider provider) { 16457 synchronized (mPackages) { 16458 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 16459 } 16460 } 16461 16462 @Override 16463 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 16464 synchronized (mPackages) { 16465 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 16466 } 16467 } 16468 16469 @Override 16470 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 16471 synchronized (mPackages) { 16472 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 16473 packageName, userId); 16474 } 16475 } 16476 16477 @Override 16478 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 16479 synchronized (mPackages) { 16480 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 16481 packageName, userId); 16482 } 16483 } 16484 } 16485 16486 @Override 16487 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 16488 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 16489 synchronized (mPackages) { 16490 final long identity = Binder.clearCallingIdentity(); 16491 try { 16492 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 16493 packageNames, userId); 16494 } finally { 16495 Binder.restoreCallingIdentity(identity); 16496 } 16497 } 16498 } 16499 16500 private static void enforceSystemOrPhoneCaller(String tag) { 16501 int callingUid = Binder.getCallingUid(); 16502 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 16503 throw new SecurityException( 16504 "Cannot call " + tag + " from UID " + callingUid); 16505 } 16506 } 16507} 16508