PackageManagerService.java revision 2a89545739b4efef4bd6535206ad0f5a813df39f
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.GRANT_REVOKE_PERMISSIONS; 20import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 21import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 22import static android.Manifest.permission.WRITE_MEDIA_STORAGE; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 27import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 28import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 29import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 31import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 32import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 34import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 35import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 36import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 37import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 40import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 41import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 42import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 43import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 44import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 45import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 46import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 47import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 48import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 49import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED; 50import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 51import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 52import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 53import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 54import static android.content.pm.PackageManager.INSTALL_INTERNAL; 55import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 60import static android.content.pm.PackageManager.MATCH_ALL; 61import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 62import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 63import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 64import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 65import static android.content.pm.PackageManager.PERMISSION_DENIED; 66import static android.content.pm.PackageManager.PERMISSION_GRANTED; 67import static android.content.pm.PackageParser.isApkFile; 68import static android.os.Process.PACKAGE_INFO_GID; 69import static android.os.Process.SYSTEM_UID; 70import static android.system.OsConstants.O_CREAT; 71import static android.system.OsConstants.O_RDWR; 72import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 73import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER; 74import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 75import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 76import static com.android.internal.util.ArrayUtils.appendInt; 77import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 78import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 79import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 80import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 81import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 82import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 83import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 84import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 85 86import android.Manifest; 87import android.app.ActivityManager; 88import android.app.ActivityManagerNative; 89import android.app.AppGlobals; 90import android.app.IActivityManager; 91import android.app.admin.IDevicePolicyManager; 92import android.app.backup.IBackupManager; 93import android.app.usage.UsageStats; 94import android.app.usage.UsageStatsManager; 95import android.content.BroadcastReceiver; 96import android.content.ComponentName; 97import android.content.Context; 98import android.content.IIntentReceiver; 99import android.content.Intent; 100import android.content.IntentFilter; 101import android.content.IntentSender; 102import android.content.IntentSender.SendIntentException; 103import android.content.ServiceConnection; 104import android.content.pm.ActivityInfo; 105import android.content.pm.ApplicationInfo; 106import android.content.pm.FeatureInfo; 107import android.content.pm.IOnPermissionsChangeListener; 108import android.content.pm.IPackageDataObserver; 109import android.content.pm.IPackageDeleteObserver; 110import android.content.pm.IPackageDeleteObserver2; 111import android.content.pm.IPackageInstallObserver2; 112import android.content.pm.IPackageInstaller; 113import android.content.pm.IPackageManager; 114import android.content.pm.IPackageMoveObserver; 115import android.content.pm.IPackageStatsObserver; 116import android.content.pm.InstrumentationInfo; 117import android.content.pm.IntentFilterVerificationInfo; 118import android.content.pm.KeySet; 119import android.content.pm.ManifestDigest; 120import android.content.pm.PackageCleanItem; 121import android.content.pm.PackageInfo; 122import android.content.pm.PackageInfoLite; 123import android.content.pm.PackageInstaller; 124import android.content.pm.PackageManager; 125import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 126import android.content.pm.PackageManagerInternal; 127import android.content.pm.PackageParser; 128import android.content.pm.PackageParser.ActivityIntentInfo; 129import android.content.pm.PackageParser.PackageLite; 130import android.content.pm.PackageParser.PackageParserException; 131import android.content.pm.PackageStats; 132import android.content.pm.PackageUserState; 133import android.content.pm.ParceledListSlice; 134import android.content.pm.PermissionGroupInfo; 135import android.content.pm.PermissionInfo; 136import android.content.pm.ProviderInfo; 137import android.content.pm.ResolveInfo; 138import android.content.pm.ServiceInfo; 139import android.content.pm.Signature; 140import android.content.pm.UserInfo; 141import android.content.pm.VerificationParams; 142import android.content.pm.VerifierDeviceIdentity; 143import android.content.pm.VerifierInfo; 144import android.content.res.Resources; 145import android.hardware.display.DisplayManager; 146import android.net.Uri; 147import android.os.Debug; 148import android.os.Binder; 149import android.os.Build; 150import android.os.Bundle; 151import android.os.Environment; 152import android.os.Environment.UserEnvironment; 153import android.os.FileUtils; 154import android.os.Handler; 155import android.os.IBinder; 156import android.os.Looper; 157import android.os.Message; 158import android.os.Parcel; 159import android.os.ParcelFileDescriptor; 160import android.os.Process; 161import android.os.RemoteCallbackList; 162import android.os.RemoteException; 163import android.os.SELinux; 164import android.os.ServiceManager; 165import android.os.SystemClock; 166import android.os.SystemProperties; 167import android.os.UserHandle; 168import android.os.UserManager; 169import android.os.storage.IMountService; 170import android.os.storage.MountServiceInternal; 171import android.os.storage.StorageEventListener; 172import android.os.storage.StorageManager; 173import android.os.storage.VolumeInfo; 174import android.os.storage.VolumeRecord; 175import android.security.KeyStore; 176import android.security.SystemKeyStore; 177import android.system.ErrnoException; 178import android.system.Os; 179import android.system.StructStat; 180import android.text.TextUtils; 181import android.text.format.DateUtils; 182import android.util.ArrayMap; 183import android.util.ArraySet; 184import android.util.AtomicFile; 185import android.util.DisplayMetrics; 186import android.util.EventLog; 187import android.util.ExceptionUtils; 188import android.util.Log; 189import android.util.LogPrinter; 190import android.util.MathUtils; 191import android.util.PrintStreamPrinter; 192import android.util.Slog; 193import android.util.SparseArray; 194import android.util.SparseBooleanArray; 195import android.util.SparseIntArray; 196import android.util.Xml; 197import android.view.Display; 198 199import dalvik.system.DexFile; 200import dalvik.system.VMRuntime; 201 202import libcore.io.IoUtils; 203import libcore.util.EmptyArray; 204 205import com.android.internal.R; 206import com.android.internal.annotations.GuardedBy; 207import com.android.internal.app.IMediaContainerService; 208import com.android.internal.app.ResolverActivity; 209import com.android.internal.content.NativeLibraryHelper; 210import com.android.internal.content.PackageHelper; 211import com.android.internal.os.IParcelFileDescriptorFactory; 212import com.android.internal.os.SomeArgs; 213import com.android.internal.os.Zygote; 214import com.android.internal.util.ArrayUtils; 215import com.android.internal.util.FastPrintWriter; 216import com.android.internal.util.FastXmlSerializer; 217import com.android.internal.util.IndentingPrintWriter; 218import com.android.internal.util.Preconditions; 219import com.android.server.EventLogTags; 220import com.android.server.FgThread; 221import com.android.server.IntentResolver; 222import com.android.server.LocalServices; 223import com.android.server.ServiceThread; 224import com.android.server.SystemConfig; 225import com.android.server.Watchdog; 226import com.android.server.pm.PermissionsState.PermissionState; 227import com.android.server.pm.Settings.DatabaseVersion; 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 boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 805 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS); 806 if (!hasHTTPorHTTPS) { 807 return false; 808 } 809 return true; 810 } 811 812 private IntentFilterVerifier mIntentFilterVerifier; 813 814 // Set of pending broadcasts for aggregating enable/disable of components. 815 static class PendingPackageBroadcasts { 816 // for each user id, a map of <package name -> components within that package> 817 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 818 819 public PendingPackageBroadcasts() { 820 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 821 } 822 823 public ArrayList<String> get(int userId, String packageName) { 824 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 825 return packages.get(packageName); 826 } 827 828 public void put(int userId, String packageName, ArrayList<String> components) { 829 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 830 packages.put(packageName, components); 831 } 832 833 public void remove(int userId, String packageName) { 834 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 835 if (packages != null) { 836 packages.remove(packageName); 837 } 838 } 839 840 public void remove(int userId) { 841 mUidMap.remove(userId); 842 } 843 844 public int userIdCount() { 845 return mUidMap.size(); 846 } 847 848 public int userIdAt(int n) { 849 return mUidMap.keyAt(n); 850 } 851 852 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 853 return mUidMap.get(userId); 854 } 855 856 public int size() { 857 // total number of pending broadcast entries across all userIds 858 int num = 0; 859 for (int i = 0; i< mUidMap.size(); i++) { 860 num += mUidMap.valueAt(i).size(); 861 } 862 return num; 863 } 864 865 public void clear() { 866 mUidMap.clear(); 867 } 868 869 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 870 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 871 if (map == null) { 872 map = new ArrayMap<String, ArrayList<String>>(); 873 mUidMap.put(userId, map); 874 } 875 return map; 876 } 877 } 878 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 879 880 // Service Connection to remote media container service to copy 881 // package uri's from external media onto secure containers 882 // or internal storage. 883 private IMediaContainerService mContainerService = null; 884 885 static final int SEND_PENDING_BROADCAST = 1; 886 static final int MCS_BOUND = 3; 887 static final int END_COPY = 4; 888 static final int INIT_COPY = 5; 889 static final int MCS_UNBIND = 6; 890 static final int START_CLEANING_PACKAGE = 7; 891 static final int FIND_INSTALL_LOC = 8; 892 static final int POST_INSTALL = 9; 893 static final int MCS_RECONNECT = 10; 894 static final int MCS_GIVE_UP = 11; 895 static final int UPDATED_MEDIA_STATUS = 12; 896 static final int WRITE_SETTINGS = 13; 897 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 898 static final int PACKAGE_VERIFIED = 15; 899 static final int CHECK_PENDING_VERIFICATION = 16; 900 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 901 static final int INTENT_FILTER_VERIFIED = 18; 902 903 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 904 905 // Delay time in millisecs 906 static final int BROADCAST_DELAY = 10 * 1000; 907 908 static UserManagerService sUserManager; 909 910 // Stores a list of users whose package restrictions file needs to be updated 911 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 912 913 final private DefaultContainerConnection mDefContainerConn = 914 new DefaultContainerConnection(); 915 class DefaultContainerConnection implements ServiceConnection { 916 public void onServiceConnected(ComponentName name, IBinder service) { 917 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 918 IMediaContainerService imcs = 919 IMediaContainerService.Stub.asInterface(service); 920 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 921 } 922 923 public void onServiceDisconnected(ComponentName name) { 924 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 925 } 926 } 927 928 // Recordkeeping of restore-after-install operations that are currently in flight 929 // between the Package Manager and the Backup Manager 930 class PostInstallData { 931 public InstallArgs args; 932 public PackageInstalledInfo res; 933 934 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 935 args = _a; 936 res = _r; 937 } 938 } 939 940 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 941 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 942 943 // XML tags for backup/restore of various bits of state 944 private static final String TAG_PREFERRED_BACKUP = "pa"; 945 private static final String TAG_DEFAULT_APPS = "da"; 946 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 947 948 final String mRequiredVerifierPackage; 949 final String mRequiredInstallerPackage; 950 951 private final PackageUsage mPackageUsage = new PackageUsage(); 952 953 private class PackageUsage { 954 private static final int WRITE_INTERVAL 955 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 956 957 private final Object mFileLock = new Object(); 958 private final AtomicLong mLastWritten = new AtomicLong(0); 959 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 960 961 private boolean mIsHistoricalPackageUsageAvailable = true; 962 963 boolean isHistoricalPackageUsageAvailable() { 964 return mIsHistoricalPackageUsageAvailable; 965 } 966 967 void write(boolean force) { 968 if (force) { 969 writeInternal(); 970 return; 971 } 972 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 973 && !DEBUG_DEXOPT) { 974 return; 975 } 976 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 977 new Thread("PackageUsage_DiskWriter") { 978 @Override 979 public void run() { 980 try { 981 writeInternal(); 982 } finally { 983 mBackgroundWriteRunning.set(false); 984 } 985 } 986 }.start(); 987 } 988 } 989 990 private void writeInternal() { 991 synchronized (mPackages) { 992 synchronized (mFileLock) { 993 AtomicFile file = getFile(); 994 FileOutputStream f = null; 995 try { 996 f = file.startWrite(); 997 BufferedOutputStream out = new BufferedOutputStream(f); 998 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 999 StringBuilder sb = new StringBuilder(); 1000 for (PackageParser.Package pkg : mPackages.values()) { 1001 if (pkg.mLastPackageUsageTimeInMills == 0) { 1002 continue; 1003 } 1004 sb.setLength(0); 1005 sb.append(pkg.packageName); 1006 sb.append(' '); 1007 sb.append((long)pkg.mLastPackageUsageTimeInMills); 1008 sb.append('\n'); 1009 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1010 } 1011 out.flush(); 1012 file.finishWrite(f); 1013 } catch (IOException e) { 1014 if (f != null) { 1015 file.failWrite(f); 1016 } 1017 Log.e(TAG, "Failed to write package usage times", e); 1018 } 1019 } 1020 } 1021 mLastWritten.set(SystemClock.elapsedRealtime()); 1022 } 1023 1024 void readLP() { 1025 synchronized (mFileLock) { 1026 AtomicFile file = getFile(); 1027 BufferedInputStream in = null; 1028 try { 1029 in = new BufferedInputStream(file.openRead()); 1030 StringBuffer sb = new StringBuffer(); 1031 while (true) { 1032 String packageName = readToken(in, sb, ' '); 1033 if (packageName == null) { 1034 break; 1035 } 1036 String timeInMillisString = readToken(in, sb, '\n'); 1037 if (timeInMillisString == null) { 1038 throw new IOException("Failed to find last usage time for package " 1039 + packageName); 1040 } 1041 PackageParser.Package pkg = mPackages.get(packageName); 1042 if (pkg == null) { 1043 continue; 1044 } 1045 long timeInMillis; 1046 try { 1047 timeInMillis = Long.parseLong(timeInMillisString.toString()); 1048 } catch (NumberFormatException e) { 1049 throw new IOException("Failed to parse " + timeInMillisString 1050 + " as a long.", e); 1051 } 1052 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1053 } 1054 } catch (FileNotFoundException expected) { 1055 mIsHistoricalPackageUsageAvailable = false; 1056 } catch (IOException e) { 1057 Log.w(TAG, "Failed to read package usage times", e); 1058 } finally { 1059 IoUtils.closeQuietly(in); 1060 } 1061 } 1062 mLastWritten.set(SystemClock.elapsedRealtime()); 1063 } 1064 1065 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1066 throws IOException { 1067 sb.setLength(0); 1068 while (true) { 1069 int ch = in.read(); 1070 if (ch == -1) { 1071 if (sb.length() == 0) { 1072 return null; 1073 } 1074 throw new IOException("Unexpected EOF"); 1075 } 1076 if (ch == endOfToken) { 1077 return sb.toString(); 1078 } 1079 sb.append((char)ch); 1080 } 1081 } 1082 1083 private AtomicFile getFile() { 1084 File dataDir = Environment.getDataDirectory(); 1085 File systemDir = new File(dataDir, "system"); 1086 File fname = new File(systemDir, "package-usage.list"); 1087 return new AtomicFile(fname); 1088 } 1089 } 1090 1091 class PackageHandler extends Handler { 1092 private boolean mBound = false; 1093 final ArrayList<HandlerParams> mPendingInstalls = 1094 new ArrayList<HandlerParams>(); 1095 1096 private boolean connectToService() { 1097 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1098 " DefaultContainerService"); 1099 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1100 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1101 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1102 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 1103 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1104 mBound = true; 1105 return true; 1106 } 1107 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1108 return false; 1109 } 1110 1111 private void disconnectService() { 1112 mContainerService = null; 1113 mBound = false; 1114 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1115 mContext.unbindService(mDefContainerConn); 1116 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1117 } 1118 1119 PackageHandler(Looper looper) { 1120 super(looper); 1121 } 1122 1123 public void handleMessage(Message msg) { 1124 try { 1125 doHandleMessage(msg); 1126 } finally { 1127 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1128 } 1129 } 1130 1131 void doHandleMessage(Message msg) { 1132 switch (msg.what) { 1133 case INIT_COPY: { 1134 HandlerParams params = (HandlerParams) msg.obj; 1135 int idx = mPendingInstalls.size(); 1136 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1137 // If a bind was already initiated we dont really 1138 // need to do anything. The pending install 1139 // will be processed later on. 1140 if (!mBound) { 1141 // If this is the only one pending we might 1142 // have to bind to the service again. 1143 if (!connectToService()) { 1144 Slog.e(TAG, "Failed to bind to media container service"); 1145 params.serviceError(); 1146 return; 1147 } else { 1148 // Once we bind to the service, the first 1149 // pending request will be processed. 1150 mPendingInstalls.add(idx, params); 1151 } 1152 } else { 1153 mPendingInstalls.add(idx, params); 1154 // Already bound to the service. Just make 1155 // sure we trigger off processing the first request. 1156 if (idx == 0) { 1157 mHandler.sendEmptyMessage(MCS_BOUND); 1158 } 1159 } 1160 break; 1161 } 1162 case MCS_BOUND: { 1163 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1164 if (msg.obj != null) { 1165 mContainerService = (IMediaContainerService) msg.obj; 1166 } 1167 if (mContainerService == null) { 1168 if (!mBound) { 1169 // Something seriously wrong since we are not bound and we are not 1170 // waiting for connection. Bail out. 1171 Slog.e(TAG, "Cannot bind to media container service"); 1172 for (HandlerParams params : mPendingInstalls) { 1173 // Indicate service bind error 1174 params.serviceError(); 1175 } 1176 mPendingInstalls.clear(); 1177 } else { 1178 Slog.w(TAG, "Waiting to connect to media container service"); 1179 } 1180 } else if (mPendingInstalls.size() > 0) { 1181 HandlerParams params = mPendingInstalls.get(0); 1182 if (params != null) { 1183 if (params.startCopy()) { 1184 // We are done... look for more work or to 1185 // go idle. 1186 if (DEBUG_SD_INSTALL) Log.i(TAG, 1187 "Checking for more work or unbind..."); 1188 // Delete pending install 1189 if (mPendingInstalls.size() > 0) { 1190 mPendingInstalls.remove(0); 1191 } 1192 if (mPendingInstalls.size() == 0) { 1193 if (mBound) { 1194 if (DEBUG_SD_INSTALL) Log.i(TAG, 1195 "Posting delayed MCS_UNBIND"); 1196 removeMessages(MCS_UNBIND); 1197 Message ubmsg = obtainMessage(MCS_UNBIND); 1198 // Unbind after a little delay, to avoid 1199 // continual thrashing. 1200 sendMessageDelayed(ubmsg, 10000); 1201 } 1202 } else { 1203 // There are more pending requests in queue. 1204 // Just post MCS_BOUND message to trigger processing 1205 // of next pending install. 1206 if (DEBUG_SD_INSTALL) Log.i(TAG, 1207 "Posting MCS_BOUND for next work"); 1208 mHandler.sendEmptyMessage(MCS_BOUND); 1209 } 1210 } 1211 } 1212 } else { 1213 // Should never happen ideally. 1214 Slog.w(TAG, "Empty queue"); 1215 } 1216 break; 1217 } 1218 case MCS_RECONNECT: { 1219 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1220 if (mPendingInstalls.size() > 0) { 1221 if (mBound) { 1222 disconnectService(); 1223 } 1224 if (!connectToService()) { 1225 Slog.e(TAG, "Failed to bind to media container service"); 1226 for (HandlerParams params : mPendingInstalls) { 1227 // Indicate service bind error 1228 params.serviceError(); 1229 } 1230 mPendingInstalls.clear(); 1231 } 1232 } 1233 break; 1234 } 1235 case MCS_UNBIND: { 1236 // If there is no actual work left, then time to unbind. 1237 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1238 1239 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1240 if (mBound) { 1241 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1242 1243 disconnectService(); 1244 } 1245 } else if (mPendingInstalls.size() > 0) { 1246 // There are more pending requests in queue. 1247 // Just post MCS_BOUND message to trigger processing 1248 // of next pending install. 1249 mHandler.sendEmptyMessage(MCS_BOUND); 1250 } 1251 1252 break; 1253 } 1254 case MCS_GIVE_UP: { 1255 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1256 mPendingInstalls.remove(0); 1257 break; 1258 } 1259 case SEND_PENDING_BROADCAST: { 1260 String packages[]; 1261 ArrayList<String> components[]; 1262 int size = 0; 1263 int uids[]; 1264 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1265 synchronized (mPackages) { 1266 if (mPendingBroadcasts == null) { 1267 return; 1268 } 1269 size = mPendingBroadcasts.size(); 1270 if (size <= 0) { 1271 // Nothing to be done. Just return 1272 return; 1273 } 1274 packages = new String[size]; 1275 components = new ArrayList[size]; 1276 uids = new int[size]; 1277 int i = 0; // filling out the above arrays 1278 1279 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1280 int packageUserId = mPendingBroadcasts.userIdAt(n); 1281 Iterator<Map.Entry<String, ArrayList<String>>> it 1282 = mPendingBroadcasts.packagesForUserId(packageUserId) 1283 .entrySet().iterator(); 1284 while (it.hasNext() && i < size) { 1285 Map.Entry<String, ArrayList<String>> ent = it.next(); 1286 packages[i] = ent.getKey(); 1287 components[i] = ent.getValue(); 1288 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1289 uids[i] = (ps != null) 1290 ? UserHandle.getUid(packageUserId, ps.appId) 1291 : -1; 1292 i++; 1293 } 1294 } 1295 size = i; 1296 mPendingBroadcasts.clear(); 1297 } 1298 // Send broadcasts 1299 for (int i = 0; i < size; i++) { 1300 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1301 } 1302 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1303 break; 1304 } 1305 case START_CLEANING_PACKAGE: { 1306 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1307 final String packageName = (String)msg.obj; 1308 final int userId = msg.arg1; 1309 final boolean andCode = msg.arg2 != 0; 1310 synchronized (mPackages) { 1311 if (userId == UserHandle.USER_ALL) { 1312 int[] users = sUserManager.getUserIds(); 1313 for (int user : users) { 1314 mSettings.addPackageToCleanLPw( 1315 new PackageCleanItem(user, packageName, andCode)); 1316 } 1317 } else { 1318 mSettings.addPackageToCleanLPw( 1319 new PackageCleanItem(userId, packageName, andCode)); 1320 } 1321 } 1322 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1323 startCleaningPackages(); 1324 } break; 1325 case POST_INSTALL: { 1326 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1327 PostInstallData data = mRunningInstalls.get(msg.arg1); 1328 mRunningInstalls.delete(msg.arg1); 1329 boolean deleteOld = false; 1330 1331 if (data != null) { 1332 InstallArgs args = data.args; 1333 PackageInstalledInfo res = data.res; 1334 1335 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1336 final String packageName = res.pkg.applicationInfo.packageName; 1337 res.removedInfo.sendBroadcast(false, true, false); 1338 Bundle extras = new Bundle(1); 1339 extras.putInt(Intent.EXTRA_UID, res.uid); 1340 1341 // Now that we successfully installed the package, grant runtime 1342 // permissions if requested before broadcasting the install. 1343 if ((args.installFlags 1344 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1345 grantRequestedRuntimePermissions(res.pkg, 1346 args.user.getIdentifier()); 1347 } 1348 1349 // Determine the set of users who are adding this 1350 // package for the first time vs. those who are seeing 1351 // an update. 1352 int[] firstUsers; 1353 int[] updateUsers = new int[0]; 1354 if (res.origUsers == null || res.origUsers.length == 0) { 1355 firstUsers = res.newUsers; 1356 } else { 1357 firstUsers = new int[0]; 1358 for (int i=0; i<res.newUsers.length; i++) { 1359 int user = res.newUsers[i]; 1360 boolean isNew = true; 1361 for (int j=0; j<res.origUsers.length; j++) { 1362 if (res.origUsers[j] == user) { 1363 isNew = false; 1364 break; 1365 } 1366 } 1367 if (isNew) { 1368 int[] newFirst = new int[firstUsers.length+1]; 1369 System.arraycopy(firstUsers, 0, newFirst, 0, 1370 firstUsers.length); 1371 newFirst[firstUsers.length] = user; 1372 firstUsers = newFirst; 1373 } else { 1374 int[] newUpdate = new int[updateUsers.length+1]; 1375 System.arraycopy(updateUsers, 0, newUpdate, 0, 1376 updateUsers.length); 1377 newUpdate[updateUsers.length] = user; 1378 updateUsers = newUpdate; 1379 } 1380 } 1381 } 1382 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1383 packageName, extras, null, null, firstUsers); 1384 final boolean update = res.removedInfo.removedPackage != null; 1385 if (update) { 1386 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1387 } 1388 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1389 packageName, extras, null, null, updateUsers); 1390 if (update) { 1391 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1392 packageName, extras, null, null, updateUsers); 1393 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1394 null, null, packageName, null, updateUsers); 1395 1396 // treat asec-hosted packages like removable media on upgrade 1397 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1398 if (DEBUG_INSTALL) { 1399 Slog.i(TAG, "upgrading pkg " + res.pkg 1400 + " is ASEC-hosted -> AVAILABLE"); 1401 } 1402 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1403 ArrayList<String> pkgList = new ArrayList<String>(1); 1404 pkgList.add(packageName); 1405 sendResourcesChangedBroadcast(true, true, 1406 pkgList,uidArray, null); 1407 } 1408 } 1409 if (res.removedInfo.args != null) { 1410 // Remove the replaced package's older resources safely now 1411 deleteOld = true; 1412 } 1413 1414 // If this app is a browser and it's newly-installed for some 1415 // users, clear any default-browser state in those users 1416 if (firstUsers.length > 0) { 1417 // the app's nature doesn't depend on the user, so we can just 1418 // check its browser nature in any user and generalize. 1419 if (packageIsBrowser(packageName, firstUsers[0])) { 1420 synchronized (mPackages) { 1421 for (int userId : firstUsers) { 1422 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1423 } 1424 } 1425 } 1426 } 1427 // Log current value of "unknown sources" setting 1428 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1429 getUnknownSourcesSettings()); 1430 } 1431 // Force a gc to clear up things 1432 Runtime.getRuntime().gc(); 1433 // We delete after a gc for applications on sdcard. 1434 if (deleteOld) { 1435 synchronized (mInstallLock) { 1436 res.removedInfo.args.doPostDeleteLI(true); 1437 } 1438 } 1439 if (args.observer != null) { 1440 try { 1441 Bundle extras = extrasForInstallResult(res); 1442 args.observer.onPackageInstalled(res.name, res.returnCode, 1443 res.returnMsg, extras); 1444 } catch (RemoteException e) { 1445 Slog.i(TAG, "Observer no longer exists."); 1446 } 1447 } 1448 } else { 1449 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1450 } 1451 } break; 1452 case UPDATED_MEDIA_STATUS: { 1453 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1454 boolean reportStatus = msg.arg1 == 1; 1455 boolean doGc = msg.arg2 == 1; 1456 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1457 if (doGc) { 1458 // Force a gc to clear up stale containers. 1459 Runtime.getRuntime().gc(); 1460 } 1461 if (msg.obj != null) { 1462 @SuppressWarnings("unchecked") 1463 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1464 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1465 // Unload containers 1466 unloadAllContainers(args); 1467 } 1468 if (reportStatus) { 1469 try { 1470 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1471 PackageHelper.getMountService().finishMediaUpdate(); 1472 } catch (RemoteException e) { 1473 Log.e(TAG, "MountService not running?"); 1474 } 1475 } 1476 } break; 1477 case WRITE_SETTINGS: { 1478 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1479 synchronized (mPackages) { 1480 removeMessages(WRITE_SETTINGS); 1481 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1482 mSettings.writeLPr(); 1483 mDirtyUsers.clear(); 1484 } 1485 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1486 } break; 1487 case WRITE_PACKAGE_RESTRICTIONS: { 1488 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1489 synchronized (mPackages) { 1490 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1491 for (int userId : mDirtyUsers) { 1492 mSettings.writePackageRestrictionsLPr(userId); 1493 } 1494 mDirtyUsers.clear(); 1495 } 1496 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1497 } break; 1498 case CHECK_PENDING_VERIFICATION: { 1499 final int verificationId = msg.arg1; 1500 final PackageVerificationState state = mPendingVerification.get(verificationId); 1501 1502 if ((state != null) && !state.timeoutExtended()) { 1503 final InstallArgs args = state.getInstallArgs(); 1504 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1505 1506 Slog.i(TAG, "Verification timed out for " + originUri); 1507 mPendingVerification.remove(verificationId); 1508 1509 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1510 1511 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1512 Slog.i(TAG, "Continuing with installation of " + originUri); 1513 state.setVerifierResponse(Binder.getCallingUid(), 1514 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1515 broadcastPackageVerified(verificationId, originUri, 1516 PackageManager.VERIFICATION_ALLOW, 1517 state.getInstallArgs().getUser()); 1518 try { 1519 ret = args.copyApk(mContainerService, true); 1520 } catch (RemoteException e) { 1521 Slog.e(TAG, "Could not contact the ContainerService"); 1522 } 1523 } else { 1524 broadcastPackageVerified(verificationId, originUri, 1525 PackageManager.VERIFICATION_REJECT, 1526 state.getInstallArgs().getUser()); 1527 } 1528 1529 processPendingInstall(args, ret); 1530 mHandler.sendEmptyMessage(MCS_UNBIND); 1531 } 1532 break; 1533 } 1534 case PACKAGE_VERIFIED: { 1535 final int verificationId = msg.arg1; 1536 1537 final PackageVerificationState state = mPendingVerification.get(verificationId); 1538 if (state == null) { 1539 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1540 break; 1541 } 1542 1543 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1544 1545 state.setVerifierResponse(response.callerUid, response.code); 1546 1547 if (state.isVerificationComplete()) { 1548 mPendingVerification.remove(verificationId); 1549 1550 final InstallArgs args = state.getInstallArgs(); 1551 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1552 1553 int ret; 1554 if (state.isInstallAllowed()) { 1555 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1556 broadcastPackageVerified(verificationId, originUri, 1557 response.code, state.getInstallArgs().getUser()); 1558 try { 1559 ret = args.copyApk(mContainerService, true); 1560 } catch (RemoteException e) { 1561 Slog.e(TAG, "Could not contact the ContainerService"); 1562 } 1563 } else { 1564 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1565 } 1566 1567 processPendingInstall(args, ret); 1568 1569 mHandler.sendEmptyMessage(MCS_UNBIND); 1570 } 1571 1572 break; 1573 } 1574 case START_INTENT_FILTER_VERIFICATIONS: { 1575 IFVerificationParams params = (IFVerificationParams) msg.obj; 1576 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1577 params.replacing, params.pkg); 1578 break; 1579 } 1580 case INTENT_FILTER_VERIFIED: { 1581 final int verificationId = msg.arg1; 1582 1583 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1584 verificationId); 1585 if (state == null) { 1586 Slog.w(TAG, "Invalid IntentFilter verification token " 1587 + verificationId + " received"); 1588 break; 1589 } 1590 1591 final int userId = state.getUserId(); 1592 1593 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1594 "Processing IntentFilter verification with token:" 1595 + verificationId + " and userId:" + userId); 1596 1597 final IntentFilterVerificationResponse response = 1598 (IntentFilterVerificationResponse) msg.obj; 1599 1600 state.setVerifierResponse(response.callerUid, response.code); 1601 1602 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1603 "IntentFilter verification with token:" + verificationId 1604 + " and userId:" + userId 1605 + " is settings verifier response with response code:" 1606 + response.code); 1607 1608 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1609 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1610 + response.getFailedDomainsString()); 1611 } 1612 1613 if (state.isVerificationComplete()) { 1614 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1615 } else { 1616 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1617 "IntentFilter verification with token:" + verificationId 1618 + " was not said to be complete"); 1619 } 1620 1621 break; 1622 } 1623 } 1624 } 1625 } 1626 1627 private StorageEventListener mStorageListener = new StorageEventListener() { 1628 @Override 1629 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1630 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1631 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1632 final String volumeUuid = vol.getFsUuid(); 1633 1634 // Clean up any users or apps that were removed or recreated 1635 // while this volume was missing 1636 reconcileUsers(volumeUuid); 1637 reconcileApps(volumeUuid); 1638 1639 // Clean up any install sessions that expired or were 1640 // cancelled while this volume was missing 1641 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1642 1643 loadPrivatePackages(vol); 1644 1645 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1646 unloadPrivatePackages(vol); 1647 } 1648 } 1649 1650 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1651 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1652 updateExternalMediaStatus(true, false); 1653 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1654 updateExternalMediaStatus(false, false); 1655 } 1656 } 1657 } 1658 1659 @Override 1660 public void onVolumeForgotten(String fsUuid) { 1661 // Remove any apps installed on the forgotten volume 1662 synchronized (mPackages) { 1663 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1664 for (PackageSetting ps : packages) { 1665 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1666 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1667 UserHandle.USER_OWNER, PackageManager.DELETE_ALL_USERS); 1668 } 1669 1670 mSettings.writeLPr(); 1671 } 1672 } 1673 }; 1674 1675 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) { 1676 if (userId >= UserHandle.USER_OWNER) { 1677 grantRequestedRuntimePermissionsForUser(pkg, userId); 1678 } else if (userId == UserHandle.USER_ALL) { 1679 for (int someUserId : UserManagerService.getInstance().getUserIds()) { 1680 grantRequestedRuntimePermissionsForUser(pkg, someUserId); 1681 } 1682 } 1683 1684 // We could have touched GID membership, so flush out packages.list 1685 synchronized (mPackages) { 1686 mSettings.writePackageListLPr(); 1687 } 1688 } 1689 1690 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) { 1691 SettingBase sb = (SettingBase) pkg.mExtras; 1692 if (sb == null) { 1693 return; 1694 } 1695 1696 PermissionsState permissionsState = sb.getPermissionsState(); 1697 1698 for (String permission : pkg.requestedPermissions) { 1699 BasePermission bp = mSettings.mPermissions.get(permission); 1700 if (bp != null && bp.isRuntime()) { 1701 permissionsState.grantRuntimePermission(bp, userId); 1702 } 1703 } 1704 } 1705 1706 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1707 Bundle extras = null; 1708 switch (res.returnCode) { 1709 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1710 extras = new Bundle(); 1711 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1712 res.origPermission); 1713 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1714 res.origPackage); 1715 break; 1716 } 1717 case PackageManager.INSTALL_SUCCEEDED: { 1718 extras = new Bundle(); 1719 extras.putBoolean(Intent.EXTRA_REPLACING, 1720 res.removedInfo != null && res.removedInfo.removedPackage != null); 1721 break; 1722 } 1723 } 1724 return extras; 1725 } 1726 1727 void scheduleWriteSettingsLocked() { 1728 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1729 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1730 } 1731 } 1732 1733 void scheduleWritePackageRestrictionsLocked(int userId) { 1734 if (!sUserManager.exists(userId)) return; 1735 mDirtyUsers.add(userId); 1736 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1737 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1738 } 1739 } 1740 1741 public static PackageManagerService main(Context context, Installer installer, 1742 boolean factoryTest, boolean onlyCore) { 1743 PackageManagerService m = new PackageManagerService(context, installer, 1744 factoryTest, onlyCore); 1745 ServiceManager.addService("package", m); 1746 return m; 1747 } 1748 1749 static String[] splitString(String str, char sep) { 1750 int count = 1; 1751 int i = 0; 1752 while ((i=str.indexOf(sep, i)) >= 0) { 1753 count++; 1754 i++; 1755 } 1756 1757 String[] res = new String[count]; 1758 i=0; 1759 count = 0; 1760 int lastI=0; 1761 while ((i=str.indexOf(sep, i)) >= 0) { 1762 res[count] = str.substring(lastI, i); 1763 count++; 1764 i++; 1765 lastI = i; 1766 } 1767 res[count] = str.substring(lastI, str.length()); 1768 return res; 1769 } 1770 1771 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1772 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1773 Context.DISPLAY_SERVICE); 1774 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1775 } 1776 1777 public PackageManagerService(Context context, Installer installer, 1778 boolean factoryTest, boolean onlyCore) { 1779 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1780 SystemClock.uptimeMillis()); 1781 1782 if (mSdkVersion <= 0) { 1783 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1784 } 1785 1786 mContext = context; 1787 mFactoryTest = factoryTest; 1788 mOnlyCore = onlyCore; 1789 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1790 mMetrics = new DisplayMetrics(); 1791 mSettings = new Settings(mPackages); 1792 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1793 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1794 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1795 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1796 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1797 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1798 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1799 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1800 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1801 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1802 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1803 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1804 1805 // TODO: add a property to control this? 1806 long dexOptLRUThresholdInMinutes; 1807 if (mLazyDexOpt) { 1808 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1809 } else { 1810 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1811 } 1812 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1813 1814 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1815 if (separateProcesses != null && separateProcesses.length() > 0) { 1816 if ("*".equals(separateProcesses)) { 1817 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1818 mSeparateProcesses = null; 1819 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1820 } else { 1821 mDefParseFlags = 0; 1822 mSeparateProcesses = separateProcesses.split(","); 1823 Slog.w(TAG, "Running with debug.separate_processes: " 1824 + separateProcesses); 1825 } 1826 } else { 1827 mDefParseFlags = 0; 1828 mSeparateProcesses = null; 1829 } 1830 1831 mInstaller = installer; 1832 mPackageDexOptimizer = new PackageDexOptimizer(this); 1833 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1834 1835 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 1836 FgThread.get().getLooper()); 1837 1838 getDefaultDisplayMetrics(context, mMetrics); 1839 1840 SystemConfig systemConfig = SystemConfig.getInstance(); 1841 mGlobalGids = systemConfig.getGlobalGids(); 1842 mSystemPermissions = systemConfig.getSystemPermissions(); 1843 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1844 1845 synchronized (mInstallLock) { 1846 // writer 1847 synchronized (mPackages) { 1848 mHandlerThread = new ServiceThread(TAG, 1849 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1850 mHandlerThread.start(); 1851 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1852 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1853 1854 File dataDir = Environment.getDataDirectory(); 1855 mAppDataDir = new File(dataDir, "data"); 1856 mAppInstallDir = new File(dataDir, "app"); 1857 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1858 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1859 mUserAppDataDir = new File(dataDir, "user"); 1860 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1861 1862 sUserManager = new UserManagerService(context, this, 1863 mInstallLock, mPackages); 1864 1865 // Propagate permission configuration in to package manager. 1866 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1867 = systemConfig.getPermissions(); 1868 for (int i=0; i<permConfig.size(); i++) { 1869 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1870 BasePermission bp = mSettings.mPermissions.get(perm.name); 1871 if (bp == null) { 1872 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1873 mSettings.mPermissions.put(perm.name, bp); 1874 } 1875 if (perm.gids != null) { 1876 bp.setGids(perm.gids, perm.perUser); 1877 } 1878 } 1879 1880 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1881 for (int i=0; i<libConfig.size(); i++) { 1882 mSharedLibraries.put(libConfig.keyAt(i), 1883 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1884 } 1885 1886 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1887 1888 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1889 mSdkVersion, mOnlyCore); 1890 1891 String customResolverActivity = Resources.getSystem().getString( 1892 R.string.config_customResolverActivity); 1893 if (TextUtils.isEmpty(customResolverActivity)) { 1894 customResolverActivity = null; 1895 } else { 1896 mCustomResolverComponentName = ComponentName.unflattenFromString( 1897 customResolverActivity); 1898 } 1899 1900 long startTime = SystemClock.uptimeMillis(); 1901 1902 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1903 startTime); 1904 1905 // Set flag to monitor and not change apk file paths when 1906 // scanning install directories. 1907 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 1908 1909 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1910 1911 /** 1912 * Add everything in the in the boot class path to the 1913 * list of process files because dexopt will have been run 1914 * if necessary during zygote startup. 1915 */ 1916 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1917 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1918 1919 if (bootClassPath != null) { 1920 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1921 for (String element : bootClassPathElements) { 1922 alreadyDexOpted.add(element); 1923 } 1924 } else { 1925 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1926 } 1927 1928 if (systemServerClassPath != null) { 1929 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1930 for (String element : systemServerClassPathElements) { 1931 alreadyDexOpted.add(element); 1932 } 1933 } else { 1934 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1935 } 1936 1937 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1938 final String[] dexCodeInstructionSets = 1939 getDexCodeInstructionSets( 1940 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1941 1942 /** 1943 * Ensure all external libraries have had dexopt run on them. 1944 */ 1945 if (mSharedLibraries.size() > 0) { 1946 // NOTE: For now, we're compiling these system "shared libraries" 1947 // (and framework jars) into all available architectures. It's possible 1948 // to compile them only when we come across an app that uses them (there's 1949 // already logic for that in scanPackageLI) but that adds some complexity. 1950 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1951 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1952 final String lib = libEntry.path; 1953 if (lib == null) { 1954 continue; 1955 } 1956 1957 try { 1958 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 1959 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1960 alreadyDexOpted.add(lib); 1961 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1962 } 1963 } catch (FileNotFoundException e) { 1964 Slog.w(TAG, "Library not found: " + lib); 1965 } catch (IOException e) { 1966 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1967 + e.getMessage()); 1968 } 1969 } 1970 } 1971 } 1972 1973 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1974 1975 // Gross hack for now: we know this file doesn't contain any 1976 // code, so don't dexopt it to avoid the resulting log spew. 1977 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1978 1979 // Gross hack for now: we know this file is only part of 1980 // the boot class path for art, so don't dexopt it to 1981 // avoid the resulting log spew. 1982 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1983 1984 /** 1985 * There are a number of commands implemented in Java, which 1986 * we currently need to do the dexopt on so that they can be 1987 * run from a non-root shell. 1988 */ 1989 String[] frameworkFiles = frameworkDir.list(); 1990 if (frameworkFiles != null) { 1991 // TODO: We could compile these only for the most preferred ABI. We should 1992 // first double check that the dex files for these commands are not referenced 1993 // by other system apps. 1994 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1995 for (int i=0; i<frameworkFiles.length; i++) { 1996 File libPath = new File(frameworkDir, frameworkFiles[i]); 1997 String path = libPath.getPath(); 1998 // Skip the file if we already did it. 1999 if (alreadyDexOpted.contains(path)) { 2000 continue; 2001 } 2002 // Skip the file if it is not a type we want to dexopt. 2003 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 2004 continue; 2005 } 2006 try { 2007 int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false); 2008 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2009 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 2010 } 2011 } catch (FileNotFoundException e) { 2012 Slog.w(TAG, "Jar not found: " + path); 2013 } catch (IOException e) { 2014 Slog.w(TAG, "Exception reading jar: " + path, e); 2015 } 2016 } 2017 } 2018 } 2019 2020 // Collect vendor overlay packages. 2021 // (Do this before scanning any apps.) 2022 // For security and version matching reason, only consider 2023 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2024 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2025 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2026 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2027 2028 // Find base frameworks (resource packages without code). 2029 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2030 | PackageParser.PARSE_IS_SYSTEM_DIR 2031 | PackageParser.PARSE_IS_PRIVILEGED, 2032 scanFlags | SCAN_NO_DEX, 0); 2033 2034 // Collected privileged system packages. 2035 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2036 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2037 | PackageParser.PARSE_IS_SYSTEM_DIR 2038 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2039 2040 // Collect ordinary system packages. 2041 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2042 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2043 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2044 2045 // Collect all vendor packages. 2046 File vendorAppDir = new File("/vendor/app"); 2047 try { 2048 vendorAppDir = vendorAppDir.getCanonicalFile(); 2049 } catch (IOException e) { 2050 // failed to look up canonical path, continue with original one 2051 } 2052 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2053 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2054 2055 // Collect all OEM packages. 2056 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2057 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2058 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2059 2060 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 2061 mInstaller.moveFiles(); 2062 2063 // Prune any system packages that no longer exist. 2064 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2065 if (!mOnlyCore) { 2066 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2067 while (psit.hasNext()) { 2068 PackageSetting ps = psit.next(); 2069 2070 /* 2071 * If this is not a system app, it can't be a 2072 * disable system app. 2073 */ 2074 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2075 continue; 2076 } 2077 2078 /* 2079 * If the package is scanned, it's not erased. 2080 */ 2081 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2082 if (scannedPkg != null) { 2083 /* 2084 * If the system app is both scanned and in the 2085 * disabled packages list, then it must have been 2086 * added via OTA. Remove it from the currently 2087 * scanned package so the previously user-installed 2088 * application can be scanned. 2089 */ 2090 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2091 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2092 + ps.name + "; removing system app. Last known codePath=" 2093 + ps.codePathString + ", installStatus=" + ps.installStatus 2094 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2095 + scannedPkg.mVersionCode); 2096 removePackageLI(ps, true); 2097 mExpectingBetter.put(ps.name, ps.codePath); 2098 } 2099 2100 continue; 2101 } 2102 2103 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2104 psit.remove(); 2105 logCriticalInfo(Log.WARN, "System package " + ps.name 2106 + " no longer exists; wiping its data"); 2107 removeDataDirsLI(null, ps.name); 2108 } else { 2109 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2110 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2111 possiblyDeletedUpdatedSystemApps.add(ps.name); 2112 } 2113 } 2114 } 2115 } 2116 2117 //look for any incomplete package installations 2118 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2119 //clean up list 2120 for(int i = 0; i < deletePkgsList.size(); i++) { 2121 //clean up here 2122 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2123 } 2124 //delete tmp files 2125 deleteTempPackageFiles(); 2126 2127 // Remove any shared userIDs that have no associated packages 2128 mSettings.pruneSharedUsersLPw(); 2129 2130 if (!mOnlyCore) { 2131 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2132 SystemClock.uptimeMillis()); 2133 scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2134 2135 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2136 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2137 2138 /** 2139 * Remove disable package settings for any updated system 2140 * apps that were removed via an OTA. If they're not a 2141 * previously-updated app, remove them completely. 2142 * Otherwise, just revoke their system-level permissions. 2143 */ 2144 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2145 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2146 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2147 2148 String msg; 2149 if (deletedPkg == null) { 2150 msg = "Updated system package " + deletedAppName 2151 + " no longer exists; wiping its data"; 2152 removeDataDirsLI(null, deletedAppName); 2153 } else { 2154 msg = "Updated system app + " + deletedAppName 2155 + " no longer present; removing system privileges for " 2156 + deletedAppName; 2157 2158 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2159 2160 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2161 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2162 } 2163 logCriticalInfo(Log.WARN, msg); 2164 } 2165 2166 /** 2167 * Make sure all system apps that we expected to appear on 2168 * the userdata partition actually showed up. If they never 2169 * appeared, crawl back and revive the system version. 2170 */ 2171 for (int i = 0; i < mExpectingBetter.size(); i++) { 2172 final String packageName = mExpectingBetter.keyAt(i); 2173 if (!mPackages.containsKey(packageName)) { 2174 final File scanFile = mExpectingBetter.valueAt(i); 2175 2176 logCriticalInfo(Log.WARN, "Expected better " + packageName 2177 + " but never showed up; reverting to system"); 2178 2179 final int reparseFlags; 2180 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2181 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2182 | PackageParser.PARSE_IS_SYSTEM_DIR 2183 | PackageParser.PARSE_IS_PRIVILEGED; 2184 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2185 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2186 | PackageParser.PARSE_IS_SYSTEM_DIR; 2187 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2188 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2189 | PackageParser.PARSE_IS_SYSTEM_DIR; 2190 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2191 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2192 | PackageParser.PARSE_IS_SYSTEM_DIR; 2193 } else { 2194 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2195 continue; 2196 } 2197 2198 mSettings.enableSystemPackageLPw(packageName); 2199 2200 try { 2201 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 2202 } catch (PackageManagerException e) { 2203 Slog.e(TAG, "Failed to parse original system package: " 2204 + e.getMessage()); 2205 } 2206 } 2207 } 2208 } 2209 mExpectingBetter.clear(); 2210 2211 // Now that we know all of the shared libraries, update all clients to have 2212 // the correct library paths. 2213 updateAllSharedLibrariesLPw(); 2214 2215 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2216 // NOTE: We ignore potential failures here during a system scan (like 2217 // the rest of the commands above) because there's precious little we 2218 // can do about it. A settings error is reported, though. 2219 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2220 false /* force dexopt */, false /* defer dexopt */); 2221 } 2222 2223 // Now that we know all the packages we are keeping, 2224 // read and update their last usage times. 2225 mPackageUsage.readLP(); 2226 2227 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2228 SystemClock.uptimeMillis()); 2229 Slog.i(TAG, "Time to scan packages: " 2230 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2231 + " seconds"); 2232 2233 // If the platform SDK has changed since the last time we booted, 2234 // we need to re-grant app permission to catch any new ones that 2235 // appear. This is really a hack, and means that apps can in some 2236 // cases get permissions that the user didn't initially explicitly 2237 // allow... it would be nice to have some better way to handle 2238 // this situation. 2239 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 2240 != mSdkVersion; 2241 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 2242 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 2243 + "; regranting permissions for internal storage"); 2244 mSettings.mInternalSdkPlatform = mSdkVersion; 2245 2246 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 2247 | (regrantPermissions 2248 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 2249 : 0)); 2250 2251 // If this is the first boot, and it is a normal boot, then 2252 // we need to initialize the default preferred apps. 2253 if (!mRestoredSettings && !onlyCore) { 2254 mSettings.applyDefaultPreferredAppsLPw(this, UserHandle.USER_OWNER); 2255 applyFactoryDefaultBrowserLPw(UserHandle.USER_OWNER); 2256 primeDomainVerificationsLPw(UserHandle.USER_OWNER); 2257 } 2258 2259 // If this is first boot after an OTA, and a normal boot, then 2260 // we need to clear code cache directories. 2261 mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint); 2262 if (mIsUpgrade && !onlyCore) { 2263 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2264 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2265 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2266 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2267 } 2268 mSettings.mFingerprint = Build.FINGERPRINT; 2269 } 2270 2271 checkDefaultBrowser(); 2272 2273 // All the changes are done during package scanning. 2274 mSettings.updateInternalDatabaseVersion(); 2275 2276 // can downgrade to reader 2277 mSettings.writeLPr(); 2278 2279 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2280 SystemClock.uptimeMillis()); 2281 2282 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2283 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2284 2285 mInstallerService = new PackageInstallerService(context, this); 2286 2287 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2288 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2289 mIntentFilterVerifierComponent); 2290 2291 } // synchronized (mPackages) 2292 } // synchronized (mInstallLock) 2293 2294 // Now after opening every single application zip, make sure they 2295 // are all flushed. Not really needed, but keeps things nice and 2296 // tidy. 2297 Runtime.getRuntime().gc(); 2298 2299 // Expose private service for system components to use. 2300 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2301 } 2302 2303 @Override 2304 public boolean isFirstBoot() { 2305 return !mRestoredSettings; 2306 } 2307 2308 @Override 2309 public boolean isOnlyCoreApps() { 2310 return mOnlyCore; 2311 } 2312 2313 @Override 2314 public boolean isUpgrade() { 2315 return mIsUpgrade; 2316 } 2317 2318 private String getRequiredVerifierLPr() { 2319 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2320 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2321 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 2322 2323 String requiredVerifier = null; 2324 2325 final int N = receivers.size(); 2326 for (int i = 0; i < N; i++) { 2327 final ResolveInfo info = receivers.get(i); 2328 2329 if (info.activityInfo == null) { 2330 continue; 2331 } 2332 2333 final String packageName = info.activityInfo.packageName; 2334 2335 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2336 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2337 continue; 2338 } 2339 2340 if (requiredVerifier != null) { 2341 throw new RuntimeException("There can be only one required verifier"); 2342 } 2343 2344 requiredVerifier = packageName; 2345 } 2346 2347 return requiredVerifier; 2348 } 2349 2350 private String getRequiredInstallerLPr() { 2351 Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2352 installerIntent.addCategory(Intent.CATEGORY_DEFAULT); 2353 installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2354 2355 final List<ResolveInfo> installers = queryIntentActivities(installerIntent, 2356 PACKAGE_MIME_TYPE, 0, 0); 2357 2358 String requiredInstaller = null; 2359 2360 final int N = installers.size(); 2361 for (int i = 0; i < N; i++) { 2362 final ResolveInfo info = installers.get(i); 2363 final String packageName = info.activityInfo.packageName; 2364 2365 if (!info.activityInfo.applicationInfo.isSystemApp()) { 2366 continue; 2367 } 2368 2369 if (requiredInstaller != null) { 2370 throw new RuntimeException("There must be one required installer"); 2371 } 2372 2373 requiredInstaller = packageName; 2374 } 2375 2376 if (requiredInstaller == null) { 2377 throw new RuntimeException("There must be one required installer"); 2378 } 2379 2380 return requiredInstaller; 2381 } 2382 2383 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2384 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2385 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2386 PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */); 2387 2388 ComponentName verifierComponentName = null; 2389 2390 int priority = -1000; 2391 final int N = receivers.size(); 2392 for (int i = 0; i < N; i++) { 2393 final ResolveInfo info = receivers.get(i); 2394 2395 if (info.activityInfo == null) { 2396 continue; 2397 } 2398 2399 final String packageName = info.activityInfo.packageName; 2400 2401 final PackageSetting ps = mSettings.mPackages.get(packageName); 2402 if (ps == null) { 2403 continue; 2404 } 2405 2406 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2407 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2408 continue; 2409 } 2410 2411 // Select the IntentFilterVerifier with the highest priority 2412 if (priority < info.priority) { 2413 priority = info.priority; 2414 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2415 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: " 2416 + verifierComponentName + " with priority: " + info.priority); 2417 } 2418 } 2419 2420 return verifierComponentName; 2421 } 2422 2423 private void primeDomainVerificationsLPw(int userId) { 2424 if (DEBUG_DOMAIN_VERIFICATION) { 2425 Slog.d(TAG, "Priming domain verifications in user " + userId); 2426 } 2427 2428 SystemConfig systemConfig = SystemConfig.getInstance(); 2429 ArraySet<String> packages = systemConfig.getLinkedApps(); 2430 ArraySet<String> domains = new ArraySet<String>(); 2431 2432 for (String packageName : packages) { 2433 PackageParser.Package pkg = mPackages.get(packageName); 2434 if (pkg != null) { 2435 if (!pkg.isSystemApp()) { 2436 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2437 continue; 2438 } 2439 2440 domains.clear(); 2441 for (PackageParser.Activity a : pkg.activities) { 2442 for (ActivityIntentInfo filter : a.intents) { 2443 if (hasValidDomains(filter)) { 2444 domains.addAll(filter.getHostsList()); 2445 } 2446 } 2447 } 2448 2449 if (domains.size() > 0) { 2450 if (DEBUG_DOMAIN_VERIFICATION) { 2451 Slog.v(TAG, " + " + packageName); 2452 } 2453 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2454 // state w.r.t. the formal app-linkage "no verification attempted" state; 2455 // and then 'always' in the per-user state actually used for intent resolution. 2456 final IntentFilterVerificationInfo ivi; 2457 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2458 new ArrayList<String>(domains)); 2459 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2460 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2461 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2462 } else { 2463 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2464 + "' does not handle web links"); 2465 } 2466 } else { 2467 Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>"); 2468 } 2469 } 2470 2471 scheduleWritePackageRestrictionsLocked(userId); 2472 scheduleWriteSettingsLocked(); 2473 } 2474 2475 private void applyFactoryDefaultBrowserLPw(int userId) { 2476 // The default browser app's package name is stored in a string resource, 2477 // with a product-specific overlay used for vendor customization. 2478 String browserPkg = mContext.getResources().getString( 2479 com.android.internal.R.string.default_browser); 2480 if (!TextUtils.isEmpty(browserPkg)) { 2481 // non-empty string => required to be a known package 2482 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2483 if (ps == null) { 2484 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2485 browserPkg = null; 2486 } else { 2487 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2488 } 2489 } 2490 2491 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2492 // default. If there's more than one, just leave everything alone. 2493 if (browserPkg == null) { 2494 calculateDefaultBrowserLPw(userId); 2495 } 2496 } 2497 2498 private void calculateDefaultBrowserLPw(int userId) { 2499 List<String> allBrowsers = resolveAllBrowserApps(userId); 2500 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2501 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2502 } 2503 2504 private List<String> resolveAllBrowserApps(int userId) { 2505 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2506 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2507 PackageManager.MATCH_ALL, userId); 2508 2509 final int count = list.size(); 2510 List<String> result = new ArrayList<String>(count); 2511 for (int i=0; i<count; i++) { 2512 ResolveInfo info = list.get(i); 2513 if (info.activityInfo == null 2514 || !info.handleAllWebDataURI 2515 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2516 || result.contains(info.activityInfo.packageName)) { 2517 continue; 2518 } 2519 result.add(info.activityInfo.packageName); 2520 } 2521 2522 return result; 2523 } 2524 2525 private boolean packageIsBrowser(String packageName, int userId) { 2526 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2527 PackageManager.MATCH_ALL, userId); 2528 final int N = list.size(); 2529 for (int i = 0; i < N; i++) { 2530 ResolveInfo info = list.get(i); 2531 if (packageName.equals(info.activityInfo.packageName)) { 2532 return true; 2533 } 2534 } 2535 return false; 2536 } 2537 2538 private void checkDefaultBrowser() { 2539 final int myUserId = UserHandle.myUserId(); 2540 final String packageName = getDefaultBrowserPackageName(myUserId); 2541 if (packageName != null) { 2542 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2543 if (info == null) { 2544 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2545 synchronized (mPackages) { 2546 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2547 } 2548 } 2549 } 2550 } 2551 2552 @Override 2553 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2554 throws RemoteException { 2555 try { 2556 return super.onTransact(code, data, reply, flags); 2557 } catch (RuntimeException e) { 2558 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2559 Slog.wtf(TAG, "Package Manager Crash", e); 2560 } 2561 throw e; 2562 } 2563 } 2564 2565 void cleanupInstallFailedPackage(PackageSetting ps) { 2566 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2567 2568 removeDataDirsLI(ps.volumeUuid, ps.name); 2569 if (ps.codePath != null) { 2570 if (ps.codePath.isDirectory()) { 2571 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2572 } else { 2573 ps.codePath.delete(); 2574 } 2575 } 2576 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2577 if (ps.resourcePath.isDirectory()) { 2578 FileUtils.deleteContents(ps.resourcePath); 2579 } 2580 ps.resourcePath.delete(); 2581 } 2582 mSettings.removePackageLPw(ps.name); 2583 } 2584 2585 static int[] appendInts(int[] cur, int[] add) { 2586 if (add == null) return cur; 2587 if (cur == null) return add; 2588 final int N = add.length; 2589 for (int i=0; i<N; i++) { 2590 cur = appendInt(cur, add[i]); 2591 } 2592 return cur; 2593 } 2594 2595 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2596 if (!sUserManager.exists(userId)) return null; 2597 final PackageSetting ps = (PackageSetting) p.mExtras; 2598 if (ps == null) { 2599 return null; 2600 } 2601 2602 final PermissionsState permissionsState = ps.getPermissionsState(); 2603 2604 final int[] gids = permissionsState.computeGids(userId); 2605 final Set<String> permissions = permissionsState.getPermissions(userId); 2606 final PackageUserState state = ps.readUserState(userId); 2607 2608 return PackageParser.generatePackageInfo(p, gids, flags, 2609 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2610 } 2611 2612 @Override 2613 public boolean isPackageFrozen(String packageName) { 2614 synchronized (mPackages) { 2615 final PackageSetting ps = mSettings.mPackages.get(packageName); 2616 if (ps != null) { 2617 return ps.frozen; 2618 } 2619 } 2620 Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen"); 2621 return true; 2622 } 2623 2624 @Override 2625 public boolean isPackageAvailable(String packageName, int userId) { 2626 if (!sUserManager.exists(userId)) return false; 2627 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2628 synchronized (mPackages) { 2629 PackageParser.Package p = mPackages.get(packageName); 2630 if (p != null) { 2631 final PackageSetting ps = (PackageSetting) p.mExtras; 2632 if (ps != null) { 2633 final PackageUserState state = ps.readUserState(userId); 2634 if (state != null) { 2635 return PackageParser.isAvailable(state); 2636 } 2637 } 2638 } 2639 } 2640 return false; 2641 } 2642 2643 @Override 2644 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2645 if (!sUserManager.exists(userId)) return null; 2646 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2647 // reader 2648 synchronized (mPackages) { 2649 PackageParser.Package p = mPackages.get(packageName); 2650 if (DEBUG_PACKAGE_INFO) 2651 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2652 if (p != null) { 2653 return generatePackageInfo(p, flags, userId); 2654 } 2655 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2656 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2657 } 2658 } 2659 return null; 2660 } 2661 2662 @Override 2663 public String[] currentToCanonicalPackageNames(String[] names) { 2664 String[] out = new String[names.length]; 2665 // reader 2666 synchronized (mPackages) { 2667 for (int i=names.length-1; i>=0; i--) { 2668 PackageSetting ps = mSettings.mPackages.get(names[i]); 2669 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2670 } 2671 } 2672 return out; 2673 } 2674 2675 @Override 2676 public String[] canonicalToCurrentPackageNames(String[] names) { 2677 String[] out = new String[names.length]; 2678 // reader 2679 synchronized (mPackages) { 2680 for (int i=names.length-1; i>=0; i--) { 2681 String cur = mSettings.mRenamedPackages.get(names[i]); 2682 out[i] = cur != null ? cur : names[i]; 2683 } 2684 } 2685 return out; 2686 } 2687 2688 @Override 2689 public int getPackageUid(String packageName, int userId) { 2690 if (!sUserManager.exists(userId)) return -1; 2691 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2692 2693 // reader 2694 synchronized (mPackages) { 2695 PackageParser.Package p = mPackages.get(packageName); 2696 if(p != null) { 2697 return UserHandle.getUid(userId, p.applicationInfo.uid); 2698 } 2699 PackageSetting ps = mSettings.mPackages.get(packageName); 2700 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2701 return -1; 2702 } 2703 p = ps.pkg; 2704 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2705 } 2706 } 2707 2708 @Override 2709 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2710 if (!sUserManager.exists(userId)) { 2711 return null; 2712 } 2713 2714 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2715 "getPackageGids"); 2716 2717 // reader 2718 synchronized (mPackages) { 2719 PackageParser.Package p = mPackages.get(packageName); 2720 if (DEBUG_PACKAGE_INFO) { 2721 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2722 } 2723 if (p != null) { 2724 PackageSetting ps = (PackageSetting) p.mExtras; 2725 return ps.getPermissionsState().computeGids(userId); 2726 } 2727 } 2728 2729 return null; 2730 } 2731 2732 static PermissionInfo generatePermissionInfo( 2733 BasePermission bp, int flags) { 2734 if (bp.perm != null) { 2735 return PackageParser.generatePermissionInfo(bp.perm, flags); 2736 } 2737 PermissionInfo pi = new PermissionInfo(); 2738 pi.name = bp.name; 2739 pi.packageName = bp.sourcePackage; 2740 pi.nonLocalizedLabel = bp.name; 2741 pi.protectionLevel = bp.protectionLevel; 2742 return pi; 2743 } 2744 2745 @Override 2746 public PermissionInfo getPermissionInfo(String name, int flags) { 2747 // reader 2748 synchronized (mPackages) { 2749 final BasePermission p = mSettings.mPermissions.get(name); 2750 if (p != null) { 2751 return generatePermissionInfo(p, flags); 2752 } 2753 return null; 2754 } 2755 } 2756 2757 @Override 2758 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2759 // reader 2760 synchronized (mPackages) { 2761 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2762 for (BasePermission p : mSettings.mPermissions.values()) { 2763 if (group == null) { 2764 if (p.perm == null || p.perm.info.group == null) { 2765 out.add(generatePermissionInfo(p, flags)); 2766 } 2767 } else { 2768 if (p.perm != null && group.equals(p.perm.info.group)) { 2769 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2770 } 2771 } 2772 } 2773 2774 if (out.size() > 0) { 2775 return out; 2776 } 2777 return mPermissionGroups.containsKey(group) ? out : null; 2778 } 2779 } 2780 2781 @Override 2782 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2783 // reader 2784 synchronized (mPackages) { 2785 return PackageParser.generatePermissionGroupInfo( 2786 mPermissionGroups.get(name), flags); 2787 } 2788 } 2789 2790 @Override 2791 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2792 // reader 2793 synchronized (mPackages) { 2794 final int N = mPermissionGroups.size(); 2795 ArrayList<PermissionGroupInfo> out 2796 = new ArrayList<PermissionGroupInfo>(N); 2797 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2798 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2799 } 2800 return out; 2801 } 2802 } 2803 2804 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2805 int userId) { 2806 if (!sUserManager.exists(userId)) return null; 2807 PackageSetting ps = mSettings.mPackages.get(packageName); 2808 if (ps != null) { 2809 if (ps.pkg == null) { 2810 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2811 flags, userId); 2812 if (pInfo != null) { 2813 return pInfo.applicationInfo; 2814 } 2815 return null; 2816 } 2817 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2818 ps.readUserState(userId), userId); 2819 } 2820 return null; 2821 } 2822 2823 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2824 int userId) { 2825 if (!sUserManager.exists(userId)) return null; 2826 PackageSetting ps = mSettings.mPackages.get(packageName); 2827 if (ps != null) { 2828 PackageParser.Package pkg = ps.pkg; 2829 if (pkg == null) { 2830 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2831 return null; 2832 } 2833 // Only data remains, so we aren't worried about code paths 2834 pkg = new PackageParser.Package(packageName); 2835 pkg.applicationInfo.packageName = packageName; 2836 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2837 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2838 pkg.applicationInfo.dataDir = Environment 2839 .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName) 2840 .getAbsolutePath(); 2841 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2842 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2843 } 2844 return generatePackageInfo(pkg, flags, userId); 2845 } 2846 return null; 2847 } 2848 2849 @Override 2850 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2851 if (!sUserManager.exists(userId)) return null; 2852 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2853 // writer 2854 synchronized (mPackages) { 2855 PackageParser.Package p = mPackages.get(packageName); 2856 if (DEBUG_PACKAGE_INFO) Log.v( 2857 TAG, "getApplicationInfo " + packageName 2858 + ": " + p); 2859 if (p != null) { 2860 PackageSetting ps = mSettings.mPackages.get(packageName); 2861 if (ps == null) return null; 2862 // Note: isEnabledLP() does not apply here - always return info 2863 return PackageParser.generateApplicationInfo( 2864 p, flags, ps.readUserState(userId), userId); 2865 } 2866 if ("android".equals(packageName)||"system".equals(packageName)) { 2867 return mAndroidApplication; 2868 } 2869 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2870 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2871 } 2872 } 2873 return null; 2874 } 2875 2876 @Override 2877 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2878 final IPackageDataObserver observer) { 2879 mContext.enforceCallingOrSelfPermission( 2880 android.Manifest.permission.CLEAR_APP_CACHE, null); 2881 // Queue up an async operation since clearing cache may take a little while. 2882 mHandler.post(new Runnable() { 2883 public void run() { 2884 mHandler.removeCallbacks(this); 2885 int retCode = -1; 2886 synchronized (mInstallLock) { 2887 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2888 if (retCode < 0) { 2889 Slog.w(TAG, "Couldn't clear application caches"); 2890 } 2891 } 2892 if (observer != null) { 2893 try { 2894 observer.onRemoveCompleted(null, (retCode >= 0)); 2895 } catch (RemoteException e) { 2896 Slog.w(TAG, "RemoveException when invoking call back"); 2897 } 2898 } 2899 } 2900 }); 2901 } 2902 2903 @Override 2904 public void freeStorage(final String volumeUuid, final long freeStorageSize, 2905 final IntentSender pi) { 2906 mContext.enforceCallingOrSelfPermission( 2907 android.Manifest.permission.CLEAR_APP_CACHE, null); 2908 // Queue up an async operation since clearing cache may take a little while. 2909 mHandler.post(new Runnable() { 2910 public void run() { 2911 mHandler.removeCallbacks(this); 2912 int retCode = -1; 2913 synchronized (mInstallLock) { 2914 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2915 if (retCode < 0) { 2916 Slog.w(TAG, "Couldn't clear application caches"); 2917 } 2918 } 2919 if(pi != null) { 2920 try { 2921 // Callback via pending intent 2922 int code = (retCode >= 0) ? 1 : 0; 2923 pi.sendIntent(null, code, null, 2924 null, null); 2925 } catch (SendIntentException e1) { 2926 Slog.i(TAG, "Failed to send pending intent"); 2927 } 2928 } 2929 } 2930 }); 2931 } 2932 2933 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 2934 synchronized (mInstallLock) { 2935 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 2936 throw new IOException("Failed to free enough space"); 2937 } 2938 } 2939 } 2940 2941 @Override 2942 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2943 if (!sUserManager.exists(userId)) return null; 2944 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2945 synchronized (mPackages) { 2946 PackageParser.Activity a = mActivities.mActivities.get(component); 2947 2948 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2949 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2950 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2951 if (ps == null) return null; 2952 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2953 userId); 2954 } 2955 if (mResolveComponentName.equals(component)) { 2956 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2957 new PackageUserState(), userId); 2958 } 2959 } 2960 return null; 2961 } 2962 2963 @Override 2964 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2965 String resolvedType) { 2966 synchronized (mPackages) { 2967 PackageParser.Activity a = mActivities.mActivities.get(component); 2968 if (a == null) { 2969 return false; 2970 } 2971 for (int i=0; i<a.intents.size(); i++) { 2972 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2973 intent.getData(), intent.getCategories(), TAG) >= 0) { 2974 return true; 2975 } 2976 } 2977 return false; 2978 } 2979 } 2980 2981 @Override 2982 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2983 if (!sUserManager.exists(userId)) return null; 2984 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 2985 synchronized (mPackages) { 2986 PackageParser.Activity a = mReceivers.mActivities.get(component); 2987 if (DEBUG_PACKAGE_INFO) Log.v( 2988 TAG, "getReceiverInfo " + component + ": " + a); 2989 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2990 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2991 if (ps == null) return null; 2992 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2993 userId); 2994 } 2995 } 2996 return null; 2997 } 2998 2999 @Override 3000 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3001 if (!sUserManager.exists(userId)) return null; 3002 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 3003 synchronized (mPackages) { 3004 PackageParser.Service s = mServices.mServices.get(component); 3005 if (DEBUG_PACKAGE_INFO) Log.v( 3006 TAG, "getServiceInfo " + component + ": " + s); 3007 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 3008 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3009 if (ps == null) return null; 3010 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3011 userId); 3012 } 3013 } 3014 return null; 3015 } 3016 3017 @Override 3018 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3019 if (!sUserManager.exists(userId)) return null; 3020 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 3021 synchronized (mPackages) { 3022 PackageParser.Provider p = mProviders.mProviders.get(component); 3023 if (DEBUG_PACKAGE_INFO) Log.v( 3024 TAG, "getProviderInfo " + component + ": " + p); 3025 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 3026 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3027 if (ps == null) return null; 3028 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3029 userId); 3030 } 3031 } 3032 return null; 3033 } 3034 3035 @Override 3036 public String[] getSystemSharedLibraryNames() { 3037 Set<String> libSet; 3038 synchronized (mPackages) { 3039 libSet = mSharedLibraries.keySet(); 3040 int size = libSet.size(); 3041 if (size > 0) { 3042 String[] libs = new String[size]; 3043 libSet.toArray(libs); 3044 return libs; 3045 } 3046 } 3047 return null; 3048 } 3049 3050 /** 3051 * @hide 3052 */ 3053 PackageParser.Package findSharedNonSystemLibrary(String libName) { 3054 synchronized (mPackages) { 3055 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 3056 if (lib != null && lib.apk != null) { 3057 return mPackages.get(lib.apk); 3058 } 3059 } 3060 return null; 3061 } 3062 3063 @Override 3064 public FeatureInfo[] getSystemAvailableFeatures() { 3065 Collection<FeatureInfo> featSet; 3066 synchronized (mPackages) { 3067 featSet = mAvailableFeatures.values(); 3068 int size = featSet.size(); 3069 if (size > 0) { 3070 FeatureInfo[] features = new FeatureInfo[size+1]; 3071 featSet.toArray(features); 3072 FeatureInfo fi = new FeatureInfo(); 3073 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3074 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3075 features[size] = fi; 3076 return features; 3077 } 3078 } 3079 return null; 3080 } 3081 3082 @Override 3083 public boolean hasSystemFeature(String name) { 3084 synchronized (mPackages) { 3085 return mAvailableFeatures.containsKey(name); 3086 } 3087 } 3088 3089 private void checkValidCaller(int uid, int userId) { 3090 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 3091 return; 3092 3093 throw new SecurityException("Caller uid=" + uid 3094 + " is not privileged to communicate with user=" + userId); 3095 } 3096 3097 @Override 3098 public int checkPermission(String permName, String pkgName, int userId) { 3099 if (!sUserManager.exists(userId)) { 3100 return PackageManager.PERMISSION_DENIED; 3101 } 3102 3103 synchronized (mPackages) { 3104 final PackageParser.Package p = mPackages.get(pkgName); 3105 if (p != null && p.mExtras != null) { 3106 final PackageSetting ps = (PackageSetting) p.mExtras; 3107 if (ps.getPermissionsState().hasPermission(permName, userId)) { 3108 return PackageManager.PERMISSION_GRANTED; 3109 } 3110 } 3111 } 3112 3113 return PackageManager.PERMISSION_DENIED; 3114 } 3115 3116 @Override 3117 public int checkUidPermission(String permName, int uid) { 3118 final int userId = UserHandle.getUserId(uid); 3119 3120 if (!sUserManager.exists(userId)) { 3121 return PackageManager.PERMISSION_DENIED; 3122 } 3123 3124 synchronized (mPackages) { 3125 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3126 if (obj != null) { 3127 final SettingBase ps = (SettingBase) obj; 3128 if (ps.getPermissionsState().hasPermission(permName, userId)) { 3129 return PackageManager.PERMISSION_GRANTED; 3130 } 3131 } else { 3132 ArraySet<String> perms = mSystemPermissions.get(uid); 3133 if (perms != null && perms.contains(permName)) { 3134 return PackageManager.PERMISSION_GRANTED; 3135 } 3136 } 3137 } 3138 3139 return PackageManager.PERMISSION_DENIED; 3140 } 3141 3142 @Override 3143 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3144 if (UserHandle.getCallingUserId() != userId) { 3145 mContext.enforceCallingPermission( 3146 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3147 "isPermissionRevokedByPolicy for user " + userId); 3148 } 3149 3150 if (checkPermission(permission, packageName, userId) 3151 == PackageManager.PERMISSION_GRANTED) { 3152 return false; 3153 } 3154 3155 final long identity = Binder.clearCallingIdentity(); 3156 try { 3157 final int flags = getPermissionFlags(permission, packageName, userId); 3158 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3159 } finally { 3160 Binder.restoreCallingIdentity(identity); 3161 } 3162 } 3163 3164 /** 3165 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3166 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3167 * @param checkShell TODO(yamasani): 3168 * @param message the message to log on security exception 3169 */ 3170 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3171 boolean checkShell, String message) { 3172 if (userId < 0) { 3173 throw new IllegalArgumentException("Invalid userId " + userId); 3174 } 3175 if (checkShell) { 3176 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3177 } 3178 if (userId == UserHandle.getUserId(callingUid)) return; 3179 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3180 if (requireFullPermission) { 3181 mContext.enforceCallingOrSelfPermission( 3182 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3183 } else { 3184 try { 3185 mContext.enforceCallingOrSelfPermission( 3186 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3187 } catch (SecurityException se) { 3188 mContext.enforceCallingOrSelfPermission( 3189 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3190 } 3191 } 3192 } 3193 } 3194 3195 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3196 if (callingUid == Process.SHELL_UID) { 3197 if (userHandle >= 0 3198 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3199 throw new SecurityException("Shell does not have permission to access user " 3200 + userHandle); 3201 } else if (userHandle < 0) { 3202 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3203 + Debug.getCallers(3)); 3204 } 3205 } 3206 } 3207 3208 private BasePermission findPermissionTreeLP(String permName) { 3209 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3210 if (permName.startsWith(bp.name) && 3211 permName.length() > bp.name.length() && 3212 permName.charAt(bp.name.length()) == '.') { 3213 return bp; 3214 } 3215 } 3216 return null; 3217 } 3218 3219 private BasePermission checkPermissionTreeLP(String permName) { 3220 if (permName != null) { 3221 BasePermission bp = findPermissionTreeLP(permName); 3222 if (bp != null) { 3223 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3224 return bp; 3225 } 3226 throw new SecurityException("Calling uid " 3227 + Binder.getCallingUid() 3228 + " is not allowed to add to permission tree " 3229 + bp.name + " owned by uid " + bp.uid); 3230 } 3231 } 3232 throw new SecurityException("No permission tree found for " + permName); 3233 } 3234 3235 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3236 if (s1 == null) { 3237 return s2 == null; 3238 } 3239 if (s2 == null) { 3240 return false; 3241 } 3242 if (s1.getClass() != s2.getClass()) { 3243 return false; 3244 } 3245 return s1.equals(s2); 3246 } 3247 3248 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3249 if (pi1.icon != pi2.icon) return false; 3250 if (pi1.logo != pi2.logo) return false; 3251 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3252 if (!compareStrings(pi1.name, pi2.name)) return false; 3253 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3254 // We'll take care of setting this one. 3255 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3256 // These are not currently stored in settings. 3257 //if (!compareStrings(pi1.group, pi2.group)) return false; 3258 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3259 //if (pi1.labelRes != pi2.labelRes) return false; 3260 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3261 return true; 3262 } 3263 3264 int permissionInfoFootprint(PermissionInfo info) { 3265 int size = info.name.length(); 3266 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3267 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3268 return size; 3269 } 3270 3271 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3272 int size = 0; 3273 for (BasePermission perm : mSettings.mPermissions.values()) { 3274 if (perm.uid == tree.uid) { 3275 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3276 } 3277 } 3278 return size; 3279 } 3280 3281 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3282 // We calculate the max size of permissions defined by this uid and throw 3283 // if that plus the size of 'info' would exceed our stated maximum. 3284 if (tree.uid != Process.SYSTEM_UID) { 3285 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3286 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3287 throw new SecurityException("Permission tree size cap exceeded"); 3288 } 3289 } 3290 } 3291 3292 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3293 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3294 throw new SecurityException("Label must be specified in permission"); 3295 } 3296 BasePermission tree = checkPermissionTreeLP(info.name); 3297 BasePermission bp = mSettings.mPermissions.get(info.name); 3298 boolean added = bp == null; 3299 boolean changed = true; 3300 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3301 if (added) { 3302 enforcePermissionCapLocked(info, tree); 3303 bp = new BasePermission(info.name, tree.sourcePackage, 3304 BasePermission.TYPE_DYNAMIC); 3305 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3306 throw new SecurityException( 3307 "Not allowed to modify non-dynamic permission " 3308 + info.name); 3309 } else { 3310 if (bp.protectionLevel == fixedLevel 3311 && bp.perm.owner.equals(tree.perm.owner) 3312 && bp.uid == tree.uid 3313 && comparePermissionInfos(bp.perm.info, info)) { 3314 changed = false; 3315 } 3316 } 3317 bp.protectionLevel = fixedLevel; 3318 info = new PermissionInfo(info); 3319 info.protectionLevel = fixedLevel; 3320 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3321 bp.perm.info.packageName = tree.perm.info.packageName; 3322 bp.uid = tree.uid; 3323 if (added) { 3324 mSettings.mPermissions.put(info.name, bp); 3325 } 3326 if (changed) { 3327 if (!async) { 3328 mSettings.writeLPr(); 3329 } else { 3330 scheduleWriteSettingsLocked(); 3331 } 3332 } 3333 return added; 3334 } 3335 3336 @Override 3337 public boolean addPermission(PermissionInfo info) { 3338 synchronized (mPackages) { 3339 return addPermissionLocked(info, false); 3340 } 3341 } 3342 3343 @Override 3344 public boolean addPermissionAsync(PermissionInfo info) { 3345 synchronized (mPackages) { 3346 return addPermissionLocked(info, true); 3347 } 3348 } 3349 3350 @Override 3351 public void removePermission(String name) { 3352 synchronized (mPackages) { 3353 checkPermissionTreeLP(name); 3354 BasePermission bp = mSettings.mPermissions.get(name); 3355 if (bp != null) { 3356 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3357 throw new SecurityException( 3358 "Not allowed to modify non-dynamic permission " 3359 + name); 3360 } 3361 mSettings.mPermissions.remove(name); 3362 mSettings.writeLPr(); 3363 } 3364 } 3365 } 3366 3367 private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg, 3368 BasePermission bp) { 3369 int index = pkg.requestedPermissions.indexOf(bp.name); 3370 if (index == -1) { 3371 throw new SecurityException("Package " + pkg.packageName 3372 + " has not requested permission " + bp.name); 3373 } 3374 if (!bp.isRuntime()) { 3375 throw new SecurityException("Permission " + bp.name 3376 + " is not a changeable permission type"); 3377 } 3378 } 3379 3380 @Override 3381 public void grantRuntimePermission(String packageName, String name, final int userId) { 3382 if (!sUserManager.exists(userId)) { 3383 Log.e(TAG, "No such user:" + userId); 3384 return; 3385 } 3386 3387 mContext.enforceCallingOrSelfPermission( 3388 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3389 "grantRuntimePermission"); 3390 3391 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3392 "grantRuntimePermission"); 3393 3394 final int uid; 3395 final SettingBase sb; 3396 3397 synchronized (mPackages) { 3398 final PackageParser.Package pkg = mPackages.get(packageName); 3399 if (pkg == null) { 3400 throw new IllegalArgumentException("Unknown package: " + packageName); 3401 } 3402 3403 final BasePermission bp = mSettings.mPermissions.get(name); 3404 if (bp == null) { 3405 throw new IllegalArgumentException("Unknown permission: " + name); 3406 } 3407 3408 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3409 3410 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3411 sb = (SettingBase) pkg.mExtras; 3412 if (sb == null) { 3413 throw new IllegalArgumentException("Unknown package: " + packageName); 3414 } 3415 3416 final PermissionsState permissionsState = sb.getPermissionsState(); 3417 3418 final int flags = permissionsState.getPermissionFlags(name, userId); 3419 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3420 throw new SecurityException("Cannot grant system fixed permission: " 3421 + name + " for package: " + packageName); 3422 } 3423 3424 final int result = permissionsState.grantRuntimePermission(bp, userId); 3425 switch (result) { 3426 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3427 return; 3428 } 3429 3430 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3431 mHandler.post(new Runnable() { 3432 @Override 3433 public void run() { 3434 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED); 3435 } 3436 }); 3437 } break; 3438 } 3439 3440 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3441 3442 // Not critical if that is lost - app has to request again. 3443 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3444 } 3445 3446 // Only need to do this if user is initialized. Otherwise it's a new user 3447 // and there are no processes running as the user yet and there's no need 3448 // to make an expensive call to remount processes for the changed permissions. 3449 if (READ_EXTERNAL_STORAGE.equals(name) 3450 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3451 final long token = Binder.clearCallingIdentity(); 3452 try { 3453 if (sUserManager.isInitialized(userId)) { 3454 MountServiceInternal mountServiceInternal = LocalServices.getService( 3455 MountServiceInternal.class); 3456 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 3457 } 3458 } finally { 3459 Binder.restoreCallingIdentity(token); 3460 } 3461 } 3462 } 3463 3464 @Override 3465 public void revokeRuntimePermission(String packageName, String name, int userId) { 3466 if (!sUserManager.exists(userId)) { 3467 Log.e(TAG, "No such user:" + userId); 3468 return; 3469 } 3470 3471 mContext.enforceCallingOrSelfPermission( 3472 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3473 "revokeRuntimePermission"); 3474 3475 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3476 "revokeRuntimePermission"); 3477 3478 final SettingBase sb; 3479 3480 synchronized (mPackages) { 3481 final PackageParser.Package pkg = mPackages.get(packageName); 3482 if (pkg == null) { 3483 throw new IllegalArgumentException("Unknown package: " + packageName); 3484 } 3485 3486 final BasePermission bp = mSettings.mPermissions.get(name); 3487 if (bp == null) { 3488 throw new IllegalArgumentException("Unknown permission: " + name); 3489 } 3490 3491 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3492 3493 sb = (SettingBase) pkg.mExtras; 3494 if (sb == null) { 3495 throw new IllegalArgumentException("Unknown package: " + packageName); 3496 } 3497 3498 final PermissionsState permissionsState = sb.getPermissionsState(); 3499 3500 final int flags = permissionsState.getPermissionFlags(name, userId); 3501 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3502 throw new SecurityException("Cannot revoke system fixed permission: " 3503 + name + " for package: " + packageName); 3504 } 3505 3506 if (permissionsState.revokeRuntimePermission(bp, userId) == 3507 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3508 return; 3509 } 3510 3511 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3512 3513 // Critical, after this call app should never have the permission. 3514 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3515 } 3516 3517 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3518 } 3519 3520 @Override 3521 public void resetRuntimePermissions() { 3522 mContext.enforceCallingOrSelfPermission( 3523 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3524 "revokeRuntimePermission"); 3525 3526 int callingUid = Binder.getCallingUid(); 3527 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3528 mContext.enforceCallingOrSelfPermission( 3529 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3530 "resetRuntimePermissions"); 3531 } 3532 3533 final int[] userIds; 3534 3535 synchronized (mPackages) { 3536 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 3537 final int userCount = UserManagerService.getInstance().getUserIds().length; 3538 userIds = Arrays.copyOf(UserManagerService.getInstance().getUserIds(), userCount); 3539 } 3540 3541 for (int userId : userIds) { 3542 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 3543 } 3544 } 3545 3546 @Override 3547 public int getPermissionFlags(String name, String packageName, int userId) { 3548 if (!sUserManager.exists(userId)) { 3549 return 0; 3550 } 3551 3552 mContext.enforceCallingOrSelfPermission( 3553 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3554 "getPermissionFlags"); 3555 3556 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3557 "getPermissionFlags"); 3558 3559 synchronized (mPackages) { 3560 final PackageParser.Package pkg = mPackages.get(packageName); 3561 if (pkg == null) { 3562 throw new IllegalArgumentException("Unknown package: " + packageName); 3563 } 3564 3565 final BasePermission bp = mSettings.mPermissions.get(name); 3566 if (bp == null) { 3567 throw new IllegalArgumentException("Unknown permission: " + name); 3568 } 3569 3570 SettingBase sb = (SettingBase) pkg.mExtras; 3571 if (sb == null) { 3572 throw new IllegalArgumentException("Unknown package: " + packageName); 3573 } 3574 3575 PermissionsState permissionsState = sb.getPermissionsState(); 3576 return permissionsState.getPermissionFlags(name, userId); 3577 } 3578 } 3579 3580 @Override 3581 public void updatePermissionFlags(String name, String packageName, int flagMask, 3582 int flagValues, int userId) { 3583 if (!sUserManager.exists(userId)) { 3584 return; 3585 } 3586 3587 mContext.enforceCallingOrSelfPermission( 3588 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3589 "updatePermissionFlags"); 3590 3591 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3592 "updatePermissionFlags"); 3593 3594 // Only the system can change system fixed flags. 3595 if (getCallingUid() != Process.SYSTEM_UID) { 3596 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3597 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3598 } 3599 3600 synchronized (mPackages) { 3601 final PackageParser.Package pkg = mPackages.get(packageName); 3602 if (pkg == null) { 3603 throw new IllegalArgumentException("Unknown package: " + packageName); 3604 } 3605 3606 final BasePermission bp = mSettings.mPermissions.get(name); 3607 if (bp == null) { 3608 throw new IllegalArgumentException("Unknown permission: " + name); 3609 } 3610 3611 SettingBase sb = (SettingBase) pkg.mExtras; 3612 if (sb == null) { 3613 throw new IllegalArgumentException("Unknown package: " + packageName); 3614 } 3615 3616 PermissionsState permissionsState = sb.getPermissionsState(); 3617 3618 // Only the package manager can change flags for system component permissions. 3619 final int flags = permissionsState.getPermissionFlags(bp.name, userId); 3620 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3621 return; 3622 } 3623 3624 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 3625 3626 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3627 // Install and runtime permissions are stored in different places, 3628 // so figure out what permission changed and persist the change. 3629 if (permissionsState.getInstallPermissionState(name) != null) { 3630 scheduleWriteSettingsLocked(); 3631 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 3632 || hadState) { 3633 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3634 } 3635 } 3636 } 3637 } 3638 3639 /** 3640 * Update the permission flags for all packages and runtime permissions of a user in order 3641 * to allow device or profile owner to remove POLICY_FIXED. 3642 */ 3643 @Override 3644 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 3645 if (!sUserManager.exists(userId)) { 3646 return; 3647 } 3648 3649 mContext.enforceCallingOrSelfPermission( 3650 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3651 "updatePermissionFlagsForAllApps"); 3652 3653 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3654 "updatePermissionFlagsForAllApps"); 3655 3656 // Only the system can change system fixed flags. 3657 if (getCallingUid() != Process.SYSTEM_UID) { 3658 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3659 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3660 } 3661 3662 synchronized (mPackages) { 3663 boolean changed = false; 3664 final int packageCount = mPackages.size(); 3665 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 3666 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 3667 SettingBase sb = (SettingBase) pkg.mExtras; 3668 if (sb == null) { 3669 continue; 3670 } 3671 PermissionsState permissionsState = sb.getPermissionsState(); 3672 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 3673 userId, flagMask, flagValues); 3674 } 3675 if (changed) { 3676 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3677 } 3678 } 3679 } 3680 3681 @Override 3682 public boolean shouldShowRequestPermissionRationale(String permissionName, 3683 String packageName, int userId) { 3684 if (UserHandle.getCallingUserId() != userId) { 3685 mContext.enforceCallingPermission( 3686 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3687 "canShowRequestPermissionRationale for user " + userId); 3688 } 3689 3690 final int uid = getPackageUid(packageName, userId); 3691 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 3692 return false; 3693 } 3694 3695 if (checkPermission(permissionName, packageName, userId) 3696 == PackageManager.PERMISSION_GRANTED) { 3697 return false; 3698 } 3699 3700 final int flags; 3701 3702 final long identity = Binder.clearCallingIdentity(); 3703 try { 3704 flags = getPermissionFlags(permissionName, 3705 packageName, userId); 3706 } finally { 3707 Binder.restoreCallingIdentity(identity); 3708 } 3709 3710 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 3711 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 3712 | PackageManager.FLAG_PERMISSION_USER_FIXED; 3713 3714 if ((flags & fixedFlags) != 0) { 3715 return false; 3716 } 3717 3718 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 3719 } 3720 3721 void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) { 3722 BasePermission bp = mSettings.mPermissions.get(permission); 3723 if (bp == null) { 3724 throw new SecurityException("Missing " + permission + " permission"); 3725 } 3726 3727 SettingBase sb = (SettingBase) pkg.mExtras; 3728 PermissionsState permissionsState = sb.getPermissionsState(); 3729 3730 if (permissionsState.grantInstallPermission(bp) != 3731 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3732 scheduleWriteSettingsLocked(); 3733 } 3734 } 3735 3736 @Override 3737 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3738 mContext.enforceCallingOrSelfPermission( 3739 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 3740 "addOnPermissionsChangeListener"); 3741 3742 synchronized (mPackages) { 3743 mOnPermissionChangeListeners.addListenerLocked(listener); 3744 } 3745 } 3746 3747 @Override 3748 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3749 synchronized (mPackages) { 3750 mOnPermissionChangeListeners.removeListenerLocked(listener); 3751 } 3752 } 3753 3754 @Override 3755 public boolean isProtectedBroadcast(String actionName) { 3756 synchronized (mPackages) { 3757 return mProtectedBroadcasts.contains(actionName); 3758 } 3759 } 3760 3761 @Override 3762 public int checkSignatures(String pkg1, String pkg2) { 3763 synchronized (mPackages) { 3764 final PackageParser.Package p1 = mPackages.get(pkg1); 3765 final PackageParser.Package p2 = mPackages.get(pkg2); 3766 if (p1 == null || p1.mExtras == null 3767 || p2 == null || p2.mExtras == null) { 3768 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3769 } 3770 return compareSignatures(p1.mSignatures, p2.mSignatures); 3771 } 3772 } 3773 3774 @Override 3775 public int checkUidSignatures(int uid1, int uid2) { 3776 // Map to base uids. 3777 uid1 = UserHandle.getAppId(uid1); 3778 uid2 = UserHandle.getAppId(uid2); 3779 // reader 3780 synchronized (mPackages) { 3781 Signature[] s1; 3782 Signature[] s2; 3783 Object obj = mSettings.getUserIdLPr(uid1); 3784 if (obj != null) { 3785 if (obj instanceof SharedUserSetting) { 3786 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3787 } else if (obj instanceof PackageSetting) { 3788 s1 = ((PackageSetting)obj).signatures.mSignatures; 3789 } else { 3790 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3791 } 3792 } else { 3793 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3794 } 3795 obj = mSettings.getUserIdLPr(uid2); 3796 if (obj != null) { 3797 if (obj instanceof SharedUserSetting) { 3798 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3799 } else if (obj instanceof PackageSetting) { 3800 s2 = ((PackageSetting)obj).signatures.mSignatures; 3801 } else { 3802 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3803 } 3804 } else { 3805 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3806 } 3807 return compareSignatures(s1, s2); 3808 } 3809 } 3810 3811 private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) { 3812 final long identity = Binder.clearCallingIdentity(); 3813 try { 3814 if (sb instanceof SharedUserSetting) { 3815 SharedUserSetting sus = (SharedUserSetting) sb; 3816 final int packageCount = sus.packages.size(); 3817 for (int i = 0; i < packageCount; i++) { 3818 PackageSetting susPs = sus.packages.valueAt(i); 3819 if (userId == UserHandle.USER_ALL) { 3820 killApplication(susPs.pkg.packageName, susPs.appId, reason); 3821 } else { 3822 final int uid = UserHandle.getUid(userId, susPs.appId); 3823 killUid(uid, reason); 3824 } 3825 } 3826 } else if (sb instanceof PackageSetting) { 3827 PackageSetting ps = (PackageSetting) sb; 3828 if (userId == UserHandle.USER_ALL) { 3829 killApplication(ps.pkg.packageName, ps.appId, reason); 3830 } else { 3831 final int uid = UserHandle.getUid(userId, ps.appId); 3832 killUid(uid, reason); 3833 } 3834 } 3835 } finally { 3836 Binder.restoreCallingIdentity(identity); 3837 } 3838 } 3839 3840 private static void killUid(int uid, String reason) { 3841 IActivityManager am = ActivityManagerNative.getDefault(); 3842 if (am != null) { 3843 try { 3844 am.killUid(uid, reason); 3845 } catch (RemoteException e) { 3846 /* ignore - same process */ 3847 } 3848 } 3849 } 3850 3851 /** 3852 * Compares two sets of signatures. Returns: 3853 * <br /> 3854 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3855 * <br /> 3856 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3857 * <br /> 3858 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3859 * <br /> 3860 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3861 * <br /> 3862 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3863 */ 3864 static int compareSignatures(Signature[] s1, Signature[] s2) { 3865 if (s1 == null) { 3866 return s2 == null 3867 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3868 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3869 } 3870 3871 if (s2 == null) { 3872 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3873 } 3874 3875 if (s1.length != s2.length) { 3876 return PackageManager.SIGNATURE_NO_MATCH; 3877 } 3878 3879 // Since both signature sets are of size 1, we can compare without HashSets. 3880 if (s1.length == 1) { 3881 return s1[0].equals(s2[0]) ? 3882 PackageManager.SIGNATURE_MATCH : 3883 PackageManager.SIGNATURE_NO_MATCH; 3884 } 3885 3886 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3887 for (Signature sig : s1) { 3888 set1.add(sig); 3889 } 3890 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3891 for (Signature sig : s2) { 3892 set2.add(sig); 3893 } 3894 // Make sure s2 contains all signatures in s1. 3895 if (set1.equals(set2)) { 3896 return PackageManager.SIGNATURE_MATCH; 3897 } 3898 return PackageManager.SIGNATURE_NO_MATCH; 3899 } 3900 3901 /** 3902 * If the database version for this type of package (internal storage or 3903 * external storage) is less than the version where package signatures 3904 * were updated, return true. 3905 */ 3906 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3907 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 3908 DatabaseVersion.SIGNATURE_END_ENTITY)) 3909 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 3910 DatabaseVersion.SIGNATURE_END_ENTITY)); 3911 } 3912 3913 /** 3914 * Used for backward compatibility to make sure any packages with 3915 * certificate chains get upgraded to the new style. {@code existingSigs} 3916 * will be in the old format (since they were stored on disk from before the 3917 * system upgrade) and {@code scannedSigs} will be in the newer format. 3918 */ 3919 private int compareSignaturesCompat(PackageSignatures existingSigs, 3920 PackageParser.Package scannedPkg) { 3921 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 3922 return PackageManager.SIGNATURE_NO_MATCH; 3923 } 3924 3925 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 3926 for (Signature sig : existingSigs.mSignatures) { 3927 existingSet.add(sig); 3928 } 3929 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 3930 for (Signature sig : scannedPkg.mSignatures) { 3931 try { 3932 Signature[] chainSignatures = sig.getChainSignatures(); 3933 for (Signature chainSig : chainSignatures) { 3934 scannedCompatSet.add(chainSig); 3935 } 3936 } catch (CertificateEncodingException e) { 3937 scannedCompatSet.add(sig); 3938 } 3939 } 3940 /* 3941 * Make sure the expanded scanned set contains all signatures in the 3942 * existing one. 3943 */ 3944 if (scannedCompatSet.equals(existingSet)) { 3945 // Migrate the old signatures to the new scheme. 3946 existingSigs.assignSignatures(scannedPkg.mSignatures); 3947 // The new KeySets will be re-added later in the scanning process. 3948 synchronized (mPackages) { 3949 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 3950 } 3951 return PackageManager.SIGNATURE_MATCH; 3952 } 3953 return PackageManager.SIGNATURE_NO_MATCH; 3954 } 3955 3956 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3957 if (isExternal(scannedPkg)) { 3958 return mSettings.isExternalDatabaseVersionOlderThan( 3959 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3960 } else { 3961 return mSettings.isInternalDatabaseVersionOlderThan( 3962 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3963 } 3964 } 3965 3966 private int compareSignaturesRecover(PackageSignatures existingSigs, 3967 PackageParser.Package scannedPkg) { 3968 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 3969 return PackageManager.SIGNATURE_NO_MATCH; 3970 } 3971 3972 String msg = null; 3973 try { 3974 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 3975 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 3976 + scannedPkg.packageName); 3977 return PackageManager.SIGNATURE_MATCH; 3978 } 3979 } catch (CertificateException e) { 3980 msg = e.getMessage(); 3981 } 3982 3983 logCriticalInfo(Log.INFO, 3984 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 3985 return PackageManager.SIGNATURE_NO_MATCH; 3986 } 3987 3988 @Override 3989 public String[] getPackagesForUid(int uid) { 3990 uid = UserHandle.getAppId(uid); 3991 // reader 3992 synchronized (mPackages) { 3993 Object obj = mSettings.getUserIdLPr(uid); 3994 if (obj instanceof SharedUserSetting) { 3995 final SharedUserSetting sus = (SharedUserSetting) obj; 3996 final int N = sus.packages.size(); 3997 final String[] res = new String[N]; 3998 final Iterator<PackageSetting> it = sus.packages.iterator(); 3999 int i = 0; 4000 while (it.hasNext()) { 4001 res[i++] = it.next().name; 4002 } 4003 return res; 4004 } else if (obj instanceof PackageSetting) { 4005 final PackageSetting ps = (PackageSetting) obj; 4006 return new String[] { ps.name }; 4007 } 4008 } 4009 return null; 4010 } 4011 4012 @Override 4013 public String getNameForUid(int uid) { 4014 // reader 4015 synchronized (mPackages) { 4016 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4017 if (obj instanceof SharedUserSetting) { 4018 final SharedUserSetting sus = (SharedUserSetting) obj; 4019 return sus.name + ":" + sus.userId; 4020 } else if (obj instanceof PackageSetting) { 4021 final PackageSetting ps = (PackageSetting) obj; 4022 return ps.name; 4023 } 4024 } 4025 return null; 4026 } 4027 4028 @Override 4029 public int getUidForSharedUser(String sharedUserName) { 4030 if(sharedUserName == null) { 4031 return -1; 4032 } 4033 // reader 4034 synchronized (mPackages) { 4035 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4036 if (suid == null) { 4037 return -1; 4038 } 4039 return suid.userId; 4040 } 4041 } 4042 4043 @Override 4044 public int getFlagsForUid(int uid) { 4045 synchronized (mPackages) { 4046 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4047 if (obj instanceof SharedUserSetting) { 4048 final SharedUserSetting sus = (SharedUserSetting) obj; 4049 return sus.pkgFlags; 4050 } else if (obj instanceof PackageSetting) { 4051 final PackageSetting ps = (PackageSetting) obj; 4052 return ps.pkgFlags; 4053 } 4054 } 4055 return 0; 4056 } 4057 4058 @Override 4059 public int getPrivateFlagsForUid(int uid) { 4060 synchronized (mPackages) { 4061 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4062 if (obj instanceof SharedUserSetting) { 4063 final SharedUserSetting sus = (SharedUserSetting) obj; 4064 return sus.pkgPrivateFlags; 4065 } else if (obj instanceof PackageSetting) { 4066 final PackageSetting ps = (PackageSetting) obj; 4067 return ps.pkgPrivateFlags; 4068 } 4069 } 4070 return 0; 4071 } 4072 4073 @Override 4074 public boolean isUidPrivileged(int uid) { 4075 uid = UserHandle.getAppId(uid); 4076 // reader 4077 synchronized (mPackages) { 4078 Object obj = mSettings.getUserIdLPr(uid); 4079 if (obj instanceof SharedUserSetting) { 4080 final SharedUserSetting sus = (SharedUserSetting) obj; 4081 final Iterator<PackageSetting> it = sus.packages.iterator(); 4082 while (it.hasNext()) { 4083 if (it.next().isPrivileged()) { 4084 return true; 4085 } 4086 } 4087 } else if (obj instanceof PackageSetting) { 4088 final PackageSetting ps = (PackageSetting) obj; 4089 return ps.isPrivileged(); 4090 } 4091 } 4092 return false; 4093 } 4094 4095 @Override 4096 public String[] getAppOpPermissionPackages(String permissionName) { 4097 synchronized (mPackages) { 4098 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4099 if (pkgs == null) { 4100 return null; 4101 } 4102 return pkgs.toArray(new String[pkgs.size()]); 4103 } 4104 } 4105 4106 @Override 4107 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4108 int flags, int userId) { 4109 if (!sUserManager.exists(userId)) return null; 4110 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 4111 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4112 return chooseBestActivity(intent, resolvedType, flags, query, userId); 4113 } 4114 4115 @Override 4116 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4117 IntentFilter filter, int match, ComponentName activity) { 4118 final int userId = UserHandle.getCallingUserId(); 4119 if (DEBUG_PREFERRED) { 4120 Log.v(TAG, "setLastChosenActivity intent=" + intent 4121 + " resolvedType=" + resolvedType 4122 + " flags=" + flags 4123 + " filter=" + filter 4124 + " match=" + match 4125 + " activity=" + activity); 4126 filter.dump(new PrintStreamPrinter(System.out), " "); 4127 } 4128 intent.setComponent(null); 4129 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4130 // Find any earlier preferred or last chosen entries and nuke them 4131 findPreferredActivity(intent, resolvedType, 4132 flags, query, 0, false, true, false, userId); 4133 // Add the new activity as the last chosen for this filter 4134 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4135 "Setting last chosen"); 4136 } 4137 4138 @Override 4139 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4140 final int userId = UserHandle.getCallingUserId(); 4141 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4142 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4143 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4144 false, false, false, userId); 4145 } 4146 4147 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4148 int flags, List<ResolveInfo> query, int userId) { 4149 if (query != null) { 4150 final int N = query.size(); 4151 if (N == 1) { 4152 return query.get(0); 4153 } else if (N > 1) { 4154 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4155 // If there is more than one activity with the same priority, 4156 // then let the user decide between them. 4157 ResolveInfo r0 = query.get(0); 4158 ResolveInfo r1 = query.get(1); 4159 if (DEBUG_INTENT_MATCHING || debug) { 4160 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4161 + r1.activityInfo.name + "=" + r1.priority); 4162 } 4163 // If the first activity has a higher priority, or a different 4164 // default, then it is always desireable to pick it. 4165 if (r0.priority != r1.priority 4166 || r0.preferredOrder != r1.preferredOrder 4167 || r0.isDefault != r1.isDefault) { 4168 return query.get(0); 4169 } 4170 // If we have saved a preference for a preferred activity for 4171 // this Intent, use that. 4172 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4173 flags, query, r0.priority, true, false, debug, userId); 4174 if (ri != null) { 4175 return ri; 4176 } 4177 if (userId != 0) { 4178 ri = new ResolveInfo(mResolveInfo); 4179 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4180 ri.activityInfo.applicationInfo = new ApplicationInfo( 4181 ri.activityInfo.applicationInfo); 4182 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4183 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4184 return ri; 4185 } 4186 return mResolveInfo; 4187 } 4188 } 4189 return null; 4190 } 4191 4192 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4193 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4194 final int N = query.size(); 4195 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4196 .get(userId); 4197 // Get the list of persistent preferred activities that handle the intent 4198 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4199 List<PersistentPreferredActivity> pprefs = ppir != null 4200 ? ppir.queryIntent(intent, resolvedType, 4201 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4202 : null; 4203 if (pprefs != null && pprefs.size() > 0) { 4204 final int M = pprefs.size(); 4205 for (int i=0; i<M; i++) { 4206 final PersistentPreferredActivity ppa = pprefs.get(i); 4207 if (DEBUG_PREFERRED || debug) { 4208 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4209 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4210 + "\n component=" + ppa.mComponent); 4211 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4212 } 4213 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4214 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4215 if (DEBUG_PREFERRED || debug) { 4216 Slog.v(TAG, "Found persistent preferred activity:"); 4217 if (ai != null) { 4218 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4219 } else { 4220 Slog.v(TAG, " null"); 4221 } 4222 } 4223 if (ai == null) { 4224 // This previously registered persistent preferred activity 4225 // component is no longer known. Ignore it and do NOT remove it. 4226 continue; 4227 } 4228 for (int j=0; j<N; j++) { 4229 final ResolveInfo ri = query.get(j); 4230 if (!ri.activityInfo.applicationInfo.packageName 4231 .equals(ai.applicationInfo.packageName)) { 4232 continue; 4233 } 4234 if (!ri.activityInfo.name.equals(ai.name)) { 4235 continue; 4236 } 4237 // Found a persistent preference that can handle the intent. 4238 if (DEBUG_PREFERRED || debug) { 4239 Slog.v(TAG, "Returning persistent preferred activity: " + 4240 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4241 } 4242 return ri; 4243 } 4244 } 4245 } 4246 return null; 4247 } 4248 4249 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4250 List<ResolveInfo> query, int priority, boolean always, 4251 boolean removeMatches, boolean debug, int userId) { 4252 if (!sUserManager.exists(userId)) return null; 4253 // writer 4254 synchronized (mPackages) { 4255 if (intent.getSelector() != null) { 4256 intent = intent.getSelector(); 4257 } 4258 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4259 4260 // Try to find a matching persistent preferred activity. 4261 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4262 debug, userId); 4263 4264 // If a persistent preferred activity matched, use it. 4265 if (pri != null) { 4266 return pri; 4267 } 4268 4269 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4270 // Get the list of preferred activities that handle the intent 4271 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4272 List<PreferredActivity> prefs = pir != null 4273 ? pir.queryIntent(intent, resolvedType, 4274 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4275 : null; 4276 if (prefs != null && prefs.size() > 0) { 4277 boolean changed = false; 4278 try { 4279 // First figure out how good the original match set is. 4280 // We will only allow preferred activities that came 4281 // from the same match quality. 4282 int match = 0; 4283 4284 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4285 4286 final int N = query.size(); 4287 for (int j=0; j<N; j++) { 4288 final ResolveInfo ri = query.get(j); 4289 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4290 + ": 0x" + Integer.toHexString(match)); 4291 if (ri.match > match) { 4292 match = ri.match; 4293 } 4294 } 4295 4296 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4297 + Integer.toHexString(match)); 4298 4299 match &= IntentFilter.MATCH_CATEGORY_MASK; 4300 final int M = prefs.size(); 4301 for (int i=0; i<M; i++) { 4302 final PreferredActivity pa = prefs.get(i); 4303 if (DEBUG_PREFERRED || debug) { 4304 Slog.v(TAG, "Checking PreferredActivity ds=" 4305 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4306 + "\n component=" + pa.mPref.mComponent); 4307 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4308 } 4309 if (pa.mPref.mMatch != match) { 4310 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4311 + Integer.toHexString(pa.mPref.mMatch)); 4312 continue; 4313 } 4314 // If it's not an "always" type preferred activity and that's what we're 4315 // looking for, skip it. 4316 if (always && !pa.mPref.mAlways) { 4317 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4318 continue; 4319 } 4320 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4321 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4322 if (DEBUG_PREFERRED || debug) { 4323 Slog.v(TAG, "Found preferred activity:"); 4324 if (ai != null) { 4325 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4326 } else { 4327 Slog.v(TAG, " null"); 4328 } 4329 } 4330 if (ai == null) { 4331 // This previously registered preferred activity 4332 // component is no longer known. Most likely an update 4333 // to the app was installed and in the new version this 4334 // component no longer exists. Clean it up by removing 4335 // it from the preferred activities list, and skip it. 4336 Slog.w(TAG, "Removing dangling preferred activity: " 4337 + pa.mPref.mComponent); 4338 pir.removeFilter(pa); 4339 changed = true; 4340 continue; 4341 } 4342 for (int j=0; j<N; j++) { 4343 final ResolveInfo ri = query.get(j); 4344 if (!ri.activityInfo.applicationInfo.packageName 4345 .equals(ai.applicationInfo.packageName)) { 4346 continue; 4347 } 4348 if (!ri.activityInfo.name.equals(ai.name)) { 4349 continue; 4350 } 4351 4352 if (removeMatches) { 4353 pir.removeFilter(pa); 4354 changed = true; 4355 if (DEBUG_PREFERRED) { 4356 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4357 } 4358 break; 4359 } 4360 4361 // Okay we found a previously set preferred or last chosen app. 4362 // If the result set is different from when this 4363 // was created, we need to clear it and re-ask the 4364 // user their preference, if we're looking for an "always" type entry. 4365 if (always && !pa.mPref.sameSet(query)) { 4366 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4367 + intent + " type " + resolvedType); 4368 if (DEBUG_PREFERRED) { 4369 Slog.v(TAG, "Removing preferred activity since set changed " 4370 + pa.mPref.mComponent); 4371 } 4372 pir.removeFilter(pa); 4373 // Re-add the filter as a "last chosen" entry (!always) 4374 PreferredActivity lastChosen = new PreferredActivity( 4375 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4376 pir.addFilter(lastChosen); 4377 changed = true; 4378 return null; 4379 } 4380 4381 // Yay! Either the set matched or we're looking for the last chosen 4382 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4383 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4384 return ri; 4385 } 4386 } 4387 } finally { 4388 if (changed) { 4389 if (DEBUG_PREFERRED) { 4390 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4391 } 4392 scheduleWritePackageRestrictionsLocked(userId); 4393 } 4394 } 4395 } 4396 } 4397 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4398 return null; 4399 } 4400 4401 /* 4402 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4403 */ 4404 @Override 4405 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4406 int targetUserId) { 4407 mContext.enforceCallingOrSelfPermission( 4408 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4409 List<CrossProfileIntentFilter> matches = 4410 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4411 if (matches != null) { 4412 int size = matches.size(); 4413 for (int i = 0; i < size; i++) { 4414 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4415 } 4416 } 4417 if (hasWebURI(intent)) { 4418 // cross-profile app linking works only towards the parent. 4419 final UserInfo parent = getProfileParent(sourceUserId); 4420 synchronized(mPackages) { 4421 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 4422 intent, resolvedType, 0, sourceUserId, parent.id); 4423 return xpDomainInfo != null 4424 && xpDomainInfo.bestDomainVerificationStatus != 4425 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 4426 } 4427 } 4428 return false; 4429 } 4430 4431 private UserInfo getProfileParent(int userId) { 4432 final long identity = Binder.clearCallingIdentity(); 4433 try { 4434 return sUserManager.getProfileParent(userId); 4435 } finally { 4436 Binder.restoreCallingIdentity(identity); 4437 } 4438 } 4439 4440 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4441 String resolvedType, int userId) { 4442 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4443 if (resolver != null) { 4444 return resolver.queryIntent(intent, resolvedType, false, userId); 4445 } 4446 return null; 4447 } 4448 4449 @Override 4450 public List<ResolveInfo> queryIntentActivities(Intent intent, 4451 String resolvedType, int flags, int userId) { 4452 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4453 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4454 ComponentName comp = intent.getComponent(); 4455 if (comp == null) { 4456 if (intent.getSelector() != null) { 4457 intent = intent.getSelector(); 4458 comp = intent.getComponent(); 4459 } 4460 } 4461 4462 if (comp != null) { 4463 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4464 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4465 if (ai != null) { 4466 final ResolveInfo ri = new ResolveInfo(); 4467 ri.activityInfo = ai; 4468 list.add(ri); 4469 } 4470 return list; 4471 } 4472 4473 // reader 4474 synchronized (mPackages) { 4475 final String pkgName = intent.getPackage(); 4476 if (pkgName == null) { 4477 List<CrossProfileIntentFilter> matchingFilters = 4478 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4479 // Check for results that need to skip the current profile. 4480 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4481 resolvedType, flags, userId); 4482 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4483 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4484 result.add(xpResolveInfo); 4485 return filterIfNotPrimaryUser(result, userId); 4486 } 4487 4488 // Check for results in the current profile. 4489 List<ResolveInfo> result = mActivities.queryIntent( 4490 intent, resolvedType, flags, userId); 4491 4492 // Check for cross profile results. 4493 xpResolveInfo = queryCrossProfileIntents( 4494 matchingFilters, intent, resolvedType, flags, userId); 4495 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4496 result.add(xpResolveInfo); 4497 Collections.sort(result, mResolvePrioritySorter); 4498 } 4499 result = filterIfNotPrimaryUser(result, userId); 4500 if (hasWebURI(intent)) { 4501 CrossProfileDomainInfo xpDomainInfo = null; 4502 final UserInfo parent = getProfileParent(userId); 4503 if (parent != null) { 4504 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 4505 flags, userId, parent.id); 4506 } 4507 if (xpDomainInfo != null) { 4508 if (xpResolveInfo != null) { 4509 // If we didn't remove it, the cross-profile ResolveInfo would be twice 4510 // in the result. 4511 result.remove(xpResolveInfo); 4512 } 4513 if (result.size() == 0) { 4514 result.add(xpDomainInfo.resolveInfo); 4515 return result; 4516 } 4517 } else if (result.size() <= 1) { 4518 return result; 4519 } 4520 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 4521 xpDomainInfo, userId); 4522 Collections.sort(result, mResolvePrioritySorter); 4523 } 4524 return result; 4525 } 4526 final PackageParser.Package pkg = mPackages.get(pkgName); 4527 if (pkg != null) { 4528 return filterIfNotPrimaryUser( 4529 mActivities.queryIntentForPackage( 4530 intent, resolvedType, flags, pkg.activities, userId), 4531 userId); 4532 } 4533 return new ArrayList<ResolveInfo>(); 4534 } 4535 } 4536 4537 private static class CrossProfileDomainInfo { 4538 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 4539 ResolveInfo resolveInfo; 4540 /* Best domain verification status of the activities found in the other profile */ 4541 int bestDomainVerificationStatus; 4542 } 4543 4544 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 4545 String resolvedType, int flags, int sourceUserId, int parentUserId) { 4546 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 4547 sourceUserId)) { 4548 return null; 4549 } 4550 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4551 resolvedType, flags, parentUserId); 4552 4553 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 4554 return null; 4555 } 4556 CrossProfileDomainInfo result = null; 4557 int size = resultTargetUser.size(); 4558 for (int i = 0; i < size; i++) { 4559 ResolveInfo riTargetUser = resultTargetUser.get(i); 4560 // Intent filter verification is only for filters that specify a host. So don't return 4561 // those that handle all web uris. 4562 if (riTargetUser.handleAllWebDataURI) { 4563 continue; 4564 } 4565 String packageName = riTargetUser.activityInfo.packageName; 4566 PackageSetting ps = mSettings.mPackages.get(packageName); 4567 if (ps == null) { 4568 continue; 4569 } 4570 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 4571 int status = (int)(verificationState >> 32); 4572 if (result == null) { 4573 result = new CrossProfileDomainInfo(); 4574 result.resolveInfo = 4575 createForwardingResolveInfo(null, sourceUserId, parentUserId); 4576 result.bestDomainVerificationStatus = status; 4577 } else { 4578 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 4579 result.bestDomainVerificationStatus); 4580 } 4581 } 4582 return result; 4583 } 4584 4585 /** 4586 * Verification statuses are ordered from the worse to the best, except for 4587 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 4588 */ 4589 private int bestDomainVerificationStatus(int status1, int status2) { 4590 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4591 return status2; 4592 } 4593 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4594 return status1; 4595 } 4596 return (int) MathUtils.max(status1, status2); 4597 } 4598 4599 private boolean isUserEnabled(int userId) { 4600 long callingId = Binder.clearCallingIdentity(); 4601 try { 4602 UserInfo userInfo = sUserManager.getUserInfo(userId); 4603 return userInfo != null && userInfo.isEnabled(); 4604 } finally { 4605 Binder.restoreCallingIdentity(callingId); 4606 } 4607 } 4608 4609 /** 4610 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 4611 * 4612 * @return filtered list 4613 */ 4614 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 4615 if (userId == UserHandle.USER_OWNER) { 4616 return resolveInfos; 4617 } 4618 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 4619 ResolveInfo info = resolveInfos.get(i); 4620 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 4621 resolveInfos.remove(i); 4622 } 4623 } 4624 return resolveInfos; 4625 } 4626 4627 private static boolean hasWebURI(Intent intent) { 4628 if (intent.getData() == null) { 4629 return false; 4630 } 4631 final String scheme = intent.getScheme(); 4632 if (TextUtils.isEmpty(scheme)) { 4633 return false; 4634 } 4635 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4636 } 4637 4638 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 4639 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 4640 int userId) { 4641 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 4642 4643 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4644 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 4645 candidates.size()); 4646 } 4647 4648 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4649 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 4650 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4651 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4652 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4653 4654 synchronized (mPackages) { 4655 final int count = candidates.size(); 4656 // First, try to use linked apps. Partition the candidates into four lists: 4657 // one for the final results, one for the "do not use ever", one for "undefined status" 4658 // and finally one for "browser app type". 4659 for (int n=0; n<count; n++) { 4660 ResolveInfo info = candidates.get(n); 4661 String packageName = info.activityInfo.packageName; 4662 PackageSetting ps = mSettings.mPackages.get(packageName); 4663 if (ps != null) { 4664 // Add to the special match all list (Browser use case) 4665 if (info.handleAllWebDataURI) { 4666 matchAllList.add(info); 4667 continue; 4668 } 4669 // Try to get the status from User settings first 4670 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4671 int status = (int)(packedStatus >> 32); 4672 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 4673 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4674 if (DEBUG_DOMAIN_VERIFICATION) { 4675 Slog.i(TAG, " + always: " + info.activityInfo.packageName 4676 + " : linkgen=" + linkGeneration); 4677 } 4678 // Use link-enabled generation as preferredOrder, i.e. 4679 // prefer newly-enabled over earlier-enabled. 4680 info.preferredOrder = linkGeneration; 4681 alwaysList.add(info); 4682 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4683 if (DEBUG_DOMAIN_VERIFICATION) { 4684 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 4685 } 4686 neverList.add(info); 4687 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 4688 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 4689 if (DEBUG_DOMAIN_VERIFICATION) { 4690 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 4691 } 4692 undefinedList.add(info); 4693 } 4694 } 4695 } 4696 // First try to add the "always" resolution(s) for the current user, if any 4697 if (alwaysList.size() > 0) { 4698 result.addAll(alwaysList); 4699 // if there is an "always" for the parent user, add it. 4700 } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus 4701 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4702 result.add(xpDomainInfo.resolveInfo); 4703 } else { 4704 // Add all undefined Apps as we want them to appear in the Disambiguation dialog. 4705 result.addAll(undefinedList); 4706 if (xpDomainInfo != null && ( 4707 xpDomainInfo.bestDomainVerificationStatus 4708 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 4709 || xpDomainInfo.bestDomainVerificationStatus 4710 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) { 4711 result.add(xpDomainInfo.resolveInfo); 4712 } 4713 // Also add Browsers (all of them or only the default one) 4714 if ((matchFlags & MATCH_ALL) != 0) { 4715 result.addAll(matchAllList); 4716 } else { 4717 // Browser/generic handling case. If there's a default browser, go straight 4718 // to that (but only if there is no other higher-priority match). 4719 final String defaultBrowserPackageName = getDefaultBrowserPackageName( 4720 UserHandle.myUserId()); 4721 int maxMatchPrio = 0; 4722 ResolveInfo defaultBrowserMatch = null; 4723 final int numCandidates = matchAllList.size(); 4724 for (int n = 0; n < numCandidates; n++) { 4725 ResolveInfo info = matchAllList.get(n); 4726 // track the highest overall match priority... 4727 if (info.priority > maxMatchPrio) { 4728 maxMatchPrio = info.priority; 4729 } 4730 // ...and the highest-priority default browser match 4731 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4732 if (defaultBrowserMatch == null 4733 || (defaultBrowserMatch.priority < info.priority)) { 4734 if (debug) { 4735 Slog.v(TAG, "Considering default browser match " + info); 4736 } 4737 defaultBrowserMatch = info; 4738 } 4739 } 4740 } 4741 if (defaultBrowserMatch != null 4742 && defaultBrowserMatch.priority >= maxMatchPrio 4743 && !TextUtils.isEmpty(defaultBrowserPackageName)) 4744 { 4745 if (debug) { 4746 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 4747 } 4748 result.add(defaultBrowserMatch); 4749 } else { 4750 result.addAll(matchAllList); 4751 } 4752 } 4753 4754 // If there is nothing selected, add all candidates and remove the ones that the user 4755 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 4756 if (result.size() == 0) { 4757 result.addAll(candidates); 4758 result.removeAll(neverList); 4759 } 4760 } 4761 } 4762 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4763 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 4764 result.size()); 4765 for (ResolveInfo info : result) { 4766 Slog.v(TAG, " + " + info.activityInfo); 4767 } 4768 } 4769 return result; 4770 } 4771 4772 // Returns a packed value as a long: 4773 // 4774 // high 'int'-sized word: link status: undefined/ask/never/always. 4775 // low 'int'-sized word: relative priority among 'always' results. 4776 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4777 long result = ps.getDomainVerificationStatusForUser(userId); 4778 // if none available, get the master status 4779 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4780 if (ps.getIntentFilterVerificationInfo() != null) { 4781 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 4782 } 4783 } 4784 return result; 4785 } 4786 4787 private ResolveInfo querySkipCurrentProfileIntents( 4788 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4789 int flags, int sourceUserId) { 4790 if (matchingFilters != null) { 4791 int size = matchingFilters.size(); 4792 for (int i = 0; i < size; i ++) { 4793 CrossProfileIntentFilter filter = matchingFilters.get(i); 4794 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4795 // Checking if there are activities in the target user that can handle the 4796 // intent. 4797 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4798 flags, sourceUserId); 4799 if (resolveInfo != null) { 4800 return resolveInfo; 4801 } 4802 } 4803 } 4804 } 4805 return null; 4806 } 4807 4808 // Return matching ResolveInfo if any for skip current profile intent filters. 4809 private ResolveInfo queryCrossProfileIntents( 4810 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4811 int flags, int sourceUserId) { 4812 if (matchingFilters != null) { 4813 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4814 // match the same intent. For performance reasons, it is better not to 4815 // run queryIntent twice for the same userId 4816 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4817 int size = matchingFilters.size(); 4818 for (int i = 0; i < size; i++) { 4819 CrossProfileIntentFilter filter = matchingFilters.get(i); 4820 int targetUserId = filter.getTargetUserId(); 4821 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4822 && !alreadyTriedUserIds.get(targetUserId)) { 4823 // Checking if there are activities in the target user that can handle the 4824 // intent. 4825 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4826 flags, sourceUserId); 4827 if (resolveInfo != null) return resolveInfo; 4828 alreadyTriedUserIds.put(targetUserId, true); 4829 } 4830 } 4831 } 4832 return null; 4833 } 4834 4835 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 4836 String resolvedType, int flags, int sourceUserId) { 4837 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4838 resolvedType, flags, filter.getTargetUserId()); 4839 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4840 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4841 } 4842 return null; 4843 } 4844 4845 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4846 int sourceUserId, int targetUserId) { 4847 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4848 String className; 4849 if (targetUserId == UserHandle.USER_OWNER) { 4850 className = FORWARD_INTENT_TO_USER_OWNER; 4851 } else { 4852 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4853 } 4854 ComponentName forwardingActivityComponentName = new ComponentName( 4855 mAndroidApplication.packageName, className); 4856 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4857 sourceUserId); 4858 if (targetUserId == UserHandle.USER_OWNER) { 4859 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 4860 forwardingResolveInfo.noResourceId = true; 4861 } 4862 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4863 forwardingResolveInfo.priority = 0; 4864 forwardingResolveInfo.preferredOrder = 0; 4865 forwardingResolveInfo.match = 0; 4866 forwardingResolveInfo.isDefault = true; 4867 forwardingResolveInfo.filter = filter; 4868 forwardingResolveInfo.targetUserId = targetUserId; 4869 return forwardingResolveInfo; 4870 } 4871 4872 @Override 4873 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4874 Intent[] specifics, String[] specificTypes, Intent intent, 4875 String resolvedType, int flags, int userId) { 4876 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4877 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4878 false, "query intent activity options"); 4879 final String resultsAction = intent.getAction(); 4880 4881 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4882 | PackageManager.GET_RESOLVED_FILTER, userId); 4883 4884 if (DEBUG_INTENT_MATCHING) { 4885 Log.v(TAG, "Query " + intent + ": " + results); 4886 } 4887 4888 int specificsPos = 0; 4889 int N; 4890 4891 // todo: note that the algorithm used here is O(N^2). This 4892 // isn't a problem in our current environment, but if we start running 4893 // into situations where we have more than 5 or 10 matches then this 4894 // should probably be changed to something smarter... 4895 4896 // First we go through and resolve each of the specific items 4897 // that were supplied, taking care of removing any corresponding 4898 // duplicate items in the generic resolve list. 4899 if (specifics != null) { 4900 for (int i=0; i<specifics.length; i++) { 4901 final Intent sintent = specifics[i]; 4902 if (sintent == null) { 4903 continue; 4904 } 4905 4906 if (DEBUG_INTENT_MATCHING) { 4907 Log.v(TAG, "Specific #" + i + ": " + sintent); 4908 } 4909 4910 String action = sintent.getAction(); 4911 if (resultsAction != null && resultsAction.equals(action)) { 4912 // If this action was explicitly requested, then don't 4913 // remove things that have it. 4914 action = null; 4915 } 4916 4917 ResolveInfo ri = null; 4918 ActivityInfo ai = null; 4919 4920 ComponentName comp = sintent.getComponent(); 4921 if (comp == null) { 4922 ri = resolveIntent( 4923 sintent, 4924 specificTypes != null ? specificTypes[i] : null, 4925 flags, userId); 4926 if (ri == null) { 4927 continue; 4928 } 4929 if (ri == mResolveInfo) { 4930 // ACK! Must do something better with this. 4931 } 4932 ai = ri.activityInfo; 4933 comp = new ComponentName(ai.applicationInfo.packageName, 4934 ai.name); 4935 } else { 4936 ai = getActivityInfo(comp, flags, userId); 4937 if (ai == null) { 4938 continue; 4939 } 4940 } 4941 4942 // Look for any generic query activities that are duplicates 4943 // of this specific one, and remove them from the results. 4944 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 4945 N = results.size(); 4946 int j; 4947 for (j=specificsPos; j<N; j++) { 4948 ResolveInfo sri = results.get(j); 4949 if ((sri.activityInfo.name.equals(comp.getClassName()) 4950 && sri.activityInfo.applicationInfo.packageName.equals( 4951 comp.getPackageName())) 4952 || (action != null && sri.filter.matchAction(action))) { 4953 results.remove(j); 4954 if (DEBUG_INTENT_MATCHING) Log.v( 4955 TAG, "Removing duplicate item from " + j 4956 + " due to specific " + specificsPos); 4957 if (ri == null) { 4958 ri = sri; 4959 } 4960 j--; 4961 N--; 4962 } 4963 } 4964 4965 // Add this specific item to its proper place. 4966 if (ri == null) { 4967 ri = new ResolveInfo(); 4968 ri.activityInfo = ai; 4969 } 4970 results.add(specificsPos, ri); 4971 ri.specificIndex = i; 4972 specificsPos++; 4973 } 4974 } 4975 4976 // Now we go through the remaining generic results and remove any 4977 // duplicate actions that are found here. 4978 N = results.size(); 4979 for (int i=specificsPos; i<N-1; i++) { 4980 final ResolveInfo rii = results.get(i); 4981 if (rii.filter == null) { 4982 continue; 4983 } 4984 4985 // Iterate over all of the actions of this result's intent 4986 // filter... typically this should be just one. 4987 final Iterator<String> it = rii.filter.actionsIterator(); 4988 if (it == null) { 4989 continue; 4990 } 4991 while (it.hasNext()) { 4992 final String action = it.next(); 4993 if (resultsAction != null && resultsAction.equals(action)) { 4994 // If this action was explicitly requested, then don't 4995 // remove things that have it. 4996 continue; 4997 } 4998 for (int j=i+1; j<N; j++) { 4999 final ResolveInfo rij = results.get(j); 5000 if (rij.filter != null && rij.filter.hasAction(action)) { 5001 results.remove(j); 5002 if (DEBUG_INTENT_MATCHING) Log.v( 5003 TAG, "Removing duplicate item from " + j 5004 + " due to action " + action + " at " + i); 5005 j--; 5006 N--; 5007 } 5008 } 5009 } 5010 5011 // If the caller didn't request filter information, drop it now 5012 // so we don't have to marshall/unmarshall it. 5013 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5014 rii.filter = null; 5015 } 5016 } 5017 5018 // Filter out the caller activity if so requested. 5019 if (caller != null) { 5020 N = results.size(); 5021 for (int i=0; i<N; i++) { 5022 ActivityInfo ainfo = results.get(i).activityInfo; 5023 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5024 && caller.getClassName().equals(ainfo.name)) { 5025 results.remove(i); 5026 break; 5027 } 5028 } 5029 } 5030 5031 // If the caller didn't request filter information, 5032 // drop them now so we don't have to 5033 // marshall/unmarshall it. 5034 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5035 N = results.size(); 5036 for (int i=0; i<N; i++) { 5037 results.get(i).filter = null; 5038 } 5039 } 5040 5041 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5042 return results; 5043 } 5044 5045 @Override 5046 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 5047 int userId) { 5048 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5049 ComponentName comp = intent.getComponent(); 5050 if (comp == null) { 5051 if (intent.getSelector() != null) { 5052 intent = intent.getSelector(); 5053 comp = intent.getComponent(); 5054 } 5055 } 5056 if (comp != null) { 5057 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5058 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5059 if (ai != null) { 5060 ResolveInfo ri = new ResolveInfo(); 5061 ri.activityInfo = ai; 5062 list.add(ri); 5063 } 5064 return list; 5065 } 5066 5067 // reader 5068 synchronized (mPackages) { 5069 String pkgName = intent.getPackage(); 5070 if (pkgName == null) { 5071 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5072 } 5073 final PackageParser.Package pkg = mPackages.get(pkgName); 5074 if (pkg != null) { 5075 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5076 userId); 5077 } 5078 return null; 5079 } 5080 } 5081 5082 @Override 5083 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5084 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 5085 if (!sUserManager.exists(userId)) return null; 5086 if (query != null) { 5087 if (query.size() >= 1) { 5088 // If there is more than one service with the same priority, 5089 // just arbitrarily pick the first one. 5090 return query.get(0); 5091 } 5092 } 5093 return null; 5094 } 5095 5096 @Override 5097 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 5098 int userId) { 5099 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5100 ComponentName comp = intent.getComponent(); 5101 if (comp == null) { 5102 if (intent.getSelector() != null) { 5103 intent = intent.getSelector(); 5104 comp = intent.getComponent(); 5105 } 5106 } 5107 if (comp != null) { 5108 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5109 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5110 if (si != null) { 5111 final ResolveInfo ri = new ResolveInfo(); 5112 ri.serviceInfo = si; 5113 list.add(ri); 5114 } 5115 return list; 5116 } 5117 5118 // reader 5119 synchronized (mPackages) { 5120 String pkgName = intent.getPackage(); 5121 if (pkgName == null) { 5122 return mServices.queryIntent(intent, resolvedType, flags, userId); 5123 } 5124 final PackageParser.Package pkg = mPackages.get(pkgName); 5125 if (pkg != null) { 5126 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5127 userId); 5128 } 5129 return null; 5130 } 5131 } 5132 5133 @Override 5134 public List<ResolveInfo> queryIntentContentProviders( 5135 Intent intent, String resolvedType, int flags, int userId) { 5136 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5137 ComponentName comp = intent.getComponent(); 5138 if (comp == null) { 5139 if (intent.getSelector() != null) { 5140 intent = intent.getSelector(); 5141 comp = intent.getComponent(); 5142 } 5143 } 5144 if (comp != null) { 5145 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5146 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5147 if (pi != null) { 5148 final ResolveInfo ri = new ResolveInfo(); 5149 ri.providerInfo = pi; 5150 list.add(ri); 5151 } 5152 return list; 5153 } 5154 5155 // reader 5156 synchronized (mPackages) { 5157 String pkgName = intent.getPackage(); 5158 if (pkgName == null) { 5159 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5160 } 5161 final PackageParser.Package pkg = mPackages.get(pkgName); 5162 if (pkg != null) { 5163 return mProviders.queryIntentForPackage( 5164 intent, resolvedType, flags, pkg.providers, userId); 5165 } 5166 return null; 5167 } 5168 } 5169 5170 @Override 5171 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5172 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5173 5174 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 5175 5176 // writer 5177 synchronized (mPackages) { 5178 ArrayList<PackageInfo> list; 5179 if (listUninstalled) { 5180 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5181 for (PackageSetting ps : mSettings.mPackages.values()) { 5182 PackageInfo pi; 5183 if (ps.pkg != null) { 5184 pi = generatePackageInfo(ps.pkg, flags, userId); 5185 } else { 5186 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5187 } 5188 if (pi != null) { 5189 list.add(pi); 5190 } 5191 } 5192 } else { 5193 list = new ArrayList<PackageInfo>(mPackages.size()); 5194 for (PackageParser.Package p : mPackages.values()) { 5195 PackageInfo pi = generatePackageInfo(p, flags, userId); 5196 if (pi != null) { 5197 list.add(pi); 5198 } 5199 } 5200 } 5201 5202 return new ParceledListSlice<PackageInfo>(list); 5203 } 5204 } 5205 5206 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5207 String[] permissions, boolean[] tmp, int flags, int userId) { 5208 int numMatch = 0; 5209 final PermissionsState permissionsState = ps.getPermissionsState(); 5210 for (int i=0; i<permissions.length; i++) { 5211 final String permission = permissions[i]; 5212 if (permissionsState.hasPermission(permission, userId)) { 5213 tmp[i] = true; 5214 numMatch++; 5215 } else { 5216 tmp[i] = false; 5217 } 5218 } 5219 if (numMatch == 0) { 5220 return; 5221 } 5222 PackageInfo pi; 5223 if (ps.pkg != null) { 5224 pi = generatePackageInfo(ps.pkg, flags, userId); 5225 } else { 5226 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5227 } 5228 // The above might return null in cases of uninstalled apps or install-state 5229 // skew across users/profiles. 5230 if (pi != null) { 5231 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5232 if (numMatch == permissions.length) { 5233 pi.requestedPermissions = permissions; 5234 } else { 5235 pi.requestedPermissions = new String[numMatch]; 5236 numMatch = 0; 5237 for (int i=0; i<permissions.length; i++) { 5238 if (tmp[i]) { 5239 pi.requestedPermissions[numMatch] = permissions[i]; 5240 numMatch++; 5241 } 5242 } 5243 } 5244 } 5245 list.add(pi); 5246 } 5247 } 5248 5249 @Override 5250 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5251 String[] permissions, int flags, int userId) { 5252 if (!sUserManager.exists(userId)) return null; 5253 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5254 5255 // writer 5256 synchronized (mPackages) { 5257 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5258 boolean[] tmpBools = new boolean[permissions.length]; 5259 if (listUninstalled) { 5260 for (PackageSetting ps : mSettings.mPackages.values()) { 5261 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5262 } 5263 } else { 5264 for (PackageParser.Package pkg : mPackages.values()) { 5265 PackageSetting ps = (PackageSetting)pkg.mExtras; 5266 if (ps != null) { 5267 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5268 userId); 5269 } 5270 } 5271 } 5272 5273 return new ParceledListSlice<PackageInfo>(list); 5274 } 5275 } 5276 5277 @Override 5278 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5279 if (!sUserManager.exists(userId)) return null; 5280 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5281 5282 // writer 5283 synchronized (mPackages) { 5284 ArrayList<ApplicationInfo> list; 5285 if (listUninstalled) { 5286 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5287 for (PackageSetting ps : mSettings.mPackages.values()) { 5288 ApplicationInfo ai; 5289 if (ps.pkg != null) { 5290 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5291 ps.readUserState(userId), userId); 5292 } else { 5293 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5294 } 5295 if (ai != null) { 5296 list.add(ai); 5297 } 5298 } 5299 } else { 5300 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5301 for (PackageParser.Package p : mPackages.values()) { 5302 if (p.mExtras != null) { 5303 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5304 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5305 if (ai != null) { 5306 list.add(ai); 5307 } 5308 } 5309 } 5310 } 5311 5312 return new ParceledListSlice<ApplicationInfo>(list); 5313 } 5314 } 5315 5316 public List<ApplicationInfo> getPersistentApplications(int flags) { 5317 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 5318 5319 // reader 5320 synchronized (mPackages) { 5321 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 5322 final int userId = UserHandle.getCallingUserId(); 5323 while (i.hasNext()) { 5324 final PackageParser.Package p = i.next(); 5325 if (p.applicationInfo != null 5326 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 5327 && (!mSafeMode || isSystemApp(p))) { 5328 PackageSetting ps = mSettings.mPackages.get(p.packageName); 5329 if (ps != null) { 5330 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5331 ps.readUserState(userId), userId); 5332 if (ai != null) { 5333 finalList.add(ai); 5334 } 5335 } 5336 } 5337 } 5338 } 5339 5340 return finalList; 5341 } 5342 5343 @Override 5344 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 5345 if (!sUserManager.exists(userId)) return null; 5346 // reader 5347 synchronized (mPackages) { 5348 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 5349 PackageSetting ps = provider != null 5350 ? mSettings.mPackages.get(provider.owner.packageName) 5351 : null; 5352 return ps != null 5353 && mSettings.isEnabledLPr(provider.info, flags, userId) 5354 && (!mSafeMode || (provider.info.applicationInfo.flags 5355 &ApplicationInfo.FLAG_SYSTEM) != 0) 5356 ? PackageParser.generateProviderInfo(provider, flags, 5357 ps.readUserState(userId), userId) 5358 : null; 5359 } 5360 } 5361 5362 /** 5363 * @deprecated 5364 */ 5365 @Deprecated 5366 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 5367 // reader 5368 synchronized (mPackages) { 5369 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 5370 .entrySet().iterator(); 5371 final int userId = UserHandle.getCallingUserId(); 5372 while (i.hasNext()) { 5373 Map.Entry<String, PackageParser.Provider> entry = i.next(); 5374 PackageParser.Provider p = entry.getValue(); 5375 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5376 5377 if (ps != null && p.syncable 5378 && (!mSafeMode || (p.info.applicationInfo.flags 5379 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 5380 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 5381 ps.readUserState(userId), userId); 5382 if (info != null) { 5383 outNames.add(entry.getKey()); 5384 outInfo.add(info); 5385 } 5386 } 5387 } 5388 } 5389 } 5390 5391 @Override 5392 public List<ProviderInfo> queryContentProviders(String processName, 5393 int uid, int flags) { 5394 ArrayList<ProviderInfo> finalList = null; 5395 // reader 5396 synchronized (mPackages) { 5397 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 5398 final int userId = processName != null ? 5399 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 5400 while (i.hasNext()) { 5401 final PackageParser.Provider p = i.next(); 5402 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5403 if (ps != null && p.info.authority != null 5404 && (processName == null 5405 || (p.info.processName.equals(processName) 5406 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 5407 && mSettings.isEnabledLPr(p.info, flags, userId) 5408 && (!mSafeMode 5409 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 5410 if (finalList == null) { 5411 finalList = new ArrayList<ProviderInfo>(3); 5412 } 5413 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 5414 ps.readUserState(userId), userId); 5415 if (info != null) { 5416 finalList.add(info); 5417 } 5418 } 5419 } 5420 } 5421 5422 if (finalList != null) { 5423 Collections.sort(finalList, mProviderInitOrderSorter); 5424 } 5425 5426 return finalList; 5427 } 5428 5429 @Override 5430 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 5431 int flags) { 5432 // reader 5433 synchronized (mPackages) { 5434 final PackageParser.Instrumentation i = mInstrumentation.get(name); 5435 return PackageParser.generateInstrumentationInfo(i, flags); 5436 } 5437 } 5438 5439 @Override 5440 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 5441 int flags) { 5442 ArrayList<InstrumentationInfo> finalList = 5443 new ArrayList<InstrumentationInfo>(); 5444 5445 // reader 5446 synchronized (mPackages) { 5447 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 5448 while (i.hasNext()) { 5449 final PackageParser.Instrumentation p = i.next(); 5450 if (targetPackage == null 5451 || targetPackage.equals(p.info.targetPackage)) { 5452 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 5453 flags); 5454 if (ii != null) { 5455 finalList.add(ii); 5456 } 5457 } 5458 } 5459 } 5460 5461 return finalList; 5462 } 5463 5464 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 5465 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 5466 if (overlays == null) { 5467 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 5468 return; 5469 } 5470 for (PackageParser.Package opkg : overlays.values()) { 5471 // Not much to do if idmap fails: we already logged the error 5472 // and we certainly don't want to abort installation of pkg simply 5473 // because an overlay didn't fit properly. For these reasons, 5474 // ignore the return value of createIdmapForPackagePairLI. 5475 createIdmapForPackagePairLI(pkg, opkg); 5476 } 5477 } 5478 5479 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 5480 PackageParser.Package opkg) { 5481 if (!opkg.mTrustedOverlay) { 5482 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 5483 opkg.baseCodePath + ": overlay not trusted"); 5484 return false; 5485 } 5486 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 5487 if (overlaySet == null) { 5488 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 5489 opkg.baseCodePath + " but target package has no known overlays"); 5490 return false; 5491 } 5492 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 5493 // TODO: generate idmap for split APKs 5494 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 5495 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 5496 + opkg.baseCodePath); 5497 return false; 5498 } 5499 PackageParser.Package[] overlayArray = 5500 overlaySet.values().toArray(new PackageParser.Package[0]); 5501 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 5502 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 5503 return p1.mOverlayPriority - p2.mOverlayPriority; 5504 } 5505 }; 5506 Arrays.sort(overlayArray, cmp); 5507 5508 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 5509 int i = 0; 5510 for (PackageParser.Package p : overlayArray) { 5511 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 5512 } 5513 return true; 5514 } 5515 5516 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5517 final File[] files = dir.listFiles(); 5518 if (ArrayUtils.isEmpty(files)) { 5519 Log.d(TAG, "No files in app dir " + dir); 5520 return; 5521 } 5522 5523 if (DEBUG_PACKAGE_SCANNING) { 5524 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 5525 + " flags=0x" + Integer.toHexString(parseFlags)); 5526 } 5527 5528 for (File file : files) { 5529 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 5530 && !PackageInstallerService.isStageName(file.getName()); 5531 if (!isPackage) { 5532 // Ignore entries which are not packages 5533 continue; 5534 } 5535 try { 5536 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 5537 scanFlags, currentTime, null); 5538 } catch (PackageManagerException e) { 5539 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 5540 5541 // Delete invalid userdata apps 5542 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 5543 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 5544 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 5545 if (file.isDirectory()) { 5546 mInstaller.rmPackageDir(file.getAbsolutePath()); 5547 } else { 5548 file.delete(); 5549 } 5550 } 5551 } 5552 } 5553 } 5554 5555 private static File getSettingsProblemFile() { 5556 File dataDir = Environment.getDataDirectory(); 5557 File systemDir = new File(dataDir, "system"); 5558 File fname = new File(systemDir, "uiderrors.txt"); 5559 return fname; 5560 } 5561 5562 static void reportSettingsProblem(int priority, String msg) { 5563 logCriticalInfo(priority, msg); 5564 } 5565 5566 static void logCriticalInfo(int priority, String msg) { 5567 Slog.println(priority, TAG, msg); 5568 EventLogTags.writePmCriticalInfo(msg); 5569 try { 5570 File fname = getSettingsProblemFile(); 5571 FileOutputStream out = new FileOutputStream(fname, true); 5572 PrintWriter pw = new FastPrintWriter(out); 5573 SimpleDateFormat formatter = new SimpleDateFormat(); 5574 String dateString = formatter.format(new Date(System.currentTimeMillis())); 5575 pw.println(dateString + ": " + msg); 5576 pw.close(); 5577 FileUtils.setPermissions( 5578 fname.toString(), 5579 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 5580 -1, -1); 5581 } catch (java.io.IOException e) { 5582 } 5583 } 5584 5585 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 5586 PackageParser.Package pkg, File srcFile, int parseFlags) 5587 throws PackageManagerException { 5588 if (ps != null 5589 && ps.codePath.equals(srcFile) 5590 && ps.timeStamp == srcFile.lastModified() 5591 && !isCompatSignatureUpdateNeeded(pkg) 5592 && !isRecoverSignatureUpdateNeeded(pkg)) { 5593 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 5594 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5595 ArraySet<PublicKey> signingKs; 5596 synchronized (mPackages) { 5597 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 5598 } 5599 if (ps.signatures.mSignatures != null 5600 && ps.signatures.mSignatures.length != 0 5601 && signingKs != null) { 5602 // Optimization: reuse the existing cached certificates 5603 // if the package appears to be unchanged. 5604 pkg.mSignatures = ps.signatures.mSignatures; 5605 pkg.mSigningKeys = signingKs; 5606 return; 5607 } 5608 5609 Slog.w(TAG, "PackageSetting for " + ps.name 5610 + " is missing signatures. Collecting certs again to recover them."); 5611 } else { 5612 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 5613 } 5614 5615 try { 5616 pp.collectCertificates(pkg, parseFlags); 5617 pp.collectManifestDigest(pkg); 5618 } catch (PackageParserException e) { 5619 throw PackageManagerException.from(e); 5620 } 5621 } 5622 5623 /* 5624 * Scan a package and return the newly parsed package. 5625 * Returns null in case of errors and the error code is stored in mLastScanError 5626 */ 5627 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 5628 long currentTime, UserHandle user) throws PackageManagerException { 5629 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 5630 parseFlags |= mDefParseFlags; 5631 PackageParser pp = new PackageParser(); 5632 pp.setSeparateProcesses(mSeparateProcesses); 5633 pp.setOnlyCoreApps(mOnlyCore); 5634 pp.setDisplayMetrics(mMetrics); 5635 5636 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 5637 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 5638 } 5639 5640 final PackageParser.Package pkg; 5641 try { 5642 pkg = pp.parsePackage(scanFile, parseFlags); 5643 } catch (PackageParserException e) { 5644 throw PackageManagerException.from(e); 5645 } 5646 5647 PackageSetting ps = null; 5648 PackageSetting updatedPkg; 5649 // reader 5650 synchronized (mPackages) { 5651 // Look to see if we already know about this package. 5652 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 5653 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 5654 // This package has been renamed to its original name. Let's 5655 // use that. 5656 ps = mSettings.peekPackageLPr(oldName); 5657 } 5658 // If there was no original package, see one for the real package name. 5659 if (ps == null) { 5660 ps = mSettings.peekPackageLPr(pkg.packageName); 5661 } 5662 // Check to see if this package could be hiding/updating a system 5663 // package. Must look for it either under the original or real 5664 // package name depending on our state. 5665 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 5666 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 5667 } 5668 boolean updatedPkgBetter = false; 5669 // First check if this is a system package that may involve an update 5670 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5671 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5672 // it needs to drop FLAG_PRIVILEGED. 5673 if (locationIsPrivileged(scanFile)) { 5674 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5675 } else { 5676 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5677 } 5678 5679 if (ps != null && !ps.codePath.equals(scanFile)) { 5680 // The path has changed from what was last scanned... check the 5681 // version of the new path against what we have stored to determine 5682 // what to do. 5683 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5684 if (pkg.mVersionCode <= ps.versionCode) { 5685 // The system package has been updated and the code path does not match 5686 // Ignore entry. Skip it. 5687 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5688 + " ignored: updated version " + ps.versionCode 5689 + " better than this " + pkg.mVersionCode); 5690 if (!updatedPkg.codePath.equals(scanFile)) { 5691 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5692 + ps.name + " changing from " + updatedPkg.codePathString 5693 + " to " + scanFile); 5694 updatedPkg.codePath = scanFile; 5695 updatedPkg.codePathString = scanFile.toString(); 5696 updatedPkg.resourcePath = scanFile; 5697 updatedPkg.resourcePathString = scanFile.toString(); 5698 } 5699 updatedPkg.pkg = pkg; 5700 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5701 "Package " + ps.name + " at " + scanFile 5702 + " ignored: updated version " + ps.versionCode 5703 + " better than this " + pkg.mVersionCode); 5704 } else { 5705 // The current app on the system partition is better than 5706 // what we have updated to on the data partition; switch 5707 // back to the system partition version. 5708 // At this point, its safely assumed that package installation for 5709 // apps in system partition will go through. If not there won't be a working 5710 // version of the app 5711 // writer 5712 synchronized (mPackages) { 5713 // Just remove the loaded entries from package lists. 5714 mPackages.remove(ps.name); 5715 } 5716 5717 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5718 + " reverting from " + ps.codePathString 5719 + ": new version " + pkg.mVersionCode 5720 + " better than installed " + ps.versionCode); 5721 5722 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5723 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5724 synchronized (mInstallLock) { 5725 args.cleanUpResourcesLI(); 5726 } 5727 synchronized (mPackages) { 5728 mSettings.enableSystemPackageLPw(ps.name); 5729 } 5730 updatedPkgBetter = true; 5731 } 5732 } 5733 } 5734 5735 if (updatedPkg != null) { 5736 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5737 // initially 5738 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5739 5740 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5741 // flag set initially 5742 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5743 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5744 } 5745 } 5746 5747 // Verify certificates against what was last scanned 5748 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5749 5750 /* 5751 * A new system app appeared, but we already had a non-system one of the 5752 * same name installed earlier. 5753 */ 5754 boolean shouldHideSystemApp = false; 5755 if (updatedPkg == null && ps != null 5756 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5757 /* 5758 * Check to make sure the signatures match first. If they don't, 5759 * wipe the installed application and its data. 5760 */ 5761 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5762 != PackageManager.SIGNATURE_MATCH) { 5763 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5764 + " signatures don't match existing userdata copy; removing"); 5765 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5766 ps = null; 5767 } else { 5768 /* 5769 * If the newly-added system app is an older version than the 5770 * already installed version, hide it. It will be scanned later 5771 * and re-added like an update. 5772 */ 5773 if (pkg.mVersionCode <= ps.versionCode) { 5774 shouldHideSystemApp = true; 5775 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5776 + " but new version " + pkg.mVersionCode + " better than installed " 5777 + ps.versionCode + "; hiding system"); 5778 } else { 5779 /* 5780 * The newly found system app is a newer version that the 5781 * one previously installed. Simply remove the 5782 * already-installed application and replace it with our own 5783 * while keeping the application data. 5784 */ 5785 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5786 + " reverting from " + ps.codePathString + ": new version " 5787 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5788 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5789 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5790 synchronized (mInstallLock) { 5791 args.cleanUpResourcesLI(); 5792 } 5793 } 5794 } 5795 } 5796 5797 // The apk is forward locked (not public) if its code and resources 5798 // are kept in different files. (except for app in either system or 5799 // vendor path). 5800 // TODO grab this value from PackageSettings 5801 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5802 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5803 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5804 } 5805 } 5806 5807 // TODO: extend to support forward-locked splits 5808 String resourcePath = null; 5809 String baseResourcePath = null; 5810 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5811 if (ps != null && ps.resourcePathString != null) { 5812 resourcePath = ps.resourcePathString; 5813 baseResourcePath = ps.resourcePathString; 5814 } else { 5815 // Should not happen at all. Just log an error. 5816 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5817 } 5818 } else { 5819 resourcePath = pkg.codePath; 5820 baseResourcePath = pkg.baseCodePath; 5821 } 5822 5823 // Set application objects path explicitly. 5824 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5825 pkg.applicationInfo.setCodePath(pkg.codePath); 5826 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5827 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5828 pkg.applicationInfo.setResourcePath(resourcePath); 5829 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5830 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5831 5832 // Note that we invoke the following method only if we are about to unpack an application 5833 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5834 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5835 5836 /* 5837 * If the system app should be overridden by a previously installed 5838 * data, hide the system app now and let the /data/app scan pick it up 5839 * again. 5840 */ 5841 if (shouldHideSystemApp) { 5842 synchronized (mPackages) { 5843 /* 5844 * We have to grant systems permissions before we hide, because 5845 * grantPermissions will assume the package update is trying to 5846 * expand its permissions. 5847 */ 5848 grantPermissionsLPw(pkg, true, pkg.packageName); 5849 mSettings.disableSystemPackageLPw(pkg.packageName); 5850 } 5851 } 5852 5853 return scannedPkg; 5854 } 5855 5856 private static String fixProcessName(String defProcessName, 5857 String processName, int uid) { 5858 if (processName == null) { 5859 return defProcessName; 5860 } 5861 return processName; 5862 } 5863 5864 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 5865 throws PackageManagerException { 5866 if (pkgSetting.signatures.mSignatures != null) { 5867 // Already existing package. Make sure signatures match 5868 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 5869 == PackageManager.SIGNATURE_MATCH; 5870 if (!match) { 5871 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 5872 == PackageManager.SIGNATURE_MATCH; 5873 } 5874 if (!match) { 5875 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 5876 == PackageManager.SIGNATURE_MATCH; 5877 } 5878 if (!match) { 5879 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5880 + pkg.packageName + " signatures do not match the " 5881 + "previously installed version; ignoring!"); 5882 } 5883 } 5884 5885 // Check for shared user signatures 5886 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 5887 // Already existing package. Make sure signatures match 5888 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5889 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 5890 if (!match) { 5891 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 5892 == PackageManager.SIGNATURE_MATCH; 5893 } 5894 if (!match) { 5895 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 5896 == PackageManager.SIGNATURE_MATCH; 5897 } 5898 if (!match) { 5899 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 5900 "Package " + pkg.packageName 5901 + " has no signatures that match those in shared user " 5902 + pkgSetting.sharedUser.name + "; ignoring!"); 5903 } 5904 } 5905 } 5906 5907 /** 5908 * Enforces that only the system UID or root's UID can call a method exposed 5909 * via Binder. 5910 * 5911 * @param message used as message if SecurityException is thrown 5912 * @throws SecurityException if the caller is not system or root 5913 */ 5914 private static final void enforceSystemOrRoot(String message) { 5915 final int uid = Binder.getCallingUid(); 5916 if (uid != Process.SYSTEM_UID && uid != 0) { 5917 throw new SecurityException(message); 5918 } 5919 } 5920 5921 @Override 5922 public void performBootDexOpt() { 5923 enforceSystemOrRoot("Only the system can request dexopt be performed"); 5924 5925 // Before everything else, see whether we need to fstrim. 5926 try { 5927 IMountService ms = PackageHelper.getMountService(); 5928 if (ms != null) { 5929 final boolean isUpgrade = isUpgrade(); 5930 boolean doTrim = isUpgrade; 5931 if (doTrim) { 5932 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 5933 } else { 5934 final long interval = android.provider.Settings.Global.getLong( 5935 mContext.getContentResolver(), 5936 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 5937 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 5938 if (interval > 0) { 5939 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 5940 if (timeSinceLast > interval) { 5941 doTrim = true; 5942 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 5943 + "; running immediately"); 5944 } 5945 } 5946 } 5947 if (doTrim) { 5948 if (!isFirstBoot()) { 5949 try { 5950 ActivityManagerNative.getDefault().showBootMessage( 5951 mContext.getResources().getString( 5952 R.string.android_upgrading_fstrim), true); 5953 } catch (RemoteException e) { 5954 } 5955 } 5956 ms.runMaintenance(); 5957 } 5958 } else { 5959 Slog.e(TAG, "Mount service unavailable!"); 5960 } 5961 } catch (RemoteException e) { 5962 // Can't happen; MountService is local 5963 } 5964 5965 final ArraySet<PackageParser.Package> pkgs; 5966 synchronized (mPackages) { 5967 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 5968 } 5969 5970 if (pkgs != null) { 5971 // Sort apps by importance for dexopt ordering. Important apps are given more priority 5972 // in case the device runs out of space. 5973 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 5974 // Give priority to core apps. 5975 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5976 PackageParser.Package pkg = it.next(); 5977 if (pkg.coreApp) { 5978 if (DEBUG_DEXOPT) { 5979 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 5980 } 5981 sortedPkgs.add(pkg); 5982 it.remove(); 5983 } 5984 } 5985 // Give priority to system apps that listen for pre boot complete. 5986 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 5987 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 5988 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5989 PackageParser.Package pkg = it.next(); 5990 if (pkgNames.contains(pkg.packageName)) { 5991 if (DEBUG_DEXOPT) { 5992 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 5993 } 5994 sortedPkgs.add(pkg); 5995 it.remove(); 5996 } 5997 } 5998 // Give priority to system apps. 5999 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6000 PackageParser.Package pkg = it.next(); 6001 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 6002 if (DEBUG_DEXOPT) { 6003 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 6004 } 6005 sortedPkgs.add(pkg); 6006 it.remove(); 6007 } 6008 } 6009 // Give priority to updated system apps. 6010 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6011 PackageParser.Package pkg = it.next(); 6012 if (pkg.isUpdatedSystemApp()) { 6013 if (DEBUG_DEXOPT) { 6014 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 6015 } 6016 sortedPkgs.add(pkg); 6017 it.remove(); 6018 } 6019 } 6020 // Give priority to apps that listen for boot complete. 6021 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 6022 pkgNames = getPackageNamesForIntent(intent); 6023 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6024 PackageParser.Package pkg = it.next(); 6025 if (pkgNames.contains(pkg.packageName)) { 6026 if (DEBUG_DEXOPT) { 6027 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 6028 } 6029 sortedPkgs.add(pkg); 6030 it.remove(); 6031 } 6032 } 6033 // Filter out packages that aren't recently used. 6034 filterRecentlyUsedApps(pkgs); 6035 // Add all remaining apps. 6036 for (PackageParser.Package pkg : pkgs) { 6037 if (DEBUG_DEXOPT) { 6038 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 6039 } 6040 sortedPkgs.add(pkg); 6041 } 6042 6043 // If we want to be lazy, filter everything that wasn't recently used. 6044 if (mLazyDexOpt) { 6045 filterRecentlyUsedApps(sortedPkgs); 6046 } 6047 6048 int i = 0; 6049 int total = sortedPkgs.size(); 6050 File dataDir = Environment.getDataDirectory(); 6051 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 6052 if (lowThreshold == 0) { 6053 throw new IllegalStateException("Invalid low memory threshold"); 6054 } 6055 for (PackageParser.Package pkg : sortedPkgs) { 6056 long usableSpace = dataDir.getUsableSpace(); 6057 if (usableSpace < lowThreshold) { 6058 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 6059 break; 6060 } 6061 performBootDexOpt(pkg, ++i, total); 6062 } 6063 } 6064 } 6065 6066 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 6067 // Filter out packages that aren't recently used. 6068 // 6069 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 6070 // should do a full dexopt. 6071 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 6072 int total = pkgs.size(); 6073 int skipped = 0; 6074 long now = System.currentTimeMillis(); 6075 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 6076 PackageParser.Package pkg = i.next(); 6077 long then = pkg.mLastPackageUsageTimeInMills; 6078 if (then + mDexOptLRUThresholdInMills < now) { 6079 if (DEBUG_DEXOPT) { 6080 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 6081 ((then == 0) ? "never" : new Date(then))); 6082 } 6083 i.remove(); 6084 skipped++; 6085 } 6086 } 6087 if (DEBUG_DEXOPT) { 6088 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 6089 } 6090 } 6091 } 6092 6093 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 6094 List<ResolveInfo> ris = null; 6095 try { 6096 ris = AppGlobals.getPackageManager().queryIntentReceivers( 6097 intent, null, 0, UserHandle.USER_OWNER); 6098 } catch (RemoteException e) { 6099 } 6100 ArraySet<String> pkgNames = new ArraySet<String>(); 6101 if (ris != null) { 6102 for (ResolveInfo ri : ris) { 6103 pkgNames.add(ri.activityInfo.packageName); 6104 } 6105 } 6106 return pkgNames; 6107 } 6108 6109 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 6110 if (DEBUG_DEXOPT) { 6111 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 6112 } 6113 if (!isFirstBoot()) { 6114 try { 6115 ActivityManagerNative.getDefault().showBootMessage( 6116 mContext.getResources().getString(R.string.android_upgrading_apk, 6117 curr, total), true); 6118 } catch (RemoteException e) { 6119 } 6120 } 6121 PackageParser.Package p = pkg; 6122 synchronized (mInstallLock) { 6123 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 6124 false /* force dex */, false /* defer */, true /* include dependencies */); 6125 } 6126 } 6127 6128 @Override 6129 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6130 return performDexOpt(packageName, instructionSet, false); 6131 } 6132 6133 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 6134 boolean dexopt = mLazyDexOpt || backgroundDexopt; 6135 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 6136 if (!dexopt && !updateUsage) { 6137 // We aren't going to dexopt or update usage, so bail early. 6138 return false; 6139 } 6140 PackageParser.Package p; 6141 final String targetInstructionSet; 6142 synchronized (mPackages) { 6143 p = mPackages.get(packageName); 6144 if (p == null) { 6145 return false; 6146 } 6147 if (updateUsage) { 6148 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6149 } 6150 mPackageUsage.write(false); 6151 if (!dexopt) { 6152 // We aren't going to dexopt, so bail early. 6153 return false; 6154 } 6155 6156 targetInstructionSet = instructionSet != null ? instructionSet : 6157 getPrimaryInstructionSet(p.applicationInfo); 6158 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 6159 return false; 6160 } 6161 } 6162 long callingId = Binder.clearCallingIdentity(); 6163 try { 6164 synchronized (mInstallLock) { 6165 final String[] instructionSets = new String[] { targetInstructionSet }; 6166 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 6167 false /* forceDex */, false /* defer */, true /* inclDependencies */); 6168 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6169 } 6170 } finally { 6171 Binder.restoreCallingIdentity(callingId); 6172 } 6173 } 6174 6175 public ArraySet<String> getPackagesThatNeedDexOpt() { 6176 ArraySet<String> pkgs = null; 6177 synchronized (mPackages) { 6178 for (PackageParser.Package p : mPackages.values()) { 6179 if (DEBUG_DEXOPT) { 6180 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 6181 } 6182 if (!p.mDexOptPerformed.isEmpty()) { 6183 continue; 6184 } 6185 if (pkgs == null) { 6186 pkgs = new ArraySet<String>(); 6187 } 6188 pkgs.add(p.packageName); 6189 } 6190 } 6191 return pkgs; 6192 } 6193 6194 public void shutdown() { 6195 mPackageUsage.write(true); 6196 } 6197 6198 @Override 6199 public void forceDexOpt(String packageName) { 6200 enforceSystemOrRoot("forceDexOpt"); 6201 6202 PackageParser.Package pkg; 6203 synchronized (mPackages) { 6204 pkg = mPackages.get(packageName); 6205 if (pkg == null) { 6206 throw new IllegalArgumentException("Missing package: " + packageName); 6207 } 6208 } 6209 6210 synchronized (mInstallLock) { 6211 final String[] instructionSets = new String[] { 6212 getPrimaryInstructionSet(pkg.applicationInfo) }; 6213 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 6214 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 6215 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 6216 throw new IllegalStateException("Failed to dexopt: " + res); 6217 } 6218 } 6219 } 6220 6221 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 6222 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 6223 Slog.w(TAG, "Unable to update from " + oldPkg.name 6224 + " to " + newPkg.packageName 6225 + ": old package not in system partition"); 6226 return false; 6227 } else if (mPackages.get(oldPkg.name) != null) { 6228 Slog.w(TAG, "Unable to update from " + oldPkg.name 6229 + " to " + newPkg.packageName 6230 + ": old package still exists"); 6231 return false; 6232 } 6233 return true; 6234 } 6235 6236 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 6237 int[] users = sUserManager.getUserIds(); 6238 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 6239 if (res < 0) { 6240 return res; 6241 } 6242 for (int user : users) { 6243 if (user != 0) { 6244 res = mInstaller.createUserData(volumeUuid, packageName, 6245 UserHandle.getUid(user, uid), user, seinfo); 6246 if (res < 0) { 6247 return res; 6248 } 6249 } 6250 } 6251 return res; 6252 } 6253 6254 private int removeDataDirsLI(String volumeUuid, String packageName) { 6255 int[] users = sUserManager.getUserIds(); 6256 int res = 0; 6257 for (int user : users) { 6258 int resInner = mInstaller.remove(volumeUuid, packageName, user); 6259 if (resInner < 0) { 6260 res = resInner; 6261 } 6262 } 6263 6264 return res; 6265 } 6266 6267 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 6268 int[] users = sUserManager.getUserIds(); 6269 int res = 0; 6270 for (int user : users) { 6271 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 6272 if (resInner < 0) { 6273 res = resInner; 6274 } 6275 } 6276 return res; 6277 } 6278 6279 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 6280 PackageParser.Package changingLib) { 6281 if (file.path != null) { 6282 usesLibraryFiles.add(file.path); 6283 return; 6284 } 6285 PackageParser.Package p = mPackages.get(file.apk); 6286 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 6287 // If we are doing this while in the middle of updating a library apk, 6288 // then we need to make sure to use that new apk for determining the 6289 // dependencies here. (We haven't yet finished committing the new apk 6290 // to the package manager state.) 6291 if (p == null || p.packageName.equals(changingLib.packageName)) { 6292 p = changingLib; 6293 } 6294 } 6295 if (p != null) { 6296 usesLibraryFiles.addAll(p.getAllCodePaths()); 6297 } 6298 } 6299 6300 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 6301 PackageParser.Package changingLib) throws PackageManagerException { 6302 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 6303 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 6304 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 6305 for (int i=0; i<N; i++) { 6306 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 6307 if (file == null) { 6308 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 6309 "Package " + pkg.packageName + " requires unavailable shared library " 6310 + pkg.usesLibraries.get(i) + "; failing!"); 6311 } 6312 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6313 } 6314 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 6315 for (int i=0; i<N; i++) { 6316 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 6317 if (file == null) { 6318 Slog.w(TAG, "Package " + pkg.packageName 6319 + " desires unavailable shared library " 6320 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 6321 } else { 6322 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6323 } 6324 } 6325 N = usesLibraryFiles.size(); 6326 if (N > 0) { 6327 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 6328 } else { 6329 pkg.usesLibraryFiles = null; 6330 } 6331 } 6332 } 6333 6334 private static boolean hasString(List<String> list, List<String> which) { 6335 if (list == null) { 6336 return false; 6337 } 6338 for (int i=list.size()-1; i>=0; i--) { 6339 for (int j=which.size()-1; j>=0; j--) { 6340 if (which.get(j).equals(list.get(i))) { 6341 return true; 6342 } 6343 } 6344 } 6345 return false; 6346 } 6347 6348 private void updateAllSharedLibrariesLPw() { 6349 for (PackageParser.Package pkg : mPackages.values()) { 6350 try { 6351 updateSharedLibrariesLPw(pkg, null); 6352 } catch (PackageManagerException e) { 6353 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6354 } 6355 } 6356 } 6357 6358 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 6359 PackageParser.Package changingPkg) { 6360 ArrayList<PackageParser.Package> res = null; 6361 for (PackageParser.Package pkg : mPackages.values()) { 6362 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 6363 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 6364 if (res == null) { 6365 res = new ArrayList<PackageParser.Package>(); 6366 } 6367 res.add(pkg); 6368 try { 6369 updateSharedLibrariesLPw(pkg, changingPkg); 6370 } catch (PackageManagerException e) { 6371 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6372 } 6373 } 6374 } 6375 return res; 6376 } 6377 6378 /** 6379 * Derive the value of the {@code cpuAbiOverride} based on the provided 6380 * value and an optional stored value from the package settings. 6381 */ 6382 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 6383 String cpuAbiOverride = null; 6384 6385 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 6386 cpuAbiOverride = null; 6387 } else if (abiOverride != null) { 6388 cpuAbiOverride = abiOverride; 6389 } else if (settings != null) { 6390 cpuAbiOverride = settings.cpuAbiOverrideString; 6391 } 6392 6393 return cpuAbiOverride; 6394 } 6395 6396 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 6397 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6398 boolean success = false; 6399 try { 6400 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 6401 currentTime, user); 6402 success = true; 6403 return res; 6404 } finally { 6405 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 6406 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 6407 } 6408 } 6409 } 6410 6411 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 6412 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6413 final File scanFile = new File(pkg.codePath); 6414 if (pkg.applicationInfo.getCodePath() == null || 6415 pkg.applicationInfo.getResourcePath() == null) { 6416 // Bail out. The resource and code paths haven't been set. 6417 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 6418 "Code and resource paths haven't been set correctly"); 6419 } 6420 6421 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 6422 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 6423 } else { 6424 // Only allow system apps to be flagged as core apps. 6425 pkg.coreApp = false; 6426 } 6427 6428 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 6429 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6430 } 6431 6432 if (mCustomResolverComponentName != null && 6433 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 6434 setUpCustomResolverActivity(pkg); 6435 } 6436 6437 if (pkg.packageName.equals("android")) { 6438 synchronized (mPackages) { 6439 if (mAndroidApplication != null) { 6440 Slog.w(TAG, "*************************************************"); 6441 Slog.w(TAG, "Core android package being redefined. Skipping."); 6442 Slog.w(TAG, " file=" + scanFile); 6443 Slog.w(TAG, "*************************************************"); 6444 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6445 "Core android package being redefined. Skipping."); 6446 } 6447 6448 // Set up information for our fall-back user intent resolution activity. 6449 mPlatformPackage = pkg; 6450 pkg.mVersionCode = mSdkVersion; 6451 mAndroidApplication = pkg.applicationInfo; 6452 6453 if (!mResolverReplaced) { 6454 mResolveActivity.applicationInfo = mAndroidApplication; 6455 mResolveActivity.name = ResolverActivity.class.getName(); 6456 mResolveActivity.packageName = mAndroidApplication.packageName; 6457 mResolveActivity.processName = "system:ui"; 6458 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6459 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 6460 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 6461 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 6462 mResolveActivity.exported = true; 6463 mResolveActivity.enabled = true; 6464 mResolveInfo.activityInfo = mResolveActivity; 6465 mResolveInfo.priority = 0; 6466 mResolveInfo.preferredOrder = 0; 6467 mResolveInfo.match = 0; 6468 mResolveComponentName = new ComponentName( 6469 mAndroidApplication.packageName, mResolveActivity.name); 6470 } 6471 } 6472 } 6473 6474 if (DEBUG_PACKAGE_SCANNING) { 6475 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6476 Log.d(TAG, "Scanning package " + pkg.packageName); 6477 } 6478 6479 if (mPackages.containsKey(pkg.packageName) 6480 || mSharedLibraries.containsKey(pkg.packageName)) { 6481 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6482 "Application package " + pkg.packageName 6483 + " already installed. Skipping duplicate."); 6484 } 6485 6486 // If we're only installing presumed-existing packages, require that the 6487 // scanned APK is both already known and at the path previously established 6488 // for it. Previously unknown packages we pick up normally, but if we have an 6489 // a priori expectation about this package's install presence, enforce it. 6490 // With a singular exception for new system packages. When an OTA contains 6491 // a new system package, we allow the codepath to change from a system location 6492 // to the user-installed location. If we don't allow this change, any newer, 6493 // user-installed version of the application will be ignored. 6494 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 6495 if (mExpectingBetter.containsKey(pkg.packageName)) { 6496 logCriticalInfo(Log.WARN, 6497 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 6498 } else { 6499 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 6500 if (known != null) { 6501 if (DEBUG_PACKAGE_SCANNING) { 6502 Log.d(TAG, "Examining " + pkg.codePath 6503 + " and requiring known paths " + known.codePathString 6504 + " & " + known.resourcePathString); 6505 } 6506 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6507 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6508 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6509 "Application package " + pkg.packageName 6510 + " found at " + pkg.applicationInfo.getCodePath() 6511 + " but expected at " + known.codePathString + "; ignoring."); 6512 } 6513 } 6514 } 6515 } 6516 6517 // Initialize package source and resource directories 6518 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6519 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6520 6521 SharedUserSetting suid = null; 6522 PackageSetting pkgSetting = null; 6523 6524 if (!isSystemApp(pkg)) { 6525 // Only system apps can use these features. 6526 pkg.mOriginalPackages = null; 6527 pkg.mRealPackage = null; 6528 pkg.mAdoptPermissions = null; 6529 } 6530 6531 // writer 6532 synchronized (mPackages) { 6533 if (pkg.mSharedUserId != null) { 6534 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 6535 if (suid == null) { 6536 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6537 "Creating application package " + pkg.packageName 6538 + " for shared user failed"); 6539 } 6540 if (DEBUG_PACKAGE_SCANNING) { 6541 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6542 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 6543 + "): packages=" + suid.packages); 6544 } 6545 } 6546 6547 // Check if we are renaming from an original package name. 6548 PackageSetting origPackage = null; 6549 String realName = null; 6550 if (pkg.mOriginalPackages != null) { 6551 // This package may need to be renamed to a previously 6552 // installed name. Let's check on that... 6553 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 6554 if (pkg.mOriginalPackages.contains(renamed)) { 6555 // This package had originally been installed as the 6556 // original name, and we have already taken care of 6557 // transitioning to the new one. Just update the new 6558 // one to continue using the old name. 6559 realName = pkg.mRealPackage; 6560 if (!pkg.packageName.equals(renamed)) { 6561 // Callers into this function may have already taken 6562 // care of renaming the package; only do it here if 6563 // it is not already done. 6564 pkg.setPackageName(renamed); 6565 } 6566 6567 } else { 6568 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 6569 if ((origPackage = mSettings.peekPackageLPr( 6570 pkg.mOriginalPackages.get(i))) != null) { 6571 // We do have the package already installed under its 6572 // original name... should we use it? 6573 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 6574 // New package is not compatible with original. 6575 origPackage = null; 6576 continue; 6577 } else if (origPackage.sharedUser != null) { 6578 // Make sure uid is compatible between packages. 6579 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 6580 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 6581 + " to " + pkg.packageName + ": old uid " 6582 + origPackage.sharedUser.name 6583 + " differs from " + pkg.mSharedUserId); 6584 origPackage = null; 6585 continue; 6586 } 6587 } else { 6588 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6589 + pkg.packageName + " to old name " + origPackage.name); 6590 } 6591 break; 6592 } 6593 } 6594 } 6595 } 6596 6597 if (mTransferedPackages.contains(pkg.packageName)) { 6598 Slog.w(TAG, "Package " + pkg.packageName 6599 + " was transferred to another, but its .apk remains"); 6600 } 6601 6602 // Just create the setting, don't add it yet. For already existing packages 6603 // the PkgSetting exists already and doesn't have to be created. 6604 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6605 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6606 pkg.applicationInfo.primaryCpuAbi, 6607 pkg.applicationInfo.secondaryCpuAbi, 6608 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6609 user, false); 6610 if (pkgSetting == null) { 6611 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6612 "Creating application package " + pkg.packageName + " failed"); 6613 } 6614 6615 if (pkgSetting.origPackage != null) { 6616 // If we are first transitioning from an original package, 6617 // fix up the new package's name now. We need to do this after 6618 // looking up the package under its new name, so getPackageLP 6619 // can take care of fiddling things correctly. 6620 pkg.setPackageName(origPackage.name); 6621 6622 // File a report about this. 6623 String msg = "New package " + pkgSetting.realName 6624 + " renamed to replace old package " + pkgSetting.name; 6625 reportSettingsProblem(Log.WARN, msg); 6626 6627 // Make a note of it. 6628 mTransferedPackages.add(origPackage.name); 6629 6630 // No longer need to retain this. 6631 pkgSetting.origPackage = null; 6632 } 6633 6634 if (realName != null) { 6635 // Make a note of it. 6636 mTransferedPackages.add(pkg.packageName); 6637 } 6638 6639 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6640 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6641 } 6642 6643 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6644 // Check all shared libraries and map to their actual file path. 6645 // We only do this here for apps not on a system dir, because those 6646 // are the only ones that can fail an install due to this. We 6647 // will take care of the system apps by updating all of their 6648 // library paths after the scan is done. 6649 updateSharedLibrariesLPw(pkg, null); 6650 } 6651 6652 if (mFoundPolicyFile) { 6653 SELinuxMMAC.assignSeinfoValue(pkg); 6654 } 6655 6656 pkg.applicationInfo.uid = pkgSetting.appId; 6657 pkg.mExtras = pkgSetting; 6658 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 6659 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 6660 // We just determined the app is signed correctly, so bring 6661 // over the latest parsed certs. 6662 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6663 } else { 6664 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6665 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6666 "Package " + pkg.packageName + " upgrade keys do not match the " 6667 + "previously installed version"); 6668 } else { 6669 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6670 String msg = "System package " + pkg.packageName 6671 + " signature changed; retaining data."; 6672 reportSettingsProblem(Log.WARN, msg); 6673 } 6674 } 6675 } else { 6676 try { 6677 verifySignaturesLP(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 } catch (PackageManagerException e) { 6682 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6683 throw e; 6684 } 6685 // The signature has changed, but this package is in the system 6686 // image... let's recover! 6687 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6688 // However... if this package is part of a shared user, but it 6689 // doesn't match the signature of the shared user, let's fail. 6690 // What this means is that you can't change the signatures 6691 // associated with an overall shared user, which doesn't seem all 6692 // that unreasonable. 6693 if (pkgSetting.sharedUser != null) { 6694 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6695 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 6696 throw new PackageManagerException( 6697 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6698 "Signature mismatch for shared user : " 6699 + pkgSetting.sharedUser); 6700 } 6701 } 6702 // File a report about this. 6703 String msg = "System package " + pkg.packageName 6704 + " signature changed; retaining data."; 6705 reportSettingsProblem(Log.WARN, msg); 6706 } 6707 } 6708 // Verify that this new package doesn't have any content providers 6709 // that conflict with existing packages. Only do this if the 6710 // package isn't already installed, since we don't want to break 6711 // things that are installed. 6712 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6713 final int N = pkg.providers.size(); 6714 int i; 6715 for (i=0; i<N; i++) { 6716 PackageParser.Provider p = pkg.providers.get(i); 6717 if (p.info.authority != null) { 6718 String names[] = p.info.authority.split(";"); 6719 for (int j = 0; j < names.length; j++) { 6720 if (mProvidersByAuthority.containsKey(names[j])) { 6721 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6722 final String otherPackageName = 6723 ((other != null && other.getComponentName() != null) ? 6724 other.getComponentName().getPackageName() : "?"); 6725 throw new PackageManagerException( 6726 INSTALL_FAILED_CONFLICTING_PROVIDER, 6727 "Can't install because provider name " + names[j] 6728 + " (in package " + pkg.applicationInfo.packageName 6729 + ") is already used by " + otherPackageName); 6730 } 6731 } 6732 } 6733 } 6734 } 6735 6736 if (pkg.mAdoptPermissions != null) { 6737 // This package wants to adopt ownership of permissions from 6738 // another package. 6739 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6740 final String origName = pkg.mAdoptPermissions.get(i); 6741 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6742 if (orig != null) { 6743 if (verifyPackageUpdateLPr(orig, pkg)) { 6744 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6745 + pkg.packageName); 6746 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6747 } 6748 } 6749 } 6750 } 6751 } 6752 6753 final String pkgName = pkg.packageName; 6754 6755 final long scanFileTime = scanFile.lastModified(); 6756 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6757 pkg.applicationInfo.processName = fixProcessName( 6758 pkg.applicationInfo.packageName, 6759 pkg.applicationInfo.processName, 6760 pkg.applicationInfo.uid); 6761 6762 File dataPath; 6763 if (mPlatformPackage == pkg) { 6764 // The system package is special. 6765 dataPath = new File(Environment.getDataDirectory(), "system"); 6766 6767 pkg.applicationInfo.dataDir = dataPath.getPath(); 6768 6769 } else { 6770 // This is a normal package, need to make its data directory. 6771 dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid, 6772 UserHandle.USER_OWNER, pkg.packageName); 6773 6774 boolean uidError = false; 6775 if (dataPath.exists()) { 6776 int currentUid = 0; 6777 try { 6778 StructStat stat = Os.stat(dataPath.getPath()); 6779 currentUid = stat.st_uid; 6780 } catch (ErrnoException e) { 6781 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6782 } 6783 6784 // If we have mismatched owners for the data path, we have a problem. 6785 if (currentUid != pkg.applicationInfo.uid) { 6786 boolean recovered = false; 6787 if (currentUid == 0) { 6788 // The directory somehow became owned by root. Wow. 6789 // This is probably because the system was stopped while 6790 // installd was in the middle of messing with its libs 6791 // directory. Ask installd to fix that. 6792 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6793 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6794 if (ret >= 0) { 6795 recovered = true; 6796 String msg = "Package " + pkg.packageName 6797 + " unexpectedly changed to uid 0; recovered to " + 6798 + pkg.applicationInfo.uid; 6799 reportSettingsProblem(Log.WARN, msg); 6800 } 6801 } 6802 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6803 || (scanFlags&SCAN_BOOTING) != 0)) { 6804 // If this is a system app, we can at least delete its 6805 // current data so the application will still work. 6806 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6807 if (ret >= 0) { 6808 // TODO: Kill the processes first 6809 // Old data gone! 6810 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6811 ? "System package " : "Third party package "; 6812 String msg = prefix + pkg.packageName 6813 + " has changed from uid: " 6814 + currentUid + " to " 6815 + pkg.applicationInfo.uid + "; old data erased"; 6816 reportSettingsProblem(Log.WARN, msg); 6817 recovered = true; 6818 6819 // And now re-install the app. 6820 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6821 pkg.applicationInfo.seinfo); 6822 if (ret == -1) { 6823 // Ack should not happen! 6824 msg = prefix + pkg.packageName 6825 + " could not have data directory re-created after delete."; 6826 reportSettingsProblem(Log.WARN, msg); 6827 throw new PackageManagerException( 6828 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6829 } 6830 } 6831 if (!recovered) { 6832 mHasSystemUidErrors = true; 6833 } 6834 } else if (!recovered) { 6835 // If we allow this install to proceed, we will be broken. 6836 // Abort, abort! 6837 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6838 "scanPackageLI"); 6839 } 6840 if (!recovered) { 6841 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6842 + pkg.applicationInfo.uid + "/fs_" 6843 + currentUid; 6844 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6845 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6846 String msg = "Package " + pkg.packageName 6847 + " has mismatched uid: " 6848 + currentUid + " on disk, " 6849 + pkg.applicationInfo.uid + " in settings"; 6850 // writer 6851 synchronized (mPackages) { 6852 mSettings.mReadMessages.append(msg); 6853 mSettings.mReadMessages.append('\n'); 6854 uidError = true; 6855 if (!pkgSetting.uidError) { 6856 reportSettingsProblem(Log.ERROR, msg); 6857 } 6858 } 6859 } 6860 } 6861 pkg.applicationInfo.dataDir = dataPath.getPath(); 6862 if (mShouldRestoreconData) { 6863 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6864 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 6865 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 6866 } 6867 } else { 6868 if (DEBUG_PACKAGE_SCANNING) { 6869 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6870 Log.v(TAG, "Want this data dir: " + dataPath); 6871 } 6872 //invoke installer to do the actual installation 6873 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6874 pkg.applicationInfo.seinfo); 6875 if (ret < 0) { 6876 // Error from installer 6877 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6878 "Unable to create data dirs [errorCode=" + ret + "]"); 6879 } 6880 6881 if (dataPath.exists()) { 6882 pkg.applicationInfo.dataDir = dataPath.getPath(); 6883 } else { 6884 Slog.w(TAG, "Unable to create data directory: " + dataPath); 6885 pkg.applicationInfo.dataDir = null; 6886 } 6887 } 6888 6889 pkgSetting.uidError = uidError; 6890 } 6891 6892 final String path = scanFile.getPath(); 6893 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6894 6895 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 6896 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 6897 6898 // Some system apps still use directory structure for native libraries 6899 // in which case we might end up not detecting abi solely based on apk 6900 // structure. Try to detect abi based on directory structure. 6901 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 6902 pkg.applicationInfo.primaryCpuAbi == null) { 6903 setBundledAppAbisAndRoots(pkg, pkgSetting); 6904 setNativeLibraryPaths(pkg); 6905 } 6906 6907 } else { 6908 if ((scanFlags & SCAN_MOVE) != 0) { 6909 // We haven't run dex-opt for this move (since we've moved the compiled output too) 6910 // but we already have this packages package info in the PackageSetting. We just 6911 // use that and derive the native library path based on the new codepath. 6912 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 6913 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 6914 } 6915 6916 // Set native library paths again. For moves, the path will be updated based on the 6917 // ABIs we've determined above. For non-moves, the path will be updated based on the 6918 // ABIs we determined during compilation, but the path will depend on the final 6919 // package path (after the rename away from the stage path). 6920 setNativeLibraryPaths(pkg); 6921 } 6922 6923 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 6924 final int[] userIds = sUserManager.getUserIds(); 6925 synchronized (mInstallLock) { 6926 // Make sure all user data directories are ready to roll; we're okay 6927 // if they already exist 6928 if (!TextUtils.isEmpty(pkg.volumeUuid)) { 6929 for (int userId : userIds) { 6930 if (userId != 0) { 6931 mInstaller.createUserData(pkg.volumeUuid, pkg.packageName, 6932 UserHandle.getUid(userId, pkg.applicationInfo.uid), userId, 6933 pkg.applicationInfo.seinfo); 6934 } 6935 } 6936 } 6937 6938 // Create a native library symlink only if we have native libraries 6939 // and if the native libraries are 32 bit libraries. We do not provide 6940 // this symlink for 64 bit libraries. 6941 if (pkg.applicationInfo.primaryCpuAbi != null && 6942 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 6943 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 6944 for (int userId : userIds) { 6945 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 6946 nativeLibPath, userId) < 0) { 6947 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6948 "Failed linking native library dir (user=" + userId + ")"); 6949 } 6950 } 6951 } 6952 } 6953 6954 // This is a special case for the "system" package, where the ABI is 6955 // dictated by the zygote configuration (and init.rc). We should keep track 6956 // of this ABI so that we can deal with "normal" applications that run under 6957 // the same UID correctly. 6958 if (mPlatformPackage == pkg) { 6959 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 6960 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 6961 } 6962 6963 // If there's a mismatch between the abi-override in the package setting 6964 // and the abiOverride specified for the install. Warn about this because we 6965 // would've already compiled the app without taking the package setting into 6966 // account. 6967 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 6968 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 6969 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 6970 " for package: " + pkg.packageName); 6971 } 6972 } 6973 6974 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6975 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6976 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 6977 6978 // Copy the derived override back to the parsed package, so that we can 6979 // update the package settings accordingly. 6980 pkg.cpuAbiOverride = cpuAbiOverride; 6981 6982 if (DEBUG_ABI_SELECTION) { 6983 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 6984 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 6985 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 6986 } 6987 6988 // Push the derived path down into PackageSettings so we know what to 6989 // clean up at uninstall time. 6990 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 6991 6992 if (DEBUG_ABI_SELECTION) { 6993 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 6994 " primary=" + pkg.applicationInfo.primaryCpuAbi + 6995 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 6996 } 6997 6998 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 6999 // We don't do this here during boot because we can do it all 7000 // at once after scanning all existing packages. 7001 // 7002 // We also do this *before* we perform dexopt on this package, so that 7003 // we can avoid redundant dexopts, and also to make sure we've got the 7004 // code and package path correct. 7005 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 7006 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 7007 } 7008 7009 if ((scanFlags & SCAN_NO_DEX) == 0) { 7010 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 7011 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 7012 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7013 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 7014 } 7015 } 7016 if (mFactoryTest && pkg.requestedPermissions.contains( 7017 android.Manifest.permission.FACTORY_TEST)) { 7018 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 7019 } 7020 7021 ArrayList<PackageParser.Package> clientLibPkgs = null; 7022 7023 // writer 7024 synchronized (mPackages) { 7025 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7026 // Only system apps can add new shared libraries. 7027 if (pkg.libraryNames != null) { 7028 for (int i=0; i<pkg.libraryNames.size(); i++) { 7029 String name = pkg.libraryNames.get(i); 7030 boolean allowed = false; 7031 if (pkg.isUpdatedSystemApp()) { 7032 // New library entries can only be added through the 7033 // system image. This is important to get rid of a lot 7034 // of nasty edge cases: for example if we allowed a non- 7035 // system update of the app to add a library, then uninstalling 7036 // the update would make the library go away, and assumptions 7037 // we made such as through app install filtering would now 7038 // have allowed apps on the device which aren't compatible 7039 // with it. Better to just have the restriction here, be 7040 // conservative, and create many fewer cases that can negatively 7041 // impact the user experience. 7042 final PackageSetting sysPs = mSettings 7043 .getDisabledSystemPkgLPr(pkg.packageName); 7044 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 7045 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 7046 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 7047 allowed = true; 7048 allowed = true; 7049 break; 7050 } 7051 } 7052 } 7053 } else { 7054 allowed = true; 7055 } 7056 if (allowed) { 7057 if (!mSharedLibraries.containsKey(name)) { 7058 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 7059 } else if (!name.equals(pkg.packageName)) { 7060 Slog.w(TAG, "Package " + pkg.packageName + " library " 7061 + name + " already exists; skipping"); 7062 } 7063 } else { 7064 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 7065 + name + " that is not declared on system image; skipping"); 7066 } 7067 } 7068 if ((scanFlags&SCAN_BOOTING) == 0) { 7069 // If we are not booting, we need to update any applications 7070 // that are clients of our shared library. If we are booting, 7071 // this will all be done once the scan is complete. 7072 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 7073 } 7074 } 7075 } 7076 } 7077 7078 // We also need to dexopt any apps that are dependent on this library. Note that 7079 // if these fail, we should abort the install since installing the library will 7080 // result in some apps being broken. 7081 if (clientLibPkgs != null) { 7082 if ((scanFlags & SCAN_NO_DEX) == 0) { 7083 for (int i = 0; i < clientLibPkgs.size(); i++) { 7084 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7085 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 7086 null /* instruction sets */, forceDex, 7087 (scanFlags & SCAN_DEFER_DEX) != 0, false); 7088 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7089 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 7090 "scanPackageLI failed to dexopt clientLibPkgs"); 7091 } 7092 } 7093 } 7094 } 7095 7096 // Also need to kill any apps that are dependent on the library. 7097 if (clientLibPkgs != null) { 7098 for (int i=0; i<clientLibPkgs.size(); i++) { 7099 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7100 killApplication(clientPkg.applicationInfo.packageName, 7101 clientPkg.applicationInfo.uid, "update lib"); 7102 } 7103 } 7104 7105 // Make sure we're not adding any bogus keyset info 7106 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7107 ksms.assertScannedPackageValid(pkg); 7108 7109 // writer 7110 synchronized (mPackages) { 7111 // We don't expect installation to fail beyond this point 7112 7113 // Add the new setting to mSettings 7114 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 7115 // Add the new setting to mPackages 7116 mPackages.put(pkg.applicationInfo.packageName, pkg); 7117 // Make sure we don't accidentally delete its data. 7118 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 7119 while (iter.hasNext()) { 7120 PackageCleanItem item = iter.next(); 7121 if (pkgName.equals(item.packageName)) { 7122 iter.remove(); 7123 } 7124 } 7125 7126 // Take care of first install / last update times. 7127 if (currentTime != 0) { 7128 if (pkgSetting.firstInstallTime == 0) { 7129 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7130 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7131 pkgSetting.lastUpdateTime = currentTime; 7132 } 7133 } else if (pkgSetting.firstInstallTime == 0) { 7134 // We need *something*. Take time time stamp of the file. 7135 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7136 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7137 if (scanFileTime != pkgSetting.timeStamp) { 7138 // A package on the system image has changed; consider this 7139 // to be an update. 7140 pkgSetting.lastUpdateTime = scanFileTime; 7141 } 7142 } 7143 7144 // Add the package's KeySets to the global KeySetManagerService 7145 ksms.addScannedPackageLPw(pkg); 7146 7147 int N = pkg.providers.size(); 7148 StringBuilder r = null; 7149 int i; 7150 for (i=0; i<N; i++) { 7151 PackageParser.Provider p = pkg.providers.get(i); 7152 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7153 p.info.processName, pkg.applicationInfo.uid); 7154 mProviders.addProvider(p); 7155 p.syncable = p.info.isSyncable; 7156 if (p.info.authority != null) { 7157 String names[] = p.info.authority.split(";"); 7158 p.info.authority = null; 7159 for (int j = 0; j < names.length; j++) { 7160 if (j == 1 && p.syncable) { 7161 // We only want the first authority for a provider to possibly be 7162 // syncable, so if we already added this provider using a different 7163 // authority clear the syncable flag. We copy the provider before 7164 // changing it because the mProviders object contains a reference 7165 // to a provider that we don't want to change. 7166 // Only do this for the second authority since the resulting provider 7167 // object can be the same for all future authorities for this provider. 7168 p = new PackageParser.Provider(p); 7169 p.syncable = false; 7170 } 7171 if (!mProvidersByAuthority.containsKey(names[j])) { 7172 mProvidersByAuthority.put(names[j], p); 7173 if (p.info.authority == null) { 7174 p.info.authority = names[j]; 7175 } else { 7176 p.info.authority = p.info.authority + ";" + names[j]; 7177 } 7178 if (DEBUG_PACKAGE_SCANNING) { 7179 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7180 Log.d(TAG, "Registered content provider: " + names[j] 7181 + ", className = " + p.info.name + ", isSyncable = " 7182 + p.info.isSyncable); 7183 } 7184 } else { 7185 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7186 Slog.w(TAG, "Skipping provider name " + names[j] + 7187 " (in package " + pkg.applicationInfo.packageName + 7188 "): name already used by " 7189 + ((other != null && other.getComponentName() != null) 7190 ? other.getComponentName().getPackageName() : "?")); 7191 } 7192 } 7193 } 7194 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7195 if (r == null) { 7196 r = new StringBuilder(256); 7197 } else { 7198 r.append(' '); 7199 } 7200 r.append(p.info.name); 7201 } 7202 } 7203 if (r != null) { 7204 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7205 } 7206 7207 N = pkg.services.size(); 7208 r = null; 7209 for (i=0; i<N; i++) { 7210 PackageParser.Service s = pkg.services.get(i); 7211 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 7212 s.info.processName, pkg.applicationInfo.uid); 7213 mServices.addService(s); 7214 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7215 if (r == null) { 7216 r = new StringBuilder(256); 7217 } else { 7218 r.append(' '); 7219 } 7220 r.append(s.info.name); 7221 } 7222 } 7223 if (r != null) { 7224 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 7225 } 7226 7227 N = pkg.receivers.size(); 7228 r = null; 7229 for (i=0; i<N; i++) { 7230 PackageParser.Activity a = pkg.receivers.get(i); 7231 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7232 a.info.processName, pkg.applicationInfo.uid); 7233 mReceivers.addActivity(a, "receiver"); 7234 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7235 if (r == null) { 7236 r = new StringBuilder(256); 7237 } else { 7238 r.append(' '); 7239 } 7240 r.append(a.info.name); 7241 } 7242 } 7243 if (r != null) { 7244 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 7245 } 7246 7247 N = pkg.activities.size(); 7248 r = null; 7249 for (i=0; i<N; i++) { 7250 PackageParser.Activity a = pkg.activities.get(i); 7251 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7252 a.info.processName, pkg.applicationInfo.uid); 7253 mActivities.addActivity(a, "activity"); 7254 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7255 if (r == null) { 7256 r = new StringBuilder(256); 7257 } else { 7258 r.append(' '); 7259 } 7260 r.append(a.info.name); 7261 } 7262 } 7263 if (r != null) { 7264 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 7265 } 7266 7267 N = pkg.permissionGroups.size(); 7268 r = null; 7269 for (i=0; i<N; i++) { 7270 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 7271 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 7272 if (cur == null) { 7273 mPermissionGroups.put(pg.info.name, pg); 7274 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7275 if (r == null) { 7276 r = new StringBuilder(256); 7277 } else { 7278 r.append(' '); 7279 } 7280 r.append(pg.info.name); 7281 } 7282 } else { 7283 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 7284 + pg.info.packageName + " ignored: original from " 7285 + cur.info.packageName); 7286 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7287 if (r == null) { 7288 r = new StringBuilder(256); 7289 } else { 7290 r.append(' '); 7291 } 7292 r.append("DUP:"); 7293 r.append(pg.info.name); 7294 } 7295 } 7296 } 7297 if (r != null) { 7298 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 7299 } 7300 7301 N = pkg.permissions.size(); 7302 r = null; 7303 for (i=0; i<N; i++) { 7304 PackageParser.Permission p = pkg.permissions.get(i); 7305 7306 // Now that permission groups have a special meaning, we ignore permission 7307 // groups for legacy apps to prevent unexpected behavior. In particular, 7308 // permissions for one app being granted to someone just becuase they happen 7309 // to be in a group defined by another app (before this had no implications). 7310 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 7311 p.group = mPermissionGroups.get(p.info.group); 7312 // Warn for a permission in an unknown group. 7313 if (p.info.group != null && p.group == null) { 7314 Slog.w(TAG, "Permission " + p.info.name + " from package " 7315 + p.info.packageName + " in an unknown group " + p.info.group); 7316 } 7317 } 7318 7319 ArrayMap<String, BasePermission> permissionMap = 7320 p.tree ? mSettings.mPermissionTrees 7321 : mSettings.mPermissions; 7322 BasePermission bp = permissionMap.get(p.info.name); 7323 7324 // Allow system apps to redefine non-system permissions 7325 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 7326 final boolean currentOwnerIsSystem = (bp.perm != null 7327 && isSystemApp(bp.perm.owner)); 7328 if (isSystemApp(p.owner)) { 7329 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 7330 // It's a built-in permission and no owner, take ownership now 7331 bp.packageSetting = pkgSetting; 7332 bp.perm = p; 7333 bp.uid = pkg.applicationInfo.uid; 7334 bp.sourcePackage = p.info.packageName; 7335 } else if (!currentOwnerIsSystem) { 7336 String msg = "New decl " + p.owner + " of permission " 7337 + p.info.name + " is system; overriding " + bp.sourcePackage; 7338 reportSettingsProblem(Log.WARN, msg); 7339 bp = null; 7340 } 7341 } 7342 } 7343 7344 if (bp == null) { 7345 bp = new BasePermission(p.info.name, p.info.packageName, 7346 BasePermission.TYPE_NORMAL); 7347 permissionMap.put(p.info.name, bp); 7348 } 7349 7350 if (bp.perm == null) { 7351 if (bp.sourcePackage == null 7352 || bp.sourcePackage.equals(p.info.packageName)) { 7353 BasePermission tree = findPermissionTreeLP(p.info.name); 7354 if (tree == null 7355 || tree.sourcePackage.equals(p.info.packageName)) { 7356 bp.packageSetting = pkgSetting; 7357 bp.perm = p; 7358 bp.uid = pkg.applicationInfo.uid; 7359 bp.sourcePackage = p.info.packageName; 7360 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7361 if (r == null) { 7362 r = new StringBuilder(256); 7363 } else { 7364 r.append(' '); 7365 } 7366 r.append(p.info.name); 7367 } 7368 } else { 7369 Slog.w(TAG, "Permission " + p.info.name + " from package " 7370 + p.info.packageName + " ignored: base tree " 7371 + tree.name + " is from package " 7372 + tree.sourcePackage); 7373 } 7374 } else { 7375 Slog.w(TAG, "Permission " + p.info.name + " from package " 7376 + p.info.packageName + " ignored: original from " 7377 + bp.sourcePackage); 7378 } 7379 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7380 if (r == null) { 7381 r = new StringBuilder(256); 7382 } else { 7383 r.append(' '); 7384 } 7385 r.append("DUP:"); 7386 r.append(p.info.name); 7387 } 7388 if (bp.perm == p) { 7389 bp.protectionLevel = p.info.protectionLevel; 7390 } 7391 } 7392 7393 if (r != null) { 7394 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 7395 } 7396 7397 N = pkg.instrumentation.size(); 7398 r = null; 7399 for (i=0; i<N; i++) { 7400 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7401 a.info.packageName = pkg.applicationInfo.packageName; 7402 a.info.sourceDir = pkg.applicationInfo.sourceDir; 7403 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 7404 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 7405 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 7406 a.info.dataDir = pkg.applicationInfo.dataDir; 7407 7408 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 7409 // need other information about the application, like the ABI and what not ? 7410 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 7411 mInstrumentation.put(a.getComponentName(), a); 7412 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7413 if (r == null) { 7414 r = new StringBuilder(256); 7415 } else { 7416 r.append(' '); 7417 } 7418 r.append(a.info.name); 7419 } 7420 } 7421 if (r != null) { 7422 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 7423 } 7424 7425 if (pkg.protectedBroadcasts != null) { 7426 N = pkg.protectedBroadcasts.size(); 7427 for (i=0; i<N; i++) { 7428 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 7429 } 7430 } 7431 7432 pkgSetting.setTimeStamp(scanFileTime); 7433 7434 // Create idmap files for pairs of (packages, overlay packages). 7435 // Note: "android", ie framework-res.apk, is handled by native layers. 7436 if (pkg.mOverlayTarget != null) { 7437 // This is an overlay package. 7438 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 7439 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 7440 mOverlays.put(pkg.mOverlayTarget, 7441 new ArrayMap<String, PackageParser.Package>()); 7442 } 7443 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 7444 map.put(pkg.packageName, pkg); 7445 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 7446 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 7447 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7448 "scanPackageLI failed to createIdmap"); 7449 } 7450 } 7451 } else if (mOverlays.containsKey(pkg.packageName) && 7452 !pkg.packageName.equals("android")) { 7453 // This is a regular package, with one or more known overlay packages. 7454 createIdmapsForPackageLI(pkg); 7455 } 7456 } 7457 7458 return pkg; 7459 } 7460 7461 /** 7462 * Derive the ABI of a non-system package located at {@code scanFile}. This information 7463 * is derived purely on the basis of the contents of {@code scanFile} and 7464 * {@code cpuAbiOverride}. 7465 * 7466 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 7467 */ 7468 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 7469 String cpuAbiOverride, boolean extractLibs) 7470 throws PackageManagerException { 7471 // TODO: We can probably be smarter about this stuff. For installed apps, 7472 // we can calculate this information at install time once and for all. For 7473 // system apps, we can probably assume that this information doesn't change 7474 // after the first boot scan. As things stand, we do lots of unnecessary work. 7475 7476 // Give ourselves some initial paths; we'll come back for another 7477 // pass once we've determined ABI below. 7478 setNativeLibraryPaths(pkg); 7479 7480 // We would never need to extract libs for forward-locked and external packages, 7481 // since the container service will do it for us. We shouldn't attempt to 7482 // extract libs from system app when it was not updated. 7483 if (pkg.isForwardLocked() || isExternal(pkg) || 7484 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) { 7485 extractLibs = false; 7486 } 7487 7488 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7489 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7490 7491 NativeLibraryHelper.Handle handle = null; 7492 try { 7493 handle = NativeLibraryHelper.Handle.create(scanFile); 7494 // TODO(multiArch): This can be null for apps that didn't go through the 7495 // usual installation process. We can calculate it again, like we 7496 // do during install time. 7497 // 7498 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7499 // unnecessary. 7500 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7501 7502 // Null out the abis so that they can be recalculated. 7503 pkg.applicationInfo.primaryCpuAbi = null; 7504 pkg.applicationInfo.secondaryCpuAbi = null; 7505 if (isMultiArch(pkg.applicationInfo)) { 7506 // Warn if we've set an abiOverride for multi-lib packages.. 7507 // By definition, we need to copy both 32 and 64 bit libraries for 7508 // such packages. 7509 if (pkg.cpuAbiOverride != null 7510 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7511 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7512 } 7513 7514 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7515 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7516 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7517 if (extractLibs) { 7518 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7519 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7520 useIsaSpecificSubdirs); 7521 } else { 7522 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7523 } 7524 } 7525 7526 maybeThrowExceptionForMultiArchCopy( 7527 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7528 7529 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7530 if (extractLibs) { 7531 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7532 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7533 useIsaSpecificSubdirs); 7534 } else { 7535 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7536 } 7537 } 7538 7539 maybeThrowExceptionForMultiArchCopy( 7540 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7541 7542 if (abi64 >= 0) { 7543 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7544 } 7545 7546 if (abi32 >= 0) { 7547 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7548 if (abi64 >= 0) { 7549 pkg.applicationInfo.secondaryCpuAbi = abi; 7550 } else { 7551 pkg.applicationInfo.primaryCpuAbi = abi; 7552 } 7553 } 7554 } else { 7555 String[] abiList = (cpuAbiOverride != null) ? 7556 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7557 7558 // Enable gross and lame hacks for apps that are built with old 7559 // SDK tools. We must scan their APKs for renderscript bitcode and 7560 // not launch them if it's present. Don't bother checking on devices 7561 // that don't have 64 bit support. 7562 boolean needsRenderScriptOverride = false; 7563 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7564 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7565 abiList = Build.SUPPORTED_32_BIT_ABIS; 7566 needsRenderScriptOverride = true; 7567 } 7568 7569 final int copyRet; 7570 if (extractLibs) { 7571 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7572 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7573 } else { 7574 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7575 } 7576 7577 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7578 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7579 "Error unpackaging native libs for app, errorCode=" + copyRet); 7580 } 7581 7582 if (copyRet >= 0) { 7583 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7584 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7585 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7586 } else if (needsRenderScriptOverride) { 7587 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7588 } 7589 } 7590 } catch (IOException ioe) { 7591 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7592 } finally { 7593 IoUtils.closeQuietly(handle); 7594 } 7595 7596 // Now that we've calculated the ABIs and determined if it's an internal app, 7597 // we will go ahead and populate the nativeLibraryPath. 7598 setNativeLibraryPaths(pkg); 7599 } 7600 7601 /** 7602 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7603 * i.e, so that all packages can be run inside a single process if required. 7604 * 7605 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7606 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7607 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7608 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7609 * updating a package that belongs to a shared user. 7610 * 7611 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7612 * adds unnecessary complexity. 7613 */ 7614 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7615 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 7616 String requiredInstructionSet = null; 7617 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7618 requiredInstructionSet = VMRuntime.getInstructionSet( 7619 scannedPackage.applicationInfo.primaryCpuAbi); 7620 } 7621 7622 PackageSetting requirer = null; 7623 for (PackageSetting ps : packagesForUser) { 7624 // If packagesForUser contains scannedPackage, we skip it. This will happen 7625 // when scannedPackage is an update of an existing package. Without this check, 7626 // we will never be able to change the ABI of any package belonging to a shared 7627 // user, even if it's compatible with other packages. 7628 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7629 if (ps.primaryCpuAbiString == null) { 7630 continue; 7631 } 7632 7633 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7634 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7635 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7636 // this but there's not much we can do. 7637 String errorMessage = "Instruction set mismatch, " 7638 + ((requirer == null) ? "[caller]" : requirer) 7639 + " requires " + requiredInstructionSet + " whereas " + ps 7640 + " requires " + instructionSet; 7641 Slog.w(TAG, errorMessage); 7642 } 7643 7644 if (requiredInstructionSet == null) { 7645 requiredInstructionSet = instructionSet; 7646 requirer = ps; 7647 } 7648 } 7649 } 7650 7651 if (requiredInstructionSet != null) { 7652 String adjustedAbi; 7653 if (requirer != null) { 7654 // requirer != null implies that either scannedPackage was null or that scannedPackage 7655 // did not require an ABI, in which case we have to adjust scannedPackage to match 7656 // the ABI of the set (which is the same as requirer's ABI) 7657 adjustedAbi = requirer.primaryCpuAbiString; 7658 if (scannedPackage != null) { 7659 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7660 } 7661 } else { 7662 // requirer == null implies that we're updating all ABIs in the set to 7663 // match scannedPackage. 7664 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7665 } 7666 7667 for (PackageSetting ps : packagesForUser) { 7668 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7669 if (ps.primaryCpuAbiString != null) { 7670 continue; 7671 } 7672 7673 ps.primaryCpuAbiString = adjustedAbi; 7674 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7675 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7676 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7677 7678 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 7679 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 7680 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7681 ps.primaryCpuAbiString = null; 7682 ps.pkg.applicationInfo.primaryCpuAbi = null; 7683 return; 7684 } else { 7685 mInstaller.rmdex(ps.codePathString, 7686 getDexCodeInstructionSet(getPreferredInstructionSet())); 7687 } 7688 } 7689 } 7690 } 7691 } 7692 } 7693 7694 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7695 synchronized (mPackages) { 7696 mResolverReplaced = true; 7697 // Set up information for custom user intent resolution activity. 7698 mResolveActivity.applicationInfo = pkg.applicationInfo; 7699 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7700 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7701 mResolveActivity.processName = pkg.applicationInfo.packageName; 7702 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7703 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7704 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7705 mResolveActivity.theme = 0; 7706 mResolveActivity.exported = true; 7707 mResolveActivity.enabled = true; 7708 mResolveInfo.activityInfo = mResolveActivity; 7709 mResolveInfo.priority = 0; 7710 mResolveInfo.preferredOrder = 0; 7711 mResolveInfo.match = 0; 7712 mResolveComponentName = mCustomResolverComponentName; 7713 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7714 mResolveComponentName); 7715 } 7716 } 7717 7718 private static String calculateBundledApkRoot(final String codePathString) { 7719 final File codePath = new File(codePathString); 7720 final File codeRoot; 7721 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 7722 codeRoot = Environment.getRootDirectory(); 7723 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7724 codeRoot = Environment.getOemDirectory(); 7725 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7726 codeRoot = Environment.getVendorDirectory(); 7727 } else { 7728 // Unrecognized code path; take its top real segment as the apk root: 7729 // e.g. /something/app/blah.apk => /something 7730 try { 7731 File f = codePath.getCanonicalFile(); 7732 File parent = f.getParentFile(); // non-null because codePath is a file 7733 File tmp; 7734 while ((tmp = parent.getParentFile()) != null) { 7735 f = parent; 7736 parent = tmp; 7737 } 7738 codeRoot = f; 7739 Slog.w(TAG, "Unrecognized code path " 7740 + codePath + " - using " + codeRoot); 7741 } catch (IOException e) { 7742 // Can't canonicalize the code path -- shenanigans? 7743 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7744 return Environment.getRootDirectory().getPath(); 7745 } 7746 } 7747 return codeRoot.getPath(); 7748 } 7749 7750 /** 7751 * Derive and set the location of native libraries for the given package, 7752 * which varies depending on where and how the package was installed. 7753 */ 7754 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7755 final ApplicationInfo info = pkg.applicationInfo; 7756 final String codePath = pkg.codePath; 7757 final File codeFile = new File(codePath); 7758 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7759 final boolean asecApp = info.isForwardLocked() || isExternal(info); 7760 7761 info.nativeLibraryRootDir = null; 7762 info.nativeLibraryRootRequiresIsa = false; 7763 info.nativeLibraryDir = null; 7764 info.secondaryNativeLibraryDir = null; 7765 7766 if (isApkFile(codeFile)) { 7767 // Monolithic install 7768 if (bundledApp) { 7769 // If "/system/lib64/apkname" exists, assume that is the per-package 7770 // native library directory to use; otherwise use "/system/lib/apkname". 7771 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7772 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7773 getPrimaryInstructionSet(info)); 7774 7775 // This is a bundled system app so choose the path based on the ABI. 7776 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7777 // is just the default path. 7778 final String apkName = deriveCodePathName(codePath); 7779 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7780 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7781 apkName).getAbsolutePath(); 7782 7783 if (info.secondaryCpuAbi != null) { 7784 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7785 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7786 secondaryLibDir, apkName).getAbsolutePath(); 7787 } 7788 } else if (asecApp) { 7789 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 7790 .getAbsolutePath(); 7791 } else { 7792 final String apkName = deriveCodePathName(codePath); 7793 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 7794 .getAbsolutePath(); 7795 } 7796 7797 info.nativeLibraryRootRequiresIsa = false; 7798 info.nativeLibraryDir = info.nativeLibraryRootDir; 7799 } else { 7800 // Cluster install 7801 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 7802 info.nativeLibraryRootRequiresIsa = true; 7803 7804 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 7805 getPrimaryInstructionSet(info)).getAbsolutePath(); 7806 7807 if (info.secondaryCpuAbi != null) { 7808 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 7809 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 7810 } 7811 } 7812 } 7813 7814 /** 7815 * Calculate the abis and roots for a bundled app. These can uniquely 7816 * be determined from the contents of the system partition, i.e whether 7817 * it contains 64 or 32 bit shared libraries etc. We do not validate any 7818 * of this information, and instead assume that the system was built 7819 * sensibly. 7820 */ 7821 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 7822 PackageSetting pkgSetting) { 7823 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 7824 7825 // If "/system/lib64/apkname" exists, assume that is the per-package 7826 // native library directory to use; otherwise use "/system/lib/apkname". 7827 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 7828 setBundledAppAbi(pkg, apkRoot, apkName); 7829 // pkgSetting might be null during rescan following uninstall of updates 7830 // to a bundled app, so accommodate that possibility. The settings in 7831 // that case will be established later from the parsed package. 7832 // 7833 // If the settings aren't null, sync them up with what we've just derived. 7834 // note that apkRoot isn't stored in the package settings. 7835 if (pkgSetting != null) { 7836 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7837 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7838 } 7839 } 7840 7841 /** 7842 * Deduces the ABI of a bundled app and sets the relevant fields on the 7843 * parsed pkg object. 7844 * 7845 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 7846 * under which system libraries are installed. 7847 * @param apkName the name of the installed package. 7848 */ 7849 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 7850 final File codeFile = new File(pkg.codePath); 7851 7852 final boolean has64BitLibs; 7853 final boolean has32BitLibs; 7854 if (isApkFile(codeFile)) { 7855 // Monolithic install 7856 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 7857 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7858 } else { 7859 // Cluster install 7860 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7861 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7862 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7863 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7864 has64BitLibs = (new File(rootDir, isa)).exists(); 7865 } else { 7866 has64BitLibs = false; 7867 } 7868 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7869 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 7870 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 7871 has32BitLibs = (new File(rootDir, isa)).exists(); 7872 } else { 7873 has32BitLibs = false; 7874 } 7875 } 7876 7877 if (has64BitLibs && !has32BitLibs) { 7878 // The package has 64 bit libs, but not 32 bit libs. Its primary 7879 // ABI should be 64 bit. We can safely assume here that the bundled 7880 // native libraries correspond to the most preferred ABI in the list. 7881 7882 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7883 pkg.applicationInfo.secondaryCpuAbi = null; 7884 } else if (has32BitLibs && !has64BitLibs) { 7885 // The package has 32 bit libs but not 64 bit libs. Its primary 7886 // ABI should be 32 bit. 7887 7888 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7889 pkg.applicationInfo.secondaryCpuAbi = null; 7890 } else if (has32BitLibs && has64BitLibs) { 7891 // The application has both 64 and 32 bit bundled libraries. We check 7892 // here that the app declares multiArch support, and warn if it doesn't. 7893 // 7894 // We will be lenient here and record both ABIs. The primary will be the 7895 // ABI that's higher on the list, i.e, a device that's configured to prefer 7896 // 64 bit apps will see a 64 bit primary ABI, 7897 7898 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 7899 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 7900 } 7901 7902 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 7903 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7904 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7905 } else { 7906 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7907 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7908 } 7909 } else { 7910 pkg.applicationInfo.primaryCpuAbi = null; 7911 pkg.applicationInfo.secondaryCpuAbi = null; 7912 } 7913 } 7914 7915 private void killApplication(String pkgName, int appId, String reason) { 7916 // Request the ActivityManager to kill the process(only for existing packages) 7917 // so that we do not end up in a confused state while the user is still using the older 7918 // version of the application while the new one gets installed. 7919 IActivityManager am = ActivityManagerNative.getDefault(); 7920 if (am != null) { 7921 try { 7922 am.killApplicationWithAppId(pkgName, appId, reason); 7923 } catch (RemoteException e) { 7924 } 7925 } 7926 } 7927 7928 void removePackageLI(PackageSetting ps, boolean chatty) { 7929 if (DEBUG_INSTALL) { 7930 if (chatty) 7931 Log.d(TAG, "Removing package " + ps.name); 7932 } 7933 7934 // writer 7935 synchronized (mPackages) { 7936 mPackages.remove(ps.name); 7937 final PackageParser.Package pkg = ps.pkg; 7938 if (pkg != null) { 7939 cleanPackageDataStructuresLILPw(pkg, chatty); 7940 } 7941 } 7942 } 7943 7944 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 7945 if (DEBUG_INSTALL) { 7946 if (chatty) 7947 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 7948 } 7949 7950 // writer 7951 synchronized (mPackages) { 7952 mPackages.remove(pkg.applicationInfo.packageName); 7953 cleanPackageDataStructuresLILPw(pkg, chatty); 7954 } 7955 } 7956 7957 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 7958 int N = pkg.providers.size(); 7959 StringBuilder r = null; 7960 int i; 7961 for (i=0; i<N; i++) { 7962 PackageParser.Provider p = pkg.providers.get(i); 7963 mProviders.removeProvider(p); 7964 if (p.info.authority == null) { 7965 7966 /* There was another ContentProvider with this authority when 7967 * this app was installed so this authority is null, 7968 * Ignore it as we don't have to unregister the provider. 7969 */ 7970 continue; 7971 } 7972 String names[] = p.info.authority.split(";"); 7973 for (int j = 0; j < names.length; j++) { 7974 if (mProvidersByAuthority.get(names[j]) == p) { 7975 mProvidersByAuthority.remove(names[j]); 7976 if (DEBUG_REMOVE) { 7977 if (chatty) 7978 Log.d(TAG, "Unregistered content provider: " + names[j] 7979 + ", className = " + p.info.name + ", isSyncable = " 7980 + p.info.isSyncable); 7981 } 7982 } 7983 } 7984 if (DEBUG_REMOVE && chatty) { 7985 if (r == null) { 7986 r = new StringBuilder(256); 7987 } else { 7988 r.append(' '); 7989 } 7990 r.append(p.info.name); 7991 } 7992 } 7993 if (r != null) { 7994 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 7995 } 7996 7997 N = pkg.services.size(); 7998 r = null; 7999 for (i=0; i<N; i++) { 8000 PackageParser.Service s = pkg.services.get(i); 8001 mServices.removeService(s); 8002 if (chatty) { 8003 if (r == null) { 8004 r = new StringBuilder(256); 8005 } else { 8006 r.append(' '); 8007 } 8008 r.append(s.info.name); 8009 } 8010 } 8011 if (r != null) { 8012 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 8013 } 8014 8015 N = pkg.receivers.size(); 8016 r = null; 8017 for (i=0; i<N; i++) { 8018 PackageParser.Activity a = pkg.receivers.get(i); 8019 mReceivers.removeActivity(a, "receiver"); 8020 if (DEBUG_REMOVE && chatty) { 8021 if (r == null) { 8022 r = new StringBuilder(256); 8023 } else { 8024 r.append(' '); 8025 } 8026 r.append(a.info.name); 8027 } 8028 } 8029 if (r != null) { 8030 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 8031 } 8032 8033 N = pkg.activities.size(); 8034 r = null; 8035 for (i=0; i<N; i++) { 8036 PackageParser.Activity a = pkg.activities.get(i); 8037 mActivities.removeActivity(a, "activity"); 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, " Activities: " + r); 8049 } 8050 8051 N = pkg.permissions.size(); 8052 r = null; 8053 for (i=0; i<N; i++) { 8054 PackageParser.Permission p = pkg.permissions.get(i); 8055 BasePermission bp = mSettings.mPermissions.get(p.info.name); 8056 if (bp == null) { 8057 bp = mSettings.mPermissionTrees.get(p.info.name); 8058 } 8059 if (bp != null && bp.perm == p) { 8060 bp.perm = null; 8061 if (DEBUG_REMOVE && chatty) { 8062 if (r == null) { 8063 r = new StringBuilder(256); 8064 } else { 8065 r.append(' '); 8066 } 8067 r.append(p.info.name); 8068 } 8069 } 8070 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8071 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 8072 if (appOpPerms != null) { 8073 appOpPerms.remove(pkg.packageName); 8074 } 8075 } 8076 } 8077 if (r != null) { 8078 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8079 } 8080 8081 N = pkg.requestedPermissions.size(); 8082 r = null; 8083 for (i=0; i<N; i++) { 8084 String perm = pkg.requestedPermissions.get(i); 8085 BasePermission bp = mSettings.mPermissions.get(perm); 8086 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8087 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 8088 if (appOpPerms != null) { 8089 appOpPerms.remove(pkg.packageName); 8090 if (appOpPerms.isEmpty()) { 8091 mAppOpPermissionPackages.remove(perm); 8092 } 8093 } 8094 } 8095 } 8096 if (r != null) { 8097 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8098 } 8099 8100 N = pkg.instrumentation.size(); 8101 r = null; 8102 for (i=0; i<N; i++) { 8103 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8104 mInstrumentation.remove(a.getComponentName()); 8105 if (DEBUG_REMOVE && chatty) { 8106 if (r == null) { 8107 r = new StringBuilder(256); 8108 } else { 8109 r.append(' '); 8110 } 8111 r.append(a.info.name); 8112 } 8113 } 8114 if (r != null) { 8115 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 8116 } 8117 8118 r = null; 8119 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8120 // Only system apps can hold shared libraries. 8121 if (pkg.libraryNames != null) { 8122 for (i=0; i<pkg.libraryNames.size(); i++) { 8123 String name = pkg.libraryNames.get(i); 8124 SharedLibraryEntry cur = mSharedLibraries.get(name); 8125 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 8126 mSharedLibraries.remove(name); 8127 if (DEBUG_REMOVE && chatty) { 8128 if (r == null) { 8129 r = new StringBuilder(256); 8130 } else { 8131 r.append(' '); 8132 } 8133 r.append(name); 8134 } 8135 } 8136 } 8137 } 8138 } 8139 if (r != null) { 8140 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 8141 } 8142 } 8143 8144 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 8145 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 8146 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 8147 return true; 8148 } 8149 } 8150 return false; 8151 } 8152 8153 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 8154 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 8155 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 8156 8157 private void updatePermissionsLPw(String changingPkg, 8158 PackageParser.Package pkgInfo, int flags) { 8159 // Make sure there are no dangling permission trees. 8160 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 8161 while (it.hasNext()) { 8162 final BasePermission bp = it.next(); 8163 if (bp.packageSetting == null) { 8164 // We may not yet have parsed the package, so just see if 8165 // we still know about its settings. 8166 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8167 } 8168 if (bp.packageSetting == null) { 8169 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 8170 + " from package " + bp.sourcePackage); 8171 it.remove(); 8172 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8173 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8174 Slog.i(TAG, "Removing old permission tree: " + bp.name 8175 + " from package " + bp.sourcePackage); 8176 flags |= UPDATE_PERMISSIONS_ALL; 8177 it.remove(); 8178 } 8179 } 8180 } 8181 8182 // Make sure all dynamic permissions have been assigned to a package, 8183 // and make sure there are no dangling permissions. 8184 it = mSettings.mPermissions.values().iterator(); 8185 while (it.hasNext()) { 8186 final BasePermission bp = it.next(); 8187 if (bp.type == BasePermission.TYPE_DYNAMIC) { 8188 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 8189 + bp.name + " pkg=" + bp.sourcePackage 8190 + " info=" + bp.pendingInfo); 8191 if (bp.packageSetting == null && bp.pendingInfo != null) { 8192 final BasePermission tree = findPermissionTreeLP(bp.name); 8193 if (tree != null && tree.perm != null) { 8194 bp.packageSetting = tree.packageSetting; 8195 bp.perm = new PackageParser.Permission(tree.perm.owner, 8196 new PermissionInfo(bp.pendingInfo)); 8197 bp.perm.info.packageName = tree.perm.info.packageName; 8198 bp.perm.info.name = bp.name; 8199 bp.uid = tree.uid; 8200 } 8201 } 8202 } 8203 if (bp.packageSetting == null) { 8204 // We may not yet have parsed the package, so just see if 8205 // we still know about its settings. 8206 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8207 } 8208 if (bp.packageSetting == null) { 8209 Slog.w(TAG, "Removing dangling permission: " + bp.name 8210 + " from package " + bp.sourcePackage); 8211 it.remove(); 8212 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8213 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8214 Slog.i(TAG, "Removing old permission: " + bp.name 8215 + " from package " + bp.sourcePackage); 8216 flags |= UPDATE_PERMISSIONS_ALL; 8217 it.remove(); 8218 } 8219 } 8220 } 8221 8222 // Now update the permissions for all packages, in particular 8223 // replace the granted permissions of the system packages. 8224 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 8225 for (PackageParser.Package pkg : mPackages.values()) { 8226 if (pkg != pkgInfo) { 8227 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 8228 changingPkg); 8229 } 8230 } 8231 } 8232 8233 if (pkgInfo != null) { 8234 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 8235 } 8236 } 8237 8238 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 8239 String packageOfInterest) { 8240 // IMPORTANT: There are two types of permissions: install and runtime. 8241 // Install time permissions are granted when the app is installed to 8242 // all device users and users added in the future. Runtime permissions 8243 // are granted at runtime explicitly to specific users. Normal and signature 8244 // protected permissions are install time permissions. Dangerous permissions 8245 // are install permissions if the app's target SDK is Lollipop MR1 or older, 8246 // otherwise they are runtime permissions. This function does not manage 8247 // runtime permissions except for the case an app targeting Lollipop MR1 8248 // being upgraded to target a newer SDK, in which case dangerous permissions 8249 // are transformed from install time to runtime ones. 8250 8251 final PackageSetting ps = (PackageSetting) pkg.mExtras; 8252 if (ps == null) { 8253 return; 8254 } 8255 8256 PermissionsState permissionsState = ps.getPermissionsState(); 8257 PermissionsState origPermissions = permissionsState; 8258 8259 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 8260 8261 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 8262 8263 boolean changedInstallPermission = false; 8264 8265 if (replace) { 8266 ps.installPermissionsFixed = false; 8267 if (!ps.isSharedUser()) { 8268 origPermissions = new PermissionsState(permissionsState); 8269 permissionsState.reset(); 8270 } 8271 } 8272 8273 permissionsState.setGlobalGids(mGlobalGids); 8274 8275 final int N = pkg.requestedPermissions.size(); 8276 for (int i=0; i<N; i++) { 8277 final String name = pkg.requestedPermissions.get(i); 8278 final BasePermission bp = mSettings.mPermissions.get(name); 8279 8280 if (DEBUG_INSTALL) { 8281 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 8282 } 8283 8284 if (bp == null || bp.packageSetting == null) { 8285 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8286 Slog.w(TAG, "Unknown permission " + name 8287 + " in package " + pkg.packageName); 8288 } 8289 continue; 8290 } 8291 8292 final String perm = bp.name; 8293 boolean allowedSig = false; 8294 int grant = GRANT_DENIED; 8295 8296 // Keep track of app op permissions. 8297 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8298 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 8299 if (pkgs == null) { 8300 pkgs = new ArraySet<>(); 8301 mAppOpPermissionPackages.put(bp.name, pkgs); 8302 } 8303 pkgs.add(pkg.packageName); 8304 } 8305 8306 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 8307 switch (level) { 8308 case PermissionInfo.PROTECTION_NORMAL: { 8309 // For all apps normal permissions are install time ones. 8310 grant = GRANT_INSTALL; 8311 } break; 8312 8313 case PermissionInfo.PROTECTION_DANGEROUS: { 8314 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 8315 // For legacy apps dangerous permissions are install time ones. 8316 grant = GRANT_INSTALL_LEGACY; 8317 } else if (origPermissions.hasInstallPermission(bp.name)) { 8318 // For legacy apps that became modern, install becomes runtime. 8319 grant = GRANT_UPGRADE; 8320 } else { 8321 // For modern apps keep runtime permissions unchanged. 8322 grant = GRANT_RUNTIME; 8323 } 8324 } break; 8325 8326 case PermissionInfo.PROTECTION_SIGNATURE: { 8327 // For all apps signature permissions are install time ones. 8328 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 8329 if (allowedSig) { 8330 grant = GRANT_INSTALL; 8331 } 8332 } break; 8333 } 8334 8335 if (DEBUG_INSTALL) { 8336 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 8337 } 8338 8339 if (grant != GRANT_DENIED) { 8340 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 8341 // If this is an existing, non-system package, then 8342 // we can't add any new permissions to it. 8343 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 8344 // Except... if this is a permission that was added 8345 // to the platform (note: need to only do this when 8346 // updating the platform). 8347 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 8348 grant = GRANT_DENIED; 8349 } 8350 } 8351 } 8352 8353 switch (grant) { 8354 case GRANT_INSTALL: { 8355 // Revoke this as runtime permission to handle the case of 8356 // a runtime permission being downgraded to an install one. 8357 for (int userId : UserManagerService.getInstance().getUserIds()) { 8358 if (origPermissions.getRuntimePermissionState( 8359 bp.name, userId) != null) { 8360 // Revoke the runtime permission and clear the flags. 8361 origPermissions.revokeRuntimePermission(bp, userId); 8362 origPermissions.updatePermissionFlags(bp, userId, 8363 PackageManager.MASK_PERMISSION_FLAGS, 0); 8364 // If we revoked a permission permission, we have to write. 8365 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8366 changedRuntimePermissionUserIds, userId); 8367 } 8368 } 8369 // Grant an install permission. 8370 if (permissionsState.grantInstallPermission(bp) != 8371 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8372 changedInstallPermission = true; 8373 } 8374 } break; 8375 8376 case GRANT_INSTALL_LEGACY: { 8377 // Grant an install permission. 8378 if (permissionsState.grantInstallPermission(bp) != 8379 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8380 changedInstallPermission = true; 8381 } 8382 } break; 8383 8384 case GRANT_RUNTIME: { 8385 // Grant previously granted runtime permissions. 8386 for (int userId : UserManagerService.getInstance().getUserIds()) { 8387 PermissionState permissionState = origPermissions 8388 .getRuntimePermissionState(bp.name, userId); 8389 final int flags = permissionState != null 8390 ? permissionState.getFlags() : 0; 8391 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8392 if (permissionsState.grantRuntimePermission(bp, userId) == 8393 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8394 // If we cannot put the permission as it was, we have to write. 8395 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8396 changedRuntimePermissionUserIds, userId); 8397 } 8398 } 8399 // Propagate the permission flags. 8400 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 8401 } 8402 } break; 8403 8404 case GRANT_UPGRADE: { 8405 // Grant runtime permissions for a previously held install permission. 8406 PermissionState permissionState = origPermissions 8407 .getInstallPermissionState(bp.name); 8408 final int flags = permissionState != null ? permissionState.getFlags() : 0; 8409 8410 if (origPermissions.revokeInstallPermission(bp) 8411 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 8412 // We will be transferring the permission flags, so clear them. 8413 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 8414 PackageManager.MASK_PERMISSION_FLAGS, 0); 8415 changedInstallPermission = true; 8416 } 8417 8418 // If the permission is not to be promoted to runtime we ignore it and 8419 // also its other flags as they are not applicable to install permissions. 8420 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 8421 for (int userId : currentUserIds) { 8422 if (permissionsState.grantRuntimePermission(bp, userId) != 8423 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8424 // Transfer the permission flags. 8425 permissionsState.updatePermissionFlags(bp, userId, 8426 flags, flags); 8427 // If we granted the permission, we have to write. 8428 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8429 changedRuntimePermissionUserIds, userId); 8430 } 8431 } 8432 } 8433 } break; 8434 8435 default: { 8436 if (packageOfInterest == null 8437 || packageOfInterest.equals(pkg.packageName)) { 8438 Slog.w(TAG, "Not granting permission " + perm 8439 + " to package " + pkg.packageName 8440 + " because it was previously installed without"); 8441 } 8442 } break; 8443 } 8444 } else { 8445 if (permissionsState.revokeInstallPermission(bp) != 8446 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8447 // Also drop the permission flags. 8448 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 8449 PackageManager.MASK_PERMISSION_FLAGS, 0); 8450 changedInstallPermission = true; 8451 Slog.i(TAG, "Un-granting permission " + perm 8452 + " from package " + pkg.packageName 8453 + " (protectionLevel=" + bp.protectionLevel 8454 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8455 + ")"); 8456 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 8457 // Don't print warning for app op permissions, since it is fine for them 8458 // not to be granted, there is a UI for the user to decide. 8459 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8460 Slog.w(TAG, "Not granting permission " + perm 8461 + " to package " + pkg.packageName 8462 + " (protectionLevel=" + bp.protectionLevel 8463 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8464 + ")"); 8465 } 8466 } 8467 } 8468 } 8469 8470 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 8471 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 8472 // This is the first that we have heard about this package, so the 8473 // permissions we have now selected are fixed until explicitly 8474 // changed. 8475 ps.installPermissionsFixed = true; 8476 } 8477 8478 // Persist the runtime permissions state for users with changes. 8479 for (int userId : changedRuntimePermissionUserIds) { 8480 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 8481 } 8482 } 8483 8484 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8485 boolean allowed = false; 8486 final int NP = PackageParser.NEW_PERMISSIONS.length; 8487 for (int ip=0; ip<NP; ip++) { 8488 final PackageParser.NewPermissionInfo npi 8489 = PackageParser.NEW_PERMISSIONS[ip]; 8490 if (npi.name.equals(perm) 8491 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8492 allowed = true; 8493 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8494 + pkg.packageName); 8495 break; 8496 } 8497 } 8498 return allowed; 8499 } 8500 8501 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 8502 BasePermission bp, PermissionsState origPermissions) { 8503 boolean allowed; 8504 allowed = (compareSignatures( 8505 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 8506 == PackageManager.SIGNATURE_MATCH) 8507 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 8508 == PackageManager.SIGNATURE_MATCH); 8509 if (!allowed && (bp.protectionLevel 8510 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 8511 if (isSystemApp(pkg)) { 8512 // For updated system applications, a system permission 8513 // is granted only if it had been defined by the original application. 8514 if (pkg.isUpdatedSystemApp()) { 8515 final PackageSetting sysPs = mSettings 8516 .getDisabledSystemPkgLPr(pkg.packageName); 8517 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 8518 // If the original was granted this permission, we take 8519 // that grant decision as read and propagate it to the 8520 // update. 8521 if (sysPs.isPrivileged()) { 8522 allowed = true; 8523 } 8524 } else { 8525 // The system apk may have been updated with an older 8526 // version of the one on the data partition, but which 8527 // granted a new system permission that it didn't have 8528 // before. In this case we do want to allow the app to 8529 // now get the new permission if the ancestral apk is 8530 // privileged to get it. 8531 if (sysPs.pkg != null && sysPs.isPrivileged()) { 8532 for (int j=0; 8533 j<sysPs.pkg.requestedPermissions.size(); j++) { 8534 if (perm.equals( 8535 sysPs.pkg.requestedPermissions.get(j))) { 8536 allowed = true; 8537 break; 8538 } 8539 } 8540 } 8541 } 8542 } else { 8543 allowed = isPrivilegedApp(pkg); 8544 } 8545 } 8546 } 8547 if (!allowed) { 8548 if (!allowed && (bp.protectionLevel 8549 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 8550 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.MNC) { 8551 // If this was a previously normal/dangerous permission that got moved 8552 // to a system permission as part of the runtime permission redesign, then 8553 // we still want to blindly grant it to old apps. 8554 allowed = true; 8555 } 8556 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 8557 && pkg.packageName.equals(mRequiredInstallerPackage)) { 8558 // If this permission is to be granted to the system installer and 8559 // this app is an installer, then it gets the permission. 8560 allowed = true; 8561 } 8562 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 8563 && pkg.packageName.equals(mRequiredVerifierPackage)) { 8564 // If this permission is to be granted to the system verifier and 8565 // this app is a verifier, then it gets the permission. 8566 allowed = true; 8567 } 8568 if (!allowed && (bp.protectionLevel 8569 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 8570 && isSystemApp(pkg)) { 8571 // Any pre-installed system app is allowed to get this permission. 8572 allowed = true; 8573 } 8574 if (!allowed && (bp.protectionLevel 8575 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 8576 // For development permissions, a development permission 8577 // is granted only if it was already granted. 8578 allowed = origPermissions.hasInstallPermission(perm); 8579 } 8580 } 8581 return allowed; 8582 } 8583 8584 final class ActivityIntentResolver 8585 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 8586 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8587 boolean defaultOnly, int userId) { 8588 if (!sUserManager.exists(userId)) return null; 8589 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8590 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8591 } 8592 8593 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8594 int userId) { 8595 if (!sUserManager.exists(userId)) return null; 8596 mFlags = flags; 8597 return super.queryIntent(intent, resolvedType, 8598 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8599 } 8600 8601 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8602 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 8603 if (!sUserManager.exists(userId)) return null; 8604 if (packageActivities == null) { 8605 return null; 8606 } 8607 mFlags = flags; 8608 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8609 final int N = packageActivities.size(); 8610 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 8611 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 8612 8613 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 8614 for (int i = 0; i < N; ++i) { 8615 intentFilters = packageActivities.get(i).intents; 8616 if (intentFilters != null && intentFilters.size() > 0) { 8617 PackageParser.ActivityIntentInfo[] array = 8618 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 8619 intentFilters.toArray(array); 8620 listCut.add(array); 8621 } 8622 } 8623 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8624 } 8625 8626 public final void addActivity(PackageParser.Activity a, String type) { 8627 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 8628 mActivities.put(a.getComponentName(), a); 8629 if (DEBUG_SHOW_INFO) 8630 Log.v( 8631 TAG, " " + type + " " + 8632 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 8633 if (DEBUG_SHOW_INFO) 8634 Log.v(TAG, " Class=" + a.info.name); 8635 final int NI = a.intents.size(); 8636 for (int j=0; j<NI; j++) { 8637 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8638 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 8639 intent.setPriority(0); 8640 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 8641 + a.className + " with priority > 0, forcing to 0"); 8642 } 8643 if (DEBUG_SHOW_INFO) { 8644 Log.v(TAG, " IntentFilter:"); 8645 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8646 } 8647 if (!intent.debugCheck()) { 8648 Log.w(TAG, "==> For Activity " + a.info.name); 8649 } 8650 addFilter(intent); 8651 } 8652 } 8653 8654 public final void removeActivity(PackageParser.Activity a, String type) { 8655 mActivities.remove(a.getComponentName()); 8656 if (DEBUG_SHOW_INFO) { 8657 Log.v(TAG, " " + type + " " 8658 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 8659 : a.info.name) + ":"); 8660 Log.v(TAG, " Class=" + a.info.name); 8661 } 8662 final int NI = a.intents.size(); 8663 for (int j=0; j<NI; j++) { 8664 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8665 if (DEBUG_SHOW_INFO) { 8666 Log.v(TAG, " IntentFilter:"); 8667 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8668 } 8669 removeFilter(intent); 8670 } 8671 } 8672 8673 @Override 8674 protected boolean allowFilterResult( 8675 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 8676 ActivityInfo filterAi = filter.activity.info; 8677 for (int i=dest.size()-1; i>=0; i--) { 8678 ActivityInfo destAi = dest.get(i).activityInfo; 8679 if (destAi.name == filterAi.name 8680 && destAi.packageName == filterAi.packageName) { 8681 return false; 8682 } 8683 } 8684 return true; 8685 } 8686 8687 @Override 8688 protected ActivityIntentInfo[] newArray(int size) { 8689 return new ActivityIntentInfo[size]; 8690 } 8691 8692 @Override 8693 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 8694 if (!sUserManager.exists(userId)) return true; 8695 PackageParser.Package p = filter.activity.owner; 8696 if (p != null) { 8697 PackageSetting ps = (PackageSetting)p.mExtras; 8698 if (ps != null) { 8699 // System apps are never considered stopped for purposes of 8700 // filtering, because there may be no way for the user to 8701 // actually re-launch them. 8702 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 8703 && ps.getStopped(userId); 8704 } 8705 } 8706 return false; 8707 } 8708 8709 @Override 8710 protected boolean isPackageForFilter(String packageName, 8711 PackageParser.ActivityIntentInfo info) { 8712 return packageName.equals(info.activity.owner.packageName); 8713 } 8714 8715 @Override 8716 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 8717 int match, int userId) { 8718 if (!sUserManager.exists(userId)) return null; 8719 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 8720 return null; 8721 } 8722 final PackageParser.Activity activity = info.activity; 8723 if (mSafeMode && (activity.info.applicationInfo.flags 8724 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8725 return null; 8726 } 8727 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 8728 if (ps == null) { 8729 return null; 8730 } 8731 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 8732 ps.readUserState(userId), userId); 8733 if (ai == null) { 8734 return null; 8735 } 8736 final ResolveInfo res = new ResolveInfo(); 8737 res.activityInfo = ai; 8738 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8739 res.filter = info; 8740 } 8741 if (info != null) { 8742 res.handleAllWebDataURI = info.handleAllWebDataURI(); 8743 } 8744 res.priority = info.getPriority(); 8745 res.preferredOrder = activity.owner.mPreferredOrder; 8746 //System.out.println("Result: " + res.activityInfo.className + 8747 // " = " + res.priority); 8748 res.match = match; 8749 res.isDefault = info.hasDefault; 8750 res.labelRes = info.labelRes; 8751 res.nonLocalizedLabel = info.nonLocalizedLabel; 8752 if (userNeedsBadging(userId)) { 8753 res.noResourceId = true; 8754 } else { 8755 res.icon = info.icon; 8756 } 8757 res.iconResourceId = info.icon; 8758 res.system = res.activityInfo.applicationInfo.isSystemApp(); 8759 return res; 8760 } 8761 8762 @Override 8763 protected void sortResults(List<ResolveInfo> results) { 8764 Collections.sort(results, mResolvePrioritySorter); 8765 } 8766 8767 @Override 8768 protected void dumpFilter(PrintWriter out, String prefix, 8769 PackageParser.ActivityIntentInfo filter) { 8770 out.print(prefix); out.print( 8771 Integer.toHexString(System.identityHashCode(filter.activity))); 8772 out.print(' '); 8773 filter.activity.printComponentShortName(out); 8774 out.print(" filter "); 8775 out.println(Integer.toHexString(System.identityHashCode(filter))); 8776 } 8777 8778 @Override 8779 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 8780 return filter.activity; 8781 } 8782 8783 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8784 PackageParser.Activity activity = (PackageParser.Activity)label; 8785 out.print(prefix); out.print( 8786 Integer.toHexString(System.identityHashCode(activity))); 8787 out.print(' '); 8788 activity.printComponentShortName(out); 8789 if (count > 1) { 8790 out.print(" ("); out.print(count); out.print(" filters)"); 8791 } 8792 out.println(); 8793 } 8794 8795// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8796// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8797// final List<ResolveInfo> retList = Lists.newArrayList(); 8798// while (i.hasNext()) { 8799// final ResolveInfo resolveInfo = i.next(); 8800// if (isEnabledLP(resolveInfo.activityInfo)) { 8801// retList.add(resolveInfo); 8802// } 8803// } 8804// return retList; 8805// } 8806 8807 // Keys are String (activity class name), values are Activity. 8808 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 8809 = new ArrayMap<ComponentName, PackageParser.Activity>(); 8810 private int mFlags; 8811 } 8812 8813 private final class ServiceIntentResolver 8814 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 8815 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8816 boolean defaultOnly, int userId) { 8817 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8818 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8819 } 8820 8821 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8822 int userId) { 8823 if (!sUserManager.exists(userId)) return null; 8824 mFlags = flags; 8825 return super.queryIntent(intent, resolvedType, 8826 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8827 } 8828 8829 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8830 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 8831 if (!sUserManager.exists(userId)) return null; 8832 if (packageServices == null) { 8833 return null; 8834 } 8835 mFlags = flags; 8836 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8837 final int N = packageServices.size(); 8838 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 8839 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 8840 8841 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 8842 for (int i = 0; i < N; ++i) { 8843 intentFilters = packageServices.get(i).intents; 8844 if (intentFilters != null && intentFilters.size() > 0) { 8845 PackageParser.ServiceIntentInfo[] array = 8846 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 8847 intentFilters.toArray(array); 8848 listCut.add(array); 8849 } 8850 } 8851 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8852 } 8853 8854 public final void addService(PackageParser.Service s) { 8855 mServices.put(s.getComponentName(), s); 8856 if (DEBUG_SHOW_INFO) { 8857 Log.v(TAG, " " 8858 + (s.info.nonLocalizedLabel != null 8859 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8860 Log.v(TAG, " Class=" + s.info.name); 8861 } 8862 final int NI = s.intents.size(); 8863 int j; 8864 for (j=0; j<NI; j++) { 8865 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8866 if (DEBUG_SHOW_INFO) { 8867 Log.v(TAG, " IntentFilter:"); 8868 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8869 } 8870 if (!intent.debugCheck()) { 8871 Log.w(TAG, "==> For Service " + s.info.name); 8872 } 8873 addFilter(intent); 8874 } 8875 } 8876 8877 public final void removeService(PackageParser.Service s) { 8878 mServices.remove(s.getComponentName()); 8879 if (DEBUG_SHOW_INFO) { 8880 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 8881 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8882 Log.v(TAG, " Class=" + s.info.name); 8883 } 8884 final int NI = s.intents.size(); 8885 int j; 8886 for (j=0; j<NI; j++) { 8887 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8888 if (DEBUG_SHOW_INFO) { 8889 Log.v(TAG, " IntentFilter:"); 8890 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8891 } 8892 removeFilter(intent); 8893 } 8894 } 8895 8896 @Override 8897 protected boolean allowFilterResult( 8898 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 8899 ServiceInfo filterSi = filter.service.info; 8900 for (int i=dest.size()-1; i>=0; i--) { 8901 ServiceInfo destAi = dest.get(i).serviceInfo; 8902 if (destAi.name == filterSi.name 8903 && destAi.packageName == filterSi.packageName) { 8904 return false; 8905 } 8906 } 8907 return true; 8908 } 8909 8910 @Override 8911 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 8912 return new PackageParser.ServiceIntentInfo[size]; 8913 } 8914 8915 @Override 8916 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 8917 if (!sUserManager.exists(userId)) return true; 8918 PackageParser.Package p = filter.service.owner; 8919 if (p != null) { 8920 PackageSetting ps = (PackageSetting)p.mExtras; 8921 if (ps != null) { 8922 // System apps are never considered stopped for purposes of 8923 // filtering, because there may be no way for the user to 8924 // actually re-launch them. 8925 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8926 && ps.getStopped(userId); 8927 } 8928 } 8929 return false; 8930 } 8931 8932 @Override 8933 protected boolean isPackageForFilter(String packageName, 8934 PackageParser.ServiceIntentInfo info) { 8935 return packageName.equals(info.service.owner.packageName); 8936 } 8937 8938 @Override 8939 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 8940 int match, int userId) { 8941 if (!sUserManager.exists(userId)) return null; 8942 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 8943 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 8944 return null; 8945 } 8946 final PackageParser.Service service = info.service; 8947 if (mSafeMode && (service.info.applicationInfo.flags 8948 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8949 return null; 8950 } 8951 PackageSetting ps = (PackageSetting) service.owner.mExtras; 8952 if (ps == null) { 8953 return null; 8954 } 8955 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 8956 ps.readUserState(userId), userId); 8957 if (si == null) { 8958 return null; 8959 } 8960 final ResolveInfo res = new ResolveInfo(); 8961 res.serviceInfo = si; 8962 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8963 res.filter = filter; 8964 } 8965 res.priority = info.getPriority(); 8966 res.preferredOrder = service.owner.mPreferredOrder; 8967 res.match = match; 8968 res.isDefault = info.hasDefault; 8969 res.labelRes = info.labelRes; 8970 res.nonLocalizedLabel = info.nonLocalizedLabel; 8971 res.icon = info.icon; 8972 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 8973 return res; 8974 } 8975 8976 @Override 8977 protected void sortResults(List<ResolveInfo> results) { 8978 Collections.sort(results, mResolvePrioritySorter); 8979 } 8980 8981 @Override 8982 protected void dumpFilter(PrintWriter out, String prefix, 8983 PackageParser.ServiceIntentInfo filter) { 8984 out.print(prefix); out.print( 8985 Integer.toHexString(System.identityHashCode(filter.service))); 8986 out.print(' '); 8987 filter.service.printComponentShortName(out); 8988 out.print(" filter "); 8989 out.println(Integer.toHexString(System.identityHashCode(filter))); 8990 } 8991 8992 @Override 8993 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 8994 return filter.service; 8995 } 8996 8997 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8998 PackageParser.Service service = (PackageParser.Service)label; 8999 out.print(prefix); out.print( 9000 Integer.toHexString(System.identityHashCode(service))); 9001 out.print(' '); 9002 service.printComponentShortName(out); 9003 if (count > 1) { 9004 out.print(" ("); out.print(count); out.print(" filters)"); 9005 } 9006 out.println(); 9007 } 9008 9009// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9010// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9011// final List<ResolveInfo> retList = Lists.newArrayList(); 9012// while (i.hasNext()) { 9013// final ResolveInfo resolveInfo = (ResolveInfo) i; 9014// if (isEnabledLP(resolveInfo.serviceInfo)) { 9015// retList.add(resolveInfo); 9016// } 9017// } 9018// return retList; 9019// } 9020 9021 // Keys are String (activity class name), values are Activity. 9022 private final ArrayMap<ComponentName, PackageParser.Service> mServices 9023 = new ArrayMap<ComponentName, PackageParser.Service>(); 9024 private int mFlags; 9025 }; 9026 9027 private final class ProviderIntentResolver 9028 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 9029 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9030 boolean defaultOnly, int userId) { 9031 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9032 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9033 } 9034 9035 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9036 int userId) { 9037 if (!sUserManager.exists(userId)) 9038 return null; 9039 mFlags = flags; 9040 return super.queryIntent(intent, resolvedType, 9041 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9042 } 9043 9044 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9045 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 9046 if (!sUserManager.exists(userId)) 9047 return null; 9048 if (packageProviders == null) { 9049 return null; 9050 } 9051 mFlags = flags; 9052 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 9053 final int N = packageProviders.size(); 9054 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 9055 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 9056 9057 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 9058 for (int i = 0; i < N; ++i) { 9059 intentFilters = packageProviders.get(i).intents; 9060 if (intentFilters != null && intentFilters.size() > 0) { 9061 PackageParser.ProviderIntentInfo[] array = 9062 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 9063 intentFilters.toArray(array); 9064 listCut.add(array); 9065 } 9066 } 9067 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9068 } 9069 9070 public final void addProvider(PackageParser.Provider p) { 9071 if (mProviders.containsKey(p.getComponentName())) { 9072 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 9073 return; 9074 } 9075 9076 mProviders.put(p.getComponentName(), p); 9077 if (DEBUG_SHOW_INFO) { 9078 Log.v(TAG, " " 9079 + (p.info.nonLocalizedLabel != null 9080 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9081 Log.v(TAG, " Class=" + p.info.name); 9082 } 9083 final int NI = p.intents.size(); 9084 int j; 9085 for (j = 0; j < NI; j++) { 9086 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9087 if (DEBUG_SHOW_INFO) { 9088 Log.v(TAG, " IntentFilter:"); 9089 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9090 } 9091 if (!intent.debugCheck()) { 9092 Log.w(TAG, "==> For Provider " + p.info.name); 9093 } 9094 addFilter(intent); 9095 } 9096 } 9097 9098 public final void removeProvider(PackageParser.Provider p) { 9099 mProviders.remove(p.getComponentName()); 9100 if (DEBUG_SHOW_INFO) { 9101 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 9102 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9103 Log.v(TAG, " Class=" + p.info.name); 9104 } 9105 final int NI = p.intents.size(); 9106 int j; 9107 for (j = 0; j < NI; j++) { 9108 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9109 if (DEBUG_SHOW_INFO) { 9110 Log.v(TAG, " IntentFilter:"); 9111 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9112 } 9113 removeFilter(intent); 9114 } 9115 } 9116 9117 @Override 9118 protected boolean allowFilterResult( 9119 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 9120 ProviderInfo filterPi = filter.provider.info; 9121 for (int i = dest.size() - 1; i >= 0; i--) { 9122 ProviderInfo destPi = dest.get(i).providerInfo; 9123 if (destPi.name == filterPi.name 9124 && destPi.packageName == filterPi.packageName) { 9125 return false; 9126 } 9127 } 9128 return true; 9129 } 9130 9131 @Override 9132 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 9133 return new PackageParser.ProviderIntentInfo[size]; 9134 } 9135 9136 @Override 9137 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 9138 if (!sUserManager.exists(userId)) 9139 return true; 9140 PackageParser.Package p = filter.provider.owner; 9141 if (p != null) { 9142 PackageSetting ps = (PackageSetting) p.mExtras; 9143 if (ps != null) { 9144 // System apps are never considered stopped for purposes of 9145 // filtering, because there may be no way for the user to 9146 // actually re-launch them. 9147 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9148 && ps.getStopped(userId); 9149 } 9150 } 9151 return false; 9152 } 9153 9154 @Override 9155 protected boolean isPackageForFilter(String packageName, 9156 PackageParser.ProviderIntentInfo info) { 9157 return packageName.equals(info.provider.owner.packageName); 9158 } 9159 9160 @Override 9161 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 9162 int match, int userId) { 9163 if (!sUserManager.exists(userId)) 9164 return null; 9165 final PackageParser.ProviderIntentInfo info = filter; 9166 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 9167 return null; 9168 } 9169 final PackageParser.Provider provider = info.provider; 9170 if (mSafeMode && (provider.info.applicationInfo.flags 9171 & ApplicationInfo.FLAG_SYSTEM) == 0) { 9172 return null; 9173 } 9174 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 9175 if (ps == null) { 9176 return null; 9177 } 9178 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 9179 ps.readUserState(userId), userId); 9180 if (pi == null) { 9181 return null; 9182 } 9183 final ResolveInfo res = new ResolveInfo(); 9184 res.providerInfo = pi; 9185 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 9186 res.filter = filter; 9187 } 9188 res.priority = info.getPriority(); 9189 res.preferredOrder = provider.owner.mPreferredOrder; 9190 res.match = match; 9191 res.isDefault = info.hasDefault; 9192 res.labelRes = info.labelRes; 9193 res.nonLocalizedLabel = info.nonLocalizedLabel; 9194 res.icon = info.icon; 9195 res.system = res.providerInfo.applicationInfo.isSystemApp(); 9196 return res; 9197 } 9198 9199 @Override 9200 protected void sortResults(List<ResolveInfo> results) { 9201 Collections.sort(results, mResolvePrioritySorter); 9202 } 9203 9204 @Override 9205 protected void dumpFilter(PrintWriter out, String prefix, 9206 PackageParser.ProviderIntentInfo filter) { 9207 out.print(prefix); 9208 out.print( 9209 Integer.toHexString(System.identityHashCode(filter.provider))); 9210 out.print(' '); 9211 filter.provider.printComponentShortName(out); 9212 out.print(" filter "); 9213 out.println(Integer.toHexString(System.identityHashCode(filter))); 9214 } 9215 9216 @Override 9217 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 9218 return filter.provider; 9219 } 9220 9221 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9222 PackageParser.Provider provider = (PackageParser.Provider)label; 9223 out.print(prefix); out.print( 9224 Integer.toHexString(System.identityHashCode(provider))); 9225 out.print(' '); 9226 provider.printComponentShortName(out); 9227 if (count > 1) { 9228 out.print(" ("); out.print(count); out.print(" filters)"); 9229 } 9230 out.println(); 9231 } 9232 9233 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 9234 = new ArrayMap<ComponentName, PackageParser.Provider>(); 9235 private int mFlags; 9236 }; 9237 9238 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 9239 new Comparator<ResolveInfo>() { 9240 public int compare(ResolveInfo r1, ResolveInfo r2) { 9241 int v1 = r1.priority; 9242 int v2 = r2.priority; 9243 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 9244 if (v1 != v2) { 9245 return (v1 > v2) ? -1 : 1; 9246 } 9247 v1 = r1.preferredOrder; 9248 v2 = r2.preferredOrder; 9249 if (v1 != v2) { 9250 return (v1 > v2) ? -1 : 1; 9251 } 9252 if (r1.isDefault != r2.isDefault) { 9253 return r1.isDefault ? -1 : 1; 9254 } 9255 v1 = r1.match; 9256 v2 = r2.match; 9257 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 9258 if (v1 != v2) { 9259 return (v1 > v2) ? -1 : 1; 9260 } 9261 if (r1.system != r2.system) { 9262 return r1.system ? -1 : 1; 9263 } 9264 return 0; 9265 } 9266 }; 9267 9268 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 9269 new Comparator<ProviderInfo>() { 9270 public int compare(ProviderInfo p1, ProviderInfo p2) { 9271 final int v1 = p1.initOrder; 9272 final int v2 = p2.initOrder; 9273 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 9274 } 9275 }; 9276 9277 final void sendPackageBroadcast(final String action, final String pkg, 9278 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 9279 final int[] userIds) { 9280 mHandler.post(new Runnable() { 9281 @Override 9282 public void run() { 9283 try { 9284 final IActivityManager am = ActivityManagerNative.getDefault(); 9285 if (am == null) return; 9286 final int[] resolvedUserIds; 9287 if (userIds == null) { 9288 resolvedUserIds = am.getRunningUserIds(); 9289 } else { 9290 resolvedUserIds = userIds; 9291 } 9292 for (int id : resolvedUserIds) { 9293 final Intent intent = new Intent(action, 9294 pkg != null ? Uri.fromParts("package", pkg, null) : null); 9295 if (extras != null) { 9296 intent.putExtras(extras); 9297 } 9298 if (targetPkg != null) { 9299 intent.setPackage(targetPkg); 9300 } 9301 // Modify the UID when posting to other users 9302 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 9303 if (uid > 0 && UserHandle.getUserId(uid) != id) { 9304 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 9305 intent.putExtra(Intent.EXTRA_UID, uid); 9306 } 9307 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 9308 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 9309 if (DEBUG_BROADCASTS) { 9310 RuntimeException here = new RuntimeException("here"); 9311 here.fillInStackTrace(); 9312 Slog.d(TAG, "Sending to user " + id + ": " 9313 + intent.toShortString(false, true, false, false) 9314 + " " + intent.getExtras(), here); 9315 } 9316 am.broadcastIntent(null, intent, null, finishedReceiver, 9317 0, null, null, null, android.app.AppOpsManager.OP_NONE, 9318 null, finishedReceiver != null, false, id); 9319 } 9320 } catch (RemoteException ex) { 9321 } 9322 } 9323 }); 9324 } 9325 9326 /** 9327 * Check if the external storage media is available. This is true if there 9328 * is a mounted external storage medium or if the external storage is 9329 * emulated. 9330 */ 9331 private boolean isExternalMediaAvailable() { 9332 return mMediaMounted || Environment.isExternalStorageEmulated(); 9333 } 9334 9335 @Override 9336 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 9337 // writer 9338 synchronized (mPackages) { 9339 if (!isExternalMediaAvailable()) { 9340 // If the external storage is no longer mounted at this point, 9341 // the caller may not have been able to delete all of this 9342 // packages files and can not delete any more. Bail. 9343 return null; 9344 } 9345 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 9346 if (lastPackage != null) { 9347 pkgs.remove(lastPackage); 9348 } 9349 if (pkgs.size() > 0) { 9350 return pkgs.get(0); 9351 } 9352 } 9353 return null; 9354 } 9355 9356 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 9357 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 9358 userId, andCode ? 1 : 0, packageName); 9359 if (mSystemReady) { 9360 msg.sendToTarget(); 9361 } else { 9362 if (mPostSystemReadyMessages == null) { 9363 mPostSystemReadyMessages = new ArrayList<>(); 9364 } 9365 mPostSystemReadyMessages.add(msg); 9366 } 9367 } 9368 9369 void startCleaningPackages() { 9370 // reader 9371 synchronized (mPackages) { 9372 if (!isExternalMediaAvailable()) { 9373 return; 9374 } 9375 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 9376 return; 9377 } 9378 } 9379 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 9380 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 9381 IActivityManager am = ActivityManagerNative.getDefault(); 9382 if (am != null) { 9383 try { 9384 am.startService(null, intent, null, mContext.getOpPackageName(), 9385 UserHandle.USER_OWNER); 9386 } catch (RemoteException e) { 9387 } 9388 } 9389 } 9390 9391 @Override 9392 public void installPackage(String originPath, IPackageInstallObserver2 observer, 9393 int installFlags, String installerPackageName, VerificationParams verificationParams, 9394 String packageAbiOverride) { 9395 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 9396 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 9397 } 9398 9399 @Override 9400 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 9401 int installFlags, String installerPackageName, VerificationParams verificationParams, 9402 String packageAbiOverride, int userId) { 9403 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 9404 9405 final int callingUid = Binder.getCallingUid(); 9406 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 9407 9408 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9409 try { 9410 if (observer != null) { 9411 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 9412 } 9413 } catch (RemoteException re) { 9414 } 9415 return; 9416 } 9417 9418 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 9419 installFlags |= PackageManager.INSTALL_FROM_ADB; 9420 9421 } else { 9422 // Caller holds INSTALL_PACKAGES permission, so we're less strict 9423 // about installerPackageName. 9424 9425 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 9426 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 9427 } 9428 9429 UserHandle user; 9430 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 9431 user = UserHandle.ALL; 9432 } else { 9433 user = new UserHandle(userId); 9434 } 9435 9436 // Only system components can circumvent runtime permissions when installing. 9437 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 9438 && mContext.checkCallingOrSelfPermission(Manifest.permission 9439 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 9440 throw new SecurityException("You need the " 9441 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 9442 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 9443 } 9444 9445 verificationParams.setInstallerUid(callingUid); 9446 9447 final File originFile = new File(originPath); 9448 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 9449 9450 final Message msg = mHandler.obtainMessage(INIT_COPY); 9451 msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName, 9452 null, verificationParams, user, packageAbiOverride); 9453 mHandler.sendMessage(msg); 9454 } 9455 9456 void installStage(String packageName, File stagedDir, String stagedCid, 9457 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 9458 String installerPackageName, int installerUid, UserHandle user) { 9459 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 9460 params.referrerUri, installerUid, null); 9461 verifParams.setInstallerUid(installerUid); 9462 9463 final OriginInfo origin; 9464 if (stagedDir != null) { 9465 origin = OriginInfo.fromStagedFile(stagedDir); 9466 } else { 9467 origin = OriginInfo.fromStagedContainer(stagedCid); 9468 } 9469 9470 final Message msg = mHandler.obtainMessage(INIT_COPY); 9471 msg.obj = new InstallParams(origin, null, observer, params.installFlags, 9472 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride); 9473 mHandler.sendMessage(msg); 9474 } 9475 9476 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 9477 Bundle extras = new Bundle(1); 9478 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 9479 9480 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 9481 packageName, extras, null, null, new int[] {userId}); 9482 try { 9483 IActivityManager am = ActivityManagerNative.getDefault(); 9484 final boolean isSystem = 9485 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 9486 if (isSystem && am.isUserRunning(userId, false)) { 9487 // The just-installed/enabled app is bundled on the system, so presumed 9488 // to be able to run automatically without needing an explicit launch. 9489 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 9490 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 9491 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 9492 .setPackage(packageName); 9493 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 9494 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 9495 } 9496 } catch (RemoteException e) { 9497 // shouldn't happen 9498 Slog.w(TAG, "Unable to bootstrap installed package", e); 9499 } 9500 } 9501 9502 @Override 9503 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 9504 int userId) { 9505 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9506 PackageSetting pkgSetting; 9507 final int uid = Binder.getCallingUid(); 9508 enforceCrossUserPermission(uid, userId, true, true, 9509 "setApplicationHiddenSetting for user " + userId); 9510 9511 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 9512 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 9513 return false; 9514 } 9515 9516 long callingId = Binder.clearCallingIdentity(); 9517 try { 9518 boolean sendAdded = false; 9519 boolean sendRemoved = false; 9520 // writer 9521 synchronized (mPackages) { 9522 pkgSetting = mSettings.mPackages.get(packageName); 9523 if (pkgSetting == null) { 9524 return false; 9525 } 9526 if (pkgSetting.getHidden(userId) != hidden) { 9527 pkgSetting.setHidden(hidden, userId); 9528 mSettings.writePackageRestrictionsLPr(userId); 9529 if (hidden) { 9530 sendRemoved = true; 9531 } else { 9532 sendAdded = true; 9533 } 9534 } 9535 } 9536 if (sendAdded) { 9537 sendPackageAddedForUser(packageName, pkgSetting, userId); 9538 return true; 9539 } 9540 if (sendRemoved) { 9541 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 9542 "hiding pkg"); 9543 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 9544 } 9545 } finally { 9546 Binder.restoreCallingIdentity(callingId); 9547 } 9548 return false; 9549 } 9550 9551 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 9552 int userId) { 9553 final PackageRemovedInfo info = new PackageRemovedInfo(); 9554 info.removedPackage = packageName; 9555 info.removedUsers = new int[] {userId}; 9556 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 9557 info.sendBroadcast(false, false, false); 9558 } 9559 9560 /** 9561 * Returns true if application is not found or there was an error. Otherwise it returns 9562 * the hidden state of the package for the given user. 9563 */ 9564 @Override 9565 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 9566 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9567 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 9568 false, "getApplicationHidden for user " + userId); 9569 PackageSetting pkgSetting; 9570 long callingId = Binder.clearCallingIdentity(); 9571 try { 9572 // writer 9573 synchronized (mPackages) { 9574 pkgSetting = mSettings.mPackages.get(packageName); 9575 if (pkgSetting == null) { 9576 return true; 9577 } 9578 return pkgSetting.getHidden(userId); 9579 } 9580 } finally { 9581 Binder.restoreCallingIdentity(callingId); 9582 } 9583 } 9584 9585 /** 9586 * @hide 9587 */ 9588 @Override 9589 public int installExistingPackageAsUser(String packageName, int userId) { 9590 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 9591 null); 9592 PackageSetting pkgSetting; 9593 final int uid = Binder.getCallingUid(); 9594 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 9595 + userId); 9596 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9597 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 9598 } 9599 9600 long callingId = Binder.clearCallingIdentity(); 9601 try { 9602 boolean sendAdded = false; 9603 9604 // writer 9605 synchronized (mPackages) { 9606 pkgSetting = mSettings.mPackages.get(packageName); 9607 if (pkgSetting == null) { 9608 return PackageManager.INSTALL_FAILED_INVALID_URI; 9609 } 9610 if (!pkgSetting.getInstalled(userId)) { 9611 pkgSetting.setInstalled(true, userId); 9612 pkgSetting.setHidden(false, userId); 9613 mSettings.writePackageRestrictionsLPr(userId); 9614 sendAdded = true; 9615 } 9616 } 9617 9618 if (sendAdded) { 9619 sendPackageAddedForUser(packageName, pkgSetting, userId); 9620 } 9621 } finally { 9622 Binder.restoreCallingIdentity(callingId); 9623 } 9624 9625 return PackageManager.INSTALL_SUCCEEDED; 9626 } 9627 9628 boolean isUserRestricted(int userId, String restrictionKey) { 9629 Bundle restrictions = sUserManager.getUserRestrictions(userId); 9630 if (restrictions.getBoolean(restrictionKey, false)) { 9631 Log.w(TAG, "User is restricted: " + restrictionKey); 9632 return true; 9633 } 9634 return false; 9635 } 9636 9637 @Override 9638 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 9639 mContext.enforceCallingOrSelfPermission( 9640 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9641 "Only package verification agents can verify applications"); 9642 9643 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9644 final PackageVerificationResponse response = new PackageVerificationResponse( 9645 verificationCode, Binder.getCallingUid()); 9646 msg.arg1 = id; 9647 msg.obj = response; 9648 mHandler.sendMessage(msg); 9649 } 9650 9651 @Override 9652 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 9653 long millisecondsToDelay) { 9654 mContext.enforceCallingOrSelfPermission( 9655 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9656 "Only package verification agents can extend verification timeouts"); 9657 9658 final PackageVerificationState state = mPendingVerification.get(id); 9659 final PackageVerificationResponse response = new PackageVerificationResponse( 9660 verificationCodeAtTimeout, Binder.getCallingUid()); 9661 9662 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 9663 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 9664 } 9665 if (millisecondsToDelay < 0) { 9666 millisecondsToDelay = 0; 9667 } 9668 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 9669 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 9670 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 9671 } 9672 9673 if ((state != null) && !state.timeoutExtended()) { 9674 state.extendTimeout(); 9675 9676 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9677 msg.arg1 = id; 9678 msg.obj = response; 9679 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 9680 } 9681 } 9682 9683 private void broadcastPackageVerified(int verificationId, Uri packageUri, 9684 int verificationCode, UserHandle user) { 9685 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 9686 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 9687 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9688 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9689 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 9690 9691 mContext.sendBroadcastAsUser(intent, user, 9692 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 9693 } 9694 9695 private ComponentName matchComponentForVerifier(String packageName, 9696 List<ResolveInfo> receivers) { 9697 ActivityInfo targetReceiver = null; 9698 9699 final int NR = receivers.size(); 9700 for (int i = 0; i < NR; i++) { 9701 final ResolveInfo info = receivers.get(i); 9702 if (info.activityInfo == null) { 9703 continue; 9704 } 9705 9706 if (packageName.equals(info.activityInfo.packageName)) { 9707 targetReceiver = info.activityInfo; 9708 break; 9709 } 9710 } 9711 9712 if (targetReceiver == null) { 9713 return null; 9714 } 9715 9716 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 9717 } 9718 9719 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 9720 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 9721 if (pkgInfo.verifiers.length == 0) { 9722 return null; 9723 } 9724 9725 final int N = pkgInfo.verifiers.length; 9726 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 9727 for (int i = 0; i < N; i++) { 9728 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 9729 9730 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 9731 receivers); 9732 if (comp == null) { 9733 continue; 9734 } 9735 9736 final int verifierUid = getUidForVerifier(verifierInfo); 9737 if (verifierUid == -1) { 9738 continue; 9739 } 9740 9741 if (DEBUG_VERIFY) { 9742 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 9743 + " with the correct signature"); 9744 } 9745 sufficientVerifiers.add(comp); 9746 verificationState.addSufficientVerifier(verifierUid); 9747 } 9748 9749 return sufficientVerifiers; 9750 } 9751 9752 private int getUidForVerifier(VerifierInfo verifierInfo) { 9753 synchronized (mPackages) { 9754 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 9755 if (pkg == null) { 9756 return -1; 9757 } else if (pkg.mSignatures.length != 1) { 9758 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9759 + " has more than one signature; ignoring"); 9760 return -1; 9761 } 9762 9763 /* 9764 * If the public key of the package's signature does not match 9765 * our expected public key, then this is a different package and 9766 * we should skip. 9767 */ 9768 9769 final byte[] expectedPublicKey; 9770 try { 9771 final Signature verifierSig = pkg.mSignatures[0]; 9772 final PublicKey publicKey = verifierSig.getPublicKey(); 9773 expectedPublicKey = publicKey.getEncoded(); 9774 } catch (CertificateException e) { 9775 return -1; 9776 } 9777 9778 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 9779 9780 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 9781 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9782 + " does not have the expected public key; ignoring"); 9783 return -1; 9784 } 9785 9786 return pkg.applicationInfo.uid; 9787 } 9788 } 9789 9790 @Override 9791 public void finishPackageInstall(int token) { 9792 enforceSystemOrRoot("Only the system is allowed to finish installs"); 9793 9794 if (DEBUG_INSTALL) { 9795 Slog.v(TAG, "BM finishing package install for " + token); 9796 } 9797 9798 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9799 mHandler.sendMessage(msg); 9800 } 9801 9802 /** 9803 * Get the verification agent timeout. 9804 * 9805 * @return verification timeout in milliseconds 9806 */ 9807 private long getVerificationTimeout() { 9808 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 9809 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 9810 DEFAULT_VERIFICATION_TIMEOUT); 9811 } 9812 9813 /** 9814 * Get the default verification agent response code. 9815 * 9816 * @return default verification response code 9817 */ 9818 private int getDefaultVerificationResponse() { 9819 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9820 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 9821 DEFAULT_VERIFICATION_RESPONSE); 9822 } 9823 9824 /** 9825 * Check whether or not package verification has been enabled. 9826 * 9827 * @return true if verification should be performed 9828 */ 9829 private boolean isVerificationEnabled(int userId, int installFlags) { 9830 if (!DEFAULT_VERIFY_ENABLE) { 9831 return false; 9832 } 9833 9834 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 9835 9836 // Check if installing from ADB 9837 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 9838 // Do not run verification in a test harness environment 9839 if (ActivityManager.isRunningInTestHarness()) { 9840 return false; 9841 } 9842 if (ensureVerifyAppsEnabled) { 9843 return true; 9844 } 9845 // Check if the developer does not want package verification for ADB installs 9846 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9847 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 9848 return false; 9849 } 9850 } 9851 9852 if (ensureVerifyAppsEnabled) { 9853 return true; 9854 } 9855 9856 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9857 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 9858 } 9859 9860 @Override 9861 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 9862 throws RemoteException { 9863 mContext.enforceCallingOrSelfPermission( 9864 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 9865 "Only intentfilter verification agents can verify applications"); 9866 9867 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 9868 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 9869 Binder.getCallingUid(), verificationCode, failedDomains); 9870 msg.arg1 = id; 9871 msg.obj = response; 9872 mHandler.sendMessage(msg); 9873 } 9874 9875 @Override 9876 public int getIntentVerificationStatus(String packageName, int userId) { 9877 synchronized (mPackages) { 9878 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 9879 } 9880 } 9881 9882 @Override 9883 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 9884 mContext.enforceCallingOrSelfPermission( 9885 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 9886 9887 boolean result = false; 9888 synchronized (mPackages) { 9889 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 9890 } 9891 if (result) { 9892 scheduleWritePackageRestrictionsLocked(userId); 9893 } 9894 return result; 9895 } 9896 9897 @Override 9898 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 9899 synchronized (mPackages) { 9900 return mSettings.getIntentFilterVerificationsLPr(packageName); 9901 } 9902 } 9903 9904 @Override 9905 public List<IntentFilter> getAllIntentFilters(String packageName) { 9906 if (TextUtils.isEmpty(packageName)) { 9907 return Collections.<IntentFilter>emptyList(); 9908 } 9909 synchronized (mPackages) { 9910 PackageParser.Package pkg = mPackages.get(packageName); 9911 if (pkg == null || pkg.activities == null) { 9912 return Collections.<IntentFilter>emptyList(); 9913 } 9914 final int count = pkg.activities.size(); 9915 ArrayList<IntentFilter> result = new ArrayList<>(); 9916 for (int n=0; n<count; n++) { 9917 PackageParser.Activity activity = pkg.activities.get(n); 9918 if (activity.intents != null || activity.intents.size() > 0) { 9919 result.addAll(activity.intents); 9920 } 9921 } 9922 return result; 9923 } 9924 } 9925 9926 @Override 9927 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 9928 mContext.enforceCallingOrSelfPermission( 9929 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 9930 9931 synchronized (mPackages) { 9932 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 9933 if (packageName != null) { 9934 result |= updateIntentVerificationStatus(packageName, 9935 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 9936 UserHandle.myUserId()); 9937 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 9938 packageName, userId); 9939 } 9940 return result; 9941 } 9942 } 9943 9944 @Override 9945 public String getDefaultBrowserPackageName(int userId) { 9946 synchronized (mPackages) { 9947 return mSettings.getDefaultBrowserPackageNameLPw(userId); 9948 } 9949 } 9950 9951 /** 9952 * Get the "allow unknown sources" setting. 9953 * 9954 * @return the current "allow unknown sources" setting 9955 */ 9956 private int getUnknownSourcesSettings() { 9957 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9958 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 9959 -1); 9960 } 9961 9962 @Override 9963 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 9964 final int uid = Binder.getCallingUid(); 9965 // writer 9966 synchronized (mPackages) { 9967 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 9968 if (targetPackageSetting == null) { 9969 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 9970 } 9971 9972 PackageSetting installerPackageSetting; 9973 if (installerPackageName != null) { 9974 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 9975 if (installerPackageSetting == null) { 9976 throw new IllegalArgumentException("Unknown installer package: " 9977 + installerPackageName); 9978 } 9979 } else { 9980 installerPackageSetting = null; 9981 } 9982 9983 Signature[] callerSignature; 9984 Object obj = mSettings.getUserIdLPr(uid); 9985 if (obj != null) { 9986 if (obj instanceof SharedUserSetting) { 9987 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 9988 } else if (obj instanceof PackageSetting) { 9989 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 9990 } else { 9991 throw new SecurityException("Bad object " + obj + " for uid " + uid); 9992 } 9993 } else { 9994 throw new SecurityException("Unknown calling uid " + uid); 9995 } 9996 9997 // Verify: can't set installerPackageName to a package that is 9998 // not signed with the same cert as the caller. 9999 if (installerPackageSetting != null) { 10000 if (compareSignatures(callerSignature, 10001 installerPackageSetting.signatures.mSignatures) 10002 != PackageManager.SIGNATURE_MATCH) { 10003 throw new SecurityException( 10004 "Caller does not have same cert as new installer package " 10005 + installerPackageName); 10006 } 10007 } 10008 10009 // Verify: if target already has an installer package, it must 10010 // be signed with the same cert as the caller. 10011 if (targetPackageSetting.installerPackageName != null) { 10012 PackageSetting setting = mSettings.mPackages.get( 10013 targetPackageSetting.installerPackageName); 10014 // If the currently set package isn't valid, then it's always 10015 // okay to change it. 10016 if (setting != null) { 10017 if (compareSignatures(callerSignature, 10018 setting.signatures.mSignatures) 10019 != PackageManager.SIGNATURE_MATCH) { 10020 throw new SecurityException( 10021 "Caller does not have same cert as old installer package " 10022 + targetPackageSetting.installerPackageName); 10023 } 10024 } 10025 } 10026 10027 // Okay! 10028 targetPackageSetting.installerPackageName = installerPackageName; 10029 scheduleWriteSettingsLocked(); 10030 } 10031 } 10032 10033 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 10034 // Queue up an async operation since the package installation may take a little while. 10035 mHandler.post(new Runnable() { 10036 public void run() { 10037 mHandler.removeCallbacks(this); 10038 // Result object to be returned 10039 PackageInstalledInfo res = new PackageInstalledInfo(); 10040 res.returnCode = currentStatus; 10041 res.uid = -1; 10042 res.pkg = null; 10043 res.removedInfo = new PackageRemovedInfo(); 10044 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10045 args.doPreInstall(res.returnCode); 10046 synchronized (mInstallLock) { 10047 installPackageLI(args, res); 10048 } 10049 args.doPostInstall(res.returnCode, res.uid); 10050 } 10051 10052 // A restore should be performed at this point if (a) the install 10053 // succeeded, (b) the operation is not an update, and (c) the new 10054 // package has not opted out of backup participation. 10055 final boolean update = res.removedInfo.removedPackage != null; 10056 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 10057 boolean doRestore = !update 10058 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 10059 10060 // Set up the post-install work request bookkeeping. This will be used 10061 // and cleaned up by the post-install event handling regardless of whether 10062 // there's a restore pass performed. Token values are >= 1. 10063 int token; 10064 if (mNextInstallToken < 0) mNextInstallToken = 1; 10065 token = mNextInstallToken++; 10066 10067 PostInstallData data = new PostInstallData(args, res); 10068 mRunningInstalls.put(token, data); 10069 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 10070 10071 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 10072 // Pass responsibility to the Backup Manager. It will perform a 10073 // restore if appropriate, then pass responsibility back to the 10074 // Package Manager to run the post-install observer callbacks 10075 // and broadcasts. 10076 IBackupManager bm = IBackupManager.Stub.asInterface( 10077 ServiceManager.getService(Context.BACKUP_SERVICE)); 10078 if (bm != null) { 10079 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 10080 + " to BM for possible restore"); 10081 try { 10082 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 10083 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 10084 } else { 10085 doRestore = false; 10086 } 10087 } catch (RemoteException e) { 10088 // can't happen; the backup manager is local 10089 } catch (Exception e) { 10090 Slog.e(TAG, "Exception trying to enqueue restore", e); 10091 doRestore = false; 10092 } 10093 } else { 10094 Slog.e(TAG, "Backup Manager not found!"); 10095 doRestore = false; 10096 } 10097 } 10098 10099 if (!doRestore) { 10100 // No restore possible, or the Backup Manager was mysteriously not 10101 // available -- just fire the post-install work request directly. 10102 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 10103 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10104 mHandler.sendMessage(msg); 10105 } 10106 } 10107 }); 10108 } 10109 10110 private abstract class HandlerParams { 10111 private static final int MAX_RETRIES = 4; 10112 10113 /** 10114 * Number of times startCopy() has been attempted and had a non-fatal 10115 * error. 10116 */ 10117 private int mRetries = 0; 10118 10119 /** User handle for the user requesting the information or installation. */ 10120 private final UserHandle mUser; 10121 10122 HandlerParams(UserHandle user) { 10123 mUser = user; 10124 } 10125 10126 UserHandle getUser() { 10127 return mUser; 10128 } 10129 10130 final boolean startCopy() { 10131 boolean res; 10132 try { 10133 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 10134 10135 if (++mRetries > MAX_RETRIES) { 10136 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 10137 mHandler.sendEmptyMessage(MCS_GIVE_UP); 10138 handleServiceError(); 10139 return false; 10140 } else { 10141 handleStartCopy(); 10142 res = true; 10143 } 10144 } catch (RemoteException e) { 10145 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 10146 mHandler.sendEmptyMessage(MCS_RECONNECT); 10147 res = false; 10148 } 10149 handleReturnCode(); 10150 return res; 10151 } 10152 10153 final void serviceError() { 10154 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 10155 handleServiceError(); 10156 handleReturnCode(); 10157 } 10158 10159 abstract void handleStartCopy() throws RemoteException; 10160 abstract void handleServiceError(); 10161 abstract void handleReturnCode(); 10162 } 10163 10164 class MeasureParams extends HandlerParams { 10165 private final PackageStats mStats; 10166 private boolean mSuccess; 10167 10168 private final IPackageStatsObserver mObserver; 10169 10170 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 10171 super(new UserHandle(stats.userHandle)); 10172 mObserver = observer; 10173 mStats = stats; 10174 } 10175 10176 @Override 10177 public String toString() { 10178 return "MeasureParams{" 10179 + Integer.toHexString(System.identityHashCode(this)) 10180 + " " + mStats.packageName + "}"; 10181 } 10182 10183 @Override 10184 void handleStartCopy() throws RemoteException { 10185 synchronized (mInstallLock) { 10186 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 10187 } 10188 10189 if (mSuccess) { 10190 final boolean mounted; 10191 if (Environment.isExternalStorageEmulated()) { 10192 mounted = true; 10193 } else { 10194 final String status = Environment.getExternalStorageState(); 10195 mounted = (Environment.MEDIA_MOUNTED.equals(status) 10196 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 10197 } 10198 10199 if (mounted) { 10200 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 10201 10202 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 10203 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 10204 10205 mStats.externalDataSize = calculateDirectorySize(mContainerService, 10206 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 10207 10208 // Always subtract cache size, since it's a subdirectory 10209 mStats.externalDataSize -= mStats.externalCacheSize; 10210 10211 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 10212 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 10213 10214 mStats.externalObbSize = calculateDirectorySize(mContainerService, 10215 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 10216 } 10217 } 10218 } 10219 10220 @Override 10221 void handleReturnCode() { 10222 if (mObserver != null) { 10223 try { 10224 mObserver.onGetStatsCompleted(mStats, mSuccess); 10225 } catch (RemoteException e) { 10226 Slog.i(TAG, "Observer no longer exists."); 10227 } 10228 } 10229 } 10230 10231 @Override 10232 void handleServiceError() { 10233 Slog.e(TAG, "Could not measure application " + mStats.packageName 10234 + " external storage"); 10235 } 10236 } 10237 10238 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 10239 throws RemoteException { 10240 long result = 0; 10241 for (File path : paths) { 10242 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 10243 } 10244 return result; 10245 } 10246 10247 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 10248 for (File path : paths) { 10249 try { 10250 mcs.clearDirectory(path.getAbsolutePath()); 10251 } catch (RemoteException e) { 10252 } 10253 } 10254 } 10255 10256 static class OriginInfo { 10257 /** 10258 * Location where install is coming from, before it has been 10259 * copied/renamed into place. This could be a single monolithic APK 10260 * file, or a cluster directory. This location may be untrusted. 10261 */ 10262 final File file; 10263 final String cid; 10264 10265 /** 10266 * Flag indicating that {@link #file} or {@link #cid} has already been 10267 * staged, meaning downstream users don't need to defensively copy the 10268 * contents. 10269 */ 10270 final boolean staged; 10271 10272 /** 10273 * Flag indicating that {@link #file} or {@link #cid} is an already 10274 * installed app that is being moved. 10275 */ 10276 final boolean existing; 10277 10278 final String resolvedPath; 10279 final File resolvedFile; 10280 10281 static OriginInfo fromNothing() { 10282 return new OriginInfo(null, null, false, false); 10283 } 10284 10285 static OriginInfo fromUntrustedFile(File file) { 10286 return new OriginInfo(file, null, false, false); 10287 } 10288 10289 static OriginInfo fromExistingFile(File file) { 10290 return new OriginInfo(file, null, false, true); 10291 } 10292 10293 static OriginInfo fromStagedFile(File file) { 10294 return new OriginInfo(file, null, true, false); 10295 } 10296 10297 static OriginInfo fromStagedContainer(String cid) { 10298 return new OriginInfo(null, cid, true, false); 10299 } 10300 10301 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 10302 this.file = file; 10303 this.cid = cid; 10304 this.staged = staged; 10305 this.existing = existing; 10306 10307 if (cid != null) { 10308 resolvedPath = PackageHelper.getSdDir(cid); 10309 resolvedFile = new File(resolvedPath); 10310 } else if (file != null) { 10311 resolvedPath = file.getAbsolutePath(); 10312 resolvedFile = file; 10313 } else { 10314 resolvedPath = null; 10315 resolvedFile = null; 10316 } 10317 } 10318 } 10319 10320 class MoveInfo { 10321 final int moveId; 10322 final String fromUuid; 10323 final String toUuid; 10324 final String packageName; 10325 final String dataAppName; 10326 final int appId; 10327 final String seinfo; 10328 10329 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 10330 String dataAppName, int appId, String seinfo) { 10331 this.moveId = moveId; 10332 this.fromUuid = fromUuid; 10333 this.toUuid = toUuid; 10334 this.packageName = packageName; 10335 this.dataAppName = dataAppName; 10336 this.appId = appId; 10337 this.seinfo = seinfo; 10338 } 10339 } 10340 10341 class InstallParams extends HandlerParams { 10342 final OriginInfo origin; 10343 final MoveInfo move; 10344 final IPackageInstallObserver2 observer; 10345 int installFlags; 10346 final String installerPackageName; 10347 final String volumeUuid; 10348 final VerificationParams verificationParams; 10349 private InstallArgs mArgs; 10350 private int mRet; 10351 final String packageAbiOverride; 10352 10353 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10354 int installFlags, String installerPackageName, String volumeUuid, 10355 VerificationParams verificationParams, UserHandle user, String packageAbiOverride) { 10356 super(user); 10357 this.origin = origin; 10358 this.move = move; 10359 this.observer = observer; 10360 this.installFlags = installFlags; 10361 this.installerPackageName = installerPackageName; 10362 this.volumeUuid = volumeUuid; 10363 this.verificationParams = verificationParams; 10364 this.packageAbiOverride = packageAbiOverride; 10365 } 10366 10367 @Override 10368 public String toString() { 10369 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 10370 + " file=" + origin.file + " cid=" + origin.cid + "}"; 10371 } 10372 10373 public ManifestDigest getManifestDigest() { 10374 if (verificationParams == null) { 10375 return null; 10376 } 10377 return verificationParams.getManifestDigest(); 10378 } 10379 10380 private int installLocationPolicy(PackageInfoLite pkgLite) { 10381 String packageName = pkgLite.packageName; 10382 int installLocation = pkgLite.installLocation; 10383 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10384 // reader 10385 synchronized (mPackages) { 10386 PackageParser.Package pkg = mPackages.get(packageName); 10387 if (pkg != null) { 10388 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10389 // Check for downgrading. 10390 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 10391 try { 10392 checkDowngrade(pkg, pkgLite); 10393 } catch (PackageManagerException e) { 10394 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 10395 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 10396 } 10397 } 10398 // Check for updated system application. 10399 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10400 if (onSd) { 10401 Slog.w(TAG, "Cannot install update to system app on sdcard"); 10402 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 10403 } 10404 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10405 } else { 10406 if (onSd) { 10407 // Install flag overrides everything. 10408 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10409 } 10410 // If current upgrade specifies particular preference 10411 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 10412 // Application explicitly specified internal. 10413 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10414 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 10415 // App explictly prefers external. Let policy decide 10416 } else { 10417 // Prefer previous location 10418 if (isExternal(pkg)) { 10419 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10420 } 10421 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10422 } 10423 } 10424 } else { 10425 // Invalid install. Return error code 10426 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 10427 } 10428 } 10429 } 10430 // All the special cases have been taken care of. 10431 // Return result based on recommended install location. 10432 if (onSd) { 10433 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10434 } 10435 return pkgLite.recommendedInstallLocation; 10436 } 10437 10438 /* 10439 * Invoke remote method to get package information and install 10440 * location values. Override install location based on default 10441 * policy if needed and then create install arguments based 10442 * on the install location. 10443 */ 10444 public void handleStartCopy() throws RemoteException { 10445 int ret = PackageManager.INSTALL_SUCCEEDED; 10446 10447 // If we're already staged, we've firmly committed to an install location 10448 if (origin.staged) { 10449 if (origin.file != null) { 10450 installFlags |= PackageManager.INSTALL_INTERNAL; 10451 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10452 } else if (origin.cid != null) { 10453 installFlags |= PackageManager.INSTALL_EXTERNAL; 10454 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10455 } else { 10456 throw new IllegalStateException("Invalid stage location"); 10457 } 10458 } 10459 10460 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10461 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 10462 10463 PackageInfoLite pkgLite = null; 10464 10465 if (onInt && onSd) { 10466 // Check if both bits are set. 10467 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 10468 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10469 } else { 10470 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 10471 packageAbiOverride); 10472 10473 /* 10474 * If we have too little free space, try to free cache 10475 * before giving up. 10476 */ 10477 if (!origin.staged && pkgLite.recommendedInstallLocation 10478 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10479 // TODO: focus freeing disk space on the target device 10480 final StorageManager storage = StorageManager.from(mContext); 10481 final long lowThreshold = storage.getStorageLowBytes( 10482 Environment.getDataDirectory()); 10483 10484 final long sizeBytes = mContainerService.calculateInstalledSize( 10485 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 10486 10487 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 10488 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 10489 installFlags, packageAbiOverride); 10490 } 10491 10492 /* 10493 * The cache free must have deleted the file we 10494 * downloaded to install. 10495 * 10496 * TODO: fix the "freeCache" call to not delete 10497 * the file we care about. 10498 */ 10499 if (pkgLite.recommendedInstallLocation 10500 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10501 pkgLite.recommendedInstallLocation 10502 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 10503 } 10504 } 10505 } 10506 10507 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10508 int loc = pkgLite.recommendedInstallLocation; 10509 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 10510 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10511 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 10512 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 10513 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10514 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10515 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 10516 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 10517 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10518 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 10519 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 10520 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 10521 } else { 10522 // Override with defaults if needed. 10523 loc = installLocationPolicy(pkgLite); 10524 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 10525 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 10526 } else if (!onSd && !onInt) { 10527 // Override install location with flags 10528 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 10529 // Set the flag to install on external media. 10530 installFlags |= PackageManager.INSTALL_EXTERNAL; 10531 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10532 } else { 10533 // Make sure the flag for installing on external 10534 // media is unset 10535 installFlags |= PackageManager.INSTALL_INTERNAL; 10536 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10537 } 10538 } 10539 } 10540 } 10541 10542 final InstallArgs args = createInstallArgs(this); 10543 mArgs = args; 10544 10545 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10546 /* 10547 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 10548 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 10549 */ 10550 int userIdentifier = getUser().getIdentifier(); 10551 if (userIdentifier == UserHandle.USER_ALL 10552 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 10553 userIdentifier = UserHandle.USER_OWNER; 10554 } 10555 10556 /* 10557 * Determine if we have any installed package verifiers. If we 10558 * do, then we'll defer to them to verify the packages. 10559 */ 10560 final int requiredUid = mRequiredVerifierPackage == null ? -1 10561 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 10562 if (!origin.existing && requiredUid != -1 10563 && isVerificationEnabled(userIdentifier, installFlags)) { 10564 final Intent verification = new Intent( 10565 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 10566 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 10567 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 10568 PACKAGE_MIME_TYPE); 10569 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10570 10571 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 10572 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 10573 0 /* TODO: Which userId? */); 10574 10575 if (DEBUG_VERIFY) { 10576 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 10577 + verification.toString() + " with " + pkgLite.verifiers.length 10578 + " optional verifiers"); 10579 } 10580 10581 final int verificationId = mPendingVerificationToken++; 10582 10583 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10584 10585 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 10586 installerPackageName); 10587 10588 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 10589 installFlags); 10590 10591 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 10592 pkgLite.packageName); 10593 10594 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 10595 pkgLite.versionCode); 10596 10597 if (verificationParams != null) { 10598 if (verificationParams.getVerificationURI() != null) { 10599 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 10600 verificationParams.getVerificationURI()); 10601 } 10602 if (verificationParams.getOriginatingURI() != null) { 10603 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 10604 verificationParams.getOriginatingURI()); 10605 } 10606 if (verificationParams.getReferrer() != null) { 10607 verification.putExtra(Intent.EXTRA_REFERRER, 10608 verificationParams.getReferrer()); 10609 } 10610 if (verificationParams.getOriginatingUid() >= 0) { 10611 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 10612 verificationParams.getOriginatingUid()); 10613 } 10614 if (verificationParams.getInstallerUid() >= 0) { 10615 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 10616 verificationParams.getInstallerUid()); 10617 } 10618 } 10619 10620 final PackageVerificationState verificationState = new PackageVerificationState( 10621 requiredUid, args); 10622 10623 mPendingVerification.append(verificationId, verificationState); 10624 10625 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 10626 receivers, verificationState); 10627 10628 /* 10629 * If any sufficient verifiers were listed in the package 10630 * manifest, attempt to ask them. 10631 */ 10632 if (sufficientVerifiers != null) { 10633 final int N = sufficientVerifiers.size(); 10634 if (N == 0) { 10635 Slog.i(TAG, "Additional verifiers required, but none installed."); 10636 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 10637 } else { 10638 for (int i = 0; i < N; i++) { 10639 final ComponentName verifierComponent = sufficientVerifiers.get(i); 10640 10641 final Intent sufficientIntent = new Intent(verification); 10642 sufficientIntent.setComponent(verifierComponent); 10643 10644 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 10645 } 10646 } 10647 } 10648 10649 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 10650 mRequiredVerifierPackage, receivers); 10651 if (ret == PackageManager.INSTALL_SUCCEEDED 10652 && mRequiredVerifierPackage != null) { 10653 /* 10654 * Send the intent to the required verification agent, 10655 * but only start the verification timeout after the 10656 * target BroadcastReceivers have run. 10657 */ 10658 verification.setComponent(requiredVerifierComponent); 10659 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 10660 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10661 new BroadcastReceiver() { 10662 @Override 10663 public void onReceive(Context context, Intent intent) { 10664 final Message msg = mHandler 10665 .obtainMessage(CHECK_PENDING_VERIFICATION); 10666 msg.arg1 = verificationId; 10667 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 10668 } 10669 }, null, 0, null, null); 10670 10671 /* 10672 * We don't want the copy to proceed until verification 10673 * succeeds, so null out this field. 10674 */ 10675 mArgs = null; 10676 } 10677 } else { 10678 /* 10679 * No package verification is enabled, so immediately start 10680 * the remote call to initiate copy using temporary file. 10681 */ 10682 ret = args.copyApk(mContainerService, true); 10683 } 10684 } 10685 10686 mRet = ret; 10687 } 10688 10689 @Override 10690 void handleReturnCode() { 10691 // If mArgs is null, then MCS couldn't be reached. When it 10692 // reconnects, it will try again to install. At that point, this 10693 // will succeed. 10694 if (mArgs != null) { 10695 processPendingInstall(mArgs, mRet); 10696 } 10697 } 10698 10699 @Override 10700 void handleServiceError() { 10701 mArgs = createInstallArgs(this); 10702 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10703 } 10704 10705 public boolean isForwardLocked() { 10706 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10707 } 10708 } 10709 10710 /** 10711 * Used during creation of InstallArgs 10712 * 10713 * @param installFlags package installation flags 10714 * @return true if should be installed on external storage 10715 */ 10716 private static boolean installOnExternalAsec(int installFlags) { 10717 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 10718 return false; 10719 } 10720 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 10721 return true; 10722 } 10723 return false; 10724 } 10725 10726 /** 10727 * Used during creation of InstallArgs 10728 * 10729 * @param installFlags package installation flags 10730 * @return true if should be installed as forward locked 10731 */ 10732 private static boolean installForwardLocked(int installFlags) { 10733 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10734 } 10735 10736 private InstallArgs createInstallArgs(InstallParams params) { 10737 if (params.move != null) { 10738 return new MoveInstallArgs(params); 10739 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 10740 return new AsecInstallArgs(params); 10741 } else { 10742 return new FileInstallArgs(params); 10743 } 10744 } 10745 10746 /** 10747 * Create args that describe an existing installed package. Typically used 10748 * when cleaning up old installs, or used as a move source. 10749 */ 10750 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 10751 String resourcePath, String[] instructionSets) { 10752 final boolean isInAsec; 10753 if (installOnExternalAsec(installFlags)) { 10754 /* Apps on SD card are always in ASEC containers. */ 10755 isInAsec = true; 10756 } else if (installForwardLocked(installFlags) 10757 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 10758 /* 10759 * Forward-locked apps are only in ASEC containers if they're the 10760 * new style 10761 */ 10762 isInAsec = true; 10763 } else { 10764 isInAsec = false; 10765 } 10766 10767 if (isInAsec) { 10768 return new AsecInstallArgs(codePath, instructionSets, 10769 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 10770 } else { 10771 return new FileInstallArgs(codePath, resourcePath, instructionSets); 10772 } 10773 } 10774 10775 static abstract class InstallArgs { 10776 /** @see InstallParams#origin */ 10777 final OriginInfo origin; 10778 /** @see InstallParams#move */ 10779 final MoveInfo move; 10780 10781 final IPackageInstallObserver2 observer; 10782 // Always refers to PackageManager flags only 10783 final int installFlags; 10784 final String installerPackageName; 10785 final String volumeUuid; 10786 final ManifestDigest manifestDigest; 10787 final UserHandle user; 10788 final String abiOverride; 10789 10790 // The list of instruction sets supported by this app. This is currently 10791 // only used during the rmdex() phase to clean up resources. We can get rid of this 10792 // if we move dex files under the common app path. 10793 /* nullable */ String[] instructionSets; 10794 10795 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10796 int installFlags, String installerPackageName, String volumeUuid, 10797 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 10798 String abiOverride) { 10799 this.origin = origin; 10800 this.move = move; 10801 this.installFlags = installFlags; 10802 this.observer = observer; 10803 this.installerPackageName = installerPackageName; 10804 this.volumeUuid = volumeUuid; 10805 this.manifestDigest = manifestDigest; 10806 this.user = user; 10807 this.instructionSets = instructionSets; 10808 this.abiOverride = abiOverride; 10809 } 10810 10811 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 10812 abstract int doPreInstall(int status); 10813 10814 /** 10815 * Rename package into final resting place. All paths on the given 10816 * scanned package should be updated to reflect the rename. 10817 */ 10818 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 10819 abstract int doPostInstall(int status, int uid); 10820 10821 /** @see PackageSettingBase#codePathString */ 10822 abstract String getCodePath(); 10823 /** @see PackageSettingBase#resourcePathString */ 10824 abstract String getResourcePath(); 10825 10826 // Need installer lock especially for dex file removal. 10827 abstract void cleanUpResourcesLI(); 10828 abstract boolean doPostDeleteLI(boolean delete); 10829 10830 /** 10831 * Called before the source arguments are copied. This is used mostly 10832 * for MoveParams when it needs to read the source file to put it in the 10833 * destination. 10834 */ 10835 int doPreCopy() { 10836 return PackageManager.INSTALL_SUCCEEDED; 10837 } 10838 10839 /** 10840 * Called after the source arguments are copied. This is used mostly for 10841 * MoveParams when it needs to read the source file to put it in the 10842 * destination. 10843 * 10844 * @return 10845 */ 10846 int doPostCopy(int uid) { 10847 return PackageManager.INSTALL_SUCCEEDED; 10848 } 10849 10850 protected boolean isFwdLocked() { 10851 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10852 } 10853 10854 protected boolean isExternalAsec() { 10855 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10856 } 10857 10858 UserHandle getUser() { 10859 return user; 10860 } 10861 } 10862 10863 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 10864 if (!allCodePaths.isEmpty()) { 10865 if (instructionSets == null) { 10866 throw new IllegalStateException("instructionSet == null"); 10867 } 10868 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 10869 for (String codePath : allCodePaths) { 10870 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 10871 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 10872 if (retCode < 0) { 10873 Slog.w(TAG, "Couldn't remove dex file for package: " 10874 + " at location " + codePath + ", retcode=" + retCode); 10875 // we don't consider this to be a failure of the core package deletion 10876 } 10877 } 10878 } 10879 } 10880 } 10881 10882 /** 10883 * Logic to handle installation of non-ASEC applications, including copying 10884 * and renaming logic. 10885 */ 10886 class FileInstallArgs extends InstallArgs { 10887 private File codeFile; 10888 private File resourceFile; 10889 10890 // Example topology: 10891 // /data/app/com.example/base.apk 10892 // /data/app/com.example/split_foo.apk 10893 // /data/app/com.example/lib/arm/libfoo.so 10894 // /data/app/com.example/lib/arm64/libfoo.so 10895 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 10896 10897 /** New install */ 10898 FileInstallArgs(InstallParams params) { 10899 super(params.origin, params.move, params.observer, params.installFlags, 10900 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10901 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10902 if (isFwdLocked()) { 10903 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 10904 } 10905 } 10906 10907 /** Existing install */ 10908 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 10909 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 10910 null); 10911 this.codeFile = (codePath != null) ? new File(codePath) : null; 10912 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 10913 } 10914 10915 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10916 if (origin.staged) { 10917 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 10918 codeFile = origin.file; 10919 resourceFile = origin.file; 10920 return PackageManager.INSTALL_SUCCEEDED; 10921 } 10922 10923 try { 10924 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 10925 codeFile = tempDir; 10926 resourceFile = tempDir; 10927 } catch (IOException e) { 10928 Slog.w(TAG, "Failed to create copy file: " + e); 10929 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10930 } 10931 10932 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 10933 @Override 10934 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 10935 if (!FileUtils.isValidExtFilename(name)) { 10936 throw new IllegalArgumentException("Invalid filename: " + name); 10937 } 10938 try { 10939 final File file = new File(codeFile, name); 10940 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 10941 O_RDWR | O_CREAT, 0644); 10942 Os.chmod(file.getAbsolutePath(), 0644); 10943 return new ParcelFileDescriptor(fd); 10944 } catch (ErrnoException e) { 10945 throw new RemoteException("Failed to open: " + e.getMessage()); 10946 } 10947 } 10948 }; 10949 10950 int ret = PackageManager.INSTALL_SUCCEEDED; 10951 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 10952 if (ret != PackageManager.INSTALL_SUCCEEDED) { 10953 Slog.e(TAG, "Failed to copy package"); 10954 return ret; 10955 } 10956 10957 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 10958 NativeLibraryHelper.Handle handle = null; 10959 try { 10960 handle = NativeLibraryHelper.Handle.create(codeFile); 10961 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 10962 abiOverride); 10963 } catch (IOException e) { 10964 Slog.e(TAG, "Copying native libraries failed", e); 10965 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10966 } finally { 10967 IoUtils.closeQuietly(handle); 10968 } 10969 10970 return ret; 10971 } 10972 10973 int doPreInstall(int status) { 10974 if (status != PackageManager.INSTALL_SUCCEEDED) { 10975 cleanUp(); 10976 } 10977 return status; 10978 } 10979 10980 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10981 if (status != PackageManager.INSTALL_SUCCEEDED) { 10982 cleanUp(); 10983 return false; 10984 } 10985 10986 final File targetDir = codeFile.getParentFile(); 10987 final File beforeCodeFile = codeFile; 10988 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 10989 10990 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 10991 try { 10992 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 10993 } catch (ErrnoException e) { 10994 Slog.w(TAG, "Failed to rename", e); 10995 return false; 10996 } 10997 10998 if (!SELinux.restoreconRecursive(afterCodeFile)) { 10999 Slog.w(TAG, "Failed to restorecon"); 11000 return false; 11001 } 11002 11003 // Reflect the rename internally 11004 codeFile = afterCodeFile; 11005 resourceFile = afterCodeFile; 11006 11007 // Reflect the rename in scanned details 11008 pkg.codePath = afterCodeFile.getAbsolutePath(); 11009 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11010 pkg.baseCodePath); 11011 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11012 pkg.splitCodePaths); 11013 11014 // Reflect the rename in app info 11015 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11016 pkg.applicationInfo.setCodePath(pkg.codePath); 11017 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11018 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11019 pkg.applicationInfo.setResourcePath(pkg.codePath); 11020 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11021 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11022 11023 return true; 11024 } 11025 11026 int doPostInstall(int status, int uid) { 11027 if (status != PackageManager.INSTALL_SUCCEEDED) { 11028 cleanUp(); 11029 } 11030 return status; 11031 } 11032 11033 @Override 11034 String getCodePath() { 11035 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11036 } 11037 11038 @Override 11039 String getResourcePath() { 11040 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11041 } 11042 11043 private boolean cleanUp() { 11044 if (codeFile == null || !codeFile.exists()) { 11045 return false; 11046 } 11047 11048 if (codeFile.isDirectory()) { 11049 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11050 } else { 11051 codeFile.delete(); 11052 } 11053 11054 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 11055 resourceFile.delete(); 11056 } 11057 11058 return true; 11059 } 11060 11061 void cleanUpResourcesLI() { 11062 // Try enumerating all code paths before deleting 11063 List<String> allCodePaths = Collections.EMPTY_LIST; 11064 if (codeFile != null && codeFile.exists()) { 11065 try { 11066 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11067 allCodePaths = pkg.getAllCodePaths(); 11068 } catch (PackageParserException e) { 11069 // Ignored; we tried our best 11070 } 11071 } 11072 11073 cleanUp(); 11074 removeDexFiles(allCodePaths, instructionSets); 11075 } 11076 11077 boolean doPostDeleteLI(boolean delete) { 11078 // XXX err, shouldn't we respect the delete flag? 11079 cleanUpResourcesLI(); 11080 return true; 11081 } 11082 } 11083 11084 private boolean isAsecExternal(String cid) { 11085 final String asecPath = PackageHelper.getSdFilesystem(cid); 11086 return !asecPath.startsWith(mAsecInternalPath); 11087 } 11088 11089 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 11090 PackageManagerException { 11091 if (copyRet < 0) { 11092 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 11093 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 11094 throw new PackageManagerException(copyRet, message); 11095 } 11096 } 11097 } 11098 11099 /** 11100 * Extract the MountService "container ID" from the full code path of an 11101 * .apk. 11102 */ 11103 static String cidFromCodePath(String fullCodePath) { 11104 int eidx = fullCodePath.lastIndexOf("/"); 11105 String subStr1 = fullCodePath.substring(0, eidx); 11106 int sidx = subStr1.lastIndexOf("/"); 11107 return subStr1.substring(sidx+1, eidx); 11108 } 11109 11110 /** 11111 * Logic to handle installation of ASEC applications, including copying and 11112 * renaming logic. 11113 */ 11114 class AsecInstallArgs extends InstallArgs { 11115 static final String RES_FILE_NAME = "pkg.apk"; 11116 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 11117 11118 String cid; 11119 String packagePath; 11120 String resourcePath; 11121 11122 /** New install */ 11123 AsecInstallArgs(InstallParams params) { 11124 super(params.origin, params.move, params.observer, params.installFlags, 11125 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11126 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 11127 } 11128 11129 /** Existing install */ 11130 AsecInstallArgs(String fullCodePath, String[] instructionSets, 11131 boolean isExternal, boolean isForwardLocked) { 11132 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 11133 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11134 instructionSets, null); 11135 // Hackily pretend we're still looking at a full code path 11136 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 11137 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 11138 } 11139 11140 // Extract cid from fullCodePath 11141 int eidx = fullCodePath.lastIndexOf("/"); 11142 String subStr1 = fullCodePath.substring(0, eidx); 11143 int sidx = subStr1.lastIndexOf("/"); 11144 cid = subStr1.substring(sidx+1, eidx); 11145 setMountPath(subStr1); 11146 } 11147 11148 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 11149 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 11150 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11151 instructionSets, null); 11152 this.cid = cid; 11153 setMountPath(PackageHelper.getSdDir(cid)); 11154 } 11155 11156 void createCopyFile() { 11157 cid = mInstallerService.allocateExternalStageCidLegacy(); 11158 } 11159 11160 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11161 if (origin.staged) { 11162 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 11163 cid = origin.cid; 11164 setMountPath(PackageHelper.getSdDir(cid)); 11165 return PackageManager.INSTALL_SUCCEEDED; 11166 } 11167 11168 if (temp) { 11169 createCopyFile(); 11170 } else { 11171 /* 11172 * Pre-emptively destroy the container since it's destroyed if 11173 * copying fails due to it existing anyway. 11174 */ 11175 PackageHelper.destroySdDir(cid); 11176 } 11177 11178 final String newMountPath = imcs.copyPackageToContainer( 11179 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 11180 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 11181 11182 if (newMountPath != null) { 11183 setMountPath(newMountPath); 11184 return PackageManager.INSTALL_SUCCEEDED; 11185 } else { 11186 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11187 } 11188 } 11189 11190 @Override 11191 String getCodePath() { 11192 return packagePath; 11193 } 11194 11195 @Override 11196 String getResourcePath() { 11197 return resourcePath; 11198 } 11199 11200 int doPreInstall(int status) { 11201 if (status != PackageManager.INSTALL_SUCCEEDED) { 11202 // Destroy container 11203 PackageHelper.destroySdDir(cid); 11204 } else { 11205 boolean mounted = PackageHelper.isContainerMounted(cid); 11206 if (!mounted) { 11207 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 11208 Process.SYSTEM_UID); 11209 if (newMountPath != null) { 11210 setMountPath(newMountPath); 11211 } else { 11212 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11213 } 11214 } 11215 } 11216 return status; 11217 } 11218 11219 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11220 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 11221 String newMountPath = null; 11222 if (PackageHelper.isContainerMounted(cid)) { 11223 // Unmount the container 11224 if (!PackageHelper.unMountSdDir(cid)) { 11225 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 11226 return false; 11227 } 11228 } 11229 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11230 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 11231 " which might be stale. Will try to clean up."); 11232 // Clean up the stale container and proceed to recreate. 11233 if (!PackageHelper.destroySdDir(newCacheId)) { 11234 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 11235 return false; 11236 } 11237 // Successfully cleaned up stale container. Try to rename again. 11238 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11239 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 11240 + " inspite of cleaning it up."); 11241 return false; 11242 } 11243 } 11244 if (!PackageHelper.isContainerMounted(newCacheId)) { 11245 Slog.w(TAG, "Mounting container " + newCacheId); 11246 newMountPath = PackageHelper.mountSdDir(newCacheId, 11247 getEncryptKey(), Process.SYSTEM_UID); 11248 } else { 11249 newMountPath = PackageHelper.getSdDir(newCacheId); 11250 } 11251 if (newMountPath == null) { 11252 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 11253 return false; 11254 } 11255 Log.i(TAG, "Succesfully renamed " + cid + 11256 " to " + newCacheId + 11257 " at new path: " + newMountPath); 11258 cid = newCacheId; 11259 11260 final File beforeCodeFile = new File(packagePath); 11261 setMountPath(newMountPath); 11262 final File afterCodeFile = new File(packagePath); 11263 11264 // Reflect the rename in scanned details 11265 pkg.codePath = afterCodeFile.getAbsolutePath(); 11266 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11267 pkg.baseCodePath); 11268 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11269 pkg.splitCodePaths); 11270 11271 // Reflect the rename in app info 11272 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11273 pkg.applicationInfo.setCodePath(pkg.codePath); 11274 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11275 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11276 pkg.applicationInfo.setResourcePath(pkg.codePath); 11277 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11278 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11279 11280 return true; 11281 } 11282 11283 private void setMountPath(String mountPath) { 11284 final File mountFile = new File(mountPath); 11285 11286 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 11287 if (monolithicFile.exists()) { 11288 packagePath = monolithicFile.getAbsolutePath(); 11289 if (isFwdLocked()) { 11290 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 11291 } else { 11292 resourcePath = packagePath; 11293 } 11294 } else { 11295 packagePath = mountFile.getAbsolutePath(); 11296 resourcePath = packagePath; 11297 } 11298 } 11299 11300 int doPostInstall(int status, int uid) { 11301 if (status != PackageManager.INSTALL_SUCCEEDED) { 11302 cleanUp(); 11303 } else { 11304 final int groupOwner; 11305 final String protectedFile; 11306 if (isFwdLocked()) { 11307 groupOwner = UserHandle.getSharedAppGid(uid); 11308 protectedFile = RES_FILE_NAME; 11309 } else { 11310 groupOwner = -1; 11311 protectedFile = null; 11312 } 11313 11314 if (uid < Process.FIRST_APPLICATION_UID 11315 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 11316 Slog.e(TAG, "Failed to finalize " + cid); 11317 PackageHelper.destroySdDir(cid); 11318 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11319 } 11320 11321 boolean mounted = PackageHelper.isContainerMounted(cid); 11322 if (!mounted) { 11323 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 11324 } 11325 } 11326 return status; 11327 } 11328 11329 private void cleanUp() { 11330 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 11331 11332 // Destroy secure container 11333 PackageHelper.destroySdDir(cid); 11334 } 11335 11336 private List<String> getAllCodePaths() { 11337 final File codeFile = new File(getCodePath()); 11338 if (codeFile != null && codeFile.exists()) { 11339 try { 11340 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11341 return pkg.getAllCodePaths(); 11342 } catch (PackageParserException e) { 11343 // Ignored; we tried our best 11344 } 11345 } 11346 return Collections.EMPTY_LIST; 11347 } 11348 11349 void cleanUpResourcesLI() { 11350 // Enumerate all code paths before deleting 11351 cleanUpResourcesLI(getAllCodePaths()); 11352 } 11353 11354 private void cleanUpResourcesLI(List<String> allCodePaths) { 11355 cleanUp(); 11356 removeDexFiles(allCodePaths, instructionSets); 11357 } 11358 11359 String getPackageName() { 11360 return getAsecPackageName(cid); 11361 } 11362 11363 boolean doPostDeleteLI(boolean delete) { 11364 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 11365 final List<String> allCodePaths = getAllCodePaths(); 11366 boolean mounted = PackageHelper.isContainerMounted(cid); 11367 if (mounted) { 11368 // Unmount first 11369 if (PackageHelper.unMountSdDir(cid)) { 11370 mounted = false; 11371 } 11372 } 11373 if (!mounted && delete) { 11374 cleanUpResourcesLI(allCodePaths); 11375 } 11376 return !mounted; 11377 } 11378 11379 @Override 11380 int doPreCopy() { 11381 if (isFwdLocked()) { 11382 if (!PackageHelper.fixSdPermissions(cid, 11383 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 11384 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11385 } 11386 } 11387 11388 return PackageManager.INSTALL_SUCCEEDED; 11389 } 11390 11391 @Override 11392 int doPostCopy(int uid) { 11393 if (isFwdLocked()) { 11394 if (uid < Process.FIRST_APPLICATION_UID 11395 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 11396 RES_FILE_NAME)) { 11397 Slog.e(TAG, "Failed to finalize " + cid); 11398 PackageHelper.destroySdDir(cid); 11399 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11400 } 11401 } 11402 11403 return PackageManager.INSTALL_SUCCEEDED; 11404 } 11405 } 11406 11407 /** 11408 * Logic to handle movement of existing installed applications. 11409 */ 11410 class MoveInstallArgs extends InstallArgs { 11411 private File codeFile; 11412 private File resourceFile; 11413 11414 /** New install */ 11415 MoveInstallArgs(InstallParams params) { 11416 super(params.origin, params.move, params.observer, params.installFlags, 11417 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11418 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 11419 } 11420 11421 int copyApk(IMediaContainerService imcs, boolean temp) { 11422 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 11423 + move.fromUuid + " to " + move.toUuid); 11424 synchronized (mInstaller) { 11425 if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName, 11426 move.dataAppName, move.appId, move.seinfo) != 0) { 11427 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11428 } 11429 } 11430 11431 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 11432 resourceFile = codeFile; 11433 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 11434 11435 return PackageManager.INSTALL_SUCCEEDED; 11436 } 11437 11438 int doPreInstall(int status) { 11439 if (status != PackageManager.INSTALL_SUCCEEDED) { 11440 cleanUp(move.toUuid); 11441 } 11442 return status; 11443 } 11444 11445 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11446 if (status != PackageManager.INSTALL_SUCCEEDED) { 11447 cleanUp(move.toUuid); 11448 return false; 11449 } 11450 11451 // Reflect the move in app info 11452 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11453 pkg.applicationInfo.setCodePath(pkg.codePath); 11454 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11455 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11456 pkg.applicationInfo.setResourcePath(pkg.codePath); 11457 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11458 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11459 11460 return true; 11461 } 11462 11463 int doPostInstall(int status, int uid) { 11464 if (status == PackageManager.INSTALL_SUCCEEDED) { 11465 cleanUp(move.fromUuid); 11466 } else { 11467 cleanUp(move.toUuid); 11468 } 11469 return status; 11470 } 11471 11472 @Override 11473 String getCodePath() { 11474 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11475 } 11476 11477 @Override 11478 String getResourcePath() { 11479 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11480 } 11481 11482 private boolean cleanUp(String volumeUuid) { 11483 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 11484 move.dataAppName); 11485 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 11486 synchronized (mInstallLock) { 11487 // Clean up both app data and code 11488 removeDataDirsLI(volumeUuid, move.packageName); 11489 if (codeFile.isDirectory()) { 11490 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11491 } else { 11492 codeFile.delete(); 11493 } 11494 } 11495 return true; 11496 } 11497 11498 void cleanUpResourcesLI() { 11499 throw new UnsupportedOperationException(); 11500 } 11501 11502 boolean doPostDeleteLI(boolean delete) { 11503 throw new UnsupportedOperationException(); 11504 } 11505 } 11506 11507 static String getAsecPackageName(String packageCid) { 11508 int idx = packageCid.lastIndexOf("-"); 11509 if (idx == -1) { 11510 return packageCid; 11511 } 11512 return packageCid.substring(0, idx); 11513 } 11514 11515 // Utility method used to create code paths based on package name and available index. 11516 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 11517 String idxStr = ""; 11518 int idx = 1; 11519 // Fall back to default value of idx=1 if prefix is not 11520 // part of oldCodePath 11521 if (oldCodePath != null) { 11522 String subStr = oldCodePath; 11523 // Drop the suffix right away 11524 if (suffix != null && subStr.endsWith(suffix)) { 11525 subStr = subStr.substring(0, subStr.length() - suffix.length()); 11526 } 11527 // If oldCodePath already contains prefix find out the 11528 // ending index to either increment or decrement. 11529 int sidx = subStr.lastIndexOf(prefix); 11530 if (sidx != -1) { 11531 subStr = subStr.substring(sidx + prefix.length()); 11532 if (subStr != null) { 11533 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 11534 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 11535 } 11536 try { 11537 idx = Integer.parseInt(subStr); 11538 if (idx <= 1) { 11539 idx++; 11540 } else { 11541 idx--; 11542 } 11543 } catch(NumberFormatException e) { 11544 } 11545 } 11546 } 11547 } 11548 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 11549 return prefix + idxStr; 11550 } 11551 11552 private File getNextCodePath(File targetDir, String packageName) { 11553 int suffix = 1; 11554 File result; 11555 do { 11556 result = new File(targetDir, packageName + "-" + suffix); 11557 suffix++; 11558 } while (result.exists()); 11559 return result; 11560 } 11561 11562 // Utility method that returns the relative package path with respect 11563 // to the installation directory. Like say for /data/data/com.test-1.apk 11564 // string com.test-1 is returned. 11565 static String deriveCodePathName(String codePath) { 11566 if (codePath == null) { 11567 return null; 11568 } 11569 final File codeFile = new File(codePath); 11570 final String name = codeFile.getName(); 11571 if (codeFile.isDirectory()) { 11572 return name; 11573 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 11574 final int lastDot = name.lastIndexOf('.'); 11575 return name.substring(0, lastDot); 11576 } else { 11577 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 11578 return null; 11579 } 11580 } 11581 11582 class PackageInstalledInfo { 11583 String name; 11584 int uid; 11585 // The set of users that originally had this package installed. 11586 int[] origUsers; 11587 // The set of users that now have this package installed. 11588 int[] newUsers; 11589 PackageParser.Package pkg; 11590 int returnCode; 11591 String returnMsg; 11592 PackageRemovedInfo removedInfo; 11593 11594 public void setError(int code, String msg) { 11595 returnCode = code; 11596 returnMsg = msg; 11597 Slog.w(TAG, msg); 11598 } 11599 11600 public void setError(String msg, PackageParserException e) { 11601 returnCode = e.error; 11602 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11603 Slog.w(TAG, msg, e); 11604 } 11605 11606 public void setError(String msg, PackageManagerException e) { 11607 returnCode = e.error; 11608 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11609 Slog.w(TAG, msg, e); 11610 } 11611 11612 // In some error cases we want to convey more info back to the observer 11613 String origPackage; 11614 String origPermission; 11615 } 11616 11617 /* 11618 * Install a non-existing package. 11619 */ 11620 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11621 UserHandle user, String installerPackageName, String volumeUuid, 11622 PackageInstalledInfo res) { 11623 // Remember this for later, in case we need to rollback this install 11624 String pkgName = pkg.packageName; 11625 11626 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 11627 final boolean dataDirExists = Environment 11628 .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists(); 11629 synchronized(mPackages) { 11630 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 11631 // A package with the same name is already installed, though 11632 // it has been renamed to an older name. The package we 11633 // are trying to install should be installed as an update to 11634 // the existing one, but that has not been requested, so bail. 11635 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11636 + " without first uninstalling package running as " 11637 + mSettings.mRenamedPackages.get(pkgName)); 11638 return; 11639 } 11640 if (mPackages.containsKey(pkgName)) { 11641 // Don't allow installation over an existing package with the same name. 11642 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11643 + " without first uninstalling."); 11644 return; 11645 } 11646 } 11647 11648 try { 11649 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 11650 System.currentTimeMillis(), user); 11651 11652 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 11653 // delete the partially installed application. the data directory will have to be 11654 // restored if it was already existing 11655 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11656 // remove package from internal structures. Note that we want deletePackageX to 11657 // delete the package data and cache directories that it created in 11658 // scanPackageLocked, unless those directories existed before we even tried to 11659 // install. 11660 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 11661 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 11662 res.removedInfo, true); 11663 } 11664 11665 } catch (PackageManagerException e) { 11666 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11667 } 11668 } 11669 11670 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 11671 // Can't rotate keys during boot or if sharedUser. 11672 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 11673 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 11674 return false; 11675 } 11676 // app is using upgradeKeySets; make sure all are valid 11677 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11678 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 11679 for (int i = 0; i < upgradeKeySets.length; i++) { 11680 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 11681 Slog.wtf(TAG, "Package " 11682 + (oldPs.name != null ? oldPs.name : "<null>") 11683 + " contains upgrade-key-set reference to unknown key-set: " 11684 + upgradeKeySets[i] 11685 + " reverting to signatures check."); 11686 return false; 11687 } 11688 } 11689 return true; 11690 } 11691 11692 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 11693 // Upgrade keysets are being used. Determine if new package has a superset of the 11694 // required keys. 11695 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 11696 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11697 for (int i = 0; i < upgradeKeySets.length; i++) { 11698 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 11699 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 11700 return true; 11701 } 11702 } 11703 return false; 11704 } 11705 11706 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11707 UserHandle user, String installerPackageName, String volumeUuid, 11708 PackageInstalledInfo res) { 11709 final PackageParser.Package oldPackage; 11710 final String pkgName = pkg.packageName; 11711 final int[] allUsers; 11712 final boolean[] perUserInstalled; 11713 final boolean weFroze; 11714 11715 // First find the old package info and check signatures 11716 synchronized(mPackages) { 11717 oldPackage = mPackages.get(pkgName); 11718 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 11719 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11720 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 11721 if(!checkUpgradeKeySetLP(ps, pkg)) { 11722 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11723 "New package not signed by keys specified by upgrade-keysets: " 11724 + pkgName); 11725 return; 11726 } 11727 } else { 11728 // default to original signature matching 11729 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 11730 != PackageManager.SIGNATURE_MATCH) { 11731 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11732 "New package has a different signature: " + pkgName); 11733 return; 11734 } 11735 } 11736 11737 // In case of rollback, remember per-user/profile install state 11738 allUsers = sUserManager.getUserIds(); 11739 perUserInstalled = new boolean[allUsers.length]; 11740 for (int i = 0; i < allUsers.length; i++) { 11741 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11742 } 11743 11744 // Mark the app as frozen to prevent launching during the upgrade 11745 // process, and then kill all running instances 11746 if (!ps.frozen) { 11747 ps.frozen = true; 11748 weFroze = true; 11749 } else { 11750 weFroze = false; 11751 } 11752 } 11753 11754 // Now that we're guarded by frozen state, kill app during upgrade 11755 killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg"); 11756 11757 try { 11758 boolean sysPkg = (isSystemApp(oldPackage)); 11759 if (sysPkg) { 11760 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11761 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11762 } else { 11763 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11764 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11765 } 11766 } finally { 11767 // Regardless of success or failure of upgrade steps above, always 11768 // unfreeze the package if we froze it 11769 if (weFroze) { 11770 unfreezePackage(pkgName); 11771 } 11772 } 11773 } 11774 11775 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 11776 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11777 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11778 String volumeUuid, PackageInstalledInfo res) { 11779 String pkgName = deletedPackage.packageName; 11780 boolean deletedPkg = true; 11781 boolean updatedSettings = false; 11782 11783 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 11784 + deletedPackage); 11785 long origUpdateTime; 11786 if (pkg.mExtras != null) { 11787 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 11788 } else { 11789 origUpdateTime = 0; 11790 } 11791 11792 // First delete the existing package while retaining the data directory 11793 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 11794 res.removedInfo, true)) { 11795 // If the existing package wasn't successfully deleted 11796 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 11797 deletedPkg = false; 11798 } else { 11799 // Successfully deleted the old package; proceed with replace. 11800 11801 // If deleted package lived in a container, give users a chance to 11802 // relinquish resources before killing. 11803 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 11804 if (DEBUG_INSTALL) { 11805 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 11806 } 11807 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 11808 final ArrayList<String> pkgList = new ArrayList<String>(1); 11809 pkgList.add(deletedPackage.applicationInfo.packageName); 11810 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 11811 } 11812 11813 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 11814 try { 11815 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 11816 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 11817 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11818 perUserInstalled, res, user); 11819 updatedSettings = true; 11820 } catch (PackageManagerException e) { 11821 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11822 } 11823 } 11824 11825 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11826 // remove package from internal structures. Note that we want deletePackageX to 11827 // delete the package data and cache directories that it created in 11828 // scanPackageLocked, unless those directories existed before we even tried to 11829 // install. 11830 if(updatedSettings) { 11831 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 11832 deletePackageLI( 11833 pkgName, null, true, allUsers, perUserInstalled, 11834 PackageManager.DELETE_KEEP_DATA, 11835 res.removedInfo, true); 11836 } 11837 // Since we failed to install the new package we need to restore the old 11838 // package that we deleted. 11839 if (deletedPkg) { 11840 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 11841 File restoreFile = new File(deletedPackage.codePath); 11842 // Parse old package 11843 boolean oldExternal = isExternal(deletedPackage); 11844 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 11845 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 11846 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11847 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 11848 try { 11849 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 11850 } catch (PackageManagerException e) { 11851 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 11852 + e.getMessage()); 11853 return; 11854 } 11855 // Restore of old package succeeded. Update permissions. 11856 // writer 11857 synchronized (mPackages) { 11858 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 11859 UPDATE_PERMISSIONS_ALL); 11860 // can downgrade to reader 11861 mSettings.writeLPr(); 11862 } 11863 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 11864 } 11865 } 11866 } 11867 11868 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 11869 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11870 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11871 String volumeUuid, PackageInstalledInfo res) { 11872 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 11873 + ", old=" + deletedPackage); 11874 boolean disabledSystem = false; 11875 boolean updatedSettings = false; 11876 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 11877 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 11878 != 0) { 11879 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11880 } 11881 String packageName = deletedPackage.packageName; 11882 if (packageName == null) { 11883 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11884 "Attempt to delete null packageName."); 11885 return; 11886 } 11887 PackageParser.Package oldPkg; 11888 PackageSetting oldPkgSetting; 11889 // reader 11890 synchronized (mPackages) { 11891 oldPkg = mPackages.get(packageName); 11892 oldPkgSetting = mSettings.mPackages.get(packageName); 11893 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 11894 (oldPkgSetting == null)) { 11895 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11896 "Couldn't find package:" + packageName + " information"); 11897 return; 11898 } 11899 } 11900 11901 res.removedInfo.uid = oldPkg.applicationInfo.uid; 11902 res.removedInfo.removedPackage = packageName; 11903 // Remove existing system package 11904 removePackageLI(oldPkgSetting, true); 11905 // writer 11906 synchronized (mPackages) { 11907 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 11908 if (!disabledSystem && deletedPackage != null) { 11909 // We didn't need to disable the .apk as a current system package, 11910 // which means we are replacing another update that is already 11911 // installed. We need to make sure to delete the older one's .apk. 11912 res.removedInfo.args = createInstallArgsForExisting(0, 11913 deletedPackage.applicationInfo.getCodePath(), 11914 deletedPackage.applicationInfo.getResourcePath(), 11915 getAppDexInstructionSets(deletedPackage.applicationInfo)); 11916 } else { 11917 res.removedInfo.args = null; 11918 } 11919 } 11920 11921 // Successfully disabled the old package. Now proceed with re-installation 11922 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 11923 11924 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11925 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 11926 11927 PackageParser.Package newPackage = null; 11928 try { 11929 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 11930 if (newPackage.mExtras != null) { 11931 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 11932 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 11933 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 11934 11935 // is the update attempting to change shared user? that isn't going to work... 11936 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 11937 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 11938 "Forbidding shared user change from " + oldPkgSetting.sharedUser 11939 + " to " + newPkgSetting.sharedUser); 11940 updatedSettings = true; 11941 } 11942 } 11943 11944 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11945 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11946 perUserInstalled, res, user); 11947 updatedSettings = true; 11948 } 11949 11950 } catch (PackageManagerException e) { 11951 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11952 } 11953 11954 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11955 // Re installation failed. Restore old information 11956 // Remove new pkg information 11957 if (newPackage != null) { 11958 removeInstalledPackageLI(newPackage, true); 11959 } 11960 // Add back the old system package 11961 try { 11962 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 11963 } catch (PackageManagerException e) { 11964 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 11965 } 11966 // Restore the old system information in Settings 11967 synchronized (mPackages) { 11968 if (disabledSystem) { 11969 mSettings.enableSystemPackageLPw(packageName); 11970 } 11971 if (updatedSettings) { 11972 mSettings.setInstallerPackageName(packageName, 11973 oldPkgSetting.installerPackageName); 11974 } 11975 mSettings.writeLPr(); 11976 } 11977 } 11978 } 11979 11980 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 11981 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 11982 UserHandle user) { 11983 String pkgName = newPackage.packageName; 11984 synchronized (mPackages) { 11985 //write settings. the installStatus will be incomplete at this stage. 11986 //note that the new package setting would have already been 11987 //added to mPackages. It hasn't been persisted yet. 11988 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 11989 mSettings.writeLPr(); 11990 } 11991 11992 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 11993 11994 synchronized (mPackages) { 11995 updatePermissionsLPw(newPackage.packageName, newPackage, 11996 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 11997 ? UPDATE_PERMISSIONS_ALL : 0)); 11998 // For system-bundled packages, we assume that installing an upgraded version 11999 // of the package implies that the user actually wants to run that new code, 12000 // so we enable the package. 12001 PackageSetting ps = mSettings.mPackages.get(pkgName); 12002 if (ps != null) { 12003 if (isSystemApp(newPackage)) { 12004 // NB: implicit assumption that system package upgrades apply to all users 12005 if (DEBUG_INSTALL) { 12006 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 12007 } 12008 if (res.origUsers != null) { 12009 for (int userHandle : res.origUsers) { 12010 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 12011 userHandle, installerPackageName); 12012 } 12013 } 12014 // Also convey the prior install/uninstall state 12015 if (allUsers != null && perUserInstalled != null) { 12016 for (int i = 0; i < allUsers.length; i++) { 12017 if (DEBUG_INSTALL) { 12018 Slog.d(TAG, " user " + allUsers[i] 12019 + " => " + perUserInstalled[i]); 12020 } 12021 ps.setInstalled(perUserInstalled[i], allUsers[i]); 12022 } 12023 // these install state changes will be persisted in the 12024 // upcoming call to mSettings.writeLPr(). 12025 } 12026 } 12027 // It's implied that when a user requests installation, they want the app to be 12028 // installed and enabled. 12029 int userId = user.getIdentifier(); 12030 if (userId != UserHandle.USER_ALL) { 12031 ps.setInstalled(true, userId); 12032 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 12033 } 12034 } 12035 res.name = pkgName; 12036 res.uid = newPackage.applicationInfo.uid; 12037 res.pkg = newPackage; 12038 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 12039 mSettings.setInstallerPackageName(pkgName, installerPackageName); 12040 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12041 //to update install status 12042 mSettings.writeLPr(); 12043 } 12044 } 12045 12046 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 12047 final int installFlags = args.installFlags; 12048 final String installerPackageName = args.installerPackageName; 12049 final String volumeUuid = args.volumeUuid; 12050 final File tmpPackageFile = new File(args.getCodePath()); 12051 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 12052 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 12053 || (args.volumeUuid != null)); 12054 boolean replace = false; 12055 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 12056 if (args.move != null) { 12057 // moving a complete application; perfom an initial scan on the new install location 12058 scanFlags |= SCAN_INITIAL; 12059 } 12060 // Result object to be returned 12061 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12062 12063 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 12064 // Retrieve PackageSettings and parse package 12065 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 12066 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 12067 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 12068 PackageParser pp = new PackageParser(); 12069 pp.setSeparateProcesses(mSeparateProcesses); 12070 pp.setDisplayMetrics(mMetrics); 12071 12072 final PackageParser.Package pkg; 12073 try { 12074 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 12075 } catch (PackageParserException e) { 12076 res.setError("Failed parse during installPackageLI", e); 12077 return; 12078 } 12079 12080 // Mark that we have an install time CPU ABI override. 12081 pkg.cpuAbiOverride = args.abiOverride; 12082 12083 String pkgName = res.name = pkg.packageName; 12084 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 12085 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 12086 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 12087 return; 12088 } 12089 } 12090 12091 try { 12092 pp.collectCertificates(pkg, parseFlags); 12093 pp.collectManifestDigest(pkg); 12094 } catch (PackageParserException e) { 12095 res.setError("Failed collect during installPackageLI", e); 12096 return; 12097 } 12098 12099 /* If the installer passed in a manifest digest, compare it now. */ 12100 if (args.manifestDigest != null) { 12101 if (DEBUG_INSTALL) { 12102 final String parsedManifest = pkg.manifestDigest == null ? "null" 12103 : pkg.manifestDigest.toString(); 12104 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 12105 + parsedManifest); 12106 } 12107 12108 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 12109 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 12110 return; 12111 } 12112 } else if (DEBUG_INSTALL) { 12113 final String parsedManifest = pkg.manifestDigest == null 12114 ? "null" : pkg.manifestDigest.toString(); 12115 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 12116 } 12117 12118 // Get rid of all references to package scan path via parser. 12119 pp = null; 12120 String oldCodePath = null; 12121 boolean systemApp = false; 12122 synchronized (mPackages) { 12123 // Check if installing already existing package 12124 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12125 String oldName = mSettings.mRenamedPackages.get(pkgName); 12126 if (pkg.mOriginalPackages != null 12127 && pkg.mOriginalPackages.contains(oldName) 12128 && mPackages.containsKey(oldName)) { 12129 // This package is derived from an original package, 12130 // and this device has been updating from that original 12131 // name. We must continue using the original name, so 12132 // rename the new package here. 12133 pkg.setPackageName(oldName); 12134 pkgName = pkg.packageName; 12135 replace = true; 12136 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 12137 + oldName + " pkgName=" + pkgName); 12138 } else if (mPackages.containsKey(pkgName)) { 12139 // This package, under its official name, already exists 12140 // on the device; we should replace it. 12141 replace = true; 12142 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 12143 } 12144 12145 // Prevent apps opting out from runtime permissions 12146 if (replace) { 12147 PackageParser.Package oldPackage = mPackages.get(pkgName); 12148 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 12149 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 12150 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 12151 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 12152 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 12153 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 12154 + " doesn't support runtime permissions but the old" 12155 + " target SDK " + oldTargetSdk + " does."); 12156 return; 12157 } 12158 } 12159 } 12160 12161 PackageSetting ps = mSettings.mPackages.get(pkgName); 12162 if (ps != null) { 12163 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 12164 12165 // Quick sanity check that we're signed correctly if updating; 12166 // we'll check this again later when scanning, but we want to 12167 // bail early here before tripping over redefined permissions. 12168 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12169 if (!checkUpgradeKeySetLP(ps, pkg)) { 12170 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 12171 + pkg.packageName + " upgrade keys do not match the " 12172 + "previously installed version"); 12173 return; 12174 } 12175 } else { 12176 try { 12177 verifySignaturesLP(ps, pkg); 12178 } catch (PackageManagerException e) { 12179 res.setError(e.error, e.getMessage()); 12180 return; 12181 } 12182 } 12183 12184 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 12185 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 12186 systemApp = (ps.pkg.applicationInfo.flags & 12187 ApplicationInfo.FLAG_SYSTEM) != 0; 12188 } 12189 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12190 } 12191 12192 // Check whether the newly-scanned package wants to define an already-defined perm 12193 int N = pkg.permissions.size(); 12194 for (int i = N-1; i >= 0; i--) { 12195 PackageParser.Permission perm = pkg.permissions.get(i); 12196 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 12197 if (bp != null) { 12198 // If the defining package is signed with our cert, it's okay. This 12199 // also includes the "updating the same package" case, of course. 12200 // "updating same package" could also involve key-rotation. 12201 final boolean sigsOk; 12202 if (bp.sourcePackage.equals(pkg.packageName) 12203 && (bp.packageSetting instanceof PackageSetting) 12204 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 12205 scanFlags))) { 12206 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 12207 } else { 12208 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 12209 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 12210 } 12211 if (!sigsOk) { 12212 // If the owning package is the system itself, we log but allow 12213 // install to proceed; we fail the install on all other permission 12214 // redefinitions. 12215 if (!bp.sourcePackage.equals("android")) { 12216 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 12217 + pkg.packageName + " attempting to redeclare permission " 12218 + perm.info.name + " already owned by " + bp.sourcePackage); 12219 res.origPermission = perm.info.name; 12220 res.origPackage = bp.sourcePackage; 12221 return; 12222 } else { 12223 Slog.w(TAG, "Package " + pkg.packageName 12224 + " attempting to redeclare system permission " 12225 + perm.info.name + "; ignoring new declaration"); 12226 pkg.permissions.remove(i); 12227 } 12228 } 12229 } 12230 } 12231 12232 } 12233 12234 if (systemApp && onExternal) { 12235 // Disable updates to system apps on sdcard 12236 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 12237 "Cannot install updates to system apps on sdcard"); 12238 return; 12239 } 12240 12241 if (args.move != null) { 12242 // We did an in-place move, so dex is ready to roll 12243 scanFlags |= SCAN_NO_DEX; 12244 scanFlags |= SCAN_MOVE; 12245 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 12246 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 12247 scanFlags |= SCAN_NO_DEX; 12248 12249 try { 12250 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 12251 true /* extract libs */); 12252 } catch (PackageManagerException pme) { 12253 Slog.e(TAG, "Error deriving application ABI", pme); 12254 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 12255 return; 12256 } 12257 12258 // Run dexopt before old package gets removed, to minimize time when app is unavailable 12259 int result = mPackageDexOptimizer 12260 .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */, 12261 false /* defer */, false /* inclDependencies */); 12262 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 12263 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 12264 return; 12265 } 12266 } 12267 12268 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 12269 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 12270 return; 12271 } 12272 12273 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 12274 12275 if (replace) { 12276 replacePackageLI(pkg, parseFlags, scanFlags, args.user, 12277 installerPackageName, volumeUuid, res); 12278 } else { 12279 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 12280 args.user, installerPackageName, volumeUuid, res); 12281 } 12282 synchronized (mPackages) { 12283 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12284 if (ps != null) { 12285 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12286 } 12287 } 12288 } 12289 12290 private void startIntentFilterVerifications(int userId, boolean replacing, 12291 PackageParser.Package pkg) { 12292 if (mIntentFilterVerifierComponent == null) { 12293 Slog.w(TAG, "No IntentFilter verification will not be done as " 12294 + "there is no IntentFilterVerifier available!"); 12295 return; 12296 } 12297 12298 final int verifierUid = getPackageUid( 12299 mIntentFilterVerifierComponent.getPackageName(), 12300 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 12301 12302 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 12303 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 12304 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 12305 mHandler.sendMessage(msg); 12306 } 12307 12308 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 12309 PackageParser.Package pkg) { 12310 int size = pkg.activities.size(); 12311 if (size == 0) { 12312 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12313 "No activity, so no need to verify any IntentFilter!"); 12314 return; 12315 } 12316 12317 final boolean hasDomainURLs = hasDomainURLs(pkg); 12318 if (!hasDomainURLs) { 12319 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12320 "No domain URLs, so no need to verify any IntentFilter!"); 12321 return; 12322 } 12323 12324 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 12325 + " if any IntentFilter from the " + size 12326 + " Activities needs verification ..."); 12327 12328 int count = 0; 12329 final String packageName = pkg.packageName; 12330 12331 synchronized (mPackages) { 12332 // If this is a new install and we see that we've already run verification for this 12333 // package, we have nothing to do: it means the state was restored from backup. 12334 if (!replacing) { 12335 IntentFilterVerificationInfo ivi = 12336 mSettings.getIntentFilterVerificationLPr(packageName); 12337 if (ivi != null) { 12338 if (DEBUG_DOMAIN_VERIFICATION) { 12339 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 12340 + ivi.getStatusString()); 12341 } 12342 return; 12343 } 12344 } 12345 12346 // If any filters need to be verified, then all need to be. 12347 boolean needToVerify = false; 12348 for (PackageParser.Activity a : pkg.activities) { 12349 for (ActivityIntentInfo filter : a.intents) { 12350 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 12351 if (DEBUG_DOMAIN_VERIFICATION) { 12352 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 12353 } 12354 needToVerify = true; 12355 break; 12356 } 12357 } 12358 } 12359 12360 if (needToVerify) { 12361 final int verificationId = mIntentFilterVerificationToken++; 12362 for (PackageParser.Activity a : pkg.activities) { 12363 for (ActivityIntentInfo filter : a.intents) { 12364 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 12365 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12366 "Verification needed for IntentFilter:" + filter.toString()); 12367 mIntentFilterVerifier.addOneIntentFilterVerification( 12368 verifierUid, userId, verificationId, filter, packageName); 12369 count++; 12370 } 12371 } 12372 } 12373 } 12374 } 12375 12376 if (count > 0) { 12377 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 12378 + " IntentFilter verification" + (count > 1 ? "s" : "") 12379 + " for userId:" + userId); 12380 mIntentFilterVerifier.startVerifications(userId); 12381 } else { 12382 if (DEBUG_DOMAIN_VERIFICATION) { 12383 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 12384 } 12385 } 12386 } 12387 12388 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 12389 final ComponentName cn = filter.activity.getComponentName(); 12390 final String packageName = cn.getPackageName(); 12391 12392 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 12393 packageName); 12394 if (ivi == null) { 12395 return true; 12396 } 12397 int status = ivi.getStatus(); 12398 switch (status) { 12399 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 12400 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 12401 return true; 12402 12403 default: 12404 // Nothing to do 12405 return false; 12406 } 12407 } 12408 12409 private static boolean isMultiArch(PackageSetting ps) { 12410 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12411 } 12412 12413 private static boolean isMultiArch(ApplicationInfo info) { 12414 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12415 } 12416 12417 private static boolean isExternal(PackageParser.Package pkg) { 12418 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12419 } 12420 12421 private static boolean isExternal(PackageSetting ps) { 12422 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12423 } 12424 12425 private static boolean isExternal(ApplicationInfo info) { 12426 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12427 } 12428 12429 private static boolean isSystemApp(PackageParser.Package pkg) { 12430 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 12431 } 12432 12433 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 12434 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 12435 } 12436 12437 private static boolean hasDomainURLs(PackageParser.Package pkg) { 12438 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 12439 } 12440 12441 private static boolean isSystemApp(PackageSetting ps) { 12442 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 12443 } 12444 12445 private static boolean isUpdatedSystemApp(PackageSetting ps) { 12446 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 12447 } 12448 12449 private int packageFlagsToInstallFlags(PackageSetting ps) { 12450 int installFlags = 0; 12451 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 12452 // This existing package was an external ASEC install when we have 12453 // the external flag without a UUID 12454 installFlags |= PackageManager.INSTALL_EXTERNAL; 12455 } 12456 if (ps.isForwardLocked()) { 12457 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12458 } 12459 return installFlags; 12460 } 12461 12462 private void deleteTempPackageFiles() { 12463 final FilenameFilter filter = new FilenameFilter() { 12464 public boolean accept(File dir, String name) { 12465 return name.startsWith("vmdl") && name.endsWith(".tmp"); 12466 } 12467 }; 12468 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 12469 file.delete(); 12470 } 12471 } 12472 12473 @Override 12474 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 12475 int flags) { 12476 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 12477 flags); 12478 } 12479 12480 @Override 12481 public void deletePackage(final String packageName, 12482 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 12483 mContext.enforceCallingOrSelfPermission( 12484 android.Manifest.permission.DELETE_PACKAGES, null); 12485 Preconditions.checkNotNull(packageName); 12486 Preconditions.checkNotNull(observer); 12487 final int uid = Binder.getCallingUid(); 12488 if (UserHandle.getUserId(uid) != userId) { 12489 mContext.enforceCallingPermission( 12490 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 12491 "deletePackage for user " + userId); 12492 } 12493 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 12494 try { 12495 observer.onPackageDeleted(packageName, 12496 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 12497 } catch (RemoteException re) { 12498 } 12499 return; 12500 } 12501 12502 boolean uninstallBlocked = false; 12503 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 12504 int[] users = sUserManager.getUserIds(); 12505 for (int i = 0; i < users.length; ++i) { 12506 if (getBlockUninstallForUser(packageName, users[i])) { 12507 uninstallBlocked = true; 12508 break; 12509 } 12510 } 12511 } else { 12512 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 12513 } 12514 if (uninstallBlocked) { 12515 try { 12516 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 12517 null); 12518 } catch (RemoteException re) { 12519 } 12520 return; 12521 } 12522 12523 if (DEBUG_REMOVE) { 12524 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 12525 } 12526 // Queue up an async operation since the package deletion may take a little while. 12527 mHandler.post(new Runnable() { 12528 public void run() { 12529 mHandler.removeCallbacks(this); 12530 final int returnCode = deletePackageX(packageName, userId, flags); 12531 if (observer != null) { 12532 try { 12533 observer.onPackageDeleted(packageName, returnCode, null); 12534 } catch (RemoteException e) { 12535 Log.i(TAG, "Observer no longer exists."); 12536 } //end catch 12537 } //end if 12538 } //end run 12539 }); 12540 } 12541 12542 private boolean isPackageDeviceAdmin(String packageName, int userId) { 12543 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 12544 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 12545 try { 12546 if (dpm != null) { 12547 if (dpm.isDeviceOwner(packageName)) { 12548 return true; 12549 } 12550 int[] users; 12551 if (userId == UserHandle.USER_ALL) { 12552 users = sUserManager.getUserIds(); 12553 } else { 12554 users = new int[]{userId}; 12555 } 12556 for (int i = 0; i < users.length; ++i) { 12557 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 12558 return true; 12559 } 12560 } 12561 } 12562 } catch (RemoteException e) { 12563 } 12564 return false; 12565 } 12566 12567 /** 12568 * This method is an internal method that could be get invoked either 12569 * to delete an installed package or to clean up a failed installation. 12570 * After deleting an installed package, a broadcast is sent to notify any 12571 * listeners that the package has been installed. For cleaning up a failed 12572 * installation, the broadcast is not necessary since the package's 12573 * installation wouldn't have sent the initial broadcast either 12574 * The key steps in deleting a package are 12575 * deleting the package information in internal structures like mPackages, 12576 * deleting the packages base directories through installd 12577 * updating mSettings to reflect current status 12578 * persisting settings for later use 12579 * sending a broadcast if necessary 12580 */ 12581 private int deletePackageX(String packageName, int userId, int flags) { 12582 final PackageRemovedInfo info = new PackageRemovedInfo(); 12583 final boolean res; 12584 12585 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 12586 ? UserHandle.ALL : new UserHandle(userId); 12587 12588 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 12589 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 12590 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 12591 } 12592 12593 boolean removedForAllUsers = false; 12594 boolean systemUpdate = false; 12595 12596 // for the uninstall-updates case and restricted profiles, remember the per- 12597 // userhandle installed state 12598 int[] allUsers; 12599 boolean[] perUserInstalled; 12600 synchronized (mPackages) { 12601 PackageSetting ps = mSettings.mPackages.get(packageName); 12602 allUsers = sUserManager.getUserIds(); 12603 perUserInstalled = new boolean[allUsers.length]; 12604 for (int i = 0; i < allUsers.length; i++) { 12605 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12606 } 12607 } 12608 12609 synchronized (mInstallLock) { 12610 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 12611 res = deletePackageLI(packageName, removeForUser, 12612 true, allUsers, perUserInstalled, 12613 flags | REMOVE_CHATTY, info, true); 12614 systemUpdate = info.isRemovedPackageSystemUpdate; 12615 if (res && !systemUpdate && mPackages.get(packageName) == null) { 12616 removedForAllUsers = true; 12617 } 12618 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 12619 + " removedForAllUsers=" + removedForAllUsers); 12620 } 12621 12622 if (res) { 12623 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 12624 12625 // If the removed package was a system update, the old system package 12626 // was re-enabled; we need to broadcast this information 12627 if (systemUpdate) { 12628 Bundle extras = new Bundle(1); 12629 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 12630 ? info.removedAppId : info.uid); 12631 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12632 12633 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 12634 extras, null, null, null); 12635 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 12636 extras, null, null, null); 12637 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 12638 null, packageName, null, null); 12639 } 12640 } 12641 // Force a gc here. 12642 Runtime.getRuntime().gc(); 12643 // Delete the resources here after sending the broadcast to let 12644 // other processes clean up before deleting resources. 12645 if (info.args != null) { 12646 synchronized (mInstallLock) { 12647 info.args.doPostDeleteLI(true); 12648 } 12649 } 12650 12651 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 12652 } 12653 12654 class PackageRemovedInfo { 12655 String removedPackage; 12656 int uid = -1; 12657 int removedAppId = -1; 12658 int[] removedUsers = null; 12659 boolean isRemovedPackageSystemUpdate = false; 12660 // Clean up resources deleted packages. 12661 InstallArgs args = null; 12662 12663 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 12664 Bundle extras = new Bundle(1); 12665 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 12666 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 12667 if (replacing) { 12668 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12669 } 12670 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 12671 if (removedPackage != null) { 12672 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 12673 extras, null, null, removedUsers); 12674 if (fullRemove && !replacing) { 12675 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 12676 extras, null, null, removedUsers); 12677 } 12678 } 12679 if (removedAppId >= 0) { 12680 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 12681 removedUsers); 12682 } 12683 } 12684 } 12685 12686 /* 12687 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 12688 * flag is not set, the data directory is removed as well. 12689 * make sure this flag is set for partially installed apps. If not its meaningless to 12690 * delete a partially installed application. 12691 */ 12692 private void removePackageDataLI(PackageSetting ps, 12693 int[] allUserHandles, boolean[] perUserInstalled, 12694 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 12695 String packageName = ps.name; 12696 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 12697 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 12698 // Retrieve object to delete permissions for shared user later on 12699 final PackageSetting deletedPs; 12700 // reader 12701 synchronized (mPackages) { 12702 deletedPs = mSettings.mPackages.get(packageName); 12703 if (outInfo != null) { 12704 outInfo.removedPackage = packageName; 12705 outInfo.removedUsers = deletedPs != null 12706 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 12707 : null; 12708 } 12709 } 12710 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12711 removeDataDirsLI(ps.volumeUuid, packageName); 12712 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 12713 } 12714 // writer 12715 synchronized (mPackages) { 12716 if (deletedPs != null) { 12717 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12718 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 12719 clearDefaultBrowserIfNeeded(packageName); 12720 if (outInfo != null) { 12721 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 12722 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 12723 } 12724 updatePermissionsLPw(deletedPs.name, null, 0); 12725 if (deletedPs.sharedUser != null) { 12726 // Remove permissions associated with package. Since runtime 12727 // permissions are per user we have to kill the removed package 12728 // or packages running under the shared user of the removed 12729 // package if revoking the permissions requested only by the removed 12730 // package is successful and this causes a change in gids. 12731 for (int userId : UserManagerService.getInstance().getUserIds()) { 12732 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 12733 userId); 12734 if (userIdToKill == UserHandle.USER_ALL 12735 || userIdToKill >= UserHandle.USER_OWNER) { 12736 // If gids changed for this user, kill all affected packages. 12737 mHandler.post(new Runnable() { 12738 @Override 12739 public void run() { 12740 // This has to happen with no lock held. 12741 killSettingPackagesForUser(deletedPs, userIdToKill, 12742 KILL_APP_REASON_GIDS_CHANGED); 12743 } 12744 }); 12745 break; 12746 } 12747 } 12748 } 12749 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 12750 } 12751 // make sure to preserve per-user disabled state if this removal was just 12752 // a downgrade of a system app to the factory package 12753 if (allUserHandles != null && perUserInstalled != null) { 12754 if (DEBUG_REMOVE) { 12755 Slog.d(TAG, "Propagating install state across downgrade"); 12756 } 12757 for (int i = 0; i < allUserHandles.length; i++) { 12758 if (DEBUG_REMOVE) { 12759 Slog.d(TAG, " user " + allUserHandles[i] 12760 + " => " + perUserInstalled[i]); 12761 } 12762 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12763 } 12764 } 12765 } 12766 // can downgrade to reader 12767 if (writeSettings) { 12768 // Save settings now 12769 mSettings.writeLPr(); 12770 } 12771 } 12772 if (outInfo != null) { 12773 // A user ID was deleted here. Go through all users and remove it 12774 // from KeyStore. 12775 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 12776 } 12777 } 12778 12779 static boolean locationIsPrivileged(File path) { 12780 try { 12781 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 12782 .getCanonicalPath(); 12783 return path.getCanonicalPath().startsWith(privilegedAppDir); 12784 } catch (IOException e) { 12785 Slog.e(TAG, "Unable to access code path " + path); 12786 } 12787 return false; 12788 } 12789 12790 /* 12791 * Tries to delete system package. 12792 */ 12793 private boolean deleteSystemPackageLI(PackageSetting newPs, 12794 int[] allUserHandles, boolean[] perUserInstalled, 12795 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 12796 final boolean applyUserRestrictions 12797 = (allUserHandles != null) && (perUserInstalled != null); 12798 PackageSetting disabledPs = null; 12799 // Confirm if the system package has been updated 12800 // An updated system app can be deleted. This will also have to restore 12801 // the system pkg from system partition 12802 // reader 12803 synchronized (mPackages) { 12804 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 12805 } 12806 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 12807 + " disabledPs=" + disabledPs); 12808 if (disabledPs == null) { 12809 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 12810 return false; 12811 } else if (DEBUG_REMOVE) { 12812 Slog.d(TAG, "Deleting system pkg from data partition"); 12813 } 12814 if (DEBUG_REMOVE) { 12815 if (applyUserRestrictions) { 12816 Slog.d(TAG, "Remembering install states:"); 12817 for (int i = 0; i < allUserHandles.length; i++) { 12818 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 12819 } 12820 } 12821 } 12822 // Delete the updated package 12823 outInfo.isRemovedPackageSystemUpdate = true; 12824 if (disabledPs.versionCode < newPs.versionCode) { 12825 // Delete data for downgrades 12826 flags &= ~PackageManager.DELETE_KEEP_DATA; 12827 } else { 12828 // Preserve data by setting flag 12829 flags |= PackageManager.DELETE_KEEP_DATA; 12830 } 12831 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 12832 allUserHandles, perUserInstalled, outInfo, writeSettings); 12833 if (!ret) { 12834 return false; 12835 } 12836 // writer 12837 synchronized (mPackages) { 12838 // Reinstate the old system package 12839 mSettings.enableSystemPackageLPw(newPs.name); 12840 // Remove any native libraries from the upgraded package. 12841 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 12842 } 12843 // Install the system package 12844 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 12845 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 12846 if (locationIsPrivileged(disabledPs.codePath)) { 12847 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12848 } 12849 12850 final PackageParser.Package newPkg; 12851 try { 12852 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 12853 } catch (PackageManagerException e) { 12854 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 12855 return false; 12856 } 12857 12858 // writer 12859 synchronized (mPackages) { 12860 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 12861 12862 // Propagate the permissions state as we do want to drop on the floor 12863 // runtime permissions. The update permissions method below will take 12864 // care of removing obsolete permissions and grant install permissions. 12865 ps.getPermissionsState().copyFrom(disabledPs.getPermissionsState()); 12866 updatePermissionsLPw(newPkg.packageName, newPkg, 12867 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 12868 12869 if (applyUserRestrictions) { 12870 if (DEBUG_REMOVE) { 12871 Slog.d(TAG, "Propagating install state across reinstall"); 12872 } 12873 for (int i = 0; i < allUserHandles.length; i++) { 12874 if (DEBUG_REMOVE) { 12875 Slog.d(TAG, " user " + allUserHandles[i] 12876 + " => " + perUserInstalled[i]); 12877 } 12878 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12879 } 12880 // Regardless of writeSettings we need to ensure that this restriction 12881 // state propagation is persisted 12882 mSettings.writeAllUsersPackageRestrictionsLPr(); 12883 } 12884 // can downgrade to reader here 12885 if (writeSettings) { 12886 mSettings.writeLPr(); 12887 } 12888 } 12889 return true; 12890 } 12891 12892 private boolean deleteInstalledPackageLI(PackageSetting ps, 12893 boolean deleteCodeAndResources, int flags, 12894 int[] allUserHandles, boolean[] perUserInstalled, 12895 PackageRemovedInfo outInfo, boolean writeSettings) { 12896 if (outInfo != null) { 12897 outInfo.uid = ps.appId; 12898 } 12899 12900 // Delete package data from internal structures and also remove data if flag is set 12901 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 12902 12903 // Delete application code and resources 12904 if (deleteCodeAndResources && (outInfo != null)) { 12905 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 12906 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 12907 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 12908 } 12909 return true; 12910 } 12911 12912 @Override 12913 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 12914 int userId) { 12915 mContext.enforceCallingOrSelfPermission( 12916 android.Manifest.permission.DELETE_PACKAGES, null); 12917 synchronized (mPackages) { 12918 PackageSetting ps = mSettings.mPackages.get(packageName); 12919 if (ps == null) { 12920 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 12921 return false; 12922 } 12923 if (!ps.getInstalled(userId)) { 12924 // Can't block uninstall for an app that is not installed or enabled. 12925 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 12926 return false; 12927 } 12928 ps.setBlockUninstall(blockUninstall, userId); 12929 mSettings.writePackageRestrictionsLPr(userId); 12930 } 12931 return true; 12932 } 12933 12934 @Override 12935 public boolean getBlockUninstallForUser(String packageName, int userId) { 12936 synchronized (mPackages) { 12937 PackageSetting ps = mSettings.mPackages.get(packageName); 12938 if (ps == null) { 12939 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 12940 return false; 12941 } 12942 return ps.getBlockUninstall(userId); 12943 } 12944 } 12945 12946 /* 12947 * This method handles package deletion in general 12948 */ 12949 private boolean deletePackageLI(String packageName, UserHandle user, 12950 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 12951 int flags, PackageRemovedInfo outInfo, 12952 boolean writeSettings) { 12953 if (packageName == null) { 12954 Slog.w(TAG, "Attempt to delete null packageName."); 12955 return false; 12956 } 12957 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 12958 PackageSetting ps; 12959 boolean dataOnly = false; 12960 int removeUser = -1; 12961 int appId = -1; 12962 synchronized (mPackages) { 12963 ps = mSettings.mPackages.get(packageName); 12964 if (ps == null) { 12965 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12966 return false; 12967 } 12968 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 12969 && user.getIdentifier() != UserHandle.USER_ALL) { 12970 // The caller is asking that the package only be deleted for a single 12971 // user. To do this, we just mark its uninstalled state and delete 12972 // its data. If this is a system app, we only allow this to happen if 12973 // they have set the special DELETE_SYSTEM_APP which requests different 12974 // semantics than normal for uninstalling system apps. 12975 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 12976 ps.setUserState(user.getIdentifier(), 12977 COMPONENT_ENABLED_STATE_DEFAULT, 12978 false, //installed 12979 true, //stopped 12980 true, //notLaunched 12981 false, //hidden 12982 null, null, null, 12983 false, // blockUninstall 12984 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED, 0); 12985 if (!isSystemApp(ps)) { 12986 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 12987 // Other user still have this package installed, so all 12988 // we need to do is clear this user's data and save that 12989 // it is uninstalled. 12990 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 12991 removeUser = user.getIdentifier(); 12992 appId = ps.appId; 12993 scheduleWritePackageRestrictionsLocked(removeUser); 12994 } else { 12995 // We need to set it back to 'installed' so the uninstall 12996 // broadcasts will be sent correctly. 12997 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 12998 ps.setInstalled(true, user.getIdentifier()); 12999 } 13000 } else { 13001 // This is a system app, so we assume that the 13002 // other users still have this package installed, so all 13003 // we need to do is clear this user's data and save that 13004 // it is uninstalled. 13005 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 13006 removeUser = user.getIdentifier(); 13007 appId = ps.appId; 13008 scheduleWritePackageRestrictionsLocked(removeUser); 13009 } 13010 } 13011 } 13012 13013 if (removeUser >= 0) { 13014 // From above, we determined that we are deleting this only 13015 // for a single user. Continue the work here. 13016 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 13017 if (outInfo != null) { 13018 outInfo.removedPackage = packageName; 13019 outInfo.removedAppId = appId; 13020 outInfo.removedUsers = new int[] {removeUser}; 13021 } 13022 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 13023 removeKeystoreDataIfNeeded(removeUser, appId); 13024 schedulePackageCleaning(packageName, removeUser, false); 13025 synchronized (mPackages) { 13026 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 13027 scheduleWritePackageRestrictionsLocked(removeUser); 13028 } 13029 resetUserChangesToRuntimePermissionsAndFlagsLocked(ps, removeUser); 13030 } 13031 return true; 13032 } 13033 13034 if (dataOnly) { 13035 // Delete application data first 13036 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 13037 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 13038 return true; 13039 } 13040 13041 boolean ret = false; 13042 if (isSystemApp(ps)) { 13043 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 13044 // When an updated system application is deleted we delete the existing resources as well and 13045 // fall back to existing code in system partition 13046 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 13047 flags, outInfo, writeSettings); 13048 } else { 13049 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 13050 // Kill application pre-emptively especially for apps on sd. 13051 killApplication(packageName, ps.appId, "uninstall pkg"); 13052 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 13053 allUserHandles, perUserInstalled, 13054 outInfo, writeSettings); 13055 } 13056 13057 return ret; 13058 } 13059 13060 private final class ClearStorageConnection implements ServiceConnection { 13061 IMediaContainerService mContainerService; 13062 13063 @Override 13064 public void onServiceConnected(ComponentName name, IBinder service) { 13065 synchronized (this) { 13066 mContainerService = IMediaContainerService.Stub.asInterface(service); 13067 notifyAll(); 13068 } 13069 } 13070 13071 @Override 13072 public void onServiceDisconnected(ComponentName name) { 13073 } 13074 } 13075 13076 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 13077 final boolean mounted; 13078 if (Environment.isExternalStorageEmulated()) { 13079 mounted = true; 13080 } else { 13081 final String status = Environment.getExternalStorageState(); 13082 13083 mounted = status.equals(Environment.MEDIA_MOUNTED) 13084 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 13085 } 13086 13087 if (!mounted) { 13088 return; 13089 } 13090 13091 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 13092 int[] users; 13093 if (userId == UserHandle.USER_ALL) { 13094 users = sUserManager.getUserIds(); 13095 } else { 13096 users = new int[] { userId }; 13097 } 13098 final ClearStorageConnection conn = new ClearStorageConnection(); 13099 if (mContext.bindServiceAsUser( 13100 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 13101 try { 13102 for (int curUser : users) { 13103 long timeout = SystemClock.uptimeMillis() + 5000; 13104 synchronized (conn) { 13105 long now = SystemClock.uptimeMillis(); 13106 while (conn.mContainerService == null && now < timeout) { 13107 try { 13108 conn.wait(timeout - now); 13109 } catch (InterruptedException e) { 13110 } 13111 } 13112 } 13113 if (conn.mContainerService == null) { 13114 return; 13115 } 13116 13117 final UserEnvironment userEnv = new UserEnvironment(curUser); 13118 clearDirectory(conn.mContainerService, 13119 userEnv.buildExternalStorageAppCacheDirs(packageName)); 13120 if (allData) { 13121 clearDirectory(conn.mContainerService, 13122 userEnv.buildExternalStorageAppDataDirs(packageName)); 13123 clearDirectory(conn.mContainerService, 13124 userEnv.buildExternalStorageAppMediaDirs(packageName)); 13125 } 13126 } 13127 } finally { 13128 mContext.unbindService(conn); 13129 } 13130 } 13131 } 13132 13133 @Override 13134 public void clearApplicationUserData(final String packageName, 13135 final IPackageDataObserver observer, final int userId) { 13136 mContext.enforceCallingOrSelfPermission( 13137 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 13138 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 13139 // Queue up an async operation since the package deletion may take a little while. 13140 mHandler.post(new Runnable() { 13141 public void run() { 13142 mHandler.removeCallbacks(this); 13143 final boolean succeeded; 13144 synchronized (mInstallLock) { 13145 succeeded = clearApplicationUserDataLI(packageName, userId); 13146 } 13147 clearExternalStorageDataSync(packageName, userId, true); 13148 if (succeeded) { 13149 // invoke DeviceStorageMonitor's update method to clear any notifications 13150 DeviceStorageMonitorInternal 13151 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13152 if (dsm != null) { 13153 dsm.checkMemory(); 13154 } 13155 } 13156 if(observer != null) { 13157 try { 13158 observer.onRemoveCompleted(packageName, succeeded); 13159 } catch (RemoteException e) { 13160 Log.i(TAG, "Observer no longer exists."); 13161 } 13162 } //end if observer 13163 } //end run 13164 }); 13165 } 13166 13167 private boolean clearApplicationUserDataLI(String packageName, int userId) { 13168 if (packageName == null) { 13169 Slog.w(TAG, "Attempt to delete null packageName."); 13170 return false; 13171 } 13172 13173 // Try finding details about the requested package 13174 PackageParser.Package pkg; 13175 synchronized (mPackages) { 13176 pkg = mPackages.get(packageName); 13177 if (pkg == null) { 13178 final PackageSetting ps = mSettings.mPackages.get(packageName); 13179 if (ps != null) { 13180 pkg = ps.pkg; 13181 } 13182 } 13183 13184 if (pkg == null) { 13185 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13186 return false; 13187 } 13188 13189 PackageSetting ps = (PackageSetting) pkg.mExtras; 13190 resetUserChangesToRuntimePermissionsAndFlagsLocked(ps, userId); 13191 } 13192 13193 // Always delete data directories for package, even if we found no other 13194 // record of app. This helps users recover from UID mismatches without 13195 // resorting to a full data wipe. 13196 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 13197 if (retCode < 0) { 13198 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 13199 return false; 13200 } 13201 13202 final int appId = pkg.applicationInfo.uid; 13203 removeKeystoreDataIfNeeded(userId, appId); 13204 13205 // Create a native library symlink only if we have native libraries 13206 // and if the native libraries are 32 bit libraries. We do not provide 13207 // this symlink for 64 bit libraries. 13208 if (pkg.applicationInfo.primaryCpuAbi != null && 13209 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 13210 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 13211 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 13212 nativeLibPath, userId) < 0) { 13213 Slog.w(TAG, "Failed linking native library dir"); 13214 return false; 13215 } 13216 } 13217 13218 return true; 13219 } 13220 13221 /** 13222 * Reverts user permission state changes (permissions and flags). 13223 * 13224 * @param ps The package for which to reset. 13225 * @param userId The device user for which to do a reset. 13226 */ 13227 private void resetUserChangesToRuntimePermissionsAndFlagsLocked( 13228 final PackageSetting ps, final int userId) { 13229 if (ps.pkg == null) { 13230 return; 13231 } 13232 13233 final int userSettableFlags = FLAG_PERMISSION_USER_SET 13234 | FLAG_PERMISSION_USER_FIXED 13235 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 13236 13237 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 13238 | FLAG_PERMISSION_POLICY_FIXED; 13239 13240 boolean writeInstallPermissions = false; 13241 boolean writeRuntimePermissions = false; 13242 13243 final int permissionCount = ps.pkg.requestedPermissions.size(); 13244 for (int i = 0; i < permissionCount; i++) { 13245 String permission = ps.pkg.requestedPermissions.get(i); 13246 13247 BasePermission bp = mSettings.mPermissions.get(permission); 13248 if (bp == null) { 13249 continue; 13250 } 13251 13252 // If shared user we just reset the state to which only this app contributed. 13253 if (ps.sharedUser != null) { 13254 boolean used = false; 13255 final int packageCount = ps.sharedUser.packages.size(); 13256 for (int j = 0; j < packageCount; j++) { 13257 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 13258 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 13259 && pkg.pkg.requestedPermissions.contains(permission)) { 13260 used = true; 13261 break; 13262 } 13263 } 13264 if (used) { 13265 continue; 13266 } 13267 } 13268 13269 PermissionsState permissionsState = ps.getPermissionsState(); 13270 13271 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 13272 13273 // Always clear the user settable flags. 13274 final boolean hasInstallState = permissionsState.getInstallPermissionState( 13275 bp.name) != null; 13276 if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) { 13277 if (hasInstallState) { 13278 writeInstallPermissions = true; 13279 } else { 13280 writeRuntimePermissions = true; 13281 } 13282 } 13283 13284 // Below is only runtime permission handling. 13285 if (!bp.isRuntime()) { 13286 continue; 13287 } 13288 13289 // Never clobber system or policy. 13290 if ((oldFlags & policyOrSystemFlags) != 0) { 13291 continue; 13292 } 13293 13294 // If this permission was granted by default, make sure it is. 13295 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 13296 if (permissionsState.grantRuntimePermission(bp, userId) 13297 != PERMISSION_OPERATION_FAILURE) { 13298 writeRuntimePermissions = true; 13299 } 13300 } else { 13301 // Otherwise, reset the permission. 13302 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 13303 switch (revokeResult) { 13304 case PERMISSION_OPERATION_SUCCESS: { 13305 writeRuntimePermissions = true; 13306 } break; 13307 13308 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 13309 writeRuntimePermissions = true; 13310 // If gids changed for this user, kill all affected packages. 13311 mHandler.post(new Runnable() { 13312 @Override 13313 public void run() { 13314 // This has to happen with no lock held. 13315 killSettingPackagesForUser(ps, userId, 13316 KILL_APP_REASON_GIDS_CHANGED); 13317 } 13318 }); 13319 } break; 13320 } 13321 } 13322 } 13323 13324 // Synchronously write as we are taking permissions away. 13325 if (writeRuntimePermissions) { 13326 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 13327 } 13328 13329 // Synchronously write as we are taking permissions away. 13330 if (writeInstallPermissions) { 13331 mSettings.writeLPr(); 13332 } 13333 } 13334 13335 /** 13336 * Remove entries from the keystore daemon. Will only remove it if the 13337 * {@code appId} is valid. 13338 */ 13339 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 13340 if (appId < 0) { 13341 return; 13342 } 13343 13344 final KeyStore keyStore = KeyStore.getInstance(); 13345 if (keyStore != null) { 13346 if (userId == UserHandle.USER_ALL) { 13347 for (final int individual : sUserManager.getUserIds()) { 13348 keyStore.clearUid(UserHandle.getUid(individual, appId)); 13349 } 13350 } else { 13351 keyStore.clearUid(UserHandle.getUid(userId, appId)); 13352 } 13353 } else { 13354 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 13355 } 13356 } 13357 13358 @Override 13359 public void deleteApplicationCacheFiles(final String packageName, 13360 final IPackageDataObserver observer) { 13361 mContext.enforceCallingOrSelfPermission( 13362 android.Manifest.permission.DELETE_CACHE_FILES, null); 13363 // Queue up an async operation since the package deletion may take a little while. 13364 final int userId = UserHandle.getCallingUserId(); 13365 mHandler.post(new Runnable() { 13366 public void run() { 13367 mHandler.removeCallbacks(this); 13368 final boolean succeded; 13369 synchronized (mInstallLock) { 13370 succeded = deleteApplicationCacheFilesLI(packageName, userId); 13371 } 13372 clearExternalStorageDataSync(packageName, userId, false); 13373 if (observer != null) { 13374 try { 13375 observer.onRemoveCompleted(packageName, succeded); 13376 } catch (RemoteException e) { 13377 Log.i(TAG, "Observer no longer exists."); 13378 } 13379 } //end if observer 13380 } //end run 13381 }); 13382 } 13383 13384 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 13385 if (packageName == null) { 13386 Slog.w(TAG, "Attempt to delete null packageName."); 13387 return false; 13388 } 13389 PackageParser.Package p; 13390 synchronized (mPackages) { 13391 p = mPackages.get(packageName); 13392 } 13393 if (p == null) { 13394 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13395 return false; 13396 } 13397 final ApplicationInfo applicationInfo = p.applicationInfo; 13398 if (applicationInfo == null) { 13399 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13400 return false; 13401 } 13402 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 13403 if (retCode < 0) { 13404 Slog.w(TAG, "Couldn't remove cache files for package: " 13405 + packageName + " u" + userId); 13406 return false; 13407 } 13408 return true; 13409 } 13410 13411 @Override 13412 public void getPackageSizeInfo(final String packageName, int userHandle, 13413 final IPackageStatsObserver observer) { 13414 mContext.enforceCallingOrSelfPermission( 13415 android.Manifest.permission.GET_PACKAGE_SIZE, null); 13416 if (packageName == null) { 13417 throw new IllegalArgumentException("Attempt to get size of null packageName"); 13418 } 13419 13420 PackageStats stats = new PackageStats(packageName, userHandle); 13421 13422 /* 13423 * Queue up an async operation since the package measurement may take a 13424 * little while. 13425 */ 13426 Message msg = mHandler.obtainMessage(INIT_COPY); 13427 msg.obj = new MeasureParams(stats, observer); 13428 mHandler.sendMessage(msg); 13429 } 13430 13431 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 13432 PackageStats pStats) { 13433 if (packageName == null) { 13434 Slog.w(TAG, "Attempt to get size of null packageName."); 13435 return false; 13436 } 13437 PackageParser.Package p; 13438 boolean dataOnly = false; 13439 String libDirRoot = null; 13440 String asecPath = null; 13441 PackageSetting ps = null; 13442 synchronized (mPackages) { 13443 p = mPackages.get(packageName); 13444 ps = mSettings.mPackages.get(packageName); 13445 if(p == null) { 13446 dataOnly = true; 13447 if((ps == null) || (ps.pkg == null)) { 13448 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13449 return false; 13450 } 13451 p = ps.pkg; 13452 } 13453 if (ps != null) { 13454 libDirRoot = ps.legacyNativeLibraryPathString; 13455 } 13456 if (p != null && (isExternal(p) || p.isForwardLocked())) { 13457 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 13458 if (secureContainerId != null) { 13459 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 13460 } 13461 } 13462 } 13463 String publicSrcDir = null; 13464 if(!dataOnly) { 13465 final ApplicationInfo applicationInfo = p.applicationInfo; 13466 if (applicationInfo == null) { 13467 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13468 return false; 13469 } 13470 if (p.isForwardLocked()) { 13471 publicSrcDir = applicationInfo.getBaseResourcePath(); 13472 } 13473 } 13474 // TODO: extend to measure size of split APKs 13475 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 13476 // not just the first level. 13477 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 13478 // just the primary. 13479 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 13480 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath, 13481 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 13482 if (res < 0) { 13483 return false; 13484 } 13485 13486 // Fix-up for forward-locked applications in ASEC containers. 13487 if (!isExternal(p)) { 13488 pStats.codeSize += pStats.externalCodeSize; 13489 pStats.externalCodeSize = 0L; 13490 } 13491 13492 return true; 13493 } 13494 13495 13496 @Override 13497 public void addPackageToPreferred(String packageName) { 13498 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 13499 } 13500 13501 @Override 13502 public void removePackageFromPreferred(String packageName) { 13503 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 13504 } 13505 13506 @Override 13507 public List<PackageInfo> getPreferredPackages(int flags) { 13508 return new ArrayList<PackageInfo>(); 13509 } 13510 13511 private int getUidTargetSdkVersionLockedLPr(int uid) { 13512 Object obj = mSettings.getUserIdLPr(uid); 13513 if (obj instanceof SharedUserSetting) { 13514 final SharedUserSetting sus = (SharedUserSetting) obj; 13515 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 13516 final Iterator<PackageSetting> it = sus.packages.iterator(); 13517 while (it.hasNext()) { 13518 final PackageSetting ps = it.next(); 13519 if (ps.pkg != null) { 13520 int v = ps.pkg.applicationInfo.targetSdkVersion; 13521 if (v < vers) vers = v; 13522 } 13523 } 13524 return vers; 13525 } else if (obj instanceof PackageSetting) { 13526 final PackageSetting ps = (PackageSetting) obj; 13527 if (ps.pkg != null) { 13528 return ps.pkg.applicationInfo.targetSdkVersion; 13529 } 13530 } 13531 return Build.VERSION_CODES.CUR_DEVELOPMENT; 13532 } 13533 13534 @Override 13535 public void addPreferredActivity(IntentFilter filter, int match, 13536 ComponentName[] set, ComponentName activity, int userId) { 13537 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13538 "Adding preferred"); 13539 } 13540 13541 private void addPreferredActivityInternal(IntentFilter filter, int match, 13542 ComponentName[] set, ComponentName activity, boolean always, int userId, 13543 String opname) { 13544 // writer 13545 int callingUid = Binder.getCallingUid(); 13546 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 13547 if (filter.countActions() == 0) { 13548 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13549 return; 13550 } 13551 synchronized (mPackages) { 13552 if (mContext.checkCallingOrSelfPermission( 13553 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13554 != PackageManager.PERMISSION_GRANTED) { 13555 if (getUidTargetSdkVersionLockedLPr(callingUid) 13556 < Build.VERSION_CODES.FROYO) { 13557 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 13558 + callingUid); 13559 return; 13560 } 13561 mContext.enforceCallingOrSelfPermission( 13562 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13563 } 13564 13565 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 13566 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 13567 + userId + ":"); 13568 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13569 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 13570 scheduleWritePackageRestrictionsLocked(userId); 13571 } 13572 } 13573 13574 @Override 13575 public void replacePreferredActivity(IntentFilter filter, int match, 13576 ComponentName[] set, ComponentName activity, int userId) { 13577 if (filter.countActions() != 1) { 13578 throw new IllegalArgumentException( 13579 "replacePreferredActivity expects filter to have only 1 action."); 13580 } 13581 if (filter.countDataAuthorities() != 0 13582 || filter.countDataPaths() != 0 13583 || filter.countDataSchemes() > 1 13584 || filter.countDataTypes() != 0) { 13585 throw new IllegalArgumentException( 13586 "replacePreferredActivity expects filter to have no data authorities, " + 13587 "paths, or types; and at most one scheme."); 13588 } 13589 13590 final int callingUid = Binder.getCallingUid(); 13591 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 13592 synchronized (mPackages) { 13593 if (mContext.checkCallingOrSelfPermission( 13594 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13595 != PackageManager.PERMISSION_GRANTED) { 13596 if (getUidTargetSdkVersionLockedLPr(callingUid) 13597 < Build.VERSION_CODES.FROYO) { 13598 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 13599 + Binder.getCallingUid()); 13600 return; 13601 } 13602 mContext.enforceCallingOrSelfPermission( 13603 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13604 } 13605 13606 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13607 if (pir != null) { 13608 // Get all of the existing entries that exactly match this filter. 13609 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 13610 if (existing != null && existing.size() == 1) { 13611 PreferredActivity cur = existing.get(0); 13612 if (DEBUG_PREFERRED) { 13613 Slog.i(TAG, "Checking replace of preferred:"); 13614 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13615 if (!cur.mPref.mAlways) { 13616 Slog.i(TAG, " -- CUR; not mAlways!"); 13617 } else { 13618 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 13619 Slog.i(TAG, " -- CUR: mSet=" 13620 + Arrays.toString(cur.mPref.mSetComponents)); 13621 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 13622 Slog.i(TAG, " -- NEW: mMatch=" 13623 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 13624 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 13625 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 13626 } 13627 } 13628 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 13629 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 13630 && cur.mPref.sameSet(set)) { 13631 // Setting the preferred activity to what it happens to be already 13632 if (DEBUG_PREFERRED) { 13633 Slog.i(TAG, "Replacing with same preferred activity " 13634 + cur.mPref.mShortComponent + " for user " 13635 + userId + ":"); 13636 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13637 } 13638 return; 13639 } 13640 } 13641 13642 if (existing != null) { 13643 if (DEBUG_PREFERRED) { 13644 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 13645 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13646 } 13647 for (int i = 0; i < existing.size(); i++) { 13648 PreferredActivity pa = existing.get(i); 13649 if (DEBUG_PREFERRED) { 13650 Slog.i(TAG, "Removing existing preferred activity " 13651 + pa.mPref.mComponent + ":"); 13652 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 13653 } 13654 pir.removeFilter(pa); 13655 } 13656 } 13657 } 13658 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13659 "Replacing preferred"); 13660 } 13661 } 13662 13663 @Override 13664 public void clearPackagePreferredActivities(String packageName) { 13665 final int uid = Binder.getCallingUid(); 13666 // writer 13667 synchronized (mPackages) { 13668 PackageParser.Package pkg = mPackages.get(packageName); 13669 if (pkg == null || pkg.applicationInfo.uid != uid) { 13670 if (mContext.checkCallingOrSelfPermission( 13671 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13672 != PackageManager.PERMISSION_GRANTED) { 13673 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 13674 < Build.VERSION_CODES.FROYO) { 13675 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 13676 + Binder.getCallingUid()); 13677 return; 13678 } 13679 mContext.enforceCallingOrSelfPermission( 13680 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13681 } 13682 } 13683 13684 int user = UserHandle.getCallingUserId(); 13685 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 13686 scheduleWritePackageRestrictionsLocked(user); 13687 } 13688 } 13689 } 13690 13691 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13692 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 13693 ArrayList<PreferredActivity> removed = null; 13694 boolean changed = false; 13695 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13696 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 13697 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13698 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 13699 continue; 13700 } 13701 Iterator<PreferredActivity> it = pir.filterIterator(); 13702 while (it.hasNext()) { 13703 PreferredActivity pa = it.next(); 13704 // Mark entry for removal only if it matches the package name 13705 // and the entry is of type "always". 13706 if (packageName == null || 13707 (pa.mPref.mComponent.getPackageName().equals(packageName) 13708 && pa.mPref.mAlways)) { 13709 if (removed == null) { 13710 removed = new ArrayList<PreferredActivity>(); 13711 } 13712 removed.add(pa); 13713 } 13714 } 13715 if (removed != null) { 13716 for (int j=0; j<removed.size(); j++) { 13717 PreferredActivity pa = removed.get(j); 13718 pir.removeFilter(pa); 13719 } 13720 changed = true; 13721 } 13722 } 13723 return changed; 13724 } 13725 13726 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13727 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 13728 if (userId == UserHandle.USER_ALL) { 13729 if (mSettings.removeIntentFilterVerificationLPw(packageName, 13730 sUserManager.getUserIds())) { 13731 for (int oneUserId : sUserManager.getUserIds()) { 13732 scheduleWritePackageRestrictionsLocked(oneUserId); 13733 } 13734 } 13735 } else { 13736 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 13737 scheduleWritePackageRestrictionsLocked(userId); 13738 } 13739 } 13740 } 13741 13742 13743 void clearDefaultBrowserIfNeeded(String packageName) { 13744 for (int oneUserId : sUserManager.getUserIds()) { 13745 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 13746 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 13747 if (packageName.equals(defaultBrowserPackageName)) { 13748 setDefaultBrowserPackageName(null, oneUserId); 13749 } 13750 } 13751 } 13752 13753 @Override 13754 public void resetPreferredActivities(int userId) { 13755 mContext.enforceCallingOrSelfPermission( 13756 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13757 // writer 13758 synchronized (mPackages) { 13759 clearPackagePreferredActivitiesLPw(null, userId); 13760 mSettings.applyDefaultPreferredAppsLPw(this, userId); 13761 applyFactoryDefaultBrowserLPw(userId); 13762 primeDomainVerificationsLPw(userId); 13763 13764 scheduleWritePackageRestrictionsLocked(userId); 13765 } 13766 } 13767 13768 @Override 13769 public int getPreferredActivities(List<IntentFilter> outFilters, 13770 List<ComponentName> outActivities, String packageName) { 13771 13772 int num = 0; 13773 final int userId = UserHandle.getCallingUserId(); 13774 // reader 13775 synchronized (mPackages) { 13776 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13777 if (pir != null) { 13778 final Iterator<PreferredActivity> it = pir.filterIterator(); 13779 while (it.hasNext()) { 13780 final PreferredActivity pa = it.next(); 13781 if (packageName == null 13782 || (pa.mPref.mComponent.getPackageName().equals(packageName) 13783 && pa.mPref.mAlways)) { 13784 if (outFilters != null) { 13785 outFilters.add(new IntentFilter(pa)); 13786 } 13787 if (outActivities != null) { 13788 outActivities.add(pa.mPref.mComponent); 13789 } 13790 } 13791 } 13792 } 13793 } 13794 13795 return num; 13796 } 13797 13798 @Override 13799 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 13800 int userId) { 13801 int callingUid = Binder.getCallingUid(); 13802 if (callingUid != Process.SYSTEM_UID) { 13803 throw new SecurityException( 13804 "addPersistentPreferredActivity can only be run by the system"); 13805 } 13806 if (filter.countActions() == 0) { 13807 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13808 return; 13809 } 13810 synchronized (mPackages) { 13811 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 13812 " :"); 13813 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13814 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 13815 new PersistentPreferredActivity(filter, activity)); 13816 scheduleWritePackageRestrictionsLocked(userId); 13817 } 13818 } 13819 13820 @Override 13821 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 13822 int callingUid = Binder.getCallingUid(); 13823 if (callingUid != Process.SYSTEM_UID) { 13824 throw new SecurityException( 13825 "clearPackagePersistentPreferredActivities can only be run by the system"); 13826 } 13827 ArrayList<PersistentPreferredActivity> removed = null; 13828 boolean changed = false; 13829 synchronized (mPackages) { 13830 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 13831 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 13832 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 13833 .valueAt(i); 13834 if (userId != thisUserId) { 13835 continue; 13836 } 13837 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 13838 while (it.hasNext()) { 13839 PersistentPreferredActivity ppa = it.next(); 13840 // Mark entry for removal only if it matches the package name. 13841 if (ppa.mComponent.getPackageName().equals(packageName)) { 13842 if (removed == null) { 13843 removed = new ArrayList<PersistentPreferredActivity>(); 13844 } 13845 removed.add(ppa); 13846 } 13847 } 13848 if (removed != null) { 13849 for (int j=0; j<removed.size(); j++) { 13850 PersistentPreferredActivity ppa = removed.get(j); 13851 ppir.removeFilter(ppa); 13852 } 13853 changed = true; 13854 } 13855 } 13856 13857 if (changed) { 13858 scheduleWritePackageRestrictionsLocked(userId); 13859 } 13860 } 13861 } 13862 13863 /** 13864 * Common machinery for picking apart a restored XML blob and passing 13865 * it to a caller-supplied functor to be applied to the running system. 13866 */ 13867 private void restoreFromXml(XmlPullParser parser, int userId, 13868 String expectedStartTag, BlobXmlRestorer functor) 13869 throws IOException, XmlPullParserException { 13870 int type; 13871 while ((type = parser.next()) != XmlPullParser.START_TAG 13872 && type != XmlPullParser.END_DOCUMENT) { 13873 } 13874 if (type != XmlPullParser.START_TAG) { 13875 // oops didn't find a start tag?! 13876 if (DEBUG_BACKUP) { 13877 Slog.e(TAG, "Didn't find start tag during restore"); 13878 } 13879 return; 13880 } 13881 13882 // this is supposed to be TAG_PREFERRED_BACKUP 13883 if (!expectedStartTag.equals(parser.getName())) { 13884 if (DEBUG_BACKUP) { 13885 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 13886 } 13887 return; 13888 } 13889 13890 // skip interfering stuff, then we're aligned with the backing implementation 13891 while ((type = parser.next()) == XmlPullParser.TEXT) { } 13892 functor.apply(parser, userId); 13893 } 13894 13895 private interface BlobXmlRestorer { 13896 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 13897 } 13898 13899 /** 13900 * Non-Binder method, support for the backup/restore mechanism: write the 13901 * full set of preferred activities in its canonical XML format. Returns the 13902 * XML output as a byte array, or null if there is none. 13903 */ 13904 @Override 13905 public byte[] getPreferredActivityBackup(int userId) { 13906 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13907 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 13908 } 13909 13910 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13911 try { 13912 final XmlSerializer serializer = new FastXmlSerializer(); 13913 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13914 serializer.startDocument(null, true); 13915 serializer.startTag(null, TAG_PREFERRED_BACKUP); 13916 13917 synchronized (mPackages) { 13918 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 13919 } 13920 13921 serializer.endTag(null, TAG_PREFERRED_BACKUP); 13922 serializer.endDocument(); 13923 serializer.flush(); 13924 } catch (Exception e) { 13925 if (DEBUG_BACKUP) { 13926 Slog.e(TAG, "Unable to write preferred activities for backup", e); 13927 } 13928 return null; 13929 } 13930 13931 return dataStream.toByteArray(); 13932 } 13933 13934 @Override 13935 public void restorePreferredActivities(byte[] backup, int userId) { 13936 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13937 throw new SecurityException("Only the system may call restorePreferredActivities()"); 13938 } 13939 13940 try { 13941 final XmlPullParser parser = Xml.newPullParser(); 13942 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13943 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 13944 new BlobXmlRestorer() { 13945 @Override 13946 public void apply(XmlPullParser parser, int userId) 13947 throws XmlPullParserException, IOException { 13948 synchronized (mPackages) { 13949 mSettings.readPreferredActivitiesLPw(parser, userId); 13950 } 13951 } 13952 } ); 13953 } catch (Exception e) { 13954 if (DEBUG_BACKUP) { 13955 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 13956 } 13957 } 13958 } 13959 13960 /** 13961 * Non-Binder method, support for the backup/restore mechanism: write the 13962 * default browser (etc) settings in its canonical XML format. Returns the default 13963 * browser XML representation as a byte array, or null if there is none. 13964 */ 13965 @Override 13966 public byte[] getDefaultAppsBackup(int userId) { 13967 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13968 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 13969 } 13970 13971 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13972 try { 13973 final XmlSerializer serializer = new FastXmlSerializer(); 13974 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13975 serializer.startDocument(null, true); 13976 serializer.startTag(null, TAG_DEFAULT_APPS); 13977 13978 synchronized (mPackages) { 13979 mSettings.writeDefaultAppsLPr(serializer, userId); 13980 } 13981 13982 serializer.endTag(null, TAG_DEFAULT_APPS); 13983 serializer.endDocument(); 13984 serializer.flush(); 13985 } catch (Exception e) { 13986 if (DEBUG_BACKUP) { 13987 Slog.e(TAG, "Unable to write default apps for backup", e); 13988 } 13989 return null; 13990 } 13991 13992 return dataStream.toByteArray(); 13993 } 13994 13995 @Override 13996 public void restoreDefaultApps(byte[] backup, int userId) { 13997 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13998 throw new SecurityException("Only the system may call restoreDefaultApps()"); 13999 } 14000 14001 try { 14002 final XmlPullParser parser = Xml.newPullParser(); 14003 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14004 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 14005 new BlobXmlRestorer() { 14006 @Override 14007 public void apply(XmlPullParser parser, int userId) 14008 throws XmlPullParserException, IOException { 14009 synchronized (mPackages) { 14010 mSettings.readDefaultAppsLPw(parser, userId); 14011 } 14012 } 14013 } ); 14014 } catch (Exception e) { 14015 if (DEBUG_BACKUP) { 14016 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 14017 } 14018 } 14019 } 14020 14021 @Override 14022 public byte[] getIntentFilterVerificationBackup(int userId) { 14023 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14024 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 14025 } 14026 14027 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14028 try { 14029 final XmlSerializer serializer = new FastXmlSerializer(); 14030 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14031 serializer.startDocument(null, true); 14032 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 14033 14034 synchronized (mPackages) { 14035 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 14036 } 14037 14038 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 14039 serializer.endDocument(); 14040 serializer.flush(); 14041 } catch (Exception e) { 14042 if (DEBUG_BACKUP) { 14043 Slog.e(TAG, "Unable to write default apps for backup", e); 14044 } 14045 return null; 14046 } 14047 14048 return dataStream.toByteArray(); 14049 } 14050 14051 @Override 14052 public void restoreIntentFilterVerification(byte[] backup, int userId) { 14053 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14054 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14055 } 14056 14057 try { 14058 final XmlPullParser parser = Xml.newPullParser(); 14059 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14060 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 14061 new BlobXmlRestorer() { 14062 @Override 14063 public void apply(XmlPullParser parser, int userId) 14064 throws XmlPullParserException, IOException { 14065 synchronized (mPackages) { 14066 mSettings.readAllDomainVerificationsLPr(parser, userId); 14067 mSettings.writeLPr(); 14068 } 14069 } 14070 } ); 14071 } catch (Exception e) { 14072 if (DEBUG_BACKUP) { 14073 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14074 } 14075 } 14076 } 14077 14078 @Override 14079 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 14080 int sourceUserId, int targetUserId, int flags) { 14081 mContext.enforceCallingOrSelfPermission( 14082 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14083 int callingUid = Binder.getCallingUid(); 14084 enforceOwnerRights(ownerPackage, callingUid); 14085 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14086 if (intentFilter.countActions() == 0) { 14087 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 14088 return; 14089 } 14090 synchronized (mPackages) { 14091 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 14092 ownerPackage, targetUserId, flags); 14093 CrossProfileIntentResolver resolver = 14094 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14095 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 14096 // We have all those whose filter is equal. Now checking if the rest is equal as well. 14097 if (existing != null) { 14098 int size = existing.size(); 14099 for (int i = 0; i < size; i++) { 14100 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 14101 return; 14102 } 14103 } 14104 } 14105 resolver.addFilter(newFilter); 14106 scheduleWritePackageRestrictionsLocked(sourceUserId); 14107 } 14108 } 14109 14110 @Override 14111 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 14112 mContext.enforceCallingOrSelfPermission( 14113 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14114 int callingUid = Binder.getCallingUid(); 14115 enforceOwnerRights(ownerPackage, callingUid); 14116 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14117 synchronized (mPackages) { 14118 CrossProfileIntentResolver resolver = 14119 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14120 ArraySet<CrossProfileIntentFilter> set = 14121 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 14122 for (CrossProfileIntentFilter filter : set) { 14123 if (filter.getOwnerPackage().equals(ownerPackage)) { 14124 resolver.removeFilter(filter); 14125 } 14126 } 14127 scheduleWritePackageRestrictionsLocked(sourceUserId); 14128 } 14129 } 14130 14131 // Enforcing that callingUid is owning pkg on userId 14132 private void enforceOwnerRights(String pkg, int callingUid) { 14133 // The system owns everything. 14134 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 14135 return; 14136 } 14137 int callingUserId = UserHandle.getUserId(callingUid); 14138 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 14139 if (pi == null) { 14140 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 14141 + callingUserId); 14142 } 14143 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 14144 throw new SecurityException("Calling uid " + callingUid 14145 + " does not own package " + pkg); 14146 } 14147 } 14148 14149 @Override 14150 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 14151 Intent intent = new Intent(Intent.ACTION_MAIN); 14152 intent.addCategory(Intent.CATEGORY_HOME); 14153 14154 final int callingUserId = UserHandle.getCallingUserId(); 14155 List<ResolveInfo> list = queryIntentActivities(intent, null, 14156 PackageManager.GET_META_DATA, callingUserId); 14157 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 14158 true, false, false, callingUserId); 14159 14160 allHomeCandidates.clear(); 14161 if (list != null) { 14162 for (ResolveInfo ri : list) { 14163 allHomeCandidates.add(ri); 14164 } 14165 } 14166 return (preferred == null || preferred.activityInfo == null) 14167 ? null 14168 : new ComponentName(preferred.activityInfo.packageName, 14169 preferred.activityInfo.name); 14170 } 14171 14172 @Override 14173 public void setApplicationEnabledSetting(String appPackageName, 14174 int newState, int flags, int userId, String callingPackage) { 14175 if (!sUserManager.exists(userId)) return; 14176 if (callingPackage == null) { 14177 callingPackage = Integer.toString(Binder.getCallingUid()); 14178 } 14179 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 14180 } 14181 14182 @Override 14183 public void setComponentEnabledSetting(ComponentName componentName, 14184 int newState, int flags, int userId) { 14185 if (!sUserManager.exists(userId)) return; 14186 setEnabledSetting(componentName.getPackageName(), 14187 componentName.getClassName(), newState, flags, userId, null); 14188 } 14189 14190 private void setEnabledSetting(final String packageName, String className, int newState, 14191 final int flags, int userId, String callingPackage) { 14192 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 14193 || newState == COMPONENT_ENABLED_STATE_ENABLED 14194 || newState == COMPONENT_ENABLED_STATE_DISABLED 14195 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 14196 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 14197 throw new IllegalArgumentException("Invalid new component state: " 14198 + newState); 14199 } 14200 PackageSetting pkgSetting; 14201 final int uid = Binder.getCallingUid(); 14202 final int permission = mContext.checkCallingOrSelfPermission( 14203 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14204 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 14205 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14206 boolean sendNow = false; 14207 boolean isApp = (className == null); 14208 String componentName = isApp ? packageName : className; 14209 int packageUid = -1; 14210 ArrayList<String> components; 14211 14212 // writer 14213 synchronized (mPackages) { 14214 pkgSetting = mSettings.mPackages.get(packageName); 14215 if (pkgSetting == null) { 14216 if (className == null) { 14217 throw new IllegalArgumentException( 14218 "Unknown package: " + packageName); 14219 } 14220 throw new IllegalArgumentException( 14221 "Unknown component: " + packageName 14222 + "/" + className); 14223 } 14224 // Allow root and verify that userId is not being specified by a different user 14225 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 14226 throw new SecurityException( 14227 "Permission Denial: attempt to change component state from pid=" 14228 + Binder.getCallingPid() 14229 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 14230 } 14231 if (className == null) { 14232 // We're dealing with an application/package level state change 14233 if (pkgSetting.getEnabled(userId) == newState) { 14234 // Nothing to do 14235 return; 14236 } 14237 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 14238 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 14239 // Don't care about who enables an app. 14240 callingPackage = null; 14241 } 14242 pkgSetting.setEnabled(newState, userId, callingPackage); 14243 // pkgSetting.pkg.mSetEnabled = newState; 14244 } else { 14245 // We're dealing with a component level state change 14246 // First, verify that this is a valid class name. 14247 PackageParser.Package pkg = pkgSetting.pkg; 14248 if (pkg == null || !pkg.hasComponentClassName(className)) { 14249 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 14250 throw new IllegalArgumentException("Component class " + className 14251 + " does not exist in " + packageName); 14252 } else { 14253 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 14254 + className + " does not exist in " + packageName); 14255 } 14256 } 14257 switch (newState) { 14258 case COMPONENT_ENABLED_STATE_ENABLED: 14259 if (!pkgSetting.enableComponentLPw(className, userId)) { 14260 return; 14261 } 14262 break; 14263 case COMPONENT_ENABLED_STATE_DISABLED: 14264 if (!pkgSetting.disableComponentLPw(className, userId)) { 14265 return; 14266 } 14267 break; 14268 case COMPONENT_ENABLED_STATE_DEFAULT: 14269 if (!pkgSetting.restoreComponentLPw(className, userId)) { 14270 return; 14271 } 14272 break; 14273 default: 14274 Slog.e(TAG, "Invalid new component state: " + newState); 14275 return; 14276 } 14277 } 14278 scheduleWritePackageRestrictionsLocked(userId); 14279 components = mPendingBroadcasts.get(userId, packageName); 14280 final boolean newPackage = components == null; 14281 if (newPackage) { 14282 components = new ArrayList<String>(); 14283 } 14284 if (!components.contains(componentName)) { 14285 components.add(componentName); 14286 } 14287 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 14288 sendNow = true; 14289 // Purge entry from pending broadcast list if another one exists already 14290 // since we are sending one right away. 14291 mPendingBroadcasts.remove(userId, packageName); 14292 } else { 14293 if (newPackage) { 14294 mPendingBroadcasts.put(userId, packageName, components); 14295 } 14296 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 14297 // Schedule a message 14298 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 14299 } 14300 } 14301 } 14302 14303 long callingId = Binder.clearCallingIdentity(); 14304 try { 14305 if (sendNow) { 14306 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 14307 sendPackageChangedBroadcast(packageName, 14308 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 14309 } 14310 } finally { 14311 Binder.restoreCallingIdentity(callingId); 14312 } 14313 } 14314 14315 private void sendPackageChangedBroadcast(String packageName, 14316 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 14317 if (DEBUG_INSTALL) 14318 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 14319 + componentNames); 14320 Bundle extras = new Bundle(4); 14321 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 14322 String nameList[] = new String[componentNames.size()]; 14323 componentNames.toArray(nameList); 14324 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 14325 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 14326 extras.putInt(Intent.EXTRA_UID, packageUid); 14327 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 14328 new int[] {UserHandle.getUserId(packageUid)}); 14329 } 14330 14331 @Override 14332 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 14333 if (!sUserManager.exists(userId)) return; 14334 final int uid = Binder.getCallingUid(); 14335 final int permission = mContext.checkCallingOrSelfPermission( 14336 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14337 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14338 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 14339 // writer 14340 synchronized (mPackages) { 14341 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 14342 allowedByPermission, uid, userId)) { 14343 scheduleWritePackageRestrictionsLocked(userId); 14344 } 14345 } 14346 } 14347 14348 @Override 14349 public String getInstallerPackageName(String packageName) { 14350 // reader 14351 synchronized (mPackages) { 14352 return mSettings.getInstallerPackageNameLPr(packageName); 14353 } 14354 } 14355 14356 @Override 14357 public int getApplicationEnabledSetting(String packageName, int userId) { 14358 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14359 int uid = Binder.getCallingUid(); 14360 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 14361 // reader 14362 synchronized (mPackages) { 14363 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 14364 } 14365 } 14366 14367 @Override 14368 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 14369 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14370 int uid = Binder.getCallingUid(); 14371 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 14372 // reader 14373 synchronized (mPackages) { 14374 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 14375 } 14376 } 14377 14378 @Override 14379 public void enterSafeMode() { 14380 enforceSystemOrRoot("Only the system can request entering safe mode"); 14381 14382 if (!mSystemReady) { 14383 mSafeMode = true; 14384 } 14385 } 14386 14387 @Override 14388 public void systemReady() { 14389 mSystemReady = true; 14390 14391 // Read the compatibilty setting when the system is ready. 14392 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 14393 mContext.getContentResolver(), 14394 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 14395 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 14396 if (DEBUG_SETTINGS) { 14397 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 14398 } 14399 14400 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 14401 14402 synchronized (mPackages) { 14403 // Verify that all of the preferred activity components actually 14404 // exist. It is possible for applications to be updated and at 14405 // that point remove a previously declared activity component that 14406 // had been set as a preferred activity. We try to clean this up 14407 // the next time we encounter that preferred activity, but it is 14408 // possible for the user flow to never be able to return to that 14409 // situation so here we do a sanity check to make sure we haven't 14410 // left any junk around. 14411 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 14412 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14413 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14414 removed.clear(); 14415 for (PreferredActivity pa : pir.filterSet()) { 14416 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 14417 removed.add(pa); 14418 } 14419 } 14420 if (removed.size() > 0) { 14421 for (int r=0; r<removed.size(); r++) { 14422 PreferredActivity pa = removed.get(r); 14423 Slog.w(TAG, "Removing dangling preferred activity: " 14424 + pa.mPref.mComponent); 14425 pir.removeFilter(pa); 14426 } 14427 mSettings.writePackageRestrictionsLPr( 14428 mSettings.mPreferredActivities.keyAt(i)); 14429 } 14430 } 14431 14432 for (int userId : UserManagerService.getInstance().getUserIds()) { 14433 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 14434 grantPermissionsUserIds = ArrayUtils.appendInt( 14435 grantPermissionsUserIds, userId); 14436 } 14437 } 14438 } 14439 sUserManager.systemReady(); 14440 14441 // If we upgraded grant all default permissions before kicking off. 14442 for (int userId : grantPermissionsUserIds) { 14443 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 14444 } 14445 14446 // Kick off any messages waiting for system ready 14447 if (mPostSystemReadyMessages != null) { 14448 for (Message msg : mPostSystemReadyMessages) { 14449 msg.sendToTarget(); 14450 } 14451 mPostSystemReadyMessages = null; 14452 } 14453 14454 // Watch for external volumes that come and go over time 14455 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14456 storage.registerListener(mStorageListener); 14457 14458 mInstallerService.systemReady(); 14459 mPackageDexOptimizer.systemReady(); 14460 14461 MountServiceInternal mountServiceInternal = LocalServices.getService( 14462 MountServiceInternal.class); 14463 mountServiceInternal.addExternalStoragePolicy( 14464 new MountServiceInternal.ExternalStorageMountPolicy() { 14465 @Override 14466 public int getMountMode(int uid, String packageName) { 14467 if (Process.isIsolated(uid)) { 14468 return Zygote.MOUNT_EXTERNAL_NONE; 14469 } 14470 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 14471 return Zygote.MOUNT_EXTERNAL_DEFAULT; 14472 } 14473 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 14474 return Zygote.MOUNT_EXTERNAL_DEFAULT; 14475 } 14476 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 14477 return Zygote.MOUNT_EXTERNAL_READ; 14478 } 14479 return Zygote.MOUNT_EXTERNAL_WRITE; 14480 } 14481 14482 @Override 14483 public boolean hasExternalStorage(int uid, String packageName) { 14484 return true; 14485 } 14486 }); 14487 } 14488 14489 @Override 14490 public boolean isSafeMode() { 14491 return mSafeMode; 14492 } 14493 14494 @Override 14495 public boolean hasSystemUidErrors() { 14496 return mHasSystemUidErrors; 14497 } 14498 14499 static String arrayToString(int[] array) { 14500 StringBuffer buf = new StringBuffer(128); 14501 buf.append('['); 14502 if (array != null) { 14503 for (int i=0; i<array.length; i++) { 14504 if (i > 0) buf.append(", "); 14505 buf.append(array[i]); 14506 } 14507 } 14508 buf.append(']'); 14509 return buf.toString(); 14510 } 14511 14512 static class DumpState { 14513 public static final int DUMP_LIBS = 1 << 0; 14514 public static final int DUMP_FEATURES = 1 << 1; 14515 public static final int DUMP_RESOLVERS = 1 << 2; 14516 public static final int DUMP_PERMISSIONS = 1 << 3; 14517 public static final int DUMP_PACKAGES = 1 << 4; 14518 public static final int DUMP_SHARED_USERS = 1 << 5; 14519 public static final int DUMP_MESSAGES = 1 << 6; 14520 public static final int DUMP_PROVIDERS = 1 << 7; 14521 public static final int DUMP_VERIFIERS = 1 << 8; 14522 public static final int DUMP_PREFERRED = 1 << 9; 14523 public static final int DUMP_PREFERRED_XML = 1 << 10; 14524 public static final int DUMP_KEYSETS = 1 << 11; 14525 public static final int DUMP_VERSION = 1 << 12; 14526 public static final int DUMP_INSTALLS = 1 << 13; 14527 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 14528 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 14529 14530 public static final int OPTION_SHOW_FILTERS = 1 << 0; 14531 14532 private int mTypes; 14533 14534 private int mOptions; 14535 14536 private boolean mTitlePrinted; 14537 14538 private SharedUserSetting mSharedUser; 14539 14540 public boolean isDumping(int type) { 14541 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 14542 return true; 14543 } 14544 14545 return (mTypes & type) != 0; 14546 } 14547 14548 public void setDump(int type) { 14549 mTypes |= type; 14550 } 14551 14552 public boolean isOptionEnabled(int option) { 14553 return (mOptions & option) != 0; 14554 } 14555 14556 public void setOptionEnabled(int option) { 14557 mOptions |= option; 14558 } 14559 14560 public boolean onTitlePrinted() { 14561 final boolean printed = mTitlePrinted; 14562 mTitlePrinted = true; 14563 return printed; 14564 } 14565 14566 public boolean getTitlePrinted() { 14567 return mTitlePrinted; 14568 } 14569 14570 public void setTitlePrinted(boolean enabled) { 14571 mTitlePrinted = enabled; 14572 } 14573 14574 public SharedUserSetting getSharedUser() { 14575 return mSharedUser; 14576 } 14577 14578 public void setSharedUser(SharedUserSetting user) { 14579 mSharedUser = user; 14580 } 14581 } 14582 14583 @Override 14584 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 14585 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 14586 != PackageManager.PERMISSION_GRANTED) { 14587 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 14588 + Binder.getCallingPid() 14589 + ", uid=" + Binder.getCallingUid() 14590 + " without permission " 14591 + android.Manifest.permission.DUMP); 14592 return; 14593 } 14594 14595 DumpState dumpState = new DumpState(); 14596 boolean fullPreferred = false; 14597 boolean checkin = false; 14598 14599 String packageName = null; 14600 ArraySet<String> permissionNames = null; 14601 14602 int opti = 0; 14603 while (opti < args.length) { 14604 String opt = args[opti]; 14605 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 14606 break; 14607 } 14608 opti++; 14609 14610 if ("-a".equals(opt)) { 14611 // Right now we only know how to print all. 14612 } else if ("-h".equals(opt)) { 14613 pw.println("Package manager dump options:"); 14614 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 14615 pw.println(" --checkin: dump for a checkin"); 14616 pw.println(" -f: print details of intent filters"); 14617 pw.println(" -h: print this help"); 14618 pw.println(" cmd may be one of:"); 14619 pw.println(" l[ibraries]: list known shared libraries"); 14620 pw.println(" f[ibraries]: list device features"); 14621 pw.println(" k[eysets]: print known keysets"); 14622 pw.println(" r[esolvers]: dump intent resolvers"); 14623 pw.println(" perm[issions]: dump permissions"); 14624 pw.println(" permission [name ...]: dump declaration and use of given permission"); 14625 pw.println(" pref[erred]: print preferred package settings"); 14626 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 14627 pw.println(" prov[iders]: dump content providers"); 14628 pw.println(" p[ackages]: dump installed packages"); 14629 pw.println(" s[hared-users]: dump shared user IDs"); 14630 pw.println(" m[essages]: print collected runtime messages"); 14631 pw.println(" v[erifiers]: print package verifier info"); 14632 pw.println(" version: print database version info"); 14633 pw.println(" write: write current settings now"); 14634 pw.println(" <package.name>: info about given package"); 14635 pw.println(" installs: details about install sessions"); 14636 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 14637 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 14638 return; 14639 } else if ("--checkin".equals(opt)) { 14640 checkin = true; 14641 } else if ("-f".equals(opt)) { 14642 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14643 } else { 14644 pw.println("Unknown argument: " + opt + "; use -h for help"); 14645 } 14646 } 14647 14648 // Is the caller requesting to dump a particular piece of data? 14649 if (opti < args.length) { 14650 String cmd = args[opti]; 14651 opti++; 14652 // Is this a package name? 14653 if ("android".equals(cmd) || cmd.contains(".")) { 14654 packageName = cmd; 14655 // When dumping a single package, we always dump all of its 14656 // filter information since the amount of data will be reasonable. 14657 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14658 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 14659 dumpState.setDump(DumpState.DUMP_LIBS); 14660 } else if ("f".equals(cmd) || "features".equals(cmd)) { 14661 dumpState.setDump(DumpState.DUMP_FEATURES); 14662 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 14663 dumpState.setDump(DumpState.DUMP_RESOLVERS); 14664 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 14665 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 14666 } else if ("permission".equals(cmd)) { 14667 if (opti >= args.length) { 14668 pw.println("Error: permission requires permission name"); 14669 return; 14670 } 14671 permissionNames = new ArraySet<>(); 14672 while (opti < args.length) { 14673 permissionNames.add(args[opti]); 14674 opti++; 14675 } 14676 dumpState.setDump(DumpState.DUMP_PERMISSIONS 14677 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 14678 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 14679 dumpState.setDump(DumpState.DUMP_PREFERRED); 14680 } else if ("preferred-xml".equals(cmd)) { 14681 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 14682 if (opti < args.length && "--full".equals(args[opti])) { 14683 fullPreferred = true; 14684 opti++; 14685 } 14686 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 14687 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 14688 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 14689 dumpState.setDump(DumpState.DUMP_PACKAGES); 14690 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 14691 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 14692 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 14693 dumpState.setDump(DumpState.DUMP_PROVIDERS); 14694 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 14695 dumpState.setDump(DumpState.DUMP_MESSAGES); 14696 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 14697 dumpState.setDump(DumpState.DUMP_VERIFIERS); 14698 } else if ("i".equals(cmd) || "ifv".equals(cmd) 14699 || "intent-filter-verifiers".equals(cmd)) { 14700 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 14701 } else if ("version".equals(cmd)) { 14702 dumpState.setDump(DumpState.DUMP_VERSION); 14703 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 14704 dumpState.setDump(DumpState.DUMP_KEYSETS); 14705 } else if ("installs".equals(cmd)) { 14706 dumpState.setDump(DumpState.DUMP_INSTALLS); 14707 } else if ("write".equals(cmd)) { 14708 synchronized (mPackages) { 14709 mSettings.writeLPr(); 14710 pw.println("Settings written."); 14711 return; 14712 } 14713 } 14714 } 14715 14716 if (checkin) { 14717 pw.println("vers,1"); 14718 } 14719 14720 // reader 14721 synchronized (mPackages) { 14722 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 14723 if (!checkin) { 14724 if (dumpState.onTitlePrinted()) 14725 pw.println(); 14726 pw.println("Database versions:"); 14727 pw.print(" SDK Version:"); 14728 pw.print(" internal="); 14729 pw.print(mSettings.mInternalSdkPlatform); 14730 pw.print(" external="); 14731 pw.println(mSettings.mExternalSdkPlatform); 14732 pw.print(" DB Version:"); 14733 pw.print(" internal="); 14734 pw.print(mSettings.mInternalDatabaseVersion); 14735 pw.print(" external="); 14736 pw.println(mSettings.mExternalDatabaseVersion); 14737 } 14738 } 14739 14740 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 14741 if (!checkin) { 14742 if (dumpState.onTitlePrinted()) 14743 pw.println(); 14744 pw.println("Verifiers:"); 14745 pw.print(" Required: "); 14746 pw.print(mRequiredVerifierPackage); 14747 pw.print(" (uid="); 14748 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 14749 pw.println(")"); 14750 } else if (mRequiredVerifierPackage != null) { 14751 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 14752 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 14753 } 14754 } 14755 14756 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 14757 packageName == null) { 14758 if (mIntentFilterVerifierComponent != null) { 14759 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 14760 if (!checkin) { 14761 if (dumpState.onTitlePrinted()) 14762 pw.println(); 14763 pw.println("Intent Filter Verifier:"); 14764 pw.print(" Using: "); 14765 pw.print(verifierPackageName); 14766 pw.print(" (uid="); 14767 pw.print(getPackageUid(verifierPackageName, 0)); 14768 pw.println(")"); 14769 } else if (verifierPackageName != null) { 14770 pw.print("ifv,"); pw.print(verifierPackageName); 14771 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 14772 } 14773 } else { 14774 pw.println(); 14775 pw.println("No Intent Filter Verifier available!"); 14776 } 14777 } 14778 14779 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 14780 boolean printedHeader = false; 14781 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 14782 while (it.hasNext()) { 14783 String name = it.next(); 14784 SharedLibraryEntry ent = mSharedLibraries.get(name); 14785 if (!checkin) { 14786 if (!printedHeader) { 14787 if (dumpState.onTitlePrinted()) 14788 pw.println(); 14789 pw.println("Libraries:"); 14790 printedHeader = true; 14791 } 14792 pw.print(" "); 14793 } else { 14794 pw.print("lib,"); 14795 } 14796 pw.print(name); 14797 if (!checkin) { 14798 pw.print(" -> "); 14799 } 14800 if (ent.path != null) { 14801 if (!checkin) { 14802 pw.print("(jar) "); 14803 pw.print(ent.path); 14804 } else { 14805 pw.print(",jar,"); 14806 pw.print(ent.path); 14807 } 14808 } else { 14809 if (!checkin) { 14810 pw.print("(apk) "); 14811 pw.print(ent.apk); 14812 } else { 14813 pw.print(",apk,"); 14814 pw.print(ent.apk); 14815 } 14816 } 14817 pw.println(); 14818 } 14819 } 14820 14821 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 14822 if (dumpState.onTitlePrinted()) 14823 pw.println(); 14824 if (!checkin) { 14825 pw.println("Features:"); 14826 } 14827 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 14828 while (it.hasNext()) { 14829 String name = it.next(); 14830 if (!checkin) { 14831 pw.print(" "); 14832 } else { 14833 pw.print("feat,"); 14834 } 14835 pw.println(name); 14836 } 14837 } 14838 14839 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 14840 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 14841 : "Activity Resolver Table:", " ", packageName, 14842 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14843 dumpState.setTitlePrinted(true); 14844 } 14845 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 14846 : "Receiver Resolver Table:", " ", packageName, 14847 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14848 dumpState.setTitlePrinted(true); 14849 } 14850 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 14851 : "Service Resolver Table:", " ", packageName, 14852 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14853 dumpState.setTitlePrinted(true); 14854 } 14855 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 14856 : "Provider Resolver Table:", " ", packageName, 14857 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14858 dumpState.setTitlePrinted(true); 14859 } 14860 } 14861 14862 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 14863 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14864 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14865 int user = mSettings.mPreferredActivities.keyAt(i); 14866 if (pir.dump(pw, 14867 dumpState.getTitlePrinted() 14868 ? "\nPreferred Activities User " + user + ":" 14869 : "Preferred Activities User " + user + ":", " ", 14870 packageName, true, false)) { 14871 dumpState.setTitlePrinted(true); 14872 } 14873 } 14874 } 14875 14876 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 14877 pw.flush(); 14878 FileOutputStream fout = new FileOutputStream(fd); 14879 BufferedOutputStream str = new BufferedOutputStream(fout); 14880 XmlSerializer serializer = new FastXmlSerializer(); 14881 try { 14882 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 14883 serializer.startDocument(null, true); 14884 serializer.setFeature( 14885 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 14886 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 14887 serializer.endDocument(); 14888 serializer.flush(); 14889 } catch (IllegalArgumentException e) { 14890 pw.println("Failed writing: " + e); 14891 } catch (IllegalStateException e) { 14892 pw.println("Failed writing: " + e); 14893 } catch (IOException e) { 14894 pw.println("Failed writing: " + e); 14895 } 14896 } 14897 14898 if (!checkin 14899 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 14900 && packageName == null) { 14901 pw.println(); 14902 int count = mSettings.mPackages.size(); 14903 if (count == 0) { 14904 pw.println("No applications!"); 14905 pw.println(); 14906 } else { 14907 final String prefix = " "; 14908 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 14909 if (allPackageSettings.size() == 0) { 14910 pw.println("No domain preferred apps!"); 14911 pw.println(); 14912 } else { 14913 pw.println("App verification status:"); 14914 pw.println(); 14915 count = 0; 14916 for (PackageSetting ps : allPackageSettings) { 14917 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 14918 if (ivi == null || ivi.getPackageName() == null) continue; 14919 pw.println(prefix + "Package: " + ivi.getPackageName()); 14920 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 14921 pw.println(prefix + "Status: " + ivi.getStatusString()); 14922 pw.println(); 14923 count++; 14924 } 14925 if (count == 0) { 14926 pw.println(prefix + "No app verification established."); 14927 pw.println(); 14928 } 14929 for (int userId : sUserManager.getUserIds()) { 14930 pw.println("App linkages for user " + userId + ":"); 14931 pw.println(); 14932 count = 0; 14933 for (PackageSetting ps : allPackageSettings) { 14934 final long status = ps.getDomainVerificationStatusForUser(userId); 14935 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 14936 continue; 14937 } 14938 pw.println(prefix + "Package: " + ps.name); 14939 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 14940 String statusStr = IntentFilterVerificationInfo. 14941 getStatusStringFromValue(status); 14942 pw.println(prefix + "Status: " + statusStr); 14943 pw.println(); 14944 count++; 14945 } 14946 if (count == 0) { 14947 pw.println(prefix + "No configured app linkages."); 14948 pw.println(); 14949 } 14950 } 14951 } 14952 } 14953 } 14954 14955 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 14956 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 14957 if (packageName == null && permissionNames == null) { 14958 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 14959 if (iperm == 0) { 14960 if (dumpState.onTitlePrinted()) 14961 pw.println(); 14962 pw.println("AppOp Permissions:"); 14963 } 14964 pw.print(" AppOp Permission "); 14965 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 14966 pw.println(":"); 14967 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 14968 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 14969 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 14970 } 14971 } 14972 } 14973 } 14974 14975 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 14976 boolean printedSomething = false; 14977 for (PackageParser.Provider p : mProviders.mProviders.values()) { 14978 if (packageName != null && !packageName.equals(p.info.packageName)) { 14979 continue; 14980 } 14981 if (!printedSomething) { 14982 if (dumpState.onTitlePrinted()) 14983 pw.println(); 14984 pw.println("Registered ContentProviders:"); 14985 printedSomething = true; 14986 } 14987 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 14988 pw.print(" "); pw.println(p.toString()); 14989 } 14990 printedSomething = false; 14991 for (Map.Entry<String, PackageParser.Provider> entry : 14992 mProvidersByAuthority.entrySet()) { 14993 PackageParser.Provider p = entry.getValue(); 14994 if (packageName != null && !packageName.equals(p.info.packageName)) { 14995 continue; 14996 } 14997 if (!printedSomething) { 14998 if (dumpState.onTitlePrinted()) 14999 pw.println(); 15000 pw.println("ContentProvider Authorities:"); 15001 printedSomething = true; 15002 } 15003 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 15004 pw.print(" "); pw.println(p.toString()); 15005 if (p.info != null && p.info.applicationInfo != null) { 15006 final String appInfo = p.info.applicationInfo.toString(); 15007 pw.print(" applicationInfo="); pw.println(appInfo); 15008 } 15009 } 15010 } 15011 15012 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 15013 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 15014 } 15015 15016 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 15017 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 15018 } 15019 15020 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 15021 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 15022 } 15023 15024 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 15025 // XXX should handle packageName != null by dumping only install data that 15026 // the given package is involved with. 15027 if (dumpState.onTitlePrinted()) pw.println(); 15028 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 15029 } 15030 15031 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 15032 if (dumpState.onTitlePrinted()) pw.println(); 15033 mSettings.dumpReadMessagesLPr(pw, dumpState); 15034 15035 pw.println(); 15036 pw.println("Package warning messages:"); 15037 BufferedReader in = null; 15038 String line = null; 15039 try { 15040 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15041 while ((line = in.readLine()) != null) { 15042 if (line.contains("ignored: updated version")) continue; 15043 pw.println(line); 15044 } 15045 } catch (IOException ignored) { 15046 } finally { 15047 IoUtils.closeQuietly(in); 15048 } 15049 } 15050 15051 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 15052 BufferedReader in = null; 15053 String line = null; 15054 try { 15055 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15056 while ((line = in.readLine()) != null) { 15057 if (line.contains("ignored: updated version")) continue; 15058 pw.print("msg,"); 15059 pw.println(line); 15060 } 15061 } catch (IOException ignored) { 15062 } finally { 15063 IoUtils.closeQuietly(in); 15064 } 15065 } 15066 } 15067 } 15068 15069 private String dumpDomainString(String packageName) { 15070 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName); 15071 List<IntentFilter> filters = getAllIntentFilters(packageName); 15072 15073 ArraySet<String> result = new ArraySet<>(); 15074 if (iviList.size() > 0) { 15075 for (IntentFilterVerificationInfo ivi : iviList) { 15076 for (String host : ivi.getDomains()) { 15077 result.add(host); 15078 } 15079 } 15080 } 15081 if (filters != null && filters.size() > 0) { 15082 for (IntentFilter filter : filters) { 15083 if (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 15084 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)) { 15085 result.addAll(filter.getHostsList()); 15086 } 15087 } 15088 } 15089 15090 StringBuilder sb = new StringBuilder(result.size() * 16); 15091 for (String domain : result) { 15092 if (sb.length() > 0) sb.append(" "); 15093 sb.append(domain); 15094 } 15095 return sb.toString(); 15096 } 15097 15098 // ------- apps on sdcard specific code ------- 15099 static final boolean DEBUG_SD_INSTALL = false; 15100 15101 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 15102 15103 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 15104 15105 private boolean mMediaMounted = false; 15106 15107 static String getEncryptKey() { 15108 try { 15109 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 15110 SD_ENCRYPTION_KEYSTORE_NAME); 15111 if (sdEncKey == null) { 15112 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 15113 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 15114 if (sdEncKey == null) { 15115 Slog.e(TAG, "Failed to create encryption keys"); 15116 return null; 15117 } 15118 } 15119 return sdEncKey; 15120 } catch (NoSuchAlgorithmException nsae) { 15121 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 15122 return null; 15123 } catch (IOException ioe) { 15124 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 15125 return null; 15126 } 15127 } 15128 15129 /* 15130 * Update media status on PackageManager. 15131 */ 15132 @Override 15133 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 15134 int callingUid = Binder.getCallingUid(); 15135 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 15136 throw new SecurityException("Media status can only be updated by the system"); 15137 } 15138 // reader; this apparently protects mMediaMounted, but should probably 15139 // be a different lock in that case. 15140 synchronized (mPackages) { 15141 Log.i(TAG, "Updating external media status from " 15142 + (mMediaMounted ? "mounted" : "unmounted") + " to " 15143 + (mediaStatus ? "mounted" : "unmounted")); 15144 if (DEBUG_SD_INSTALL) 15145 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 15146 + ", mMediaMounted=" + mMediaMounted); 15147 if (mediaStatus == mMediaMounted) { 15148 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 15149 : 0, -1); 15150 mHandler.sendMessage(msg); 15151 return; 15152 } 15153 mMediaMounted = mediaStatus; 15154 } 15155 // Queue up an async operation since the package installation may take a 15156 // little while. 15157 mHandler.post(new Runnable() { 15158 public void run() { 15159 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 15160 } 15161 }); 15162 } 15163 15164 /** 15165 * Called by MountService when the initial ASECs to scan are available. 15166 * Should block until all the ASEC containers are finished being scanned. 15167 */ 15168 public void scanAvailableAsecs() { 15169 updateExternalMediaStatusInner(true, false, false); 15170 if (mShouldRestoreconData) { 15171 SELinuxMMAC.setRestoreconDone(); 15172 mShouldRestoreconData = false; 15173 } 15174 } 15175 15176 /* 15177 * Collect information of applications on external media, map them against 15178 * existing containers and update information based on current mount status. 15179 * Please note that we always have to report status if reportStatus has been 15180 * set to true especially when unloading packages. 15181 */ 15182 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 15183 boolean externalStorage) { 15184 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 15185 int[] uidArr = EmptyArray.INT; 15186 15187 final String[] list = PackageHelper.getSecureContainerList(); 15188 if (ArrayUtils.isEmpty(list)) { 15189 Log.i(TAG, "No secure containers found"); 15190 } else { 15191 // Process list of secure containers and categorize them 15192 // as active or stale based on their package internal state. 15193 15194 // reader 15195 synchronized (mPackages) { 15196 for (String cid : list) { 15197 // Leave stages untouched for now; installer service owns them 15198 if (PackageInstallerService.isStageName(cid)) continue; 15199 15200 if (DEBUG_SD_INSTALL) 15201 Log.i(TAG, "Processing container " + cid); 15202 String pkgName = getAsecPackageName(cid); 15203 if (pkgName == null) { 15204 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 15205 continue; 15206 } 15207 if (DEBUG_SD_INSTALL) 15208 Log.i(TAG, "Looking for pkg : " + pkgName); 15209 15210 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15211 if (ps == null) { 15212 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 15213 continue; 15214 } 15215 15216 /* 15217 * Skip packages that are not external if we're unmounting 15218 * external storage. 15219 */ 15220 if (externalStorage && !isMounted && !isExternal(ps)) { 15221 continue; 15222 } 15223 15224 final AsecInstallArgs args = new AsecInstallArgs(cid, 15225 getAppDexInstructionSets(ps), ps.isForwardLocked()); 15226 // The package status is changed only if the code path 15227 // matches between settings and the container id. 15228 if (ps.codePathString != null 15229 && ps.codePathString.startsWith(args.getCodePath())) { 15230 if (DEBUG_SD_INSTALL) { 15231 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 15232 + " at code path: " + ps.codePathString); 15233 } 15234 15235 // We do have a valid package installed on sdcard 15236 processCids.put(args, ps.codePathString); 15237 final int uid = ps.appId; 15238 if (uid != -1) { 15239 uidArr = ArrayUtils.appendInt(uidArr, uid); 15240 } 15241 } else { 15242 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 15243 + ps.codePathString); 15244 } 15245 } 15246 } 15247 15248 Arrays.sort(uidArr); 15249 } 15250 15251 // Process packages with valid entries. 15252 if (isMounted) { 15253 if (DEBUG_SD_INSTALL) 15254 Log.i(TAG, "Loading packages"); 15255 loadMediaPackages(processCids, uidArr); 15256 startCleaningPackages(); 15257 mInstallerService.onSecureContainersAvailable(); 15258 } else { 15259 if (DEBUG_SD_INSTALL) 15260 Log.i(TAG, "Unloading packages"); 15261 unloadMediaPackages(processCids, uidArr, reportStatus); 15262 } 15263 } 15264 15265 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15266 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 15267 final int size = infos.size(); 15268 final String[] packageNames = new String[size]; 15269 final int[] packageUids = new int[size]; 15270 for (int i = 0; i < size; i++) { 15271 final ApplicationInfo info = infos.get(i); 15272 packageNames[i] = info.packageName; 15273 packageUids[i] = info.uid; 15274 } 15275 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 15276 finishedReceiver); 15277 } 15278 15279 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15280 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15281 sendResourcesChangedBroadcast(mediaStatus, replacing, 15282 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 15283 } 15284 15285 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15286 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15287 int size = pkgList.length; 15288 if (size > 0) { 15289 // Send broadcasts here 15290 Bundle extras = new Bundle(); 15291 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 15292 if (uidArr != null) { 15293 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 15294 } 15295 if (replacing) { 15296 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 15297 } 15298 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 15299 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 15300 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 15301 } 15302 } 15303 15304 /* 15305 * Look at potentially valid container ids from processCids If package 15306 * information doesn't match the one on record or package scanning fails, 15307 * the cid is added to list of removeCids. We currently don't delete stale 15308 * containers. 15309 */ 15310 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 15311 ArrayList<String> pkgList = new ArrayList<String>(); 15312 Set<AsecInstallArgs> keys = processCids.keySet(); 15313 15314 for (AsecInstallArgs args : keys) { 15315 String codePath = processCids.get(args); 15316 if (DEBUG_SD_INSTALL) 15317 Log.i(TAG, "Loading container : " + args.cid); 15318 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15319 try { 15320 // Make sure there are no container errors first. 15321 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 15322 Slog.e(TAG, "Failed to mount cid : " + args.cid 15323 + " when installing from sdcard"); 15324 continue; 15325 } 15326 // Check code path here. 15327 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 15328 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 15329 + " does not match one in settings " + codePath); 15330 continue; 15331 } 15332 // Parse package 15333 int parseFlags = mDefParseFlags; 15334 if (args.isExternalAsec()) { 15335 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 15336 } 15337 if (args.isFwdLocked()) { 15338 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 15339 } 15340 15341 synchronized (mInstallLock) { 15342 PackageParser.Package pkg = null; 15343 try { 15344 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 15345 } catch (PackageManagerException e) { 15346 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 15347 } 15348 // Scan the package 15349 if (pkg != null) { 15350 /* 15351 * TODO why is the lock being held? doPostInstall is 15352 * called in other places without the lock. This needs 15353 * to be straightened out. 15354 */ 15355 // writer 15356 synchronized (mPackages) { 15357 retCode = PackageManager.INSTALL_SUCCEEDED; 15358 pkgList.add(pkg.packageName); 15359 // Post process args 15360 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 15361 pkg.applicationInfo.uid); 15362 } 15363 } else { 15364 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 15365 } 15366 } 15367 15368 } finally { 15369 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 15370 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 15371 } 15372 } 15373 } 15374 // writer 15375 synchronized (mPackages) { 15376 // If the platform SDK has changed since the last time we booted, 15377 // we need to re-grant app permission to catch any new ones that 15378 // appear. This is really a hack, and means that apps can in some 15379 // cases get permissions that the user didn't initially explicitly 15380 // allow... it would be nice to have some better way to handle 15381 // this situation. 15382 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 15383 if (regrantPermissions) 15384 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 15385 + mSdkVersion + "; regranting permissions for external storage"); 15386 mSettings.mExternalSdkPlatform = mSdkVersion; 15387 15388 // Make sure group IDs have been assigned, and any permission 15389 // changes in other apps are accounted for 15390 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 15391 | (regrantPermissions 15392 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 15393 : 0)); 15394 15395 mSettings.updateExternalDatabaseVersion(); 15396 15397 // can downgrade to reader 15398 // Persist settings 15399 mSettings.writeLPr(); 15400 } 15401 // Send a broadcast to let everyone know we are done processing 15402 if (pkgList.size() > 0) { 15403 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 15404 } 15405 } 15406 15407 /* 15408 * Utility method to unload a list of specified containers 15409 */ 15410 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 15411 // Just unmount all valid containers. 15412 for (AsecInstallArgs arg : cidArgs) { 15413 synchronized (mInstallLock) { 15414 arg.doPostDeleteLI(false); 15415 } 15416 } 15417 } 15418 15419 /* 15420 * Unload packages mounted on external media. This involves deleting package 15421 * data from internal structures, sending broadcasts about diabled packages, 15422 * gc'ing to free up references, unmounting all secure containers 15423 * corresponding to packages on external media, and posting a 15424 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 15425 * that we always have to post this message if status has been requested no 15426 * matter what. 15427 */ 15428 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 15429 final boolean reportStatus) { 15430 if (DEBUG_SD_INSTALL) 15431 Log.i(TAG, "unloading media packages"); 15432 ArrayList<String> pkgList = new ArrayList<String>(); 15433 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 15434 final Set<AsecInstallArgs> keys = processCids.keySet(); 15435 for (AsecInstallArgs args : keys) { 15436 String pkgName = args.getPackageName(); 15437 if (DEBUG_SD_INSTALL) 15438 Log.i(TAG, "Trying to unload pkg : " + pkgName); 15439 // Delete package internally 15440 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15441 synchronized (mInstallLock) { 15442 boolean res = deletePackageLI(pkgName, null, false, null, null, 15443 PackageManager.DELETE_KEEP_DATA, outInfo, false); 15444 if (res) { 15445 pkgList.add(pkgName); 15446 } else { 15447 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 15448 failedList.add(args); 15449 } 15450 } 15451 } 15452 15453 // reader 15454 synchronized (mPackages) { 15455 // We didn't update the settings after removing each package; 15456 // write them now for all packages. 15457 mSettings.writeLPr(); 15458 } 15459 15460 // We have to absolutely send UPDATED_MEDIA_STATUS only 15461 // after confirming that all the receivers processed the ordered 15462 // broadcast when packages get disabled, force a gc to clean things up. 15463 // and unload all the containers. 15464 if (pkgList.size() > 0) { 15465 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 15466 new IIntentReceiver.Stub() { 15467 public void performReceive(Intent intent, int resultCode, String data, 15468 Bundle extras, boolean ordered, boolean sticky, 15469 int sendingUser) throws RemoteException { 15470 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 15471 reportStatus ? 1 : 0, 1, keys); 15472 mHandler.sendMessage(msg); 15473 } 15474 }); 15475 } else { 15476 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 15477 keys); 15478 mHandler.sendMessage(msg); 15479 } 15480 } 15481 15482 private void loadPrivatePackages(VolumeInfo vol) { 15483 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 15484 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 15485 synchronized (mInstallLock) { 15486 synchronized (mPackages) { 15487 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15488 for (PackageSetting ps : packages) { 15489 final PackageParser.Package pkg; 15490 try { 15491 pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null); 15492 loaded.add(pkg.applicationInfo); 15493 } catch (PackageManagerException e) { 15494 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 15495 } 15496 } 15497 15498 // TODO: regrant any permissions that changed based since original install 15499 15500 mSettings.writeLPr(); 15501 } 15502 } 15503 15504 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 15505 sendResourcesChangedBroadcast(true, false, loaded, null); 15506 } 15507 15508 private void unloadPrivatePackages(VolumeInfo vol) { 15509 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 15510 synchronized (mInstallLock) { 15511 synchronized (mPackages) { 15512 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15513 for (PackageSetting ps : packages) { 15514 if (ps.pkg == null) continue; 15515 15516 final ApplicationInfo info = ps.pkg.applicationInfo; 15517 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15518 if (deletePackageLI(ps.name, null, false, null, null, 15519 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 15520 unloaded.add(info); 15521 } else { 15522 Slog.w(TAG, "Failed to unload " + ps.codePath); 15523 } 15524 } 15525 15526 mSettings.writeLPr(); 15527 } 15528 } 15529 15530 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 15531 sendResourcesChangedBroadcast(false, false, unloaded, null); 15532 } 15533 15534 /** 15535 * Examine all users present on given mounted volume, and destroy data 15536 * belonging to users that are no longer valid, or whose user ID has been 15537 * recycled. 15538 */ 15539 private void reconcileUsers(String volumeUuid) { 15540 final File[] files = Environment.getDataUserDirectory(volumeUuid).listFiles(); 15541 if (ArrayUtils.isEmpty(files)) { 15542 Slog.d(TAG, "No users found on " + volumeUuid); 15543 return; 15544 } 15545 15546 for (File file : files) { 15547 if (!file.isDirectory()) continue; 15548 15549 final int userId; 15550 final UserInfo info; 15551 try { 15552 userId = Integer.parseInt(file.getName()); 15553 info = sUserManager.getUserInfo(userId); 15554 } catch (NumberFormatException e) { 15555 Slog.w(TAG, "Invalid user directory " + file); 15556 continue; 15557 } 15558 15559 boolean destroyUser = false; 15560 if (info == null) { 15561 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15562 + " because no matching user was found"); 15563 destroyUser = true; 15564 } else { 15565 try { 15566 UserManagerService.enforceSerialNumber(file, info.serialNumber); 15567 } catch (IOException e) { 15568 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15569 + " because we failed to enforce serial number: " + e); 15570 destroyUser = true; 15571 } 15572 } 15573 15574 if (destroyUser) { 15575 synchronized (mInstallLock) { 15576 mInstaller.removeUserDataDirs(volumeUuid, userId); 15577 } 15578 } 15579 } 15580 15581 final UserManager um = mContext.getSystemService(UserManager.class); 15582 for (UserInfo user : um.getUsers()) { 15583 final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id); 15584 if (userDir.exists()) continue; 15585 15586 try { 15587 UserManagerService.prepareUserDirectory(userDir); 15588 UserManagerService.enforceSerialNumber(userDir, user.serialNumber); 15589 } catch (IOException e) { 15590 Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e); 15591 } 15592 } 15593 } 15594 15595 /** 15596 * Examine all apps present on given mounted volume, and destroy apps that 15597 * aren't expected, either due to uninstallation or reinstallation on 15598 * another volume. 15599 */ 15600 private void reconcileApps(String volumeUuid) { 15601 final File[] files = Environment.getDataAppDirectory(volumeUuid).listFiles(); 15602 if (ArrayUtils.isEmpty(files)) { 15603 Slog.d(TAG, "No apps found on " + volumeUuid); 15604 return; 15605 } 15606 15607 for (File file : files) { 15608 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 15609 && !PackageInstallerService.isStageName(file.getName()); 15610 if (!isPackage) { 15611 // Ignore entries which are not packages 15612 continue; 15613 } 15614 15615 boolean destroyApp = false; 15616 String packageName = null; 15617 try { 15618 final PackageLite pkg = PackageParser.parsePackageLite(file, 15619 PackageParser.PARSE_MUST_BE_APK); 15620 packageName = pkg.packageName; 15621 15622 synchronized (mPackages) { 15623 final PackageSetting ps = mSettings.mPackages.get(packageName); 15624 if (ps == null) { 15625 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + " 15626 + volumeUuid + " because we found no install record"); 15627 destroyApp = true; 15628 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 15629 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on " 15630 + volumeUuid + " because we expected it on " + ps.volumeUuid); 15631 destroyApp = true; 15632 } 15633 } 15634 15635 } catch (PackageParserException e) { 15636 logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e); 15637 destroyApp = true; 15638 } 15639 15640 if (destroyApp) { 15641 synchronized (mInstallLock) { 15642 if (packageName != null) { 15643 removeDataDirsLI(volumeUuid, packageName); 15644 } 15645 if (file.isDirectory()) { 15646 mInstaller.rmPackageDir(file.getAbsolutePath()); 15647 } else { 15648 file.delete(); 15649 } 15650 } 15651 } 15652 } 15653 } 15654 15655 private void unfreezePackage(String packageName) { 15656 synchronized (mPackages) { 15657 final PackageSetting ps = mSettings.mPackages.get(packageName); 15658 if (ps != null) { 15659 ps.frozen = false; 15660 } 15661 } 15662 } 15663 15664 @Override 15665 public int movePackage(final String packageName, final String volumeUuid) { 15666 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15667 15668 final int moveId = mNextMoveId.getAndIncrement(); 15669 try { 15670 movePackageInternal(packageName, volumeUuid, moveId); 15671 } catch (PackageManagerException e) { 15672 Slog.w(TAG, "Failed to move " + packageName, e); 15673 mMoveCallbacks.notifyStatusChanged(moveId, 15674 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15675 } 15676 return moveId; 15677 } 15678 15679 private void movePackageInternal(final String packageName, final String volumeUuid, 15680 final int moveId) throws PackageManagerException { 15681 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 15682 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15683 final PackageManager pm = mContext.getPackageManager(); 15684 15685 final boolean currentAsec; 15686 final String currentVolumeUuid; 15687 final File codeFile; 15688 final String installerPackageName; 15689 final String packageAbiOverride; 15690 final int appId; 15691 final String seinfo; 15692 final String label; 15693 15694 // reader 15695 synchronized (mPackages) { 15696 final PackageParser.Package pkg = mPackages.get(packageName); 15697 final PackageSetting ps = mSettings.mPackages.get(packageName); 15698 if (pkg == null || ps == null) { 15699 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 15700 } 15701 15702 if (pkg.applicationInfo.isSystemApp()) { 15703 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 15704 "Cannot move system application"); 15705 } 15706 15707 if (Objects.equals(ps.volumeUuid, volumeUuid)) { 15708 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15709 "Package already moved to " + volumeUuid); 15710 } 15711 15712 final File probe = new File(pkg.codePath); 15713 final File probeOat = new File(probe, "oat"); 15714 if (!probe.isDirectory() || !probeOat.isDirectory()) { 15715 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15716 "Move only supported for modern cluster style installs"); 15717 } 15718 15719 if (ps.frozen) { 15720 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 15721 "Failed to move already frozen package"); 15722 } 15723 ps.frozen = true; 15724 15725 currentAsec = pkg.applicationInfo.isForwardLocked() 15726 || pkg.applicationInfo.isExternalAsec(); 15727 currentVolumeUuid = ps.volumeUuid; 15728 codeFile = new File(pkg.codePath); 15729 installerPackageName = ps.installerPackageName; 15730 packageAbiOverride = ps.cpuAbiOverrideString; 15731 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 15732 seinfo = pkg.applicationInfo.seinfo; 15733 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 15734 } 15735 15736 // Now that we're guarded by frozen state, kill app during move 15737 killApplication(packageName, appId, "move pkg"); 15738 15739 final Bundle extras = new Bundle(); 15740 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 15741 extras.putString(Intent.EXTRA_TITLE, label); 15742 mMoveCallbacks.notifyCreated(moveId, extras); 15743 15744 int installFlags; 15745 final boolean moveCompleteApp; 15746 final File measurePath; 15747 15748 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 15749 installFlags = INSTALL_INTERNAL; 15750 moveCompleteApp = !currentAsec; 15751 measurePath = Environment.getDataAppDirectory(volumeUuid); 15752 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 15753 installFlags = INSTALL_EXTERNAL; 15754 moveCompleteApp = false; 15755 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 15756 } else { 15757 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 15758 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 15759 || !volume.isMountedWritable()) { 15760 unfreezePackage(packageName); 15761 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15762 "Move location not mounted private volume"); 15763 } 15764 15765 Preconditions.checkState(!currentAsec); 15766 15767 installFlags = INSTALL_INTERNAL; 15768 moveCompleteApp = true; 15769 measurePath = Environment.getDataAppDirectory(volumeUuid); 15770 } 15771 15772 final PackageStats stats = new PackageStats(null, -1); 15773 synchronized (mInstaller) { 15774 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 15775 unfreezePackage(packageName); 15776 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15777 "Failed to measure package size"); 15778 } 15779 } 15780 15781 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 15782 + stats.dataSize); 15783 15784 final long startFreeBytes = measurePath.getFreeSpace(); 15785 final long sizeBytes; 15786 if (moveCompleteApp) { 15787 sizeBytes = stats.codeSize + stats.dataSize; 15788 } else { 15789 sizeBytes = stats.codeSize; 15790 } 15791 15792 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 15793 unfreezePackage(packageName); 15794 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15795 "Not enough free space to move"); 15796 } 15797 15798 mMoveCallbacks.notifyStatusChanged(moveId, 10); 15799 15800 final CountDownLatch installedLatch = new CountDownLatch(1); 15801 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 15802 @Override 15803 public void onUserActionRequired(Intent intent) throws RemoteException { 15804 throw new IllegalStateException(); 15805 } 15806 15807 @Override 15808 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 15809 Bundle extras) throws RemoteException { 15810 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 15811 + PackageManager.installStatusToString(returnCode, msg)); 15812 15813 installedLatch.countDown(); 15814 15815 // Regardless of success or failure of the move operation, 15816 // always unfreeze the package 15817 unfreezePackage(packageName); 15818 15819 final int status = PackageManager.installStatusToPublicStatus(returnCode); 15820 switch (status) { 15821 case PackageInstaller.STATUS_SUCCESS: 15822 mMoveCallbacks.notifyStatusChanged(moveId, 15823 PackageManager.MOVE_SUCCEEDED); 15824 break; 15825 case PackageInstaller.STATUS_FAILURE_STORAGE: 15826 mMoveCallbacks.notifyStatusChanged(moveId, 15827 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 15828 break; 15829 default: 15830 mMoveCallbacks.notifyStatusChanged(moveId, 15831 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15832 break; 15833 } 15834 } 15835 }; 15836 15837 final MoveInfo move; 15838 if (moveCompleteApp) { 15839 // Kick off a thread to report progress estimates 15840 new Thread() { 15841 @Override 15842 public void run() { 15843 while (true) { 15844 try { 15845 if (installedLatch.await(1, TimeUnit.SECONDS)) { 15846 break; 15847 } 15848 } catch (InterruptedException ignored) { 15849 } 15850 15851 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 15852 final int progress = 10 + (int) MathUtils.constrain( 15853 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 15854 mMoveCallbacks.notifyStatusChanged(moveId, progress); 15855 } 15856 } 15857 }.start(); 15858 15859 final String dataAppName = codeFile.getName(); 15860 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 15861 dataAppName, appId, seinfo); 15862 } else { 15863 move = null; 15864 } 15865 15866 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 15867 15868 final Message msg = mHandler.obtainMessage(INIT_COPY); 15869 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 15870 msg.obj = new InstallParams(origin, move, installObserver, installFlags, 15871 installerPackageName, volumeUuid, null, user, packageAbiOverride); 15872 mHandler.sendMessage(msg); 15873 } 15874 15875 @Override 15876 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 15877 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15878 15879 final int realMoveId = mNextMoveId.getAndIncrement(); 15880 final Bundle extras = new Bundle(); 15881 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 15882 mMoveCallbacks.notifyCreated(realMoveId, extras); 15883 15884 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 15885 @Override 15886 public void onCreated(int moveId, Bundle extras) { 15887 // Ignored 15888 } 15889 15890 @Override 15891 public void onStatusChanged(int moveId, int status, long estMillis) { 15892 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 15893 } 15894 }; 15895 15896 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15897 storage.setPrimaryStorageUuid(volumeUuid, callback); 15898 return realMoveId; 15899 } 15900 15901 @Override 15902 public int getMoveStatus(int moveId) { 15903 mContext.enforceCallingOrSelfPermission( 15904 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15905 return mMoveCallbacks.mLastStatus.get(moveId); 15906 } 15907 15908 @Override 15909 public void registerMoveCallback(IPackageMoveObserver callback) { 15910 mContext.enforceCallingOrSelfPermission( 15911 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15912 mMoveCallbacks.register(callback); 15913 } 15914 15915 @Override 15916 public void unregisterMoveCallback(IPackageMoveObserver callback) { 15917 mContext.enforceCallingOrSelfPermission( 15918 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15919 mMoveCallbacks.unregister(callback); 15920 } 15921 15922 @Override 15923 public boolean setInstallLocation(int loc) { 15924 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 15925 null); 15926 if (getInstallLocation() == loc) { 15927 return true; 15928 } 15929 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 15930 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 15931 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 15932 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 15933 return true; 15934 } 15935 return false; 15936 } 15937 15938 @Override 15939 public int getInstallLocation() { 15940 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 15941 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 15942 PackageHelper.APP_INSTALL_AUTO); 15943 } 15944 15945 /** Called by UserManagerService */ 15946 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 15947 mDirtyUsers.remove(userHandle); 15948 mSettings.removeUserLPw(userHandle); 15949 mPendingBroadcasts.remove(userHandle); 15950 if (mInstaller != null) { 15951 // Technically, we shouldn't be doing this with the package lock 15952 // held. However, this is very rare, and there is already so much 15953 // other disk I/O going on, that we'll let it slide for now. 15954 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15955 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 15956 final String volumeUuid = vol.getFsUuid(); 15957 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 15958 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 15959 } 15960 } 15961 mUserNeedsBadging.delete(userHandle); 15962 removeUnusedPackagesLILPw(userManager, userHandle); 15963 } 15964 15965 /** 15966 * We're removing userHandle and would like to remove any downloaded packages 15967 * that are no longer in use by any other user. 15968 * @param userHandle the user being removed 15969 */ 15970 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 15971 final boolean DEBUG_CLEAN_APKS = false; 15972 int [] users = userManager.getUserIdsLPr(); 15973 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 15974 while (psit.hasNext()) { 15975 PackageSetting ps = psit.next(); 15976 if (ps.pkg == null) { 15977 continue; 15978 } 15979 final String packageName = ps.pkg.packageName; 15980 // Skip over if system app 15981 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 15982 continue; 15983 } 15984 if (DEBUG_CLEAN_APKS) { 15985 Slog.i(TAG, "Checking package " + packageName); 15986 } 15987 boolean keep = false; 15988 for (int i = 0; i < users.length; i++) { 15989 if (users[i] != userHandle && ps.getInstalled(users[i])) { 15990 keep = true; 15991 if (DEBUG_CLEAN_APKS) { 15992 Slog.i(TAG, " Keeping package " + packageName + " for user " 15993 + users[i]); 15994 } 15995 break; 15996 } 15997 } 15998 if (!keep) { 15999 if (DEBUG_CLEAN_APKS) { 16000 Slog.i(TAG, " Removing package " + packageName); 16001 } 16002 mHandler.post(new Runnable() { 16003 public void run() { 16004 deletePackageX(packageName, userHandle, 0); 16005 } //end run 16006 }); 16007 } 16008 } 16009 } 16010 16011 /** Called by UserManagerService */ 16012 void createNewUserLILPw(int userHandle) { 16013 if (mInstaller != null) { 16014 mInstaller.createUserConfig(userHandle); 16015 mSettings.createNewUserLILPw(this, mInstaller, userHandle); 16016 applyFactoryDefaultBrowserLPw(userHandle); 16017 primeDomainVerificationsLPw(userHandle); 16018 } 16019 } 16020 16021 void newUserCreated(final int userHandle) { 16022 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 16023 } 16024 16025 @Override 16026 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 16027 mContext.enforceCallingOrSelfPermission( 16028 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 16029 "Only package verification agents can read the verifier device identity"); 16030 16031 synchronized (mPackages) { 16032 return mSettings.getVerifierDeviceIdentityLPw(); 16033 } 16034 } 16035 16036 @Override 16037 public void setPermissionEnforced(String permission, boolean enforced) { 16038 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 16039 if (READ_EXTERNAL_STORAGE.equals(permission)) { 16040 synchronized (mPackages) { 16041 if (mSettings.mReadExternalStorageEnforced == null 16042 || mSettings.mReadExternalStorageEnforced != enforced) { 16043 mSettings.mReadExternalStorageEnforced = enforced; 16044 mSettings.writeLPr(); 16045 } 16046 } 16047 // kill any non-foreground processes so we restart them and 16048 // grant/revoke the GID. 16049 final IActivityManager am = ActivityManagerNative.getDefault(); 16050 if (am != null) { 16051 final long token = Binder.clearCallingIdentity(); 16052 try { 16053 am.killProcessesBelowForeground("setPermissionEnforcement"); 16054 } catch (RemoteException e) { 16055 } finally { 16056 Binder.restoreCallingIdentity(token); 16057 } 16058 } 16059 } else { 16060 throw new IllegalArgumentException("No selective enforcement for " + permission); 16061 } 16062 } 16063 16064 @Override 16065 @Deprecated 16066 public boolean isPermissionEnforced(String permission) { 16067 return true; 16068 } 16069 16070 @Override 16071 public boolean isStorageLow() { 16072 final long token = Binder.clearCallingIdentity(); 16073 try { 16074 final DeviceStorageMonitorInternal 16075 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 16076 if (dsm != null) { 16077 return dsm.isMemoryLow(); 16078 } else { 16079 return false; 16080 } 16081 } finally { 16082 Binder.restoreCallingIdentity(token); 16083 } 16084 } 16085 16086 @Override 16087 public IPackageInstaller getPackageInstaller() { 16088 return mInstallerService; 16089 } 16090 16091 private boolean userNeedsBadging(int userId) { 16092 int index = mUserNeedsBadging.indexOfKey(userId); 16093 if (index < 0) { 16094 final UserInfo userInfo; 16095 final long token = Binder.clearCallingIdentity(); 16096 try { 16097 userInfo = sUserManager.getUserInfo(userId); 16098 } finally { 16099 Binder.restoreCallingIdentity(token); 16100 } 16101 final boolean b; 16102 if (userInfo != null && userInfo.isManagedProfile()) { 16103 b = true; 16104 } else { 16105 b = false; 16106 } 16107 mUserNeedsBadging.put(userId, b); 16108 return b; 16109 } 16110 return mUserNeedsBadging.valueAt(index); 16111 } 16112 16113 @Override 16114 public KeySet getKeySetByAlias(String packageName, String alias) { 16115 if (packageName == null || alias == null) { 16116 return null; 16117 } 16118 synchronized(mPackages) { 16119 final PackageParser.Package pkg = mPackages.get(packageName); 16120 if (pkg == null) { 16121 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16122 throw new IllegalArgumentException("Unknown package: " + packageName); 16123 } 16124 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16125 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 16126 } 16127 } 16128 16129 @Override 16130 public KeySet getSigningKeySet(String packageName) { 16131 if (packageName == null) { 16132 return null; 16133 } 16134 synchronized(mPackages) { 16135 final PackageParser.Package pkg = mPackages.get(packageName); 16136 if (pkg == null) { 16137 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16138 throw new IllegalArgumentException("Unknown package: " + packageName); 16139 } 16140 if (pkg.applicationInfo.uid != Binder.getCallingUid() 16141 && Process.SYSTEM_UID != Binder.getCallingUid()) { 16142 throw new SecurityException("May not access signing KeySet of other apps."); 16143 } 16144 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16145 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 16146 } 16147 } 16148 16149 @Override 16150 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 16151 if (packageName == null || ks == null) { 16152 return false; 16153 } 16154 synchronized(mPackages) { 16155 final PackageParser.Package pkg = mPackages.get(packageName); 16156 if (pkg == null) { 16157 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16158 throw new IllegalArgumentException("Unknown package: " + packageName); 16159 } 16160 IBinder ksh = ks.getToken(); 16161 if (ksh instanceof KeySetHandle) { 16162 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16163 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 16164 } 16165 return false; 16166 } 16167 } 16168 16169 @Override 16170 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 16171 if (packageName == null || ks == null) { 16172 return false; 16173 } 16174 synchronized(mPackages) { 16175 final PackageParser.Package pkg = mPackages.get(packageName); 16176 if (pkg == null) { 16177 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16178 throw new IllegalArgumentException("Unknown package: " + packageName); 16179 } 16180 IBinder ksh = ks.getToken(); 16181 if (ksh instanceof KeySetHandle) { 16182 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16183 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 16184 } 16185 return false; 16186 } 16187 } 16188 16189 public void getUsageStatsIfNoPackageUsageInfo() { 16190 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 16191 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 16192 if (usm == null) { 16193 throw new IllegalStateException("UsageStatsManager must be initialized"); 16194 } 16195 long now = System.currentTimeMillis(); 16196 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 16197 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 16198 String packageName = entry.getKey(); 16199 PackageParser.Package pkg = mPackages.get(packageName); 16200 if (pkg == null) { 16201 continue; 16202 } 16203 UsageStats usage = entry.getValue(); 16204 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 16205 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 16206 } 16207 } 16208 } 16209 16210 /** 16211 * Check and throw if the given before/after packages would be considered a 16212 * downgrade. 16213 */ 16214 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 16215 throws PackageManagerException { 16216 if (after.versionCode < before.mVersionCode) { 16217 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16218 "Update version code " + after.versionCode + " is older than current " 16219 + before.mVersionCode); 16220 } else if (after.versionCode == before.mVersionCode) { 16221 if (after.baseRevisionCode < before.baseRevisionCode) { 16222 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16223 "Update base revision code " + after.baseRevisionCode 16224 + " is older than current " + before.baseRevisionCode); 16225 } 16226 16227 if (!ArrayUtils.isEmpty(after.splitNames)) { 16228 for (int i = 0; i < after.splitNames.length; i++) { 16229 final String splitName = after.splitNames[i]; 16230 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 16231 if (j != -1) { 16232 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 16233 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16234 "Update split " + splitName + " revision code " 16235 + after.splitRevisionCodes[i] + " is older than current " 16236 + before.splitRevisionCodes[j]); 16237 } 16238 } 16239 } 16240 } 16241 } 16242 } 16243 16244 private static class MoveCallbacks extends Handler { 16245 private static final int MSG_CREATED = 1; 16246 private static final int MSG_STATUS_CHANGED = 2; 16247 16248 private final RemoteCallbackList<IPackageMoveObserver> 16249 mCallbacks = new RemoteCallbackList<>(); 16250 16251 private final SparseIntArray mLastStatus = new SparseIntArray(); 16252 16253 public MoveCallbacks(Looper looper) { 16254 super(looper); 16255 } 16256 16257 public void register(IPackageMoveObserver callback) { 16258 mCallbacks.register(callback); 16259 } 16260 16261 public void unregister(IPackageMoveObserver callback) { 16262 mCallbacks.unregister(callback); 16263 } 16264 16265 @Override 16266 public void handleMessage(Message msg) { 16267 final SomeArgs args = (SomeArgs) msg.obj; 16268 final int n = mCallbacks.beginBroadcast(); 16269 for (int i = 0; i < n; i++) { 16270 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 16271 try { 16272 invokeCallback(callback, msg.what, args); 16273 } catch (RemoteException ignored) { 16274 } 16275 } 16276 mCallbacks.finishBroadcast(); 16277 args.recycle(); 16278 } 16279 16280 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 16281 throws RemoteException { 16282 switch (what) { 16283 case MSG_CREATED: { 16284 callback.onCreated(args.argi1, (Bundle) args.arg2); 16285 break; 16286 } 16287 case MSG_STATUS_CHANGED: { 16288 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 16289 break; 16290 } 16291 } 16292 } 16293 16294 private void notifyCreated(int moveId, Bundle extras) { 16295 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 16296 16297 final SomeArgs args = SomeArgs.obtain(); 16298 args.argi1 = moveId; 16299 args.arg2 = extras; 16300 obtainMessage(MSG_CREATED, args).sendToTarget(); 16301 } 16302 16303 private void notifyStatusChanged(int moveId, int status) { 16304 notifyStatusChanged(moveId, status, -1); 16305 } 16306 16307 private void notifyStatusChanged(int moveId, int status, long estMillis) { 16308 Slog.v(TAG, "Move " + moveId + " status " + status); 16309 16310 final SomeArgs args = SomeArgs.obtain(); 16311 args.argi1 = moveId; 16312 args.argi2 = status; 16313 args.arg3 = estMillis; 16314 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 16315 16316 synchronized (mLastStatus) { 16317 mLastStatus.put(moveId, status); 16318 } 16319 } 16320 } 16321 16322 private final class OnPermissionChangeListeners extends Handler { 16323 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 16324 16325 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 16326 new RemoteCallbackList<>(); 16327 16328 public OnPermissionChangeListeners(Looper looper) { 16329 super(looper); 16330 } 16331 16332 @Override 16333 public void handleMessage(Message msg) { 16334 switch (msg.what) { 16335 case MSG_ON_PERMISSIONS_CHANGED: { 16336 final int uid = msg.arg1; 16337 handleOnPermissionsChanged(uid); 16338 } break; 16339 } 16340 } 16341 16342 public void addListenerLocked(IOnPermissionsChangeListener listener) { 16343 mPermissionListeners.register(listener); 16344 16345 } 16346 16347 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 16348 mPermissionListeners.unregister(listener); 16349 } 16350 16351 public void onPermissionsChanged(int uid) { 16352 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 16353 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 16354 } 16355 } 16356 16357 private void handleOnPermissionsChanged(int uid) { 16358 final int count = mPermissionListeners.beginBroadcast(); 16359 try { 16360 for (int i = 0; i < count; i++) { 16361 IOnPermissionsChangeListener callback = mPermissionListeners 16362 .getBroadcastItem(i); 16363 try { 16364 callback.onPermissionsChanged(uid); 16365 } catch (RemoteException e) { 16366 Log.e(TAG, "Permission listener is dead", e); 16367 } 16368 } 16369 } finally { 16370 mPermissionListeners.finishBroadcast(); 16371 } 16372 } 16373 } 16374 16375 private class PackageManagerInternalImpl extends PackageManagerInternal { 16376 @Override 16377 public void setLocationPackagesProvider(PackagesProvider provider) { 16378 synchronized (mPackages) { 16379 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 16380 } 16381 } 16382 16383 @Override 16384 public void setImePackagesProvider(PackagesProvider provider) { 16385 synchronized (mPackages) { 16386 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 16387 } 16388 } 16389 16390 @Override 16391 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 16392 synchronized (mPackages) { 16393 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 16394 } 16395 } 16396 16397 @Override 16398 public void setSmsAppPackagesProvider(PackagesProvider provider) { 16399 synchronized (mPackages) { 16400 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 16401 } 16402 } 16403 16404 @Override 16405 public void setDialerAppPackagesProvider(PackagesProvider provider) { 16406 synchronized (mPackages) { 16407 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 16408 } 16409 } 16410 16411 @Override 16412 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 16413 synchronized (mPackages) { 16414 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 16415 } 16416 } 16417 16418 @Override 16419 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 16420 synchronized (mPackages) { 16421 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 16422 packageName, userId); 16423 } 16424 } 16425 16426 @Override 16427 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 16428 synchronized (mPackages) { 16429 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 16430 packageName, userId); 16431 } 16432 } 16433 } 16434 16435 @Override 16436 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 16437 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 16438 synchronized (mPackages) { 16439 final long identity = Binder.clearCallingIdentity(); 16440 try { 16441 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 16442 packageNames, userId); 16443 } finally { 16444 Binder.restoreCallingIdentity(identity); 16445 } 16446 } 16447 } 16448 16449 private static void enforceSystemOrPhoneCaller(String tag) { 16450 int callingUid = Binder.getCallingUid(); 16451 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 16452 throw new SecurityException( 16453 "Cannot call " + tag + " from UID " + callingUid); 16454 } 16455 } 16456} 16457