PackageManagerService.java revision 4248250c936ded1d5c32b47681817c52f0600c7e
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 6163 synchronized (mInstallLock) { 6164 final String[] instructionSets = new String[] { targetInstructionSet }; 6165 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 6166 false /* forceDex */, false /* defer */, true /* inclDependencies */); 6167 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6168 } 6169 } 6170 6171 public ArraySet<String> getPackagesThatNeedDexOpt() { 6172 ArraySet<String> pkgs = null; 6173 synchronized (mPackages) { 6174 for (PackageParser.Package p : mPackages.values()) { 6175 if (DEBUG_DEXOPT) { 6176 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 6177 } 6178 if (!p.mDexOptPerformed.isEmpty()) { 6179 continue; 6180 } 6181 if (pkgs == null) { 6182 pkgs = new ArraySet<String>(); 6183 } 6184 pkgs.add(p.packageName); 6185 } 6186 } 6187 return pkgs; 6188 } 6189 6190 public void shutdown() { 6191 mPackageUsage.write(true); 6192 } 6193 6194 @Override 6195 public void forceDexOpt(String packageName) { 6196 enforceSystemOrRoot("forceDexOpt"); 6197 6198 PackageParser.Package pkg; 6199 synchronized (mPackages) { 6200 pkg = mPackages.get(packageName); 6201 if (pkg == null) { 6202 throw new IllegalArgumentException("Missing package: " + packageName); 6203 } 6204 } 6205 6206 synchronized (mInstallLock) { 6207 final String[] instructionSets = new String[] { 6208 getPrimaryInstructionSet(pkg.applicationInfo) }; 6209 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 6210 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 6211 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 6212 throw new IllegalStateException("Failed to dexopt: " + res); 6213 } 6214 } 6215 } 6216 6217 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 6218 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 6219 Slog.w(TAG, "Unable to update from " + oldPkg.name 6220 + " to " + newPkg.packageName 6221 + ": old package not in system partition"); 6222 return false; 6223 } else if (mPackages.get(oldPkg.name) != null) { 6224 Slog.w(TAG, "Unable to update from " + oldPkg.name 6225 + " to " + newPkg.packageName 6226 + ": old package still exists"); 6227 return false; 6228 } 6229 return true; 6230 } 6231 6232 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 6233 int[] users = sUserManager.getUserIds(); 6234 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 6235 if (res < 0) { 6236 return res; 6237 } 6238 for (int user : users) { 6239 if (user != 0) { 6240 res = mInstaller.createUserData(volumeUuid, packageName, 6241 UserHandle.getUid(user, uid), user, seinfo); 6242 if (res < 0) { 6243 return res; 6244 } 6245 } 6246 } 6247 return res; 6248 } 6249 6250 private int removeDataDirsLI(String volumeUuid, String packageName) { 6251 int[] users = sUserManager.getUserIds(); 6252 int res = 0; 6253 for (int user : users) { 6254 int resInner = mInstaller.remove(volumeUuid, packageName, user); 6255 if (resInner < 0) { 6256 res = resInner; 6257 } 6258 } 6259 6260 return res; 6261 } 6262 6263 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 6264 int[] users = sUserManager.getUserIds(); 6265 int res = 0; 6266 for (int user : users) { 6267 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 6268 if (resInner < 0) { 6269 res = resInner; 6270 } 6271 } 6272 return res; 6273 } 6274 6275 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 6276 PackageParser.Package changingLib) { 6277 if (file.path != null) { 6278 usesLibraryFiles.add(file.path); 6279 return; 6280 } 6281 PackageParser.Package p = mPackages.get(file.apk); 6282 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 6283 // If we are doing this while in the middle of updating a library apk, 6284 // then we need to make sure to use that new apk for determining the 6285 // dependencies here. (We haven't yet finished committing the new apk 6286 // to the package manager state.) 6287 if (p == null || p.packageName.equals(changingLib.packageName)) { 6288 p = changingLib; 6289 } 6290 } 6291 if (p != null) { 6292 usesLibraryFiles.addAll(p.getAllCodePaths()); 6293 } 6294 } 6295 6296 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 6297 PackageParser.Package changingLib) throws PackageManagerException { 6298 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 6299 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 6300 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 6301 for (int i=0; i<N; i++) { 6302 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 6303 if (file == null) { 6304 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 6305 "Package " + pkg.packageName + " requires unavailable shared library " 6306 + pkg.usesLibraries.get(i) + "; failing!"); 6307 } 6308 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6309 } 6310 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 6311 for (int i=0; i<N; i++) { 6312 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 6313 if (file == null) { 6314 Slog.w(TAG, "Package " + pkg.packageName 6315 + " desires unavailable shared library " 6316 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 6317 } else { 6318 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6319 } 6320 } 6321 N = usesLibraryFiles.size(); 6322 if (N > 0) { 6323 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 6324 } else { 6325 pkg.usesLibraryFiles = null; 6326 } 6327 } 6328 } 6329 6330 private static boolean hasString(List<String> list, List<String> which) { 6331 if (list == null) { 6332 return false; 6333 } 6334 for (int i=list.size()-1; i>=0; i--) { 6335 for (int j=which.size()-1; j>=0; j--) { 6336 if (which.get(j).equals(list.get(i))) { 6337 return true; 6338 } 6339 } 6340 } 6341 return false; 6342 } 6343 6344 private void updateAllSharedLibrariesLPw() { 6345 for (PackageParser.Package pkg : mPackages.values()) { 6346 try { 6347 updateSharedLibrariesLPw(pkg, null); 6348 } catch (PackageManagerException e) { 6349 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6350 } 6351 } 6352 } 6353 6354 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 6355 PackageParser.Package changingPkg) { 6356 ArrayList<PackageParser.Package> res = null; 6357 for (PackageParser.Package pkg : mPackages.values()) { 6358 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 6359 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 6360 if (res == null) { 6361 res = new ArrayList<PackageParser.Package>(); 6362 } 6363 res.add(pkg); 6364 try { 6365 updateSharedLibrariesLPw(pkg, changingPkg); 6366 } catch (PackageManagerException e) { 6367 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6368 } 6369 } 6370 } 6371 return res; 6372 } 6373 6374 /** 6375 * Derive the value of the {@code cpuAbiOverride} based on the provided 6376 * value and an optional stored value from the package settings. 6377 */ 6378 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 6379 String cpuAbiOverride = null; 6380 6381 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 6382 cpuAbiOverride = null; 6383 } else if (abiOverride != null) { 6384 cpuAbiOverride = abiOverride; 6385 } else if (settings != null) { 6386 cpuAbiOverride = settings.cpuAbiOverrideString; 6387 } 6388 6389 return cpuAbiOverride; 6390 } 6391 6392 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 6393 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6394 boolean success = false; 6395 try { 6396 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 6397 currentTime, user); 6398 success = true; 6399 return res; 6400 } finally { 6401 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 6402 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 6403 } 6404 } 6405 } 6406 6407 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 6408 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6409 final File scanFile = new File(pkg.codePath); 6410 if (pkg.applicationInfo.getCodePath() == null || 6411 pkg.applicationInfo.getResourcePath() == null) { 6412 // Bail out. The resource and code paths haven't been set. 6413 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 6414 "Code and resource paths haven't been set correctly"); 6415 } 6416 6417 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 6418 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 6419 } else { 6420 // Only allow system apps to be flagged as core apps. 6421 pkg.coreApp = false; 6422 } 6423 6424 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 6425 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6426 } 6427 6428 if (mCustomResolverComponentName != null && 6429 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 6430 setUpCustomResolverActivity(pkg); 6431 } 6432 6433 if (pkg.packageName.equals("android")) { 6434 synchronized (mPackages) { 6435 if (mAndroidApplication != null) { 6436 Slog.w(TAG, "*************************************************"); 6437 Slog.w(TAG, "Core android package being redefined. Skipping."); 6438 Slog.w(TAG, " file=" + scanFile); 6439 Slog.w(TAG, "*************************************************"); 6440 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6441 "Core android package being redefined. Skipping."); 6442 } 6443 6444 // Set up information for our fall-back user intent resolution activity. 6445 mPlatformPackage = pkg; 6446 pkg.mVersionCode = mSdkVersion; 6447 mAndroidApplication = pkg.applicationInfo; 6448 6449 if (!mResolverReplaced) { 6450 mResolveActivity.applicationInfo = mAndroidApplication; 6451 mResolveActivity.name = ResolverActivity.class.getName(); 6452 mResolveActivity.packageName = mAndroidApplication.packageName; 6453 mResolveActivity.processName = "system:ui"; 6454 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6455 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 6456 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 6457 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 6458 mResolveActivity.exported = true; 6459 mResolveActivity.enabled = true; 6460 mResolveInfo.activityInfo = mResolveActivity; 6461 mResolveInfo.priority = 0; 6462 mResolveInfo.preferredOrder = 0; 6463 mResolveInfo.match = 0; 6464 mResolveComponentName = new ComponentName( 6465 mAndroidApplication.packageName, mResolveActivity.name); 6466 } 6467 } 6468 } 6469 6470 if (DEBUG_PACKAGE_SCANNING) { 6471 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6472 Log.d(TAG, "Scanning package " + pkg.packageName); 6473 } 6474 6475 if (mPackages.containsKey(pkg.packageName) 6476 || mSharedLibraries.containsKey(pkg.packageName)) { 6477 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6478 "Application package " + pkg.packageName 6479 + " already installed. Skipping duplicate."); 6480 } 6481 6482 // If we're only installing presumed-existing packages, require that the 6483 // scanned APK is both already known and at the path previously established 6484 // for it. Previously unknown packages we pick up normally, but if we have an 6485 // a priori expectation about this package's install presence, enforce it. 6486 // With a singular exception for new system packages. When an OTA contains 6487 // a new system package, we allow the codepath to change from a system location 6488 // to the user-installed location. If we don't allow this change, any newer, 6489 // user-installed version of the application will be ignored. 6490 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 6491 if (mExpectingBetter.containsKey(pkg.packageName)) { 6492 logCriticalInfo(Log.WARN, 6493 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 6494 } else { 6495 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 6496 if (known != null) { 6497 if (DEBUG_PACKAGE_SCANNING) { 6498 Log.d(TAG, "Examining " + pkg.codePath 6499 + " and requiring known paths " + known.codePathString 6500 + " & " + known.resourcePathString); 6501 } 6502 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6503 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6504 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6505 "Application package " + pkg.packageName 6506 + " found at " + pkg.applicationInfo.getCodePath() 6507 + " but expected at " + known.codePathString + "; ignoring."); 6508 } 6509 } 6510 } 6511 } 6512 6513 // Initialize package source and resource directories 6514 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6515 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6516 6517 SharedUserSetting suid = null; 6518 PackageSetting pkgSetting = null; 6519 6520 if (!isSystemApp(pkg)) { 6521 // Only system apps can use these features. 6522 pkg.mOriginalPackages = null; 6523 pkg.mRealPackage = null; 6524 pkg.mAdoptPermissions = null; 6525 } 6526 6527 // writer 6528 synchronized (mPackages) { 6529 if (pkg.mSharedUserId != null) { 6530 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 6531 if (suid == null) { 6532 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6533 "Creating application package " + pkg.packageName 6534 + " for shared user failed"); 6535 } 6536 if (DEBUG_PACKAGE_SCANNING) { 6537 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6538 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 6539 + "): packages=" + suid.packages); 6540 } 6541 } 6542 6543 // Check if we are renaming from an original package name. 6544 PackageSetting origPackage = null; 6545 String realName = null; 6546 if (pkg.mOriginalPackages != null) { 6547 // This package may need to be renamed to a previously 6548 // installed name. Let's check on that... 6549 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 6550 if (pkg.mOriginalPackages.contains(renamed)) { 6551 // This package had originally been installed as the 6552 // original name, and we have already taken care of 6553 // transitioning to the new one. Just update the new 6554 // one to continue using the old name. 6555 realName = pkg.mRealPackage; 6556 if (!pkg.packageName.equals(renamed)) { 6557 // Callers into this function may have already taken 6558 // care of renaming the package; only do it here if 6559 // it is not already done. 6560 pkg.setPackageName(renamed); 6561 } 6562 6563 } else { 6564 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 6565 if ((origPackage = mSettings.peekPackageLPr( 6566 pkg.mOriginalPackages.get(i))) != null) { 6567 // We do have the package already installed under its 6568 // original name... should we use it? 6569 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 6570 // New package is not compatible with original. 6571 origPackage = null; 6572 continue; 6573 } else if (origPackage.sharedUser != null) { 6574 // Make sure uid is compatible between packages. 6575 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 6576 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 6577 + " to " + pkg.packageName + ": old uid " 6578 + origPackage.sharedUser.name 6579 + " differs from " + pkg.mSharedUserId); 6580 origPackage = null; 6581 continue; 6582 } 6583 } else { 6584 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6585 + pkg.packageName + " to old name " + origPackage.name); 6586 } 6587 break; 6588 } 6589 } 6590 } 6591 } 6592 6593 if (mTransferedPackages.contains(pkg.packageName)) { 6594 Slog.w(TAG, "Package " + pkg.packageName 6595 + " was transferred to another, but its .apk remains"); 6596 } 6597 6598 // Just create the setting, don't add it yet. For already existing packages 6599 // the PkgSetting exists already and doesn't have to be created. 6600 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6601 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6602 pkg.applicationInfo.primaryCpuAbi, 6603 pkg.applicationInfo.secondaryCpuAbi, 6604 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6605 user, false); 6606 if (pkgSetting == null) { 6607 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6608 "Creating application package " + pkg.packageName + " failed"); 6609 } 6610 6611 if (pkgSetting.origPackage != null) { 6612 // If we are first transitioning from an original package, 6613 // fix up the new package's name now. We need to do this after 6614 // looking up the package under its new name, so getPackageLP 6615 // can take care of fiddling things correctly. 6616 pkg.setPackageName(origPackage.name); 6617 6618 // File a report about this. 6619 String msg = "New package " + pkgSetting.realName 6620 + " renamed to replace old package " + pkgSetting.name; 6621 reportSettingsProblem(Log.WARN, msg); 6622 6623 // Make a note of it. 6624 mTransferedPackages.add(origPackage.name); 6625 6626 // No longer need to retain this. 6627 pkgSetting.origPackage = null; 6628 } 6629 6630 if (realName != null) { 6631 // Make a note of it. 6632 mTransferedPackages.add(pkg.packageName); 6633 } 6634 6635 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6636 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6637 } 6638 6639 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6640 // Check all shared libraries and map to their actual file path. 6641 // We only do this here for apps not on a system dir, because those 6642 // are the only ones that can fail an install due to this. We 6643 // will take care of the system apps by updating all of their 6644 // library paths after the scan is done. 6645 updateSharedLibrariesLPw(pkg, null); 6646 } 6647 6648 if (mFoundPolicyFile) { 6649 SELinuxMMAC.assignSeinfoValue(pkg); 6650 } 6651 6652 pkg.applicationInfo.uid = pkgSetting.appId; 6653 pkg.mExtras = pkgSetting; 6654 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 6655 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 6656 // We just determined the app is signed correctly, so bring 6657 // over the latest parsed certs. 6658 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6659 } else { 6660 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6661 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6662 "Package " + pkg.packageName + " upgrade keys do not match the " 6663 + "previously installed version"); 6664 } else { 6665 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6666 String msg = "System package " + pkg.packageName 6667 + " signature changed; retaining data."; 6668 reportSettingsProblem(Log.WARN, msg); 6669 } 6670 } 6671 } else { 6672 try { 6673 verifySignaturesLP(pkgSetting, pkg); 6674 // We just determined the app is signed correctly, so bring 6675 // over the latest parsed certs. 6676 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6677 } catch (PackageManagerException e) { 6678 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6679 throw e; 6680 } 6681 // The signature has changed, but this package is in the system 6682 // image... let's recover! 6683 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6684 // However... if this package is part of a shared user, but it 6685 // doesn't match the signature of the shared user, let's fail. 6686 // What this means is that you can't change the signatures 6687 // associated with an overall shared user, which doesn't seem all 6688 // that unreasonable. 6689 if (pkgSetting.sharedUser != null) { 6690 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6691 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 6692 throw new PackageManagerException( 6693 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6694 "Signature mismatch for shared user : " 6695 + pkgSetting.sharedUser); 6696 } 6697 } 6698 // File a report about this. 6699 String msg = "System package " + pkg.packageName 6700 + " signature changed; retaining data."; 6701 reportSettingsProblem(Log.WARN, msg); 6702 } 6703 } 6704 // Verify that this new package doesn't have any content providers 6705 // that conflict with existing packages. Only do this if the 6706 // package isn't already installed, since we don't want to break 6707 // things that are installed. 6708 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6709 final int N = pkg.providers.size(); 6710 int i; 6711 for (i=0; i<N; i++) { 6712 PackageParser.Provider p = pkg.providers.get(i); 6713 if (p.info.authority != null) { 6714 String names[] = p.info.authority.split(";"); 6715 for (int j = 0; j < names.length; j++) { 6716 if (mProvidersByAuthority.containsKey(names[j])) { 6717 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6718 final String otherPackageName = 6719 ((other != null && other.getComponentName() != null) ? 6720 other.getComponentName().getPackageName() : "?"); 6721 throw new PackageManagerException( 6722 INSTALL_FAILED_CONFLICTING_PROVIDER, 6723 "Can't install because provider name " + names[j] 6724 + " (in package " + pkg.applicationInfo.packageName 6725 + ") is already used by " + otherPackageName); 6726 } 6727 } 6728 } 6729 } 6730 } 6731 6732 if (pkg.mAdoptPermissions != null) { 6733 // This package wants to adopt ownership of permissions from 6734 // another package. 6735 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6736 final String origName = pkg.mAdoptPermissions.get(i); 6737 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6738 if (orig != null) { 6739 if (verifyPackageUpdateLPr(orig, pkg)) { 6740 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6741 + pkg.packageName); 6742 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6743 } 6744 } 6745 } 6746 } 6747 } 6748 6749 final String pkgName = pkg.packageName; 6750 6751 final long scanFileTime = scanFile.lastModified(); 6752 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6753 pkg.applicationInfo.processName = fixProcessName( 6754 pkg.applicationInfo.packageName, 6755 pkg.applicationInfo.processName, 6756 pkg.applicationInfo.uid); 6757 6758 File dataPath; 6759 if (mPlatformPackage == pkg) { 6760 // The system package is special. 6761 dataPath = new File(Environment.getDataDirectory(), "system"); 6762 6763 pkg.applicationInfo.dataDir = dataPath.getPath(); 6764 6765 } else { 6766 // This is a normal package, need to make its data directory. 6767 dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid, 6768 UserHandle.USER_OWNER, pkg.packageName); 6769 6770 boolean uidError = false; 6771 if (dataPath.exists()) { 6772 int currentUid = 0; 6773 try { 6774 StructStat stat = Os.stat(dataPath.getPath()); 6775 currentUid = stat.st_uid; 6776 } catch (ErrnoException e) { 6777 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6778 } 6779 6780 // If we have mismatched owners for the data path, we have a problem. 6781 if (currentUid != pkg.applicationInfo.uid) { 6782 boolean recovered = false; 6783 if (currentUid == 0) { 6784 // The directory somehow became owned by root. Wow. 6785 // This is probably because the system was stopped while 6786 // installd was in the middle of messing with its libs 6787 // directory. Ask installd to fix that. 6788 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6789 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6790 if (ret >= 0) { 6791 recovered = true; 6792 String msg = "Package " + pkg.packageName 6793 + " unexpectedly changed to uid 0; recovered to " + 6794 + pkg.applicationInfo.uid; 6795 reportSettingsProblem(Log.WARN, msg); 6796 } 6797 } 6798 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6799 || (scanFlags&SCAN_BOOTING) != 0)) { 6800 // If this is a system app, we can at least delete its 6801 // current data so the application will still work. 6802 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6803 if (ret >= 0) { 6804 // TODO: Kill the processes first 6805 // Old data gone! 6806 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6807 ? "System package " : "Third party package "; 6808 String msg = prefix + pkg.packageName 6809 + " has changed from uid: " 6810 + currentUid + " to " 6811 + pkg.applicationInfo.uid + "; old data erased"; 6812 reportSettingsProblem(Log.WARN, msg); 6813 recovered = true; 6814 6815 // And now re-install the app. 6816 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6817 pkg.applicationInfo.seinfo); 6818 if (ret == -1) { 6819 // Ack should not happen! 6820 msg = prefix + pkg.packageName 6821 + " could not have data directory re-created after delete."; 6822 reportSettingsProblem(Log.WARN, msg); 6823 throw new PackageManagerException( 6824 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6825 } 6826 } 6827 if (!recovered) { 6828 mHasSystemUidErrors = true; 6829 } 6830 } else if (!recovered) { 6831 // If we allow this install to proceed, we will be broken. 6832 // Abort, abort! 6833 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6834 "scanPackageLI"); 6835 } 6836 if (!recovered) { 6837 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6838 + pkg.applicationInfo.uid + "/fs_" 6839 + currentUid; 6840 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6841 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6842 String msg = "Package " + pkg.packageName 6843 + " has mismatched uid: " 6844 + currentUid + " on disk, " 6845 + pkg.applicationInfo.uid + " in settings"; 6846 // writer 6847 synchronized (mPackages) { 6848 mSettings.mReadMessages.append(msg); 6849 mSettings.mReadMessages.append('\n'); 6850 uidError = true; 6851 if (!pkgSetting.uidError) { 6852 reportSettingsProblem(Log.ERROR, msg); 6853 } 6854 } 6855 } 6856 } 6857 pkg.applicationInfo.dataDir = dataPath.getPath(); 6858 if (mShouldRestoreconData) { 6859 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6860 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 6861 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 6862 } 6863 } else { 6864 if (DEBUG_PACKAGE_SCANNING) { 6865 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6866 Log.v(TAG, "Want this data dir: " + dataPath); 6867 } 6868 //invoke installer to do the actual installation 6869 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6870 pkg.applicationInfo.seinfo); 6871 if (ret < 0) { 6872 // Error from installer 6873 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6874 "Unable to create data dirs [errorCode=" + ret + "]"); 6875 } 6876 6877 if (dataPath.exists()) { 6878 pkg.applicationInfo.dataDir = dataPath.getPath(); 6879 } else { 6880 Slog.w(TAG, "Unable to create data directory: " + dataPath); 6881 pkg.applicationInfo.dataDir = null; 6882 } 6883 } 6884 6885 pkgSetting.uidError = uidError; 6886 } 6887 6888 final String path = scanFile.getPath(); 6889 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6890 6891 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 6892 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 6893 6894 // Some system apps still use directory structure for native libraries 6895 // in which case we might end up not detecting abi solely based on apk 6896 // structure. Try to detect abi based on directory structure. 6897 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 6898 pkg.applicationInfo.primaryCpuAbi == null) { 6899 setBundledAppAbisAndRoots(pkg, pkgSetting); 6900 setNativeLibraryPaths(pkg); 6901 } 6902 6903 } else { 6904 if ((scanFlags & SCAN_MOVE) != 0) { 6905 // We haven't run dex-opt for this move (since we've moved the compiled output too) 6906 // but we already have this packages package info in the PackageSetting. We just 6907 // use that and derive the native library path based on the new codepath. 6908 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 6909 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 6910 } 6911 6912 // Set native library paths again. For moves, the path will be updated based on the 6913 // ABIs we've determined above. For non-moves, the path will be updated based on the 6914 // ABIs we determined during compilation, but the path will depend on the final 6915 // package path (after the rename away from the stage path). 6916 setNativeLibraryPaths(pkg); 6917 } 6918 6919 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 6920 final int[] userIds = sUserManager.getUserIds(); 6921 synchronized (mInstallLock) { 6922 // Make sure all user data directories are ready to roll; we're okay 6923 // if they already exist 6924 if (!TextUtils.isEmpty(pkg.volumeUuid)) { 6925 for (int userId : userIds) { 6926 if (userId != 0) { 6927 mInstaller.createUserData(pkg.volumeUuid, pkg.packageName, 6928 UserHandle.getUid(userId, pkg.applicationInfo.uid), userId, 6929 pkg.applicationInfo.seinfo); 6930 } 6931 } 6932 } 6933 6934 // Create a native library symlink only if we have native libraries 6935 // and if the native libraries are 32 bit libraries. We do not provide 6936 // this symlink for 64 bit libraries. 6937 if (pkg.applicationInfo.primaryCpuAbi != null && 6938 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 6939 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 6940 for (int userId : userIds) { 6941 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 6942 nativeLibPath, userId) < 0) { 6943 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6944 "Failed linking native library dir (user=" + userId + ")"); 6945 } 6946 } 6947 } 6948 } 6949 6950 // This is a special case for the "system" package, where the ABI is 6951 // dictated by the zygote configuration (and init.rc). We should keep track 6952 // of this ABI so that we can deal with "normal" applications that run under 6953 // the same UID correctly. 6954 if (mPlatformPackage == pkg) { 6955 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 6956 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 6957 } 6958 6959 // If there's a mismatch between the abi-override in the package setting 6960 // and the abiOverride specified for the install. Warn about this because we 6961 // would've already compiled the app without taking the package setting into 6962 // account. 6963 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 6964 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 6965 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 6966 " for package: " + pkg.packageName); 6967 } 6968 } 6969 6970 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6971 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6972 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 6973 6974 // Copy the derived override back to the parsed package, so that we can 6975 // update the package settings accordingly. 6976 pkg.cpuAbiOverride = cpuAbiOverride; 6977 6978 if (DEBUG_ABI_SELECTION) { 6979 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 6980 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 6981 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 6982 } 6983 6984 // Push the derived path down into PackageSettings so we know what to 6985 // clean up at uninstall time. 6986 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 6987 6988 if (DEBUG_ABI_SELECTION) { 6989 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 6990 " primary=" + pkg.applicationInfo.primaryCpuAbi + 6991 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 6992 } 6993 6994 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 6995 // We don't do this here during boot because we can do it all 6996 // at once after scanning all existing packages. 6997 // 6998 // We also do this *before* we perform dexopt on this package, so that 6999 // we can avoid redundant dexopts, and also to make sure we've got the 7000 // code and package path correct. 7001 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 7002 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 7003 } 7004 7005 if ((scanFlags & SCAN_NO_DEX) == 0) { 7006 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 7007 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 7008 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7009 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 7010 } 7011 } 7012 if (mFactoryTest && pkg.requestedPermissions.contains( 7013 android.Manifest.permission.FACTORY_TEST)) { 7014 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 7015 } 7016 7017 ArrayList<PackageParser.Package> clientLibPkgs = null; 7018 7019 // writer 7020 synchronized (mPackages) { 7021 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7022 // Only system apps can add new shared libraries. 7023 if (pkg.libraryNames != null) { 7024 for (int i=0; i<pkg.libraryNames.size(); i++) { 7025 String name = pkg.libraryNames.get(i); 7026 boolean allowed = false; 7027 if (pkg.isUpdatedSystemApp()) { 7028 // New library entries can only be added through the 7029 // system image. This is important to get rid of a lot 7030 // of nasty edge cases: for example if we allowed a non- 7031 // system update of the app to add a library, then uninstalling 7032 // the update would make the library go away, and assumptions 7033 // we made such as through app install filtering would now 7034 // have allowed apps on the device which aren't compatible 7035 // with it. Better to just have the restriction here, be 7036 // conservative, and create many fewer cases that can negatively 7037 // impact the user experience. 7038 final PackageSetting sysPs = mSettings 7039 .getDisabledSystemPkgLPr(pkg.packageName); 7040 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 7041 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 7042 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 7043 allowed = true; 7044 allowed = true; 7045 break; 7046 } 7047 } 7048 } 7049 } else { 7050 allowed = true; 7051 } 7052 if (allowed) { 7053 if (!mSharedLibraries.containsKey(name)) { 7054 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 7055 } else if (!name.equals(pkg.packageName)) { 7056 Slog.w(TAG, "Package " + pkg.packageName + " library " 7057 + name + " already exists; skipping"); 7058 } 7059 } else { 7060 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 7061 + name + " that is not declared on system image; skipping"); 7062 } 7063 } 7064 if ((scanFlags&SCAN_BOOTING) == 0) { 7065 // If we are not booting, we need to update any applications 7066 // that are clients of our shared library. If we are booting, 7067 // this will all be done once the scan is complete. 7068 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 7069 } 7070 } 7071 } 7072 } 7073 7074 // We also need to dexopt any apps that are dependent on this library. Note that 7075 // if these fail, we should abort the install since installing the library will 7076 // result in some apps being broken. 7077 if (clientLibPkgs != null) { 7078 if ((scanFlags & SCAN_NO_DEX) == 0) { 7079 for (int i = 0; i < clientLibPkgs.size(); i++) { 7080 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7081 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 7082 null /* instruction sets */, forceDex, 7083 (scanFlags & SCAN_DEFER_DEX) != 0, false); 7084 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7085 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 7086 "scanPackageLI failed to dexopt clientLibPkgs"); 7087 } 7088 } 7089 } 7090 } 7091 7092 // Also need to kill any apps that are dependent on the library. 7093 if (clientLibPkgs != null) { 7094 for (int i=0; i<clientLibPkgs.size(); i++) { 7095 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7096 killApplication(clientPkg.applicationInfo.packageName, 7097 clientPkg.applicationInfo.uid, "update lib"); 7098 } 7099 } 7100 7101 // Make sure we're not adding any bogus keyset info 7102 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7103 ksms.assertScannedPackageValid(pkg); 7104 7105 // writer 7106 synchronized (mPackages) { 7107 // We don't expect installation to fail beyond this point 7108 7109 // Add the new setting to mSettings 7110 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 7111 // Add the new setting to mPackages 7112 mPackages.put(pkg.applicationInfo.packageName, pkg); 7113 // Make sure we don't accidentally delete its data. 7114 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 7115 while (iter.hasNext()) { 7116 PackageCleanItem item = iter.next(); 7117 if (pkgName.equals(item.packageName)) { 7118 iter.remove(); 7119 } 7120 } 7121 7122 // Take care of first install / last update times. 7123 if (currentTime != 0) { 7124 if (pkgSetting.firstInstallTime == 0) { 7125 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7126 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7127 pkgSetting.lastUpdateTime = currentTime; 7128 } 7129 } else if (pkgSetting.firstInstallTime == 0) { 7130 // We need *something*. Take time time stamp of the file. 7131 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7132 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7133 if (scanFileTime != pkgSetting.timeStamp) { 7134 // A package on the system image has changed; consider this 7135 // to be an update. 7136 pkgSetting.lastUpdateTime = scanFileTime; 7137 } 7138 } 7139 7140 // Add the package's KeySets to the global KeySetManagerService 7141 ksms.addScannedPackageLPw(pkg); 7142 7143 int N = pkg.providers.size(); 7144 StringBuilder r = null; 7145 int i; 7146 for (i=0; i<N; i++) { 7147 PackageParser.Provider p = pkg.providers.get(i); 7148 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7149 p.info.processName, pkg.applicationInfo.uid); 7150 mProviders.addProvider(p); 7151 p.syncable = p.info.isSyncable; 7152 if (p.info.authority != null) { 7153 String names[] = p.info.authority.split(";"); 7154 p.info.authority = null; 7155 for (int j = 0; j < names.length; j++) { 7156 if (j == 1 && p.syncable) { 7157 // We only want the first authority for a provider to possibly be 7158 // syncable, so if we already added this provider using a different 7159 // authority clear the syncable flag. We copy the provider before 7160 // changing it because the mProviders object contains a reference 7161 // to a provider that we don't want to change. 7162 // Only do this for the second authority since the resulting provider 7163 // object can be the same for all future authorities for this provider. 7164 p = new PackageParser.Provider(p); 7165 p.syncable = false; 7166 } 7167 if (!mProvidersByAuthority.containsKey(names[j])) { 7168 mProvidersByAuthority.put(names[j], p); 7169 if (p.info.authority == null) { 7170 p.info.authority = names[j]; 7171 } else { 7172 p.info.authority = p.info.authority + ";" + names[j]; 7173 } 7174 if (DEBUG_PACKAGE_SCANNING) { 7175 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7176 Log.d(TAG, "Registered content provider: " + names[j] 7177 + ", className = " + p.info.name + ", isSyncable = " 7178 + p.info.isSyncable); 7179 } 7180 } else { 7181 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7182 Slog.w(TAG, "Skipping provider name " + names[j] + 7183 " (in package " + pkg.applicationInfo.packageName + 7184 "): name already used by " 7185 + ((other != null && other.getComponentName() != null) 7186 ? other.getComponentName().getPackageName() : "?")); 7187 } 7188 } 7189 } 7190 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7191 if (r == null) { 7192 r = new StringBuilder(256); 7193 } else { 7194 r.append(' '); 7195 } 7196 r.append(p.info.name); 7197 } 7198 } 7199 if (r != null) { 7200 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7201 } 7202 7203 N = pkg.services.size(); 7204 r = null; 7205 for (i=0; i<N; i++) { 7206 PackageParser.Service s = pkg.services.get(i); 7207 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 7208 s.info.processName, pkg.applicationInfo.uid); 7209 mServices.addService(s); 7210 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7211 if (r == null) { 7212 r = new StringBuilder(256); 7213 } else { 7214 r.append(' '); 7215 } 7216 r.append(s.info.name); 7217 } 7218 } 7219 if (r != null) { 7220 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 7221 } 7222 7223 N = pkg.receivers.size(); 7224 r = null; 7225 for (i=0; i<N; i++) { 7226 PackageParser.Activity a = pkg.receivers.get(i); 7227 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7228 a.info.processName, pkg.applicationInfo.uid); 7229 mReceivers.addActivity(a, "receiver"); 7230 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7231 if (r == null) { 7232 r = new StringBuilder(256); 7233 } else { 7234 r.append(' '); 7235 } 7236 r.append(a.info.name); 7237 } 7238 } 7239 if (r != null) { 7240 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 7241 } 7242 7243 N = pkg.activities.size(); 7244 r = null; 7245 for (i=0; i<N; i++) { 7246 PackageParser.Activity a = pkg.activities.get(i); 7247 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7248 a.info.processName, pkg.applicationInfo.uid); 7249 mActivities.addActivity(a, "activity"); 7250 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7251 if (r == null) { 7252 r = new StringBuilder(256); 7253 } else { 7254 r.append(' '); 7255 } 7256 r.append(a.info.name); 7257 } 7258 } 7259 if (r != null) { 7260 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 7261 } 7262 7263 N = pkg.permissionGroups.size(); 7264 r = null; 7265 for (i=0; i<N; i++) { 7266 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 7267 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 7268 if (cur == null) { 7269 mPermissionGroups.put(pg.info.name, pg); 7270 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7271 if (r == null) { 7272 r = new StringBuilder(256); 7273 } else { 7274 r.append(' '); 7275 } 7276 r.append(pg.info.name); 7277 } 7278 } else { 7279 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 7280 + pg.info.packageName + " ignored: original from " 7281 + cur.info.packageName); 7282 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7283 if (r == null) { 7284 r = new StringBuilder(256); 7285 } else { 7286 r.append(' '); 7287 } 7288 r.append("DUP:"); 7289 r.append(pg.info.name); 7290 } 7291 } 7292 } 7293 if (r != null) { 7294 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 7295 } 7296 7297 N = pkg.permissions.size(); 7298 r = null; 7299 for (i=0; i<N; i++) { 7300 PackageParser.Permission p = pkg.permissions.get(i); 7301 7302 // Now that permission groups have a special meaning, we ignore permission 7303 // groups for legacy apps to prevent unexpected behavior. In particular, 7304 // permissions for one app being granted to someone just becuase they happen 7305 // to be in a group defined by another app (before this had no implications). 7306 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 7307 p.group = mPermissionGroups.get(p.info.group); 7308 // Warn for a permission in an unknown group. 7309 if (p.info.group != null && p.group == null) { 7310 Slog.w(TAG, "Permission " + p.info.name + " from package " 7311 + p.info.packageName + " in an unknown group " + p.info.group); 7312 } 7313 } 7314 7315 ArrayMap<String, BasePermission> permissionMap = 7316 p.tree ? mSettings.mPermissionTrees 7317 : mSettings.mPermissions; 7318 BasePermission bp = permissionMap.get(p.info.name); 7319 7320 // Allow system apps to redefine non-system permissions 7321 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 7322 final boolean currentOwnerIsSystem = (bp.perm != null 7323 && isSystemApp(bp.perm.owner)); 7324 if (isSystemApp(p.owner)) { 7325 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 7326 // It's a built-in permission and no owner, take ownership now 7327 bp.packageSetting = pkgSetting; 7328 bp.perm = p; 7329 bp.uid = pkg.applicationInfo.uid; 7330 bp.sourcePackage = p.info.packageName; 7331 } else if (!currentOwnerIsSystem) { 7332 String msg = "New decl " + p.owner + " of permission " 7333 + p.info.name + " is system; overriding " + bp.sourcePackage; 7334 reportSettingsProblem(Log.WARN, msg); 7335 bp = null; 7336 } 7337 } 7338 } 7339 7340 if (bp == null) { 7341 bp = new BasePermission(p.info.name, p.info.packageName, 7342 BasePermission.TYPE_NORMAL); 7343 permissionMap.put(p.info.name, bp); 7344 } 7345 7346 if (bp.perm == null) { 7347 if (bp.sourcePackage == null 7348 || bp.sourcePackage.equals(p.info.packageName)) { 7349 BasePermission tree = findPermissionTreeLP(p.info.name); 7350 if (tree == null 7351 || tree.sourcePackage.equals(p.info.packageName)) { 7352 bp.packageSetting = pkgSetting; 7353 bp.perm = p; 7354 bp.uid = pkg.applicationInfo.uid; 7355 bp.sourcePackage = p.info.packageName; 7356 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7357 if (r == null) { 7358 r = new StringBuilder(256); 7359 } else { 7360 r.append(' '); 7361 } 7362 r.append(p.info.name); 7363 } 7364 } else { 7365 Slog.w(TAG, "Permission " + p.info.name + " from package " 7366 + p.info.packageName + " ignored: base tree " 7367 + tree.name + " is from package " 7368 + tree.sourcePackage); 7369 } 7370 } else { 7371 Slog.w(TAG, "Permission " + p.info.name + " from package " 7372 + p.info.packageName + " ignored: original from " 7373 + bp.sourcePackage); 7374 } 7375 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7376 if (r == null) { 7377 r = new StringBuilder(256); 7378 } else { 7379 r.append(' '); 7380 } 7381 r.append("DUP:"); 7382 r.append(p.info.name); 7383 } 7384 if (bp.perm == p) { 7385 bp.protectionLevel = p.info.protectionLevel; 7386 } 7387 } 7388 7389 if (r != null) { 7390 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 7391 } 7392 7393 N = pkg.instrumentation.size(); 7394 r = null; 7395 for (i=0; i<N; i++) { 7396 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7397 a.info.packageName = pkg.applicationInfo.packageName; 7398 a.info.sourceDir = pkg.applicationInfo.sourceDir; 7399 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 7400 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 7401 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 7402 a.info.dataDir = pkg.applicationInfo.dataDir; 7403 7404 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 7405 // need other information about the application, like the ABI and what not ? 7406 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 7407 mInstrumentation.put(a.getComponentName(), a); 7408 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7409 if (r == null) { 7410 r = new StringBuilder(256); 7411 } else { 7412 r.append(' '); 7413 } 7414 r.append(a.info.name); 7415 } 7416 } 7417 if (r != null) { 7418 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 7419 } 7420 7421 if (pkg.protectedBroadcasts != null) { 7422 N = pkg.protectedBroadcasts.size(); 7423 for (i=0; i<N; i++) { 7424 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 7425 } 7426 } 7427 7428 pkgSetting.setTimeStamp(scanFileTime); 7429 7430 // Create idmap files for pairs of (packages, overlay packages). 7431 // Note: "android", ie framework-res.apk, is handled by native layers. 7432 if (pkg.mOverlayTarget != null) { 7433 // This is an overlay package. 7434 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 7435 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 7436 mOverlays.put(pkg.mOverlayTarget, 7437 new ArrayMap<String, PackageParser.Package>()); 7438 } 7439 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 7440 map.put(pkg.packageName, pkg); 7441 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 7442 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 7443 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7444 "scanPackageLI failed to createIdmap"); 7445 } 7446 } 7447 } else if (mOverlays.containsKey(pkg.packageName) && 7448 !pkg.packageName.equals("android")) { 7449 // This is a regular package, with one or more known overlay packages. 7450 createIdmapsForPackageLI(pkg); 7451 } 7452 } 7453 7454 return pkg; 7455 } 7456 7457 /** 7458 * Derive the ABI of a non-system package located at {@code scanFile}. This information 7459 * is derived purely on the basis of the contents of {@code scanFile} and 7460 * {@code cpuAbiOverride}. 7461 * 7462 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 7463 */ 7464 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 7465 String cpuAbiOverride, boolean extractLibs) 7466 throws PackageManagerException { 7467 // TODO: We can probably be smarter about this stuff. For installed apps, 7468 // we can calculate this information at install time once and for all. For 7469 // system apps, we can probably assume that this information doesn't change 7470 // after the first boot scan. As things stand, we do lots of unnecessary work. 7471 7472 // Give ourselves some initial paths; we'll come back for another 7473 // pass once we've determined ABI below. 7474 setNativeLibraryPaths(pkg); 7475 7476 // We would never need to extract libs for forward-locked and external packages, 7477 // since the container service will do it for us. We shouldn't attempt to 7478 // extract libs from system app when it was not updated. 7479 if (pkg.isForwardLocked() || isExternal(pkg) || 7480 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) { 7481 extractLibs = false; 7482 } 7483 7484 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7485 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7486 7487 NativeLibraryHelper.Handle handle = null; 7488 try { 7489 handle = NativeLibraryHelper.Handle.create(scanFile); 7490 // TODO(multiArch): This can be null for apps that didn't go through the 7491 // usual installation process. We can calculate it again, like we 7492 // do during install time. 7493 // 7494 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7495 // unnecessary. 7496 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7497 7498 // Null out the abis so that they can be recalculated. 7499 pkg.applicationInfo.primaryCpuAbi = null; 7500 pkg.applicationInfo.secondaryCpuAbi = null; 7501 if (isMultiArch(pkg.applicationInfo)) { 7502 // Warn if we've set an abiOverride for multi-lib packages.. 7503 // By definition, we need to copy both 32 and 64 bit libraries for 7504 // such packages. 7505 if (pkg.cpuAbiOverride != null 7506 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7507 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7508 } 7509 7510 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7511 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7512 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7513 if (extractLibs) { 7514 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7515 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7516 useIsaSpecificSubdirs); 7517 } else { 7518 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7519 } 7520 } 7521 7522 maybeThrowExceptionForMultiArchCopy( 7523 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7524 7525 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7526 if (extractLibs) { 7527 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7528 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7529 useIsaSpecificSubdirs); 7530 } else { 7531 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7532 } 7533 } 7534 7535 maybeThrowExceptionForMultiArchCopy( 7536 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7537 7538 if (abi64 >= 0) { 7539 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7540 } 7541 7542 if (abi32 >= 0) { 7543 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7544 if (abi64 >= 0) { 7545 pkg.applicationInfo.secondaryCpuAbi = abi; 7546 } else { 7547 pkg.applicationInfo.primaryCpuAbi = abi; 7548 } 7549 } 7550 } else { 7551 String[] abiList = (cpuAbiOverride != null) ? 7552 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7553 7554 // Enable gross and lame hacks for apps that are built with old 7555 // SDK tools. We must scan their APKs for renderscript bitcode and 7556 // not launch them if it's present. Don't bother checking on devices 7557 // that don't have 64 bit support. 7558 boolean needsRenderScriptOverride = false; 7559 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7560 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7561 abiList = Build.SUPPORTED_32_BIT_ABIS; 7562 needsRenderScriptOverride = true; 7563 } 7564 7565 final int copyRet; 7566 if (extractLibs) { 7567 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7568 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7569 } else { 7570 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7571 } 7572 7573 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7574 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7575 "Error unpackaging native libs for app, errorCode=" + copyRet); 7576 } 7577 7578 if (copyRet >= 0) { 7579 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7580 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7581 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7582 } else if (needsRenderScriptOverride) { 7583 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7584 } 7585 } 7586 } catch (IOException ioe) { 7587 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7588 } finally { 7589 IoUtils.closeQuietly(handle); 7590 } 7591 7592 // Now that we've calculated the ABIs and determined if it's an internal app, 7593 // we will go ahead and populate the nativeLibraryPath. 7594 setNativeLibraryPaths(pkg); 7595 } 7596 7597 /** 7598 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7599 * i.e, so that all packages can be run inside a single process if required. 7600 * 7601 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7602 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7603 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7604 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7605 * updating a package that belongs to a shared user. 7606 * 7607 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7608 * adds unnecessary complexity. 7609 */ 7610 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7611 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 7612 String requiredInstructionSet = null; 7613 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7614 requiredInstructionSet = VMRuntime.getInstructionSet( 7615 scannedPackage.applicationInfo.primaryCpuAbi); 7616 } 7617 7618 PackageSetting requirer = null; 7619 for (PackageSetting ps : packagesForUser) { 7620 // If packagesForUser contains scannedPackage, we skip it. This will happen 7621 // when scannedPackage is an update of an existing package. Without this check, 7622 // we will never be able to change the ABI of any package belonging to a shared 7623 // user, even if it's compatible with other packages. 7624 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7625 if (ps.primaryCpuAbiString == null) { 7626 continue; 7627 } 7628 7629 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7630 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7631 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7632 // this but there's not much we can do. 7633 String errorMessage = "Instruction set mismatch, " 7634 + ((requirer == null) ? "[caller]" : requirer) 7635 + " requires " + requiredInstructionSet + " whereas " + ps 7636 + " requires " + instructionSet; 7637 Slog.w(TAG, errorMessage); 7638 } 7639 7640 if (requiredInstructionSet == null) { 7641 requiredInstructionSet = instructionSet; 7642 requirer = ps; 7643 } 7644 } 7645 } 7646 7647 if (requiredInstructionSet != null) { 7648 String adjustedAbi; 7649 if (requirer != null) { 7650 // requirer != null implies that either scannedPackage was null or that scannedPackage 7651 // did not require an ABI, in which case we have to adjust scannedPackage to match 7652 // the ABI of the set (which is the same as requirer's ABI) 7653 adjustedAbi = requirer.primaryCpuAbiString; 7654 if (scannedPackage != null) { 7655 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7656 } 7657 } else { 7658 // requirer == null implies that we're updating all ABIs in the set to 7659 // match scannedPackage. 7660 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7661 } 7662 7663 for (PackageSetting ps : packagesForUser) { 7664 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7665 if (ps.primaryCpuAbiString != null) { 7666 continue; 7667 } 7668 7669 ps.primaryCpuAbiString = adjustedAbi; 7670 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7671 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7672 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7673 7674 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 7675 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 7676 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7677 ps.primaryCpuAbiString = null; 7678 ps.pkg.applicationInfo.primaryCpuAbi = null; 7679 return; 7680 } else { 7681 mInstaller.rmdex(ps.codePathString, 7682 getDexCodeInstructionSet(getPreferredInstructionSet())); 7683 } 7684 } 7685 } 7686 } 7687 } 7688 } 7689 7690 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7691 synchronized (mPackages) { 7692 mResolverReplaced = true; 7693 // Set up information for custom user intent resolution activity. 7694 mResolveActivity.applicationInfo = pkg.applicationInfo; 7695 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7696 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7697 mResolveActivity.processName = pkg.applicationInfo.packageName; 7698 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7699 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7700 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7701 mResolveActivity.theme = 0; 7702 mResolveActivity.exported = true; 7703 mResolveActivity.enabled = true; 7704 mResolveInfo.activityInfo = mResolveActivity; 7705 mResolveInfo.priority = 0; 7706 mResolveInfo.preferredOrder = 0; 7707 mResolveInfo.match = 0; 7708 mResolveComponentName = mCustomResolverComponentName; 7709 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7710 mResolveComponentName); 7711 } 7712 } 7713 7714 private static String calculateBundledApkRoot(final String codePathString) { 7715 final File codePath = new File(codePathString); 7716 final File codeRoot; 7717 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 7718 codeRoot = Environment.getRootDirectory(); 7719 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7720 codeRoot = Environment.getOemDirectory(); 7721 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7722 codeRoot = Environment.getVendorDirectory(); 7723 } else { 7724 // Unrecognized code path; take its top real segment as the apk root: 7725 // e.g. /something/app/blah.apk => /something 7726 try { 7727 File f = codePath.getCanonicalFile(); 7728 File parent = f.getParentFile(); // non-null because codePath is a file 7729 File tmp; 7730 while ((tmp = parent.getParentFile()) != null) { 7731 f = parent; 7732 parent = tmp; 7733 } 7734 codeRoot = f; 7735 Slog.w(TAG, "Unrecognized code path " 7736 + codePath + " - using " + codeRoot); 7737 } catch (IOException e) { 7738 // Can't canonicalize the code path -- shenanigans? 7739 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7740 return Environment.getRootDirectory().getPath(); 7741 } 7742 } 7743 return codeRoot.getPath(); 7744 } 7745 7746 /** 7747 * Derive and set the location of native libraries for the given package, 7748 * which varies depending on where and how the package was installed. 7749 */ 7750 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7751 final ApplicationInfo info = pkg.applicationInfo; 7752 final String codePath = pkg.codePath; 7753 final File codeFile = new File(codePath); 7754 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7755 final boolean asecApp = info.isForwardLocked() || isExternal(info); 7756 7757 info.nativeLibraryRootDir = null; 7758 info.nativeLibraryRootRequiresIsa = false; 7759 info.nativeLibraryDir = null; 7760 info.secondaryNativeLibraryDir = null; 7761 7762 if (isApkFile(codeFile)) { 7763 // Monolithic install 7764 if (bundledApp) { 7765 // If "/system/lib64/apkname" exists, assume that is the per-package 7766 // native library directory to use; otherwise use "/system/lib/apkname". 7767 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7768 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7769 getPrimaryInstructionSet(info)); 7770 7771 // This is a bundled system app so choose the path based on the ABI. 7772 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7773 // is just the default path. 7774 final String apkName = deriveCodePathName(codePath); 7775 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7776 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7777 apkName).getAbsolutePath(); 7778 7779 if (info.secondaryCpuAbi != null) { 7780 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7781 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7782 secondaryLibDir, apkName).getAbsolutePath(); 7783 } 7784 } else if (asecApp) { 7785 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 7786 .getAbsolutePath(); 7787 } else { 7788 final String apkName = deriveCodePathName(codePath); 7789 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 7790 .getAbsolutePath(); 7791 } 7792 7793 info.nativeLibraryRootRequiresIsa = false; 7794 info.nativeLibraryDir = info.nativeLibraryRootDir; 7795 } else { 7796 // Cluster install 7797 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 7798 info.nativeLibraryRootRequiresIsa = true; 7799 7800 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 7801 getPrimaryInstructionSet(info)).getAbsolutePath(); 7802 7803 if (info.secondaryCpuAbi != null) { 7804 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 7805 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 7806 } 7807 } 7808 } 7809 7810 /** 7811 * Calculate the abis and roots for a bundled app. These can uniquely 7812 * be determined from the contents of the system partition, i.e whether 7813 * it contains 64 or 32 bit shared libraries etc. We do not validate any 7814 * of this information, and instead assume that the system was built 7815 * sensibly. 7816 */ 7817 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 7818 PackageSetting pkgSetting) { 7819 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 7820 7821 // If "/system/lib64/apkname" exists, assume that is the per-package 7822 // native library directory to use; otherwise use "/system/lib/apkname". 7823 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 7824 setBundledAppAbi(pkg, apkRoot, apkName); 7825 // pkgSetting might be null during rescan following uninstall of updates 7826 // to a bundled app, so accommodate that possibility. The settings in 7827 // that case will be established later from the parsed package. 7828 // 7829 // If the settings aren't null, sync them up with what we've just derived. 7830 // note that apkRoot isn't stored in the package settings. 7831 if (pkgSetting != null) { 7832 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7833 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7834 } 7835 } 7836 7837 /** 7838 * Deduces the ABI of a bundled app and sets the relevant fields on the 7839 * parsed pkg object. 7840 * 7841 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 7842 * under which system libraries are installed. 7843 * @param apkName the name of the installed package. 7844 */ 7845 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 7846 final File codeFile = new File(pkg.codePath); 7847 7848 final boolean has64BitLibs; 7849 final boolean has32BitLibs; 7850 if (isApkFile(codeFile)) { 7851 // Monolithic install 7852 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 7853 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7854 } else { 7855 // Cluster install 7856 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7857 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7858 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7859 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7860 has64BitLibs = (new File(rootDir, isa)).exists(); 7861 } else { 7862 has64BitLibs = false; 7863 } 7864 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7865 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 7866 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 7867 has32BitLibs = (new File(rootDir, isa)).exists(); 7868 } else { 7869 has32BitLibs = false; 7870 } 7871 } 7872 7873 if (has64BitLibs && !has32BitLibs) { 7874 // The package has 64 bit libs, but not 32 bit libs. Its primary 7875 // ABI should be 64 bit. We can safely assume here that the bundled 7876 // native libraries correspond to the most preferred ABI in the list. 7877 7878 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7879 pkg.applicationInfo.secondaryCpuAbi = null; 7880 } else if (has32BitLibs && !has64BitLibs) { 7881 // The package has 32 bit libs but not 64 bit libs. Its primary 7882 // ABI should be 32 bit. 7883 7884 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7885 pkg.applicationInfo.secondaryCpuAbi = null; 7886 } else if (has32BitLibs && has64BitLibs) { 7887 // The application has both 64 and 32 bit bundled libraries. We check 7888 // here that the app declares multiArch support, and warn if it doesn't. 7889 // 7890 // We will be lenient here and record both ABIs. The primary will be the 7891 // ABI that's higher on the list, i.e, a device that's configured to prefer 7892 // 64 bit apps will see a 64 bit primary ABI, 7893 7894 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 7895 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 7896 } 7897 7898 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 7899 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7900 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7901 } else { 7902 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7903 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7904 } 7905 } else { 7906 pkg.applicationInfo.primaryCpuAbi = null; 7907 pkg.applicationInfo.secondaryCpuAbi = null; 7908 } 7909 } 7910 7911 private void killApplication(String pkgName, int appId, String reason) { 7912 // Request the ActivityManager to kill the process(only for existing packages) 7913 // so that we do not end up in a confused state while the user is still using the older 7914 // version of the application while the new one gets installed. 7915 IActivityManager am = ActivityManagerNative.getDefault(); 7916 if (am != null) { 7917 try { 7918 am.killApplicationWithAppId(pkgName, appId, reason); 7919 } catch (RemoteException e) { 7920 } 7921 } 7922 } 7923 7924 void removePackageLI(PackageSetting ps, boolean chatty) { 7925 if (DEBUG_INSTALL) { 7926 if (chatty) 7927 Log.d(TAG, "Removing package " + ps.name); 7928 } 7929 7930 // writer 7931 synchronized (mPackages) { 7932 mPackages.remove(ps.name); 7933 final PackageParser.Package pkg = ps.pkg; 7934 if (pkg != null) { 7935 cleanPackageDataStructuresLILPw(pkg, chatty); 7936 } 7937 } 7938 } 7939 7940 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 7941 if (DEBUG_INSTALL) { 7942 if (chatty) 7943 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 7944 } 7945 7946 // writer 7947 synchronized (mPackages) { 7948 mPackages.remove(pkg.applicationInfo.packageName); 7949 cleanPackageDataStructuresLILPw(pkg, chatty); 7950 } 7951 } 7952 7953 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 7954 int N = pkg.providers.size(); 7955 StringBuilder r = null; 7956 int i; 7957 for (i=0; i<N; i++) { 7958 PackageParser.Provider p = pkg.providers.get(i); 7959 mProviders.removeProvider(p); 7960 if (p.info.authority == null) { 7961 7962 /* There was another ContentProvider with this authority when 7963 * this app was installed so this authority is null, 7964 * Ignore it as we don't have to unregister the provider. 7965 */ 7966 continue; 7967 } 7968 String names[] = p.info.authority.split(";"); 7969 for (int j = 0; j < names.length; j++) { 7970 if (mProvidersByAuthority.get(names[j]) == p) { 7971 mProvidersByAuthority.remove(names[j]); 7972 if (DEBUG_REMOVE) { 7973 if (chatty) 7974 Log.d(TAG, "Unregistered content provider: " + names[j] 7975 + ", className = " + p.info.name + ", isSyncable = " 7976 + p.info.isSyncable); 7977 } 7978 } 7979 } 7980 if (DEBUG_REMOVE && chatty) { 7981 if (r == null) { 7982 r = new StringBuilder(256); 7983 } else { 7984 r.append(' '); 7985 } 7986 r.append(p.info.name); 7987 } 7988 } 7989 if (r != null) { 7990 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 7991 } 7992 7993 N = pkg.services.size(); 7994 r = null; 7995 for (i=0; i<N; i++) { 7996 PackageParser.Service s = pkg.services.get(i); 7997 mServices.removeService(s); 7998 if (chatty) { 7999 if (r == null) { 8000 r = new StringBuilder(256); 8001 } else { 8002 r.append(' '); 8003 } 8004 r.append(s.info.name); 8005 } 8006 } 8007 if (r != null) { 8008 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 8009 } 8010 8011 N = pkg.receivers.size(); 8012 r = null; 8013 for (i=0; i<N; i++) { 8014 PackageParser.Activity a = pkg.receivers.get(i); 8015 mReceivers.removeActivity(a, "receiver"); 8016 if (DEBUG_REMOVE && chatty) { 8017 if (r == null) { 8018 r = new StringBuilder(256); 8019 } else { 8020 r.append(' '); 8021 } 8022 r.append(a.info.name); 8023 } 8024 } 8025 if (r != null) { 8026 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 8027 } 8028 8029 N = pkg.activities.size(); 8030 r = null; 8031 for (i=0; i<N; i++) { 8032 PackageParser.Activity a = pkg.activities.get(i); 8033 mActivities.removeActivity(a, "activity"); 8034 if (DEBUG_REMOVE && chatty) { 8035 if (r == null) { 8036 r = new StringBuilder(256); 8037 } else { 8038 r.append(' '); 8039 } 8040 r.append(a.info.name); 8041 } 8042 } 8043 if (r != null) { 8044 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 8045 } 8046 8047 N = pkg.permissions.size(); 8048 r = null; 8049 for (i=0; i<N; i++) { 8050 PackageParser.Permission p = pkg.permissions.get(i); 8051 BasePermission bp = mSettings.mPermissions.get(p.info.name); 8052 if (bp == null) { 8053 bp = mSettings.mPermissionTrees.get(p.info.name); 8054 } 8055 if (bp != null && bp.perm == p) { 8056 bp.perm = null; 8057 if (DEBUG_REMOVE && chatty) { 8058 if (r == null) { 8059 r = new StringBuilder(256); 8060 } else { 8061 r.append(' '); 8062 } 8063 r.append(p.info.name); 8064 } 8065 } 8066 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8067 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 8068 if (appOpPerms != null) { 8069 appOpPerms.remove(pkg.packageName); 8070 } 8071 } 8072 } 8073 if (r != null) { 8074 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8075 } 8076 8077 N = pkg.requestedPermissions.size(); 8078 r = null; 8079 for (i=0; i<N; i++) { 8080 String perm = pkg.requestedPermissions.get(i); 8081 BasePermission bp = mSettings.mPermissions.get(perm); 8082 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8083 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 8084 if (appOpPerms != null) { 8085 appOpPerms.remove(pkg.packageName); 8086 if (appOpPerms.isEmpty()) { 8087 mAppOpPermissionPackages.remove(perm); 8088 } 8089 } 8090 } 8091 } 8092 if (r != null) { 8093 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8094 } 8095 8096 N = pkg.instrumentation.size(); 8097 r = null; 8098 for (i=0; i<N; i++) { 8099 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8100 mInstrumentation.remove(a.getComponentName()); 8101 if (DEBUG_REMOVE && chatty) { 8102 if (r == null) { 8103 r = new StringBuilder(256); 8104 } else { 8105 r.append(' '); 8106 } 8107 r.append(a.info.name); 8108 } 8109 } 8110 if (r != null) { 8111 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 8112 } 8113 8114 r = null; 8115 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8116 // Only system apps can hold shared libraries. 8117 if (pkg.libraryNames != null) { 8118 for (i=0; i<pkg.libraryNames.size(); i++) { 8119 String name = pkg.libraryNames.get(i); 8120 SharedLibraryEntry cur = mSharedLibraries.get(name); 8121 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 8122 mSharedLibraries.remove(name); 8123 if (DEBUG_REMOVE && chatty) { 8124 if (r == null) { 8125 r = new StringBuilder(256); 8126 } else { 8127 r.append(' '); 8128 } 8129 r.append(name); 8130 } 8131 } 8132 } 8133 } 8134 } 8135 if (r != null) { 8136 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 8137 } 8138 } 8139 8140 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 8141 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 8142 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 8143 return true; 8144 } 8145 } 8146 return false; 8147 } 8148 8149 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 8150 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 8151 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 8152 8153 private void updatePermissionsLPw(String changingPkg, 8154 PackageParser.Package pkgInfo, int flags) { 8155 // Make sure there are no dangling permission trees. 8156 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 8157 while (it.hasNext()) { 8158 final BasePermission bp = it.next(); 8159 if (bp.packageSetting == null) { 8160 // We may not yet have parsed the package, so just see if 8161 // we still know about its settings. 8162 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8163 } 8164 if (bp.packageSetting == null) { 8165 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 8166 + " from package " + bp.sourcePackage); 8167 it.remove(); 8168 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8169 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8170 Slog.i(TAG, "Removing old permission tree: " + bp.name 8171 + " from package " + bp.sourcePackage); 8172 flags |= UPDATE_PERMISSIONS_ALL; 8173 it.remove(); 8174 } 8175 } 8176 } 8177 8178 // Make sure all dynamic permissions have been assigned to a package, 8179 // and make sure there are no dangling permissions. 8180 it = mSettings.mPermissions.values().iterator(); 8181 while (it.hasNext()) { 8182 final BasePermission bp = it.next(); 8183 if (bp.type == BasePermission.TYPE_DYNAMIC) { 8184 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 8185 + bp.name + " pkg=" + bp.sourcePackage 8186 + " info=" + bp.pendingInfo); 8187 if (bp.packageSetting == null && bp.pendingInfo != null) { 8188 final BasePermission tree = findPermissionTreeLP(bp.name); 8189 if (tree != null && tree.perm != null) { 8190 bp.packageSetting = tree.packageSetting; 8191 bp.perm = new PackageParser.Permission(tree.perm.owner, 8192 new PermissionInfo(bp.pendingInfo)); 8193 bp.perm.info.packageName = tree.perm.info.packageName; 8194 bp.perm.info.name = bp.name; 8195 bp.uid = tree.uid; 8196 } 8197 } 8198 } 8199 if (bp.packageSetting == null) { 8200 // We may not yet have parsed the package, so just see if 8201 // we still know about its settings. 8202 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8203 } 8204 if (bp.packageSetting == null) { 8205 Slog.w(TAG, "Removing dangling permission: " + bp.name 8206 + " from package " + bp.sourcePackage); 8207 it.remove(); 8208 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8209 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8210 Slog.i(TAG, "Removing old permission: " + bp.name 8211 + " from package " + bp.sourcePackage); 8212 flags |= UPDATE_PERMISSIONS_ALL; 8213 it.remove(); 8214 } 8215 } 8216 } 8217 8218 // Now update the permissions for all packages, in particular 8219 // replace the granted permissions of the system packages. 8220 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 8221 for (PackageParser.Package pkg : mPackages.values()) { 8222 if (pkg != pkgInfo) { 8223 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 8224 changingPkg); 8225 } 8226 } 8227 } 8228 8229 if (pkgInfo != null) { 8230 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 8231 } 8232 } 8233 8234 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 8235 String packageOfInterest) { 8236 // IMPORTANT: There are two types of permissions: install and runtime. 8237 // Install time permissions are granted when the app is installed to 8238 // all device users and users added in the future. Runtime permissions 8239 // are granted at runtime explicitly to specific users. Normal and signature 8240 // protected permissions are install time permissions. Dangerous permissions 8241 // are install permissions if the app's target SDK is Lollipop MR1 or older, 8242 // otherwise they are runtime permissions. This function does not manage 8243 // runtime permissions except for the case an app targeting Lollipop MR1 8244 // being upgraded to target a newer SDK, in which case dangerous permissions 8245 // are transformed from install time to runtime ones. 8246 8247 final PackageSetting ps = (PackageSetting) pkg.mExtras; 8248 if (ps == null) { 8249 return; 8250 } 8251 8252 PermissionsState permissionsState = ps.getPermissionsState(); 8253 PermissionsState origPermissions = permissionsState; 8254 8255 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 8256 8257 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 8258 8259 boolean changedInstallPermission = false; 8260 8261 if (replace) { 8262 ps.installPermissionsFixed = false; 8263 if (!ps.isSharedUser()) { 8264 origPermissions = new PermissionsState(permissionsState); 8265 permissionsState.reset(); 8266 } 8267 } 8268 8269 permissionsState.setGlobalGids(mGlobalGids); 8270 8271 final int N = pkg.requestedPermissions.size(); 8272 for (int i=0; i<N; i++) { 8273 final String name = pkg.requestedPermissions.get(i); 8274 final BasePermission bp = mSettings.mPermissions.get(name); 8275 8276 if (DEBUG_INSTALL) { 8277 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 8278 } 8279 8280 if (bp == null || bp.packageSetting == null) { 8281 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8282 Slog.w(TAG, "Unknown permission " + name 8283 + " in package " + pkg.packageName); 8284 } 8285 continue; 8286 } 8287 8288 final String perm = bp.name; 8289 boolean allowedSig = false; 8290 int grant = GRANT_DENIED; 8291 8292 // Keep track of app op permissions. 8293 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8294 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 8295 if (pkgs == null) { 8296 pkgs = new ArraySet<>(); 8297 mAppOpPermissionPackages.put(bp.name, pkgs); 8298 } 8299 pkgs.add(pkg.packageName); 8300 } 8301 8302 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 8303 switch (level) { 8304 case PermissionInfo.PROTECTION_NORMAL: { 8305 // For all apps normal permissions are install time ones. 8306 grant = GRANT_INSTALL; 8307 } break; 8308 8309 case PermissionInfo.PROTECTION_DANGEROUS: { 8310 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 8311 // For legacy apps dangerous permissions are install time ones. 8312 grant = GRANT_INSTALL_LEGACY; 8313 } else if (origPermissions.hasInstallPermission(bp.name)) { 8314 // For legacy apps that became modern, install becomes runtime. 8315 grant = GRANT_UPGRADE; 8316 } else { 8317 // For modern apps keep runtime permissions unchanged. 8318 grant = GRANT_RUNTIME; 8319 } 8320 } break; 8321 8322 case PermissionInfo.PROTECTION_SIGNATURE: { 8323 // For all apps signature permissions are install time ones. 8324 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 8325 if (allowedSig) { 8326 grant = GRANT_INSTALL; 8327 } 8328 } break; 8329 } 8330 8331 if (DEBUG_INSTALL) { 8332 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 8333 } 8334 8335 if (grant != GRANT_DENIED) { 8336 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 8337 // If this is an existing, non-system package, then 8338 // we can't add any new permissions to it. 8339 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 8340 // Except... if this is a permission that was added 8341 // to the platform (note: need to only do this when 8342 // updating the platform). 8343 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 8344 grant = GRANT_DENIED; 8345 } 8346 } 8347 } 8348 8349 switch (grant) { 8350 case GRANT_INSTALL: { 8351 // Revoke this as runtime permission to handle the case of 8352 // a runtime permission being downgraded to an install one. 8353 for (int userId : UserManagerService.getInstance().getUserIds()) { 8354 if (origPermissions.getRuntimePermissionState( 8355 bp.name, userId) != null) { 8356 // Revoke the runtime permission and clear the flags. 8357 origPermissions.revokeRuntimePermission(bp, userId); 8358 origPermissions.updatePermissionFlags(bp, userId, 8359 PackageManager.MASK_PERMISSION_FLAGS, 0); 8360 // If we revoked a permission permission, we have to write. 8361 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8362 changedRuntimePermissionUserIds, userId); 8363 } 8364 } 8365 // Grant an install permission. 8366 if (permissionsState.grantInstallPermission(bp) != 8367 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8368 changedInstallPermission = true; 8369 } 8370 } break; 8371 8372 case GRANT_INSTALL_LEGACY: { 8373 // Grant an install permission. 8374 if (permissionsState.grantInstallPermission(bp) != 8375 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8376 changedInstallPermission = true; 8377 } 8378 } break; 8379 8380 case GRANT_RUNTIME: { 8381 // Grant previously granted runtime permissions. 8382 for (int userId : UserManagerService.getInstance().getUserIds()) { 8383 PermissionState permissionState = origPermissions 8384 .getRuntimePermissionState(bp.name, userId); 8385 final int flags = permissionState != null 8386 ? permissionState.getFlags() : 0; 8387 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8388 if (permissionsState.grantRuntimePermission(bp, userId) == 8389 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8390 // If we cannot put the permission as it was, we have to write. 8391 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8392 changedRuntimePermissionUserIds, userId); 8393 } 8394 } 8395 // Propagate the permission flags. 8396 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 8397 } 8398 } break; 8399 8400 case GRANT_UPGRADE: { 8401 // Grant runtime permissions for a previously held install permission. 8402 PermissionState permissionState = origPermissions 8403 .getInstallPermissionState(bp.name); 8404 final int flags = permissionState != null ? permissionState.getFlags() : 0; 8405 8406 if (origPermissions.revokeInstallPermission(bp) 8407 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 8408 // We will be transferring the permission flags, so clear them. 8409 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 8410 PackageManager.MASK_PERMISSION_FLAGS, 0); 8411 changedInstallPermission = true; 8412 } 8413 8414 // If the permission is not to be promoted to runtime we ignore it and 8415 // also its other flags as they are not applicable to install permissions. 8416 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 8417 for (int userId : currentUserIds) { 8418 if (permissionsState.grantRuntimePermission(bp, userId) != 8419 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8420 // Transfer the permission flags. 8421 permissionsState.updatePermissionFlags(bp, userId, 8422 flags, flags); 8423 // If we granted the permission, we have to write. 8424 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8425 changedRuntimePermissionUserIds, userId); 8426 } 8427 } 8428 } 8429 } break; 8430 8431 default: { 8432 if (packageOfInterest == null 8433 || packageOfInterest.equals(pkg.packageName)) { 8434 Slog.w(TAG, "Not granting permission " + perm 8435 + " to package " + pkg.packageName 8436 + " because it was previously installed without"); 8437 } 8438 } break; 8439 } 8440 } else { 8441 if (permissionsState.revokeInstallPermission(bp) != 8442 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8443 // Also drop the permission flags. 8444 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 8445 PackageManager.MASK_PERMISSION_FLAGS, 0); 8446 changedInstallPermission = true; 8447 Slog.i(TAG, "Un-granting permission " + perm 8448 + " from package " + pkg.packageName 8449 + " (protectionLevel=" + bp.protectionLevel 8450 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8451 + ")"); 8452 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 8453 // Don't print warning for app op permissions, since it is fine for them 8454 // not to be granted, there is a UI for the user to decide. 8455 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8456 Slog.w(TAG, "Not granting permission " + perm 8457 + " to package " + pkg.packageName 8458 + " (protectionLevel=" + bp.protectionLevel 8459 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8460 + ")"); 8461 } 8462 } 8463 } 8464 } 8465 8466 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 8467 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 8468 // This is the first that we have heard about this package, so the 8469 // permissions we have now selected are fixed until explicitly 8470 // changed. 8471 ps.installPermissionsFixed = true; 8472 } 8473 8474 // Persist the runtime permissions state for users with changes. 8475 for (int userId : changedRuntimePermissionUserIds) { 8476 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 8477 } 8478 } 8479 8480 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8481 boolean allowed = false; 8482 final int NP = PackageParser.NEW_PERMISSIONS.length; 8483 for (int ip=0; ip<NP; ip++) { 8484 final PackageParser.NewPermissionInfo npi 8485 = PackageParser.NEW_PERMISSIONS[ip]; 8486 if (npi.name.equals(perm) 8487 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8488 allowed = true; 8489 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8490 + pkg.packageName); 8491 break; 8492 } 8493 } 8494 return allowed; 8495 } 8496 8497 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 8498 BasePermission bp, PermissionsState origPermissions) { 8499 boolean allowed; 8500 allowed = (compareSignatures( 8501 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 8502 == PackageManager.SIGNATURE_MATCH) 8503 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 8504 == PackageManager.SIGNATURE_MATCH); 8505 if (!allowed && (bp.protectionLevel 8506 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 8507 if (isSystemApp(pkg)) { 8508 // For updated system applications, a system permission 8509 // is granted only if it had been defined by the original application. 8510 if (pkg.isUpdatedSystemApp()) { 8511 final PackageSetting sysPs = mSettings 8512 .getDisabledSystemPkgLPr(pkg.packageName); 8513 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 8514 // If the original was granted this permission, we take 8515 // that grant decision as read and propagate it to the 8516 // update. 8517 if (sysPs.isPrivileged()) { 8518 allowed = true; 8519 } 8520 } else { 8521 // The system apk may have been updated with an older 8522 // version of the one on the data partition, but which 8523 // granted a new system permission that it didn't have 8524 // before. In this case we do want to allow the app to 8525 // now get the new permission if the ancestral apk is 8526 // privileged to get it. 8527 if (sysPs.pkg != null && sysPs.isPrivileged()) { 8528 for (int j=0; 8529 j<sysPs.pkg.requestedPermissions.size(); j++) { 8530 if (perm.equals( 8531 sysPs.pkg.requestedPermissions.get(j))) { 8532 allowed = true; 8533 break; 8534 } 8535 } 8536 } 8537 } 8538 } else { 8539 allowed = isPrivilegedApp(pkg); 8540 } 8541 } 8542 } 8543 if (!allowed) { 8544 if (!allowed && (bp.protectionLevel 8545 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 8546 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.MNC) { 8547 // If this was a previously normal/dangerous permission that got moved 8548 // to a system permission as part of the runtime permission redesign, then 8549 // we still want to blindly grant it to old apps. 8550 allowed = true; 8551 } 8552 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 8553 && pkg.packageName.equals(mRequiredInstallerPackage)) { 8554 // If this permission is to be granted to the system installer and 8555 // this app is an installer, then it gets the permission. 8556 allowed = true; 8557 } 8558 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 8559 && pkg.packageName.equals(mRequiredVerifierPackage)) { 8560 // If this permission is to be granted to the system verifier and 8561 // this app is a verifier, then it gets the permission. 8562 allowed = true; 8563 } 8564 if (!allowed && (bp.protectionLevel 8565 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 8566 && isSystemApp(pkg)) { 8567 // Any pre-installed system app is allowed to get this permission. 8568 allowed = true; 8569 } 8570 if (!allowed && (bp.protectionLevel 8571 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 8572 // For development permissions, a development permission 8573 // is granted only if it was already granted. 8574 allowed = origPermissions.hasInstallPermission(perm); 8575 } 8576 } 8577 return allowed; 8578 } 8579 8580 final class ActivityIntentResolver 8581 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 8582 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8583 boolean defaultOnly, int userId) { 8584 if (!sUserManager.exists(userId)) return null; 8585 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8586 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8587 } 8588 8589 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8590 int userId) { 8591 if (!sUserManager.exists(userId)) return null; 8592 mFlags = flags; 8593 return super.queryIntent(intent, resolvedType, 8594 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8595 } 8596 8597 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8598 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 8599 if (!sUserManager.exists(userId)) return null; 8600 if (packageActivities == null) { 8601 return null; 8602 } 8603 mFlags = flags; 8604 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8605 final int N = packageActivities.size(); 8606 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 8607 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 8608 8609 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 8610 for (int i = 0; i < N; ++i) { 8611 intentFilters = packageActivities.get(i).intents; 8612 if (intentFilters != null && intentFilters.size() > 0) { 8613 PackageParser.ActivityIntentInfo[] array = 8614 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 8615 intentFilters.toArray(array); 8616 listCut.add(array); 8617 } 8618 } 8619 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8620 } 8621 8622 public final void addActivity(PackageParser.Activity a, String type) { 8623 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 8624 mActivities.put(a.getComponentName(), a); 8625 if (DEBUG_SHOW_INFO) 8626 Log.v( 8627 TAG, " " + type + " " + 8628 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 8629 if (DEBUG_SHOW_INFO) 8630 Log.v(TAG, " Class=" + a.info.name); 8631 final int NI = a.intents.size(); 8632 for (int j=0; j<NI; j++) { 8633 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8634 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 8635 intent.setPriority(0); 8636 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 8637 + a.className + " with priority > 0, forcing to 0"); 8638 } 8639 if (DEBUG_SHOW_INFO) { 8640 Log.v(TAG, " IntentFilter:"); 8641 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8642 } 8643 if (!intent.debugCheck()) { 8644 Log.w(TAG, "==> For Activity " + a.info.name); 8645 } 8646 addFilter(intent); 8647 } 8648 } 8649 8650 public final void removeActivity(PackageParser.Activity a, String type) { 8651 mActivities.remove(a.getComponentName()); 8652 if (DEBUG_SHOW_INFO) { 8653 Log.v(TAG, " " + type + " " 8654 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 8655 : a.info.name) + ":"); 8656 Log.v(TAG, " Class=" + a.info.name); 8657 } 8658 final int NI = a.intents.size(); 8659 for (int j=0; j<NI; j++) { 8660 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8661 if (DEBUG_SHOW_INFO) { 8662 Log.v(TAG, " IntentFilter:"); 8663 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8664 } 8665 removeFilter(intent); 8666 } 8667 } 8668 8669 @Override 8670 protected boolean allowFilterResult( 8671 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 8672 ActivityInfo filterAi = filter.activity.info; 8673 for (int i=dest.size()-1; i>=0; i--) { 8674 ActivityInfo destAi = dest.get(i).activityInfo; 8675 if (destAi.name == filterAi.name 8676 && destAi.packageName == filterAi.packageName) { 8677 return false; 8678 } 8679 } 8680 return true; 8681 } 8682 8683 @Override 8684 protected ActivityIntentInfo[] newArray(int size) { 8685 return new ActivityIntentInfo[size]; 8686 } 8687 8688 @Override 8689 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 8690 if (!sUserManager.exists(userId)) return true; 8691 PackageParser.Package p = filter.activity.owner; 8692 if (p != null) { 8693 PackageSetting ps = (PackageSetting)p.mExtras; 8694 if (ps != null) { 8695 // System apps are never considered stopped for purposes of 8696 // filtering, because there may be no way for the user to 8697 // actually re-launch them. 8698 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 8699 && ps.getStopped(userId); 8700 } 8701 } 8702 return false; 8703 } 8704 8705 @Override 8706 protected boolean isPackageForFilter(String packageName, 8707 PackageParser.ActivityIntentInfo info) { 8708 return packageName.equals(info.activity.owner.packageName); 8709 } 8710 8711 @Override 8712 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 8713 int match, int userId) { 8714 if (!sUserManager.exists(userId)) return null; 8715 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 8716 return null; 8717 } 8718 final PackageParser.Activity activity = info.activity; 8719 if (mSafeMode && (activity.info.applicationInfo.flags 8720 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8721 return null; 8722 } 8723 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 8724 if (ps == null) { 8725 return null; 8726 } 8727 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 8728 ps.readUserState(userId), userId); 8729 if (ai == null) { 8730 return null; 8731 } 8732 final ResolveInfo res = new ResolveInfo(); 8733 res.activityInfo = ai; 8734 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8735 res.filter = info; 8736 } 8737 if (info != null) { 8738 res.handleAllWebDataURI = info.handleAllWebDataURI(); 8739 } 8740 res.priority = info.getPriority(); 8741 res.preferredOrder = activity.owner.mPreferredOrder; 8742 //System.out.println("Result: " + res.activityInfo.className + 8743 // " = " + res.priority); 8744 res.match = match; 8745 res.isDefault = info.hasDefault; 8746 res.labelRes = info.labelRes; 8747 res.nonLocalizedLabel = info.nonLocalizedLabel; 8748 if (userNeedsBadging(userId)) { 8749 res.noResourceId = true; 8750 } else { 8751 res.icon = info.icon; 8752 } 8753 res.iconResourceId = info.icon; 8754 res.system = res.activityInfo.applicationInfo.isSystemApp(); 8755 return res; 8756 } 8757 8758 @Override 8759 protected void sortResults(List<ResolveInfo> results) { 8760 Collections.sort(results, mResolvePrioritySorter); 8761 } 8762 8763 @Override 8764 protected void dumpFilter(PrintWriter out, String prefix, 8765 PackageParser.ActivityIntentInfo filter) { 8766 out.print(prefix); out.print( 8767 Integer.toHexString(System.identityHashCode(filter.activity))); 8768 out.print(' '); 8769 filter.activity.printComponentShortName(out); 8770 out.print(" filter "); 8771 out.println(Integer.toHexString(System.identityHashCode(filter))); 8772 } 8773 8774 @Override 8775 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 8776 return filter.activity; 8777 } 8778 8779 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8780 PackageParser.Activity activity = (PackageParser.Activity)label; 8781 out.print(prefix); out.print( 8782 Integer.toHexString(System.identityHashCode(activity))); 8783 out.print(' '); 8784 activity.printComponentShortName(out); 8785 if (count > 1) { 8786 out.print(" ("); out.print(count); out.print(" filters)"); 8787 } 8788 out.println(); 8789 } 8790 8791// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8792// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8793// final List<ResolveInfo> retList = Lists.newArrayList(); 8794// while (i.hasNext()) { 8795// final ResolveInfo resolveInfo = i.next(); 8796// if (isEnabledLP(resolveInfo.activityInfo)) { 8797// retList.add(resolveInfo); 8798// } 8799// } 8800// return retList; 8801// } 8802 8803 // Keys are String (activity class name), values are Activity. 8804 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 8805 = new ArrayMap<ComponentName, PackageParser.Activity>(); 8806 private int mFlags; 8807 } 8808 8809 private final class ServiceIntentResolver 8810 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 8811 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8812 boolean defaultOnly, int userId) { 8813 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8814 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8815 } 8816 8817 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8818 int userId) { 8819 if (!sUserManager.exists(userId)) return null; 8820 mFlags = flags; 8821 return super.queryIntent(intent, resolvedType, 8822 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8823 } 8824 8825 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8826 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 8827 if (!sUserManager.exists(userId)) return null; 8828 if (packageServices == null) { 8829 return null; 8830 } 8831 mFlags = flags; 8832 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8833 final int N = packageServices.size(); 8834 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 8835 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 8836 8837 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 8838 for (int i = 0; i < N; ++i) { 8839 intentFilters = packageServices.get(i).intents; 8840 if (intentFilters != null && intentFilters.size() > 0) { 8841 PackageParser.ServiceIntentInfo[] array = 8842 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 8843 intentFilters.toArray(array); 8844 listCut.add(array); 8845 } 8846 } 8847 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8848 } 8849 8850 public final void addService(PackageParser.Service s) { 8851 mServices.put(s.getComponentName(), s); 8852 if (DEBUG_SHOW_INFO) { 8853 Log.v(TAG, " " 8854 + (s.info.nonLocalizedLabel != null 8855 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8856 Log.v(TAG, " Class=" + s.info.name); 8857 } 8858 final int NI = s.intents.size(); 8859 int j; 8860 for (j=0; j<NI; j++) { 8861 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8862 if (DEBUG_SHOW_INFO) { 8863 Log.v(TAG, " IntentFilter:"); 8864 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8865 } 8866 if (!intent.debugCheck()) { 8867 Log.w(TAG, "==> For Service " + s.info.name); 8868 } 8869 addFilter(intent); 8870 } 8871 } 8872 8873 public final void removeService(PackageParser.Service s) { 8874 mServices.remove(s.getComponentName()); 8875 if (DEBUG_SHOW_INFO) { 8876 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 8877 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8878 Log.v(TAG, " Class=" + s.info.name); 8879 } 8880 final int NI = s.intents.size(); 8881 int j; 8882 for (j=0; j<NI; j++) { 8883 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8884 if (DEBUG_SHOW_INFO) { 8885 Log.v(TAG, " IntentFilter:"); 8886 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8887 } 8888 removeFilter(intent); 8889 } 8890 } 8891 8892 @Override 8893 protected boolean allowFilterResult( 8894 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 8895 ServiceInfo filterSi = filter.service.info; 8896 for (int i=dest.size()-1; i>=0; i--) { 8897 ServiceInfo destAi = dest.get(i).serviceInfo; 8898 if (destAi.name == filterSi.name 8899 && destAi.packageName == filterSi.packageName) { 8900 return false; 8901 } 8902 } 8903 return true; 8904 } 8905 8906 @Override 8907 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 8908 return new PackageParser.ServiceIntentInfo[size]; 8909 } 8910 8911 @Override 8912 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 8913 if (!sUserManager.exists(userId)) return true; 8914 PackageParser.Package p = filter.service.owner; 8915 if (p != null) { 8916 PackageSetting ps = (PackageSetting)p.mExtras; 8917 if (ps != null) { 8918 // System apps are never considered stopped for purposes of 8919 // filtering, because there may be no way for the user to 8920 // actually re-launch them. 8921 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8922 && ps.getStopped(userId); 8923 } 8924 } 8925 return false; 8926 } 8927 8928 @Override 8929 protected boolean isPackageForFilter(String packageName, 8930 PackageParser.ServiceIntentInfo info) { 8931 return packageName.equals(info.service.owner.packageName); 8932 } 8933 8934 @Override 8935 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 8936 int match, int userId) { 8937 if (!sUserManager.exists(userId)) return null; 8938 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 8939 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 8940 return null; 8941 } 8942 final PackageParser.Service service = info.service; 8943 if (mSafeMode && (service.info.applicationInfo.flags 8944 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8945 return null; 8946 } 8947 PackageSetting ps = (PackageSetting) service.owner.mExtras; 8948 if (ps == null) { 8949 return null; 8950 } 8951 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 8952 ps.readUserState(userId), userId); 8953 if (si == null) { 8954 return null; 8955 } 8956 final ResolveInfo res = new ResolveInfo(); 8957 res.serviceInfo = si; 8958 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8959 res.filter = filter; 8960 } 8961 res.priority = info.getPriority(); 8962 res.preferredOrder = service.owner.mPreferredOrder; 8963 res.match = match; 8964 res.isDefault = info.hasDefault; 8965 res.labelRes = info.labelRes; 8966 res.nonLocalizedLabel = info.nonLocalizedLabel; 8967 res.icon = info.icon; 8968 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 8969 return res; 8970 } 8971 8972 @Override 8973 protected void sortResults(List<ResolveInfo> results) { 8974 Collections.sort(results, mResolvePrioritySorter); 8975 } 8976 8977 @Override 8978 protected void dumpFilter(PrintWriter out, String prefix, 8979 PackageParser.ServiceIntentInfo filter) { 8980 out.print(prefix); out.print( 8981 Integer.toHexString(System.identityHashCode(filter.service))); 8982 out.print(' '); 8983 filter.service.printComponentShortName(out); 8984 out.print(" filter "); 8985 out.println(Integer.toHexString(System.identityHashCode(filter))); 8986 } 8987 8988 @Override 8989 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 8990 return filter.service; 8991 } 8992 8993 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8994 PackageParser.Service service = (PackageParser.Service)label; 8995 out.print(prefix); out.print( 8996 Integer.toHexString(System.identityHashCode(service))); 8997 out.print(' '); 8998 service.printComponentShortName(out); 8999 if (count > 1) { 9000 out.print(" ("); out.print(count); out.print(" filters)"); 9001 } 9002 out.println(); 9003 } 9004 9005// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9006// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9007// final List<ResolveInfo> retList = Lists.newArrayList(); 9008// while (i.hasNext()) { 9009// final ResolveInfo resolveInfo = (ResolveInfo) i; 9010// if (isEnabledLP(resolveInfo.serviceInfo)) { 9011// retList.add(resolveInfo); 9012// } 9013// } 9014// return retList; 9015// } 9016 9017 // Keys are String (activity class name), values are Activity. 9018 private final ArrayMap<ComponentName, PackageParser.Service> mServices 9019 = new ArrayMap<ComponentName, PackageParser.Service>(); 9020 private int mFlags; 9021 }; 9022 9023 private final class ProviderIntentResolver 9024 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 9025 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9026 boolean defaultOnly, int userId) { 9027 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9028 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9029 } 9030 9031 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9032 int userId) { 9033 if (!sUserManager.exists(userId)) 9034 return null; 9035 mFlags = flags; 9036 return super.queryIntent(intent, resolvedType, 9037 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9038 } 9039 9040 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9041 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 9042 if (!sUserManager.exists(userId)) 9043 return null; 9044 if (packageProviders == null) { 9045 return null; 9046 } 9047 mFlags = flags; 9048 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 9049 final int N = packageProviders.size(); 9050 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 9051 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 9052 9053 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 9054 for (int i = 0; i < N; ++i) { 9055 intentFilters = packageProviders.get(i).intents; 9056 if (intentFilters != null && intentFilters.size() > 0) { 9057 PackageParser.ProviderIntentInfo[] array = 9058 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 9059 intentFilters.toArray(array); 9060 listCut.add(array); 9061 } 9062 } 9063 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9064 } 9065 9066 public final void addProvider(PackageParser.Provider p) { 9067 if (mProviders.containsKey(p.getComponentName())) { 9068 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 9069 return; 9070 } 9071 9072 mProviders.put(p.getComponentName(), p); 9073 if (DEBUG_SHOW_INFO) { 9074 Log.v(TAG, " " 9075 + (p.info.nonLocalizedLabel != null 9076 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9077 Log.v(TAG, " Class=" + p.info.name); 9078 } 9079 final int NI = p.intents.size(); 9080 int j; 9081 for (j = 0; j < NI; j++) { 9082 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9083 if (DEBUG_SHOW_INFO) { 9084 Log.v(TAG, " IntentFilter:"); 9085 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9086 } 9087 if (!intent.debugCheck()) { 9088 Log.w(TAG, "==> For Provider " + p.info.name); 9089 } 9090 addFilter(intent); 9091 } 9092 } 9093 9094 public final void removeProvider(PackageParser.Provider p) { 9095 mProviders.remove(p.getComponentName()); 9096 if (DEBUG_SHOW_INFO) { 9097 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 9098 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9099 Log.v(TAG, " Class=" + p.info.name); 9100 } 9101 final int NI = p.intents.size(); 9102 int j; 9103 for (j = 0; j < NI; j++) { 9104 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9105 if (DEBUG_SHOW_INFO) { 9106 Log.v(TAG, " IntentFilter:"); 9107 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9108 } 9109 removeFilter(intent); 9110 } 9111 } 9112 9113 @Override 9114 protected boolean allowFilterResult( 9115 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 9116 ProviderInfo filterPi = filter.provider.info; 9117 for (int i = dest.size() - 1; i >= 0; i--) { 9118 ProviderInfo destPi = dest.get(i).providerInfo; 9119 if (destPi.name == filterPi.name 9120 && destPi.packageName == filterPi.packageName) { 9121 return false; 9122 } 9123 } 9124 return true; 9125 } 9126 9127 @Override 9128 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 9129 return new PackageParser.ProviderIntentInfo[size]; 9130 } 9131 9132 @Override 9133 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 9134 if (!sUserManager.exists(userId)) 9135 return true; 9136 PackageParser.Package p = filter.provider.owner; 9137 if (p != null) { 9138 PackageSetting ps = (PackageSetting) p.mExtras; 9139 if (ps != null) { 9140 // System apps are never considered stopped for purposes of 9141 // filtering, because there may be no way for the user to 9142 // actually re-launch them. 9143 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9144 && ps.getStopped(userId); 9145 } 9146 } 9147 return false; 9148 } 9149 9150 @Override 9151 protected boolean isPackageForFilter(String packageName, 9152 PackageParser.ProviderIntentInfo info) { 9153 return packageName.equals(info.provider.owner.packageName); 9154 } 9155 9156 @Override 9157 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 9158 int match, int userId) { 9159 if (!sUserManager.exists(userId)) 9160 return null; 9161 final PackageParser.ProviderIntentInfo info = filter; 9162 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 9163 return null; 9164 } 9165 final PackageParser.Provider provider = info.provider; 9166 if (mSafeMode && (provider.info.applicationInfo.flags 9167 & ApplicationInfo.FLAG_SYSTEM) == 0) { 9168 return null; 9169 } 9170 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 9171 if (ps == null) { 9172 return null; 9173 } 9174 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 9175 ps.readUserState(userId), userId); 9176 if (pi == null) { 9177 return null; 9178 } 9179 final ResolveInfo res = new ResolveInfo(); 9180 res.providerInfo = pi; 9181 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 9182 res.filter = filter; 9183 } 9184 res.priority = info.getPriority(); 9185 res.preferredOrder = provider.owner.mPreferredOrder; 9186 res.match = match; 9187 res.isDefault = info.hasDefault; 9188 res.labelRes = info.labelRes; 9189 res.nonLocalizedLabel = info.nonLocalizedLabel; 9190 res.icon = info.icon; 9191 res.system = res.providerInfo.applicationInfo.isSystemApp(); 9192 return res; 9193 } 9194 9195 @Override 9196 protected void sortResults(List<ResolveInfo> results) { 9197 Collections.sort(results, mResolvePrioritySorter); 9198 } 9199 9200 @Override 9201 protected void dumpFilter(PrintWriter out, String prefix, 9202 PackageParser.ProviderIntentInfo filter) { 9203 out.print(prefix); 9204 out.print( 9205 Integer.toHexString(System.identityHashCode(filter.provider))); 9206 out.print(' '); 9207 filter.provider.printComponentShortName(out); 9208 out.print(" filter "); 9209 out.println(Integer.toHexString(System.identityHashCode(filter))); 9210 } 9211 9212 @Override 9213 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 9214 return filter.provider; 9215 } 9216 9217 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9218 PackageParser.Provider provider = (PackageParser.Provider)label; 9219 out.print(prefix); out.print( 9220 Integer.toHexString(System.identityHashCode(provider))); 9221 out.print(' '); 9222 provider.printComponentShortName(out); 9223 if (count > 1) { 9224 out.print(" ("); out.print(count); out.print(" filters)"); 9225 } 9226 out.println(); 9227 } 9228 9229 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 9230 = new ArrayMap<ComponentName, PackageParser.Provider>(); 9231 private int mFlags; 9232 }; 9233 9234 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 9235 new Comparator<ResolveInfo>() { 9236 public int compare(ResolveInfo r1, ResolveInfo r2) { 9237 int v1 = r1.priority; 9238 int v2 = r2.priority; 9239 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 9240 if (v1 != v2) { 9241 return (v1 > v2) ? -1 : 1; 9242 } 9243 v1 = r1.preferredOrder; 9244 v2 = r2.preferredOrder; 9245 if (v1 != v2) { 9246 return (v1 > v2) ? -1 : 1; 9247 } 9248 if (r1.isDefault != r2.isDefault) { 9249 return r1.isDefault ? -1 : 1; 9250 } 9251 v1 = r1.match; 9252 v2 = r2.match; 9253 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 9254 if (v1 != v2) { 9255 return (v1 > v2) ? -1 : 1; 9256 } 9257 if (r1.system != r2.system) { 9258 return r1.system ? -1 : 1; 9259 } 9260 return 0; 9261 } 9262 }; 9263 9264 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 9265 new Comparator<ProviderInfo>() { 9266 public int compare(ProviderInfo p1, ProviderInfo p2) { 9267 final int v1 = p1.initOrder; 9268 final int v2 = p2.initOrder; 9269 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 9270 } 9271 }; 9272 9273 final void sendPackageBroadcast(final String action, final String pkg, 9274 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 9275 final int[] userIds) { 9276 mHandler.post(new Runnable() { 9277 @Override 9278 public void run() { 9279 try { 9280 final IActivityManager am = ActivityManagerNative.getDefault(); 9281 if (am == null) return; 9282 final int[] resolvedUserIds; 9283 if (userIds == null) { 9284 resolvedUserIds = am.getRunningUserIds(); 9285 } else { 9286 resolvedUserIds = userIds; 9287 } 9288 for (int id : resolvedUserIds) { 9289 final Intent intent = new Intent(action, 9290 pkg != null ? Uri.fromParts("package", pkg, null) : null); 9291 if (extras != null) { 9292 intent.putExtras(extras); 9293 } 9294 if (targetPkg != null) { 9295 intent.setPackage(targetPkg); 9296 } 9297 // Modify the UID when posting to other users 9298 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 9299 if (uid > 0 && UserHandle.getUserId(uid) != id) { 9300 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 9301 intent.putExtra(Intent.EXTRA_UID, uid); 9302 } 9303 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 9304 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 9305 if (DEBUG_BROADCASTS) { 9306 RuntimeException here = new RuntimeException("here"); 9307 here.fillInStackTrace(); 9308 Slog.d(TAG, "Sending to user " + id + ": " 9309 + intent.toShortString(false, true, false, false) 9310 + " " + intent.getExtras(), here); 9311 } 9312 am.broadcastIntent(null, intent, null, finishedReceiver, 9313 0, null, null, null, android.app.AppOpsManager.OP_NONE, 9314 null, finishedReceiver != null, false, id); 9315 } 9316 } catch (RemoteException ex) { 9317 } 9318 } 9319 }); 9320 } 9321 9322 /** 9323 * Check if the external storage media is available. This is true if there 9324 * is a mounted external storage medium or if the external storage is 9325 * emulated. 9326 */ 9327 private boolean isExternalMediaAvailable() { 9328 return mMediaMounted || Environment.isExternalStorageEmulated(); 9329 } 9330 9331 @Override 9332 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 9333 // writer 9334 synchronized (mPackages) { 9335 if (!isExternalMediaAvailable()) { 9336 // If the external storage is no longer mounted at this point, 9337 // the caller may not have been able to delete all of this 9338 // packages files and can not delete any more. Bail. 9339 return null; 9340 } 9341 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 9342 if (lastPackage != null) { 9343 pkgs.remove(lastPackage); 9344 } 9345 if (pkgs.size() > 0) { 9346 return pkgs.get(0); 9347 } 9348 } 9349 return null; 9350 } 9351 9352 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 9353 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 9354 userId, andCode ? 1 : 0, packageName); 9355 if (mSystemReady) { 9356 msg.sendToTarget(); 9357 } else { 9358 if (mPostSystemReadyMessages == null) { 9359 mPostSystemReadyMessages = new ArrayList<>(); 9360 } 9361 mPostSystemReadyMessages.add(msg); 9362 } 9363 } 9364 9365 void startCleaningPackages() { 9366 // reader 9367 synchronized (mPackages) { 9368 if (!isExternalMediaAvailable()) { 9369 return; 9370 } 9371 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 9372 return; 9373 } 9374 } 9375 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 9376 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 9377 IActivityManager am = ActivityManagerNative.getDefault(); 9378 if (am != null) { 9379 try { 9380 am.startService(null, intent, null, mContext.getOpPackageName(), 9381 UserHandle.USER_OWNER); 9382 } catch (RemoteException e) { 9383 } 9384 } 9385 } 9386 9387 @Override 9388 public void installPackage(String originPath, IPackageInstallObserver2 observer, 9389 int installFlags, String installerPackageName, VerificationParams verificationParams, 9390 String packageAbiOverride) { 9391 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 9392 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 9393 } 9394 9395 @Override 9396 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 9397 int installFlags, String installerPackageName, VerificationParams verificationParams, 9398 String packageAbiOverride, int userId) { 9399 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 9400 9401 final int callingUid = Binder.getCallingUid(); 9402 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 9403 9404 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9405 try { 9406 if (observer != null) { 9407 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 9408 } 9409 } catch (RemoteException re) { 9410 } 9411 return; 9412 } 9413 9414 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 9415 installFlags |= PackageManager.INSTALL_FROM_ADB; 9416 9417 } else { 9418 // Caller holds INSTALL_PACKAGES permission, so we're less strict 9419 // about installerPackageName. 9420 9421 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 9422 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 9423 } 9424 9425 UserHandle user; 9426 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 9427 user = UserHandle.ALL; 9428 } else { 9429 user = new UserHandle(userId); 9430 } 9431 9432 // Only system components can circumvent runtime permissions when installing. 9433 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 9434 && mContext.checkCallingOrSelfPermission(Manifest.permission 9435 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 9436 throw new SecurityException("You need the " 9437 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 9438 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 9439 } 9440 9441 verificationParams.setInstallerUid(callingUid); 9442 9443 final File originFile = new File(originPath); 9444 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 9445 9446 final Message msg = mHandler.obtainMessage(INIT_COPY); 9447 msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName, 9448 null, verificationParams, user, packageAbiOverride); 9449 mHandler.sendMessage(msg); 9450 } 9451 9452 void installStage(String packageName, File stagedDir, String stagedCid, 9453 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 9454 String installerPackageName, int installerUid, UserHandle user) { 9455 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 9456 params.referrerUri, installerUid, null); 9457 verifParams.setInstallerUid(installerUid); 9458 9459 final OriginInfo origin; 9460 if (stagedDir != null) { 9461 origin = OriginInfo.fromStagedFile(stagedDir); 9462 } else { 9463 origin = OriginInfo.fromStagedContainer(stagedCid); 9464 } 9465 9466 final Message msg = mHandler.obtainMessage(INIT_COPY); 9467 msg.obj = new InstallParams(origin, null, observer, params.installFlags, 9468 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride); 9469 mHandler.sendMessage(msg); 9470 } 9471 9472 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 9473 Bundle extras = new Bundle(1); 9474 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 9475 9476 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 9477 packageName, extras, null, null, new int[] {userId}); 9478 try { 9479 IActivityManager am = ActivityManagerNative.getDefault(); 9480 final boolean isSystem = 9481 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 9482 if (isSystem && am.isUserRunning(userId, false)) { 9483 // The just-installed/enabled app is bundled on the system, so presumed 9484 // to be able to run automatically without needing an explicit launch. 9485 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 9486 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 9487 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 9488 .setPackage(packageName); 9489 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 9490 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 9491 } 9492 } catch (RemoteException e) { 9493 // shouldn't happen 9494 Slog.w(TAG, "Unable to bootstrap installed package", e); 9495 } 9496 } 9497 9498 @Override 9499 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 9500 int userId) { 9501 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9502 PackageSetting pkgSetting; 9503 final int uid = Binder.getCallingUid(); 9504 enforceCrossUserPermission(uid, userId, true, true, 9505 "setApplicationHiddenSetting for user " + userId); 9506 9507 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 9508 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 9509 return false; 9510 } 9511 9512 long callingId = Binder.clearCallingIdentity(); 9513 try { 9514 boolean sendAdded = false; 9515 boolean sendRemoved = false; 9516 // writer 9517 synchronized (mPackages) { 9518 pkgSetting = mSettings.mPackages.get(packageName); 9519 if (pkgSetting == null) { 9520 return false; 9521 } 9522 if (pkgSetting.getHidden(userId) != hidden) { 9523 pkgSetting.setHidden(hidden, userId); 9524 mSettings.writePackageRestrictionsLPr(userId); 9525 if (hidden) { 9526 sendRemoved = true; 9527 } else { 9528 sendAdded = true; 9529 } 9530 } 9531 } 9532 if (sendAdded) { 9533 sendPackageAddedForUser(packageName, pkgSetting, userId); 9534 return true; 9535 } 9536 if (sendRemoved) { 9537 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 9538 "hiding pkg"); 9539 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 9540 } 9541 } finally { 9542 Binder.restoreCallingIdentity(callingId); 9543 } 9544 return false; 9545 } 9546 9547 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 9548 int userId) { 9549 final PackageRemovedInfo info = new PackageRemovedInfo(); 9550 info.removedPackage = packageName; 9551 info.removedUsers = new int[] {userId}; 9552 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 9553 info.sendBroadcast(false, false, false); 9554 } 9555 9556 /** 9557 * Returns true if application is not found or there was an error. Otherwise it returns 9558 * the hidden state of the package for the given user. 9559 */ 9560 @Override 9561 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 9562 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9563 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 9564 false, "getApplicationHidden for user " + userId); 9565 PackageSetting pkgSetting; 9566 long callingId = Binder.clearCallingIdentity(); 9567 try { 9568 // writer 9569 synchronized (mPackages) { 9570 pkgSetting = mSettings.mPackages.get(packageName); 9571 if (pkgSetting == null) { 9572 return true; 9573 } 9574 return pkgSetting.getHidden(userId); 9575 } 9576 } finally { 9577 Binder.restoreCallingIdentity(callingId); 9578 } 9579 } 9580 9581 /** 9582 * @hide 9583 */ 9584 @Override 9585 public int installExistingPackageAsUser(String packageName, int userId) { 9586 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 9587 null); 9588 PackageSetting pkgSetting; 9589 final int uid = Binder.getCallingUid(); 9590 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 9591 + userId); 9592 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9593 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 9594 } 9595 9596 long callingId = Binder.clearCallingIdentity(); 9597 try { 9598 boolean sendAdded = false; 9599 9600 // writer 9601 synchronized (mPackages) { 9602 pkgSetting = mSettings.mPackages.get(packageName); 9603 if (pkgSetting == null) { 9604 return PackageManager.INSTALL_FAILED_INVALID_URI; 9605 } 9606 if (!pkgSetting.getInstalled(userId)) { 9607 pkgSetting.setInstalled(true, userId); 9608 pkgSetting.setHidden(false, userId); 9609 mSettings.writePackageRestrictionsLPr(userId); 9610 sendAdded = true; 9611 } 9612 } 9613 9614 if (sendAdded) { 9615 sendPackageAddedForUser(packageName, pkgSetting, userId); 9616 } 9617 } finally { 9618 Binder.restoreCallingIdentity(callingId); 9619 } 9620 9621 return PackageManager.INSTALL_SUCCEEDED; 9622 } 9623 9624 boolean isUserRestricted(int userId, String restrictionKey) { 9625 Bundle restrictions = sUserManager.getUserRestrictions(userId); 9626 if (restrictions.getBoolean(restrictionKey, false)) { 9627 Log.w(TAG, "User is restricted: " + restrictionKey); 9628 return true; 9629 } 9630 return false; 9631 } 9632 9633 @Override 9634 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 9635 mContext.enforceCallingOrSelfPermission( 9636 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9637 "Only package verification agents can verify applications"); 9638 9639 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9640 final PackageVerificationResponse response = new PackageVerificationResponse( 9641 verificationCode, Binder.getCallingUid()); 9642 msg.arg1 = id; 9643 msg.obj = response; 9644 mHandler.sendMessage(msg); 9645 } 9646 9647 @Override 9648 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 9649 long millisecondsToDelay) { 9650 mContext.enforceCallingOrSelfPermission( 9651 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9652 "Only package verification agents can extend verification timeouts"); 9653 9654 final PackageVerificationState state = mPendingVerification.get(id); 9655 final PackageVerificationResponse response = new PackageVerificationResponse( 9656 verificationCodeAtTimeout, Binder.getCallingUid()); 9657 9658 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 9659 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 9660 } 9661 if (millisecondsToDelay < 0) { 9662 millisecondsToDelay = 0; 9663 } 9664 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 9665 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 9666 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 9667 } 9668 9669 if ((state != null) && !state.timeoutExtended()) { 9670 state.extendTimeout(); 9671 9672 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9673 msg.arg1 = id; 9674 msg.obj = response; 9675 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 9676 } 9677 } 9678 9679 private void broadcastPackageVerified(int verificationId, Uri packageUri, 9680 int verificationCode, UserHandle user) { 9681 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 9682 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 9683 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9684 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9685 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 9686 9687 mContext.sendBroadcastAsUser(intent, user, 9688 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 9689 } 9690 9691 private ComponentName matchComponentForVerifier(String packageName, 9692 List<ResolveInfo> receivers) { 9693 ActivityInfo targetReceiver = null; 9694 9695 final int NR = receivers.size(); 9696 for (int i = 0; i < NR; i++) { 9697 final ResolveInfo info = receivers.get(i); 9698 if (info.activityInfo == null) { 9699 continue; 9700 } 9701 9702 if (packageName.equals(info.activityInfo.packageName)) { 9703 targetReceiver = info.activityInfo; 9704 break; 9705 } 9706 } 9707 9708 if (targetReceiver == null) { 9709 return null; 9710 } 9711 9712 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 9713 } 9714 9715 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 9716 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 9717 if (pkgInfo.verifiers.length == 0) { 9718 return null; 9719 } 9720 9721 final int N = pkgInfo.verifiers.length; 9722 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 9723 for (int i = 0; i < N; i++) { 9724 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 9725 9726 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 9727 receivers); 9728 if (comp == null) { 9729 continue; 9730 } 9731 9732 final int verifierUid = getUidForVerifier(verifierInfo); 9733 if (verifierUid == -1) { 9734 continue; 9735 } 9736 9737 if (DEBUG_VERIFY) { 9738 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 9739 + " with the correct signature"); 9740 } 9741 sufficientVerifiers.add(comp); 9742 verificationState.addSufficientVerifier(verifierUid); 9743 } 9744 9745 return sufficientVerifiers; 9746 } 9747 9748 private int getUidForVerifier(VerifierInfo verifierInfo) { 9749 synchronized (mPackages) { 9750 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 9751 if (pkg == null) { 9752 return -1; 9753 } else if (pkg.mSignatures.length != 1) { 9754 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9755 + " has more than one signature; ignoring"); 9756 return -1; 9757 } 9758 9759 /* 9760 * If the public key of the package's signature does not match 9761 * our expected public key, then this is a different package and 9762 * we should skip. 9763 */ 9764 9765 final byte[] expectedPublicKey; 9766 try { 9767 final Signature verifierSig = pkg.mSignatures[0]; 9768 final PublicKey publicKey = verifierSig.getPublicKey(); 9769 expectedPublicKey = publicKey.getEncoded(); 9770 } catch (CertificateException e) { 9771 return -1; 9772 } 9773 9774 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 9775 9776 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 9777 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9778 + " does not have the expected public key; ignoring"); 9779 return -1; 9780 } 9781 9782 return pkg.applicationInfo.uid; 9783 } 9784 } 9785 9786 @Override 9787 public void finishPackageInstall(int token) { 9788 enforceSystemOrRoot("Only the system is allowed to finish installs"); 9789 9790 if (DEBUG_INSTALL) { 9791 Slog.v(TAG, "BM finishing package install for " + token); 9792 } 9793 9794 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9795 mHandler.sendMessage(msg); 9796 } 9797 9798 /** 9799 * Get the verification agent timeout. 9800 * 9801 * @return verification timeout in milliseconds 9802 */ 9803 private long getVerificationTimeout() { 9804 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 9805 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 9806 DEFAULT_VERIFICATION_TIMEOUT); 9807 } 9808 9809 /** 9810 * Get the default verification agent response code. 9811 * 9812 * @return default verification response code 9813 */ 9814 private int getDefaultVerificationResponse() { 9815 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9816 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 9817 DEFAULT_VERIFICATION_RESPONSE); 9818 } 9819 9820 /** 9821 * Check whether or not package verification has been enabled. 9822 * 9823 * @return true if verification should be performed 9824 */ 9825 private boolean isVerificationEnabled(int userId, int installFlags) { 9826 if (!DEFAULT_VERIFY_ENABLE) { 9827 return false; 9828 } 9829 9830 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 9831 9832 // Check if installing from ADB 9833 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 9834 // Do not run verification in a test harness environment 9835 if (ActivityManager.isRunningInTestHarness()) { 9836 return false; 9837 } 9838 if (ensureVerifyAppsEnabled) { 9839 return true; 9840 } 9841 // Check if the developer does not want package verification for ADB installs 9842 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9843 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 9844 return false; 9845 } 9846 } 9847 9848 if (ensureVerifyAppsEnabled) { 9849 return true; 9850 } 9851 9852 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9853 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 9854 } 9855 9856 @Override 9857 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 9858 throws RemoteException { 9859 mContext.enforceCallingOrSelfPermission( 9860 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 9861 "Only intentfilter verification agents can verify applications"); 9862 9863 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 9864 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 9865 Binder.getCallingUid(), verificationCode, failedDomains); 9866 msg.arg1 = id; 9867 msg.obj = response; 9868 mHandler.sendMessage(msg); 9869 } 9870 9871 @Override 9872 public int getIntentVerificationStatus(String packageName, int userId) { 9873 synchronized (mPackages) { 9874 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 9875 } 9876 } 9877 9878 @Override 9879 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 9880 mContext.enforceCallingOrSelfPermission( 9881 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 9882 9883 boolean result = false; 9884 synchronized (mPackages) { 9885 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 9886 } 9887 if (result) { 9888 scheduleWritePackageRestrictionsLocked(userId); 9889 } 9890 return result; 9891 } 9892 9893 @Override 9894 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 9895 synchronized (mPackages) { 9896 return mSettings.getIntentFilterVerificationsLPr(packageName); 9897 } 9898 } 9899 9900 @Override 9901 public List<IntentFilter> getAllIntentFilters(String packageName) { 9902 if (TextUtils.isEmpty(packageName)) { 9903 return Collections.<IntentFilter>emptyList(); 9904 } 9905 synchronized (mPackages) { 9906 PackageParser.Package pkg = mPackages.get(packageName); 9907 if (pkg == null || pkg.activities == null) { 9908 return Collections.<IntentFilter>emptyList(); 9909 } 9910 final int count = pkg.activities.size(); 9911 ArrayList<IntentFilter> result = new ArrayList<>(); 9912 for (int n=0; n<count; n++) { 9913 PackageParser.Activity activity = pkg.activities.get(n); 9914 if (activity.intents != null || activity.intents.size() > 0) { 9915 result.addAll(activity.intents); 9916 } 9917 } 9918 return result; 9919 } 9920 } 9921 9922 @Override 9923 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 9924 mContext.enforceCallingOrSelfPermission( 9925 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 9926 9927 synchronized (mPackages) { 9928 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 9929 if (packageName != null) { 9930 result |= updateIntentVerificationStatus(packageName, 9931 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 9932 UserHandle.myUserId()); 9933 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 9934 packageName, userId); 9935 } 9936 return result; 9937 } 9938 } 9939 9940 @Override 9941 public String getDefaultBrowserPackageName(int userId) { 9942 synchronized (mPackages) { 9943 return mSettings.getDefaultBrowserPackageNameLPw(userId); 9944 } 9945 } 9946 9947 /** 9948 * Get the "allow unknown sources" setting. 9949 * 9950 * @return the current "allow unknown sources" setting 9951 */ 9952 private int getUnknownSourcesSettings() { 9953 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9954 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 9955 -1); 9956 } 9957 9958 @Override 9959 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 9960 final int uid = Binder.getCallingUid(); 9961 // writer 9962 synchronized (mPackages) { 9963 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 9964 if (targetPackageSetting == null) { 9965 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 9966 } 9967 9968 PackageSetting installerPackageSetting; 9969 if (installerPackageName != null) { 9970 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 9971 if (installerPackageSetting == null) { 9972 throw new IllegalArgumentException("Unknown installer package: " 9973 + installerPackageName); 9974 } 9975 } else { 9976 installerPackageSetting = null; 9977 } 9978 9979 Signature[] callerSignature; 9980 Object obj = mSettings.getUserIdLPr(uid); 9981 if (obj != null) { 9982 if (obj instanceof SharedUserSetting) { 9983 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 9984 } else if (obj instanceof PackageSetting) { 9985 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 9986 } else { 9987 throw new SecurityException("Bad object " + obj + " for uid " + uid); 9988 } 9989 } else { 9990 throw new SecurityException("Unknown calling uid " + uid); 9991 } 9992 9993 // Verify: can't set installerPackageName to a package that is 9994 // not signed with the same cert as the caller. 9995 if (installerPackageSetting != null) { 9996 if (compareSignatures(callerSignature, 9997 installerPackageSetting.signatures.mSignatures) 9998 != PackageManager.SIGNATURE_MATCH) { 9999 throw new SecurityException( 10000 "Caller does not have same cert as new installer package " 10001 + installerPackageName); 10002 } 10003 } 10004 10005 // Verify: if target already has an installer package, it must 10006 // be signed with the same cert as the caller. 10007 if (targetPackageSetting.installerPackageName != null) { 10008 PackageSetting setting = mSettings.mPackages.get( 10009 targetPackageSetting.installerPackageName); 10010 // If the currently set package isn't valid, then it's always 10011 // okay to change it. 10012 if (setting != null) { 10013 if (compareSignatures(callerSignature, 10014 setting.signatures.mSignatures) 10015 != PackageManager.SIGNATURE_MATCH) { 10016 throw new SecurityException( 10017 "Caller does not have same cert as old installer package " 10018 + targetPackageSetting.installerPackageName); 10019 } 10020 } 10021 } 10022 10023 // Okay! 10024 targetPackageSetting.installerPackageName = installerPackageName; 10025 scheduleWriteSettingsLocked(); 10026 } 10027 } 10028 10029 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 10030 // Queue up an async operation since the package installation may take a little while. 10031 mHandler.post(new Runnable() { 10032 public void run() { 10033 mHandler.removeCallbacks(this); 10034 // Result object to be returned 10035 PackageInstalledInfo res = new PackageInstalledInfo(); 10036 res.returnCode = currentStatus; 10037 res.uid = -1; 10038 res.pkg = null; 10039 res.removedInfo = new PackageRemovedInfo(); 10040 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10041 args.doPreInstall(res.returnCode); 10042 synchronized (mInstallLock) { 10043 installPackageLI(args, res); 10044 } 10045 args.doPostInstall(res.returnCode, res.uid); 10046 } 10047 10048 // A restore should be performed at this point if (a) the install 10049 // succeeded, (b) the operation is not an update, and (c) the new 10050 // package has not opted out of backup participation. 10051 final boolean update = res.removedInfo.removedPackage != null; 10052 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 10053 boolean doRestore = !update 10054 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 10055 10056 // Set up the post-install work request bookkeeping. This will be used 10057 // and cleaned up by the post-install event handling regardless of whether 10058 // there's a restore pass performed. Token values are >= 1. 10059 int token; 10060 if (mNextInstallToken < 0) mNextInstallToken = 1; 10061 token = mNextInstallToken++; 10062 10063 PostInstallData data = new PostInstallData(args, res); 10064 mRunningInstalls.put(token, data); 10065 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 10066 10067 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 10068 // Pass responsibility to the Backup Manager. It will perform a 10069 // restore if appropriate, then pass responsibility back to the 10070 // Package Manager to run the post-install observer callbacks 10071 // and broadcasts. 10072 IBackupManager bm = IBackupManager.Stub.asInterface( 10073 ServiceManager.getService(Context.BACKUP_SERVICE)); 10074 if (bm != null) { 10075 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 10076 + " to BM for possible restore"); 10077 try { 10078 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 10079 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 10080 } else { 10081 doRestore = false; 10082 } 10083 } catch (RemoteException e) { 10084 // can't happen; the backup manager is local 10085 } catch (Exception e) { 10086 Slog.e(TAG, "Exception trying to enqueue restore", e); 10087 doRestore = false; 10088 } 10089 } else { 10090 Slog.e(TAG, "Backup Manager not found!"); 10091 doRestore = false; 10092 } 10093 } 10094 10095 if (!doRestore) { 10096 // No restore possible, or the Backup Manager was mysteriously not 10097 // available -- just fire the post-install work request directly. 10098 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 10099 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10100 mHandler.sendMessage(msg); 10101 } 10102 } 10103 }); 10104 } 10105 10106 private abstract class HandlerParams { 10107 private static final int MAX_RETRIES = 4; 10108 10109 /** 10110 * Number of times startCopy() has been attempted and had a non-fatal 10111 * error. 10112 */ 10113 private int mRetries = 0; 10114 10115 /** User handle for the user requesting the information or installation. */ 10116 private final UserHandle mUser; 10117 10118 HandlerParams(UserHandle user) { 10119 mUser = user; 10120 } 10121 10122 UserHandle getUser() { 10123 return mUser; 10124 } 10125 10126 final boolean startCopy() { 10127 boolean res; 10128 try { 10129 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 10130 10131 if (++mRetries > MAX_RETRIES) { 10132 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 10133 mHandler.sendEmptyMessage(MCS_GIVE_UP); 10134 handleServiceError(); 10135 return false; 10136 } else { 10137 handleStartCopy(); 10138 res = true; 10139 } 10140 } catch (RemoteException e) { 10141 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 10142 mHandler.sendEmptyMessage(MCS_RECONNECT); 10143 res = false; 10144 } 10145 handleReturnCode(); 10146 return res; 10147 } 10148 10149 final void serviceError() { 10150 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 10151 handleServiceError(); 10152 handleReturnCode(); 10153 } 10154 10155 abstract void handleStartCopy() throws RemoteException; 10156 abstract void handleServiceError(); 10157 abstract void handleReturnCode(); 10158 } 10159 10160 class MeasureParams extends HandlerParams { 10161 private final PackageStats mStats; 10162 private boolean mSuccess; 10163 10164 private final IPackageStatsObserver mObserver; 10165 10166 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 10167 super(new UserHandle(stats.userHandle)); 10168 mObserver = observer; 10169 mStats = stats; 10170 } 10171 10172 @Override 10173 public String toString() { 10174 return "MeasureParams{" 10175 + Integer.toHexString(System.identityHashCode(this)) 10176 + " " + mStats.packageName + "}"; 10177 } 10178 10179 @Override 10180 void handleStartCopy() throws RemoteException { 10181 synchronized (mInstallLock) { 10182 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 10183 } 10184 10185 if (mSuccess) { 10186 final boolean mounted; 10187 if (Environment.isExternalStorageEmulated()) { 10188 mounted = true; 10189 } else { 10190 final String status = Environment.getExternalStorageState(); 10191 mounted = (Environment.MEDIA_MOUNTED.equals(status) 10192 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 10193 } 10194 10195 if (mounted) { 10196 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 10197 10198 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 10199 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 10200 10201 mStats.externalDataSize = calculateDirectorySize(mContainerService, 10202 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 10203 10204 // Always subtract cache size, since it's a subdirectory 10205 mStats.externalDataSize -= mStats.externalCacheSize; 10206 10207 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 10208 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 10209 10210 mStats.externalObbSize = calculateDirectorySize(mContainerService, 10211 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 10212 } 10213 } 10214 } 10215 10216 @Override 10217 void handleReturnCode() { 10218 if (mObserver != null) { 10219 try { 10220 mObserver.onGetStatsCompleted(mStats, mSuccess); 10221 } catch (RemoteException e) { 10222 Slog.i(TAG, "Observer no longer exists."); 10223 } 10224 } 10225 } 10226 10227 @Override 10228 void handleServiceError() { 10229 Slog.e(TAG, "Could not measure application " + mStats.packageName 10230 + " external storage"); 10231 } 10232 } 10233 10234 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 10235 throws RemoteException { 10236 long result = 0; 10237 for (File path : paths) { 10238 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 10239 } 10240 return result; 10241 } 10242 10243 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 10244 for (File path : paths) { 10245 try { 10246 mcs.clearDirectory(path.getAbsolutePath()); 10247 } catch (RemoteException e) { 10248 } 10249 } 10250 } 10251 10252 static class OriginInfo { 10253 /** 10254 * Location where install is coming from, before it has been 10255 * copied/renamed into place. This could be a single monolithic APK 10256 * file, or a cluster directory. This location may be untrusted. 10257 */ 10258 final File file; 10259 final String cid; 10260 10261 /** 10262 * Flag indicating that {@link #file} or {@link #cid} has already been 10263 * staged, meaning downstream users don't need to defensively copy the 10264 * contents. 10265 */ 10266 final boolean staged; 10267 10268 /** 10269 * Flag indicating that {@link #file} or {@link #cid} is an already 10270 * installed app that is being moved. 10271 */ 10272 final boolean existing; 10273 10274 final String resolvedPath; 10275 final File resolvedFile; 10276 10277 static OriginInfo fromNothing() { 10278 return new OriginInfo(null, null, false, false); 10279 } 10280 10281 static OriginInfo fromUntrustedFile(File file) { 10282 return new OriginInfo(file, null, false, false); 10283 } 10284 10285 static OriginInfo fromExistingFile(File file) { 10286 return new OriginInfo(file, null, false, true); 10287 } 10288 10289 static OriginInfo fromStagedFile(File file) { 10290 return new OriginInfo(file, null, true, false); 10291 } 10292 10293 static OriginInfo fromStagedContainer(String cid) { 10294 return new OriginInfo(null, cid, true, false); 10295 } 10296 10297 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 10298 this.file = file; 10299 this.cid = cid; 10300 this.staged = staged; 10301 this.existing = existing; 10302 10303 if (cid != null) { 10304 resolvedPath = PackageHelper.getSdDir(cid); 10305 resolvedFile = new File(resolvedPath); 10306 } else if (file != null) { 10307 resolvedPath = file.getAbsolutePath(); 10308 resolvedFile = file; 10309 } else { 10310 resolvedPath = null; 10311 resolvedFile = null; 10312 } 10313 } 10314 } 10315 10316 class MoveInfo { 10317 final int moveId; 10318 final String fromUuid; 10319 final String toUuid; 10320 final String packageName; 10321 final String dataAppName; 10322 final int appId; 10323 final String seinfo; 10324 10325 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 10326 String dataAppName, int appId, String seinfo) { 10327 this.moveId = moveId; 10328 this.fromUuid = fromUuid; 10329 this.toUuid = toUuid; 10330 this.packageName = packageName; 10331 this.dataAppName = dataAppName; 10332 this.appId = appId; 10333 this.seinfo = seinfo; 10334 } 10335 } 10336 10337 class InstallParams extends HandlerParams { 10338 final OriginInfo origin; 10339 final MoveInfo move; 10340 final IPackageInstallObserver2 observer; 10341 int installFlags; 10342 final String installerPackageName; 10343 final String volumeUuid; 10344 final VerificationParams verificationParams; 10345 private InstallArgs mArgs; 10346 private int mRet; 10347 final String packageAbiOverride; 10348 10349 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10350 int installFlags, String installerPackageName, String volumeUuid, 10351 VerificationParams verificationParams, UserHandle user, String packageAbiOverride) { 10352 super(user); 10353 this.origin = origin; 10354 this.move = move; 10355 this.observer = observer; 10356 this.installFlags = installFlags; 10357 this.installerPackageName = installerPackageName; 10358 this.volumeUuid = volumeUuid; 10359 this.verificationParams = verificationParams; 10360 this.packageAbiOverride = packageAbiOverride; 10361 } 10362 10363 @Override 10364 public String toString() { 10365 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 10366 + " file=" + origin.file + " cid=" + origin.cid + "}"; 10367 } 10368 10369 public ManifestDigest getManifestDigest() { 10370 if (verificationParams == null) { 10371 return null; 10372 } 10373 return verificationParams.getManifestDigest(); 10374 } 10375 10376 private int installLocationPolicy(PackageInfoLite pkgLite) { 10377 String packageName = pkgLite.packageName; 10378 int installLocation = pkgLite.installLocation; 10379 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10380 // reader 10381 synchronized (mPackages) { 10382 PackageParser.Package pkg = mPackages.get(packageName); 10383 if (pkg != null) { 10384 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10385 // Check for downgrading. 10386 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 10387 try { 10388 checkDowngrade(pkg, pkgLite); 10389 } catch (PackageManagerException e) { 10390 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 10391 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 10392 } 10393 } 10394 // Check for updated system application. 10395 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10396 if (onSd) { 10397 Slog.w(TAG, "Cannot install update to system app on sdcard"); 10398 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 10399 } 10400 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10401 } else { 10402 if (onSd) { 10403 // Install flag overrides everything. 10404 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10405 } 10406 // If current upgrade specifies particular preference 10407 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 10408 // Application explicitly specified internal. 10409 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10410 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 10411 // App explictly prefers external. Let policy decide 10412 } else { 10413 // Prefer previous location 10414 if (isExternal(pkg)) { 10415 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10416 } 10417 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10418 } 10419 } 10420 } else { 10421 // Invalid install. Return error code 10422 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 10423 } 10424 } 10425 } 10426 // All the special cases have been taken care of. 10427 // Return result based on recommended install location. 10428 if (onSd) { 10429 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10430 } 10431 return pkgLite.recommendedInstallLocation; 10432 } 10433 10434 /* 10435 * Invoke remote method to get package information and install 10436 * location values. Override install location based on default 10437 * policy if needed and then create install arguments based 10438 * on the install location. 10439 */ 10440 public void handleStartCopy() throws RemoteException { 10441 int ret = PackageManager.INSTALL_SUCCEEDED; 10442 10443 // If we're already staged, we've firmly committed to an install location 10444 if (origin.staged) { 10445 if (origin.file != null) { 10446 installFlags |= PackageManager.INSTALL_INTERNAL; 10447 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10448 } else if (origin.cid != null) { 10449 installFlags |= PackageManager.INSTALL_EXTERNAL; 10450 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10451 } else { 10452 throw new IllegalStateException("Invalid stage location"); 10453 } 10454 } 10455 10456 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10457 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 10458 10459 PackageInfoLite pkgLite = null; 10460 10461 if (onInt && onSd) { 10462 // Check if both bits are set. 10463 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 10464 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10465 } else { 10466 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 10467 packageAbiOverride); 10468 10469 /* 10470 * If we have too little free space, try to free cache 10471 * before giving up. 10472 */ 10473 if (!origin.staged && pkgLite.recommendedInstallLocation 10474 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10475 // TODO: focus freeing disk space on the target device 10476 final StorageManager storage = StorageManager.from(mContext); 10477 final long lowThreshold = storage.getStorageLowBytes( 10478 Environment.getDataDirectory()); 10479 10480 final long sizeBytes = mContainerService.calculateInstalledSize( 10481 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 10482 10483 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 10484 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 10485 installFlags, packageAbiOverride); 10486 } 10487 10488 /* 10489 * The cache free must have deleted the file we 10490 * downloaded to install. 10491 * 10492 * TODO: fix the "freeCache" call to not delete 10493 * the file we care about. 10494 */ 10495 if (pkgLite.recommendedInstallLocation 10496 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10497 pkgLite.recommendedInstallLocation 10498 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 10499 } 10500 } 10501 } 10502 10503 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10504 int loc = pkgLite.recommendedInstallLocation; 10505 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 10506 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10507 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 10508 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 10509 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10510 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10511 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 10512 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 10513 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10514 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 10515 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 10516 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 10517 } else { 10518 // Override with defaults if needed. 10519 loc = installLocationPolicy(pkgLite); 10520 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 10521 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 10522 } else if (!onSd && !onInt) { 10523 // Override install location with flags 10524 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 10525 // Set the flag to install on external media. 10526 installFlags |= PackageManager.INSTALL_EXTERNAL; 10527 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10528 } else { 10529 // Make sure the flag for installing on external 10530 // media is unset 10531 installFlags |= PackageManager.INSTALL_INTERNAL; 10532 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10533 } 10534 } 10535 } 10536 } 10537 10538 final InstallArgs args = createInstallArgs(this); 10539 mArgs = args; 10540 10541 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10542 /* 10543 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 10544 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 10545 */ 10546 int userIdentifier = getUser().getIdentifier(); 10547 if (userIdentifier == UserHandle.USER_ALL 10548 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 10549 userIdentifier = UserHandle.USER_OWNER; 10550 } 10551 10552 /* 10553 * Determine if we have any installed package verifiers. If we 10554 * do, then we'll defer to them to verify the packages. 10555 */ 10556 final int requiredUid = mRequiredVerifierPackage == null ? -1 10557 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 10558 if (!origin.existing && requiredUid != -1 10559 && isVerificationEnabled(userIdentifier, installFlags)) { 10560 final Intent verification = new Intent( 10561 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 10562 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 10563 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 10564 PACKAGE_MIME_TYPE); 10565 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10566 10567 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 10568 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 10569 0 /* TODO: Which userId? */); 10570 10571 if (DEBUG_VERIFY) { 10572 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 10573 + verification.toString() + " with " + pkgLite.verifiers.length 10574 + " optional verifiers"); 10575 } 10576 10577 final int verificationId = mPendingVerificationToken++; 10578 10579 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10580 10581 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 10582 installerPackageName); 10583 10584 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 10585 installFlags); 10586 10587 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 10588 pkgLite.packageName); 10589 10590 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 10591 pkgLite.versionCode); 10592 10593 if (verificationParams != null) { 10594 if (verificationParams.getVerificationURI() != null) { 10595 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 10596 verificationParams.getVerificationURI()); 10597 } 10598 if (verificationParams.getOriginatingURI() != null) { 10599 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 10600 verificationParams.getOriginatingURI()); 10601 } 10602 if (verificationParams.getReferrer() != null) { 10603 verification.putExtra(Intent.EXTRA_REFERRER, 10604 verificationParams.getReferrer()); 10605 } 10606 if (verificationParams.getOriginatingUid() >= 0) { 10607 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 10608 verificationParams.getOriginatingUid()); 10609 } 10610 if (verificationParams.getInstallerUid() >= 0) { 10611 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 10612 verificationParams.getInstallerUid()); 10613 } 10614 } 10615 10616 final PackageVerificationState verificationState = new PackageVerificationState( 10617 requiredUid, args); 10618 10619 mPendingVerification.append(verificationId, verificationState); 10620 10621 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 10622 receivers, verificationState); 10623 10624 /* 10625 * If any sufficient verifiers were listed in the package 10626 * manifest, attempt to ask them. 10627 */ 10628 if (sufficientVerifiers != null) { 10629 final int N = sufficientVerifiers.size(); 10630 if (N == 0) { 10631 Slog.i(TAG, "Additional verifiers required, but none installed."); 10632 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 10633 } else { 10634 for (int i = 0; i < N; i++) { 10635 final ComponentName verifierComponent = sufficientVerifiers.get(i); 10636 10637 final Intent sufficientIntent = new Intent(verification); 10638 sufficientIntent.setComponent(verifierComponent); 10639 10640 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 10641 } 10642 } 10643 } 10644 10645 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 10646 mRequiredVerifierPackage, receivers); 10647 if (ret == PackageManager.INSTALL_SUCCEEDED 10648 && mRequiredVerifierPackage != null) { 10649 /* 10650 * Send the intent to the required verification agent, 10651 * but only start the verification timeout after the 10652 * target BroadcastReceivers have run. 10653 */ 10654 verification.setComponent(requiredVerifierComponent); 10655 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 10656 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10657 new BroadcastReceiver() { 10658 @Override 10659 public void onReceive(Context context, Intent intent) { 10660 final Message msg = mHandler 10661 .obtainMessage(CHECK_PENDING_VERIFICATION); 10662 msg.arg1 = verificationId; 10663 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 10664 } 10665 }, null, 0, null, null); 10666 10667 /* 10668 * We don't want the copy to proceed until verification 10669 * succeeds, so null out this field. 10670 */ 10671 mArgs = null; 10672 } 10673 } else { 10674 /* 10675 * No package verification is enabled, so immediately start 10676 * the remote call to initiate copy using temporary file. 10677 */ 10678 ret = args.copyApk(mContainerService, true); 10679 } 10680 } 10681 10682 mRet = ret; 10683 } 10684 10685 @Override 10686 void handleReturnCode() { 10687 // If mArgs is null, then MCS couldn't be reached. When it 10688 // reconnects, it will try again to install. At that point, this 10689 // will succeed. 10690 if (mArgs != null) { 10691 processPendingInstall(mArgs, mRet); 10692 } 10693 } 10694 10695 @Override 10696 void handleServiceError() { 10697 mArgs = createInstallArgs(this); 10698 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10699 } 10700 10701 public boolean isForwardLocked() { 10702 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10703 } 10704 } 10705 10706 /** 10707 * Used during creation of InstallArgs 10708 * 10709 * @param installFlags package installation flags 10710 * @return true if should be installed on external storage 10711 */ 10712 private static boolean installOnExternalAsec(int installFlags) { 10713 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 10714 return false; 10715 } 10716 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 10717 return true; 10718 } 10719 return false; 10720 } 10721 10722 /** 10723 * Used during creation of InstallArgs 10724 * 10725 * @param installFlags package installation flags 10726 * @return true if should be installed as forward locked 10727 */ 10728 private static boolean installForwardLocked(int installFlags) { 10729 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10730 } 10731 10732 private InstallArgs createInstallArgs(InstallParams params) { 10733 if (params.move != null) { 10734 return new MoveInstallArgs(params); 10735 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 10736 return new AsecInstallArgs(params); 10737 } else { 10738 return new FileInstallArgs(params); 10739 } 10740 } 10741 10742 /** 10743 * Create args that describe an existing installed package. Typically used 10744 * when cleaning up old installs, or used as a move source. 10745 */ 10746 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 10747 String resourcePath, String[] instructionSets) { 10748 final boolean isInAsec; 10749 if (installOnExternalAsec(installFlags)) { 10750 /* Apps on SD card are always in ASEC containers. */ 10751 isInAsec = true; 10752 } else if (installForwardLocked(installFlags) 10753 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 10754 /* 10755 * Forward-locked apps are only in ASEC containers if they're the 10756 * new style 10757 */ 10758 isInAsec = true; 10759 } else { 10760 isInAsec = false; 10761 } 10762 10763 if (isInAsec) { 10764 return new AsecInstallArgs(codePath, instructionSets, 10765 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 10766 } else { 10767 return new FileInstallArgs(codePath, resourcePath, instructionSets); 10768 } 10769 } 10770 10771 static abstract class InstallArgs { 10772 /** @see InstallParams#origin */ 10773 final OriginInfo origin; 10774 /** @see InstallParams#move */ 10775 final MoveInfo move; 10776 10777 final IPackageInstallObserver2 observer; 10778 // Always refers to PackageManager flags only 10779 final int installFlags; 10780 final String installerPackageName; 10781 final String volumeUuid; 10782 final ManifestDigest manifestDigest; 10783 final UserHandle user; 10784 final String abiOverride; 10785 10786 // The list of instruction sets supported by this app. This is currently 10787 // only used during the rmdex() phase to clean up resources. We can get rid of this 10788 // if we move dex files under the common app path. 10789 /* nullable */ String[] instructionSets; 10790 10791 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10792 int installFlags, String installerPackageName, String volumeUuid, 10793 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 10794 String abiOverride) { 10795 this.origin = origin; 10796 this.move = move; 10797 this.installFlags = installFlags; 10798 this.observer = observer; 10799 this.installerPackageName = installerPackageName; 10800 this.volumeUuid = volumeUuid; 10801 this.manifestDigest = manifestDigest; 10802 this.user = user; 10803 this.instructionSets = instructionSets; 10804 this.abiOverride = abiOverride; 10805 } 10806 10807 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 10808 abstract int doPreInstall(int status); 10809 10810 /** 10811 * Rename package into final resting place. All paths on the given 10812 * scanned package should be updated to reflect the rename. 10813 */ 10814 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 10815 abstract int doPostInstall(int status, int uid); 10816 10817 /** @see PackageSettingBase#codePathString */ 10818 abstract String getCodePath(); 10819 /** @see PackageSettingBase#resourcePathString */ 10820 abstract String getResourcePath(); 10821 10822 // Need installer lock especially for dex file removal. 10823 abstract void cleanUpResourcesLI(); 10824 abstract boolean doPostDeleteLI(boolean delete); 10825 10826 /** 10827 * Called before the source arguments are copied. This is used mostly 10828 * for MoveParams when it needs to read the source file to put it in the 10829 * destination. 10830 */ 10831 int doPreCopy() { 10832 return PackageManager.INSTALL_SUCCEEDED; 10833 } 10834 10835 /** 10836 * Called after the source arguments are copied. This is used mostly for 10837 * MoveParams when it needs to read the source file to put it in the 10838 * destination. 10839 * 10840 * @return 10841 */ 10842 int doPostCopy(int uid) { 10843 return PackageManager.INSTALL_SUCCEEDED; 10844 } 10845 10846 protected boolean isFwdLocked() { 10847 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10848 } 10849 10850 protected boolean isExternalAsec() { 10851 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10852 } 10853 10854 UserHandle getUser() { 10855 return user; 10856 } 10857 } 10858 10859 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 10860 if (!allCodePaths.isEmpty()) { 10861 if (instructionSets == null) { 10862 throw new IllegalStateException("instructionSet == null"); 10863 } 10864 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 10865 for (String codePath : allCodePaths) { 10866 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 10867 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 10868 if (retCode < 0) { 10869 Slog.w(TAG, "Couldn't remove dex file for package: " 10870 + " at location " + codePath + ", retcode=" + retCode); 10871 // we don't consider this to be a failure of the core package deletion 10872 } 10873 } 10874 } 10875 } 10876 } 10877 10878 /** 10879 * Logic to handle installation of non-ASEC applications, including copying 10880 * and renaming logic. 10881 */ 10882 class FileInstallArgs extends InstallArgs { 10883 private File codeFile; 10884 private File resourceFile; 10885 10886 // Example topology: 10887 // /data/app/com.example/base.apk 10888 // /data/app/com.example/split_foo.apk 10889 // /data/app/com.example/lib/arm/libfoo.so 10890 // /data/app/com.example/lib/arm64/libfoo.so 10891 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 10892 10893 /** New install */ 10894 FileInstallArgs(InstallParams params) { 10895 super(params.origin, params.move, params.observer, params.installFlags, 10896 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10897 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10898 if (isFwdLocked()) { 10899 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 10900 } 10901 } 10902 10903 /** Existing install */ 10904 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 10905 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 10906 null); 10907 this.codeFile = (codePath != null) ? new File(codePath) : null; 10908 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 10909 } 10910 10911 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10912 if (origin.staged) { 10913 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 10914 codeFile = origin.file; 10915 resourceFile = origin.file; 10916 return PackageManager.INSTALL_SUCCEEDED; 10917 } 10918 10919 try { 10920 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 10921 codeFile = tempDir; 10922 resourceFile = tempDir; 10923 } catch (IOException e) { 10924 Slog.w(TAG, "Failed to create copy file: " + e); 10925 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10926 } 10927 10928 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 10929 @Override 10930 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 10931 if (!FileUtils.isValidExtFilename(name)) { 10932 throw new IllegalArgumentException("Invalid filename: " + name); 10933 } 10934 try { 10935 final File file = new File(codeFile, name); 10936 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 10937 O_RDWR | O_CREAT, 0644); 10938 Os.chmod(file.getAbsolutePath(), 0644); 10939 return new ParcelFileDescriptor(fd); 10940 } catch (ErrnoException e) { 10941 throw new RemoteException("Failed to open: " + e.getMessage()); 10942 } 10943 } 10944 }; 10945 10946 int ret = PackageManager.INSTALL_SUCCEEDED; 10947 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 10948 if (ret != PackageManager.INSTALL_SUCCEEDED) { 10949 Slog.e(TAG, "Failed to copy package"); 10950 return ret; 10951 } 10952 10953 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 10954 NativeLibraryHelper.Handle handle = null; 10955 try { 10956 handle = NativeLibraryHelper.Handle.create(codeFile); 10957 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 10958 abiOverride); 10959 } catch (IOException e) { 10960 Slog.e(TAG, "Copying native libraries failed", e); 10961 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10962 } finally { 10963 IoUtils.closeQuietly(handle); 10964 } 10965 10966 return ret; 10967 } 10968 10969 int doPreInstall(int status) { 10970 if (status != PackageManager.INSTALL_SUCCEEDED) { 10971 cleanUp(); 10972 } 10973 return status; 10974 } 10975 10976 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10977 if (status != PackageManager.INSTALL_SUCCEEDED) { 10978 cleanUp(); 10979 return false; 10980 } 10981 10982 final File targetDir = codeFile.getParentFile(); 10983 final File beforeCodeFile = codeFile; 10984 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 10985 10986 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 10987 try { 10988 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 10989 } catch (ErrnoException e) { 10990 Slog.w(TAG, "Failed to rename", e); 10991 return false; 10992 } 10993 10994 if (!SELinux.restoreconRecursive(afterCodeFile)) { 10995 Slog.w(TAG, "Failed to restorecon"); 10996 return false; 10997 } 10998 10999 // Reflect the rename internally 11000 codeFile = afterCodeFile; 11001 resourceFile = afterCodeFile; 11002 11003 // Reflect the rename in scanned details 11004 pkg.codePath = afterCodeFile.getAbsolutePath(); 11005 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11006 pkg.baseCodePath); 11007 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11008 pkg.splitCodePaths); 11009 11010 // Reflect the rename in app info 11011 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11012 pkg.applicationInfo.setCodePath(pkg.codePath); 11013 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11014 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11015 pkg.applicationInfo.setResourcePath(pkg.codePath); 11016 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11017 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11018 11019 return true; 11020 } 11021 11022 int doPostInstall(int status, int uid) { 11023 if (status != PackageManager.INSTALL_SUCCEEDED) { 11024 cleanUp(); 11025 } 11026 return status; 11027 } 11028 11029 @Override 11030 String getCodePath() { 11031 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11032 } 11033 11034 @Override 11035 String getResourcePath() { 11036 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11037 } 11038 11039 private boolean cleanUp() { 11040 if (codeFile == null || !codeFile.exists()) { 11041 return false; 11042 } 11043 11044 if (codeFile.isDirectory()) { 11045 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11046 } else { 11047 codeFile.delete(); 11048 } 11049 11050 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 11051 resourceFile.delete(); 11052 } 11053 11054 return true; 11055 } 11056 11057 void cleanUpResourcesLI() { 11058 // Try enumerating all code paths before deleting 11059 List<String> allCodePaths = Collections.EMPTY_LIST; 11060 if (codeFile != null && codeFile.exists()) { 11061 try { 11062 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11063 allCodePaths = pkg.getAllCodePaths(); 11064 } catch (PackageParserException e) { 11065 // Ignored; we tried our best 11066 } 11067 } 11068 11069 cleanUp(); 11070 removeDexFiles(allCodePaths, instructionSets); 11071 } 11072 11073 boolean doPostDeleteLI(boolean delete) { 11074 // XXX err, shouldn't we respect the delete flag? 11075 cleanUpResourcesLI(); 11076 return true; 11077 } 11078 } 11079 11080 private boolean isAsecExternal(String cid) { 11081 final String asecPath = PackageHelper.getSdFilesystem(cid); 11082 return !asecPath.startsWith(mAsecInternalPath); 11083 } 11084 11085 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 11086 PackageManagerException { 11087 if (copyRet < 0) { 11088 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 11089 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 11090 throw new PackageManagerException(copyRet, message); 11091 } 11092 } 11093 } 11094 11095 /** 11096 * Extract the MountService "container ID" from the full code path of an 11097 * .apk. 11098 */ 11099 static String cidFromCodePath(String fullCodePath) { 11100 int eidx = fullCodePath.lastIndexOf("/"); 11101 String subStr1 = fullCodePath.substring(0, eidx); 11102 int sidx = subStr1.lastIndexOf("/"); 11103 return subStr1.substring(sidx+1, eidx); 11104 } 11105 11106 /** 11107 * Logic to handle installation of ASEC applications, including copying and 11108 * renaming logic. 11109 */ 11110 class AsecInstallArgs extends InstallArgs { 11111 static final String RES_FILE_NAME = "pkg.apk"; 11112 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 11113 11114 String cid; 11115 String packagePath; 11116 String resourcePath; 11117 11118 /** New install */ 11119 AsecInstallArgs(InstallParams params) { 11120 super(params.origin, params.move, params.observer, params.installFlags, 11121 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11122 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 11123 } 11124 11125 /** Existing install */ 11126 AsecInstallArgs(String fullCodePath, String[] instructionSets, 11127 boolean isExternal, boolean isForwardLocked) { 11128 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 11129 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11130 instructionSets, null); 11131 // Hackily pretend we're still looking at a full code path 11132 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 11133 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 11134 } 11135 11136 // Extract cid from fullCodePath 11137 int eidx = fullCodePath.lastIndexOf("/"); 11138 String subStr1 = fullCodePath.substring(0, eidx); 11139 int sidx = subStr1.lastIndexOf("/"); 11140 cid = subStr1.substring(sidx+1, eidx); 11141 setMountPath(subStr1); 11142 } 11143 11144 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 11145 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 11146 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11147 instructionSets, null); 11148 this.cid = cid; 11149 setMountPath(PackageHelper.getSdDir(cid)); 11150 } 11151 11152 void createCopyFile() { 11153 cid = mInstallerService.allocateExternalStageCidLegacy(); 11154 } 11155 11156 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11157 if (origin.staged) { 11158 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 11159 cid = origin.cid; 11160 setMountPath(PackageHelper.getSdDir(cid)); 11161 return PackageManager.INSTALL_SUCCEEDED; 11162 } 11163 11164 if (temp) { 11165 createCopyFile(); 11166 } else { 11167 /* 11168 * Pre-emptively destroy the container since it's destroyed if 11169 * copying fails due to it existing anyway. 11170 */ 11171 PackageHelper.destroySdDir(cid); 11172 } 11173 11174 final String newMountPath = imcs.copyPackageToContainer( 11175 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 11176 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 11177 11178 if (newMountPath != null) { 11179 setMountPath(newMountPath); 11180 return PackageManager.INSTALL_SUCCEEDED; 11181 } else { 11182 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11183 } 11184 } 11185 11186 @Override 11187 String getCodePath() { 11188 return packagePath; 11189 } 11190 11191 @Override 11192 String getResourcePath() { 11193 return resourcePath; 11194 } 11195 11196 int doPreInstall(int status) { 11197 if (status != PackageManager.INSTALL_SUCCEEDED) { 11198 // Destroy container 11199 PackageHelper.destroySdDir(cid); 11200 } else { 11201 boolean mounted = PackageHelper.isContainerMounted(cid); 11202 if (!mounted) { 11203 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 11204 Process.SYSTEM_UID); 11205 if (newMountPath != null) { 11206 setMountPath(newMountPath); 11207 } else { 11208 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11209 } 11210 } 11211 } 11212 return status; 11213 } 11214 11215 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11216 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 11217 String newMountPath = null; 11218 if (PackageHelper.isContainerMounted(cid)) { 11219 // Unmount the container 11220 if (!PackageHelper.unMountSdDir(cid)) { 11221 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 11222 return false; 11223 } 11224 } 11225 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11226 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 11227 " which might be stale. Will try to clean up."); 11228 // Clean up the stale container and proceed to recreate. 11229 if (!PackageHelper.destroySdDir(newCacheId)) { 11230 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 11231 return false; 11232 } 11233 // Successfully cleaned up stale container. Try to rename again. 11234 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11235 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 11236 + " inspite of cleaning it up."); 11237 return false; 11238 } 11239 } 11240 if (!PackageHelper.isContainerMounted(newCacheId)) { 11241 Slog.w(TAG, "Mounting container " + newCacheId); 11242 newMountPath = PackageHelper.mountSdDir(newCacheId, 11243 getEncryptKey(), Process.SYSTEM_UID); 11244 } else { 11245 newMountPath = PackageHelper.getSdDir(newCacheId); 11246 } 11247 if (newMountPath == null) { 11248 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 11249 return false; 11250 } 11251 Log.i(TAG, "Succesfully renamed " + cid + 11252 " to " + newCacheId + 11253 " at new path: " + newMountPath); 11254 cid = newCacheId; 11255 11256 final File beforeCodeFile = new File(packagePath); 11257 setMountPath(newMountPath); 11258 final File afterCodeFile = new File(packagePath); 11259 11260 // Reflect the rename in scanned details 11261 pkg.codePath = afterCodeFile.getAbsolutePath(); 11262 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11263 pkg.baseCodePath); 11264 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11265 pkg.splitCodePaths); 11266 11267 // Reflect the rename in app info 11268 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11269 pkg.applicationInfo.setCodePath(pkg.codePath); 11270 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11271 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11272 pkg.applicationInfo.setResourcePath(pkg.codePath); 11273 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11274 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11275 11276 return true; 11277 } 11278 11279 private void setMountPath(String mountPath) { 11280 final File mountFile = new File(mountPath); 11281 11282 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 11283 if (monolithicFile.exists()) { 11284 packagePath = monolithicFile.getAbsolutePath(); 11285 if (isFwdLocked()) { 11286 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 11287 } else { 11288 resourcePath = packagePath; 11289 } 11290 } else { 11291 packagePath = mountFile.getAbsolutePath(); 11292 resourcePath = packagePath; 11293 } 11294 } 11295 11296 int doPostInstall(int status, int uid) { 11297 if (status != PackageManager.INSTALL_SUCCEEDED) { 11298 cleanUp(); 11299 } else { 11300 final int groupOwner; 11301 final String protectedFile; 11302 if (isFwdLocked()) { 11303 groupOwner = UserHandle.getSharedAppGid(uid); 11304 protectedFile = RES_FILE_NAME; 11305 } else { 11306 groupOwner = -1; 11307 protectedFile = null; 11308 } 11309 11310 if (uid < Process.FIRST_APPLICATION_UID 11311 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 11312 Slog.e(TAG, "Failed to finalize " + cid); 11313 PackageHelper.destroySdDir(cid); 11314 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11315 } 11316 11317 boolean mounted = PackageHelper.isContainerMounted(cid); 11318 if (!mounted) { 11319 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 11320 } 11321 } 11322 return status; 11323 } 11324 11325 private void cleanUp() { 11326 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 11327 11328 // Destroy secure container 11329 PackageHelper.destroySdDir(cid); 11330 } 11331 11332 private List<String> getAllCodePaths() { 11333 final File codeFile = new File(getCodePath()); 11334 if (codeFile != null && codeFile.exists()) { 11335 try { 11336 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11337 return pkg.getAllCodePaths(); 11338 } catch (PackageParserException e) { 11339 // Ignored; we tried our best 11340 } 11341 } 11342 return Collections.EMPTY_LIST; 11343 } 11344 11345 void cleanUpResourcesLI() { 11346 // Enumerate all code paths before deleting 11347 cleanUpResourcesLI(getAllCodePaths()); 11348 } 11349 11350 private void cleanUpResourcesLI(List<String> allCodePaths) { 11351 cleanUp(); 11352 removeDexFiles(allCodePaths, instructionSets); 11353 } 11354 11355 String getPackageName() { 11356 return getAsecPackageName(cid); 11357 } 11358 11359 boolean doPostDeleteLI(boolean delete) { 11360 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 11361 final List<String> allCodePaths = getAllCodePaths(); 11362 boolean mounted = PackageHelper.isContainerMounted(cid); 11363 if (mounted) { 11364 // Unmount first 11365 if (PackageHelper.unMountSdDir(cid)) { 11366 mounted = false; 11367 } 11368 } 11369 if (!mounted && delete) { 11370 cleanUpResourcesLI(allCodePaths); 11371 } 11372 return !mounted; 11373 } 11374 11375 @Override 11376 int doPreCopy() { 11377 if (isFwdLocked()) { 11378 if (!PackageHelper.fixSdPermissions(cid, 11379 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 11380 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11381 } 11382 } 11383 11384 return PackageManager.INSTALL_SUCCEEDED; 11385 } 11386 11387 @Override 11388 int doPostCopy(int uid) { 11389 if (isFwdLocked()) { 11390 if (uid < Process.FIRST_APPLICATION_UID 11391 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 11392 RES_FILE_NAME)) { 11393 Slog.e(TAG, "Failed to finalize " + cid); 11394 PackageHelper.destroySdDir(cid); 11395 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11396 } 11397 } 11398 11399 return PackageManager.INSTALL_SUCCEEDED; 11400 } 11401 } 11402 11403 /** 11404 * Logic to handle movement of existing installed applications. 11405 */ 11406 class MoveInstallArgs extends InstallArgs { 11407 private File codeFile; 11408 private File resourceFile; 11409 11410 /** New install */ 11411 MoveInstallArgs(InstallParams params) { 11412 super(params.origin, params.move, params.observer, params.installFlags, 11413 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11414 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 11415 } 11416 11417 int copyApk(IMediaContainerService imcs, boolean temp) { 11418 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 11419 + move.fromUuid + " to " + move.toUuid); 11420 synchronized (mInstaller) { 11421 if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName, 11422 move.dataAppName, move.appId, move.seinfo) != 0) { 11423 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11424 } 11425 } 11426 11427 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 11428 resourceFile = codeFile; 11429 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 11430 11431 return PackageManager.INSTALL_SUCCEEDED; 11432 } 11433 11434 int doPreInstall(int status) { 11435 if (status != PackageManager.INSTALL_SUCCEEDED) { 11436 cleanUp(move.toUuid); 11437 } 11438 return status; 11439 } 11440 11441 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11442 if (status != PackageManager.INSTALL_SUCCEEDED) { 11443 cleanUp(move.toUuid); 11444 return false; 11445 } 11446 11447 // Reflect the move in app info 11448 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11449 pkg.applicationInfo.setCodePath(pkg.codePath); 11450 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11451 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11452 pkg.applicationInfo.setResourcePath(pkg.codePath); 11453 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11454 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11455 11456 return true; 11457 } 11458 11459 int doPostInstall(int status, int uid) { 11460 if (status == PackageManager.INSTALL_SUCCEEDED) { 11461 cleanUp(move.fromUuid); 11462 } else { 11463 cleanUp(move.toUuid); 11464 } 11465 return status; 11466 } 11467 11468 @Override 11469 String getCodePath() { 11470 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11471 } 11472 11473 @Override 11474 String getResourcePath() { 11475 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11476 } 11477 11478 private boolean cleanUp(String volumeUuid) { 11479 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 11480 move.dataAppName); 11481 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 11482 synchronized (mInstallLock) { 11483 // Clean up both app data and code 11484 removeDataDirsLI(volumeUuid, move.packageName); 11485 if (codeFile.isDirectory()) { 11486 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11487 } else { 11488 codeFile.delete(); 11489 } 11490 } 11491 return true; 11492 } 11493 11494 void cleanUpResourcesLI() { 11495 throw new UnsupportedOperationException(); 11496 } 11497 11498 boolean doPostDeleteLI(boolean delete) { 11499 throw new UnsupportedOperationException(); 11500 } 11501 } 11502 11503 static String getAsecPackageName(String packageCid) { 11504 int idx = packageCid.lastIndexOf("-"); 11505 if (idx == -1) { 11506 return packageCid; 11507 } 11508 return packageCid.substring(0, idx); 11509 } 11510 11511 // Utility method used to create code paths based on package name and available index. 11512 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 11513 String idxStr = ""; 11514 int idx = 1; 11515 // Fall back to default value of idx=1 if prefix is not 11516 // part of oldCodePath 11517 if (oldCodePath != null) { 11518 String subStr = oldCodePath; 11519 // Drop the suffix right away 11520 if (suffix != null && subStr.endsWith(suffix)) { 11521 subStr = subStr.substring(0, subStr.length() - suffix.length()); 11522 } 11523 // If oldCodePath already contains prefix find out the 11524 // ending index to either increment or decrement. 11525 int sidx = subStr.lastIndexOf(prefix); 11526 if (sidx != -1) { 11527 subStr = subStr.substring(sidx + prefix.length()); 11528 if (subStr != null) { 11529 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 11530 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 11531 } 11532 try { 11533 idx = Integer.parseInt(subStr); 11534 if (idx <= 1) { 11535 idx++; 11536 } else { 11537 idx--; 11538 } 11539 } catch(NumberFormatException e) { 11540 } 11541 } 11542 } 11543 } 11544 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 11545 return prefix + idxStr; 11546 } 11547 11548 private File getNextCodePath(File targetDir, String packageName) { 11549 int suffix = 1; 11550 File result; 11551 do { 11552 result = new File(targetDir, packageName + "-" + suffix); 11553 suffix++; 11554 } while (result.exists()); 11555 return result; 11556 } 11557 11558 // Utility method that returns the relative package path with respect 11559 // to the installation directory. Like say for /data/data/com.test-1.apk 11560 // string com.test-1 is returned. 11561 static String deriveCodePathName(String codePath) { 11562 if (codePath == null) { 11563 return null; 11564 } 11565 final File codeFile = new File(codePath); 11566 final String name = codeFile.getName(); 11567 if (codeFile.isDirectory()) { 11568 return name; 11569 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 11570 final int lastDot = name.lastIndexOf('.'); 11571 return name.substring(0, lastDot); 11572 } else { 11573 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 11574 return null; 11575 } 11576 } 11577 11578 class PackageInstalledInfo { 11579 String name; 11580 int uid; 11581 // The set of users that originally had this package installed. 11582 int[] origUsers; 11583 // The set of users that now have this package installed. 11584 int[] newUsers; 11585 PackageParser.Package pkg; 11586 int returnCode; 11587 String returnMsg; 11588 PackageRemovedInfo removedInfo; 11589 11590 public void setError(int code, String msg) { 11591 returnCode = code; 11592 returnMsg = msg; 11593 Slog.w(TAG, msg); 11594 } 11595 11596 public void setError(String msg, PackageParserException e) { 11597 returnCode = e.error; 11598 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11599 Slog.w(TAG, msg, e); 11600 } 11601 11602 public void setError(String msg, PackageManagerException e) { 11603 returnCode = e.error; 11604 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11605 Slog.w(TAG, msg, e); 11606 } 11607 11608 // In some error cases we want to convey more info back to the observer 11609 String origPackage; 11610 String origPermission; 11611 } 11612 11613 /* 11614 * Install a non-existing package. 11615 */ 11616 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11617 UserHandle user, String installerPackageName, String volumeUuid, 11618 PackageInstalledInfo res) { 11619 // Remember this for later, in case we need to rollback this install 11620 String pkgName = pkg.packageName; 11621 11622 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 11623 final boolean dataDirExists = Environment 11624 .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists(); 11625 synchronized(mPackages) { 11626 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 11627 // A package with the same name is already installed, though 11628 // it has been renamed to an older name. The package we 11629 // are trying to install should be installed as an update to 11630 // the existing one, but that has not been requested, so bail. 11631 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11632 + " without first uninstalling package running as " 11633 + mSettings.mRenamedPackages.get(pkgName)); 11634 return; 11635 } 11636 if (mPackages.containsKey(pkgName)) { 11637 // Don't allow installation over an existing package with the same name. 11638 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11639 + " without first uninstalling."); 11640 return; 11641 } 11642 } 11643 11644 try { 11645 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 11646 System.currentTimeMillis(), user); 11647 11648 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 11649 // delete the partially installed application. the data directory will have to be 11650 // restored if it was already existing 11651 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11652 // remove package from internal structures. Note that we want deletePackageX to 11653 // delete the package data and cache directories that it created in 11654 // scanPackageLocked, unless those directories existed before we even tried to 11655 // install. 11656 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 11657 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 11658 res.removedInfo, true); 11659 } 11660 11661 } catch (PackageManagerException e) { 11662 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11663 } 11664 } 11665 11666 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 11667 // Can't rotate keys during boot or if sharedUser. 11668 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 11669 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 11670 return false; 11671 } 11672 // app is using upgradeKeySets; make sure all are valid 11673 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11674 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 11675 for (int i = 0; i < upgradeKeySets.length; i++) { 11676 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 11677 Slog.wtf(TAG, "Package " 11678 + (oldPs.name != null ? oldPs.name : "<null>") 11679 + " contains upgrade-key-set reference to unknown key-set: " 11680 + upgradeKeySets[i] 11681 + " reverting to signatures check."); 11682 return false; 11683 } 11684 } 11685 return true; 11686 } 11687 11688 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 11689 // Upgrade keysets are being used. Determine if new package has a superset of the 11690 // required keys. 11691 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 11692 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11693 for (int i = 0; i < upgradeKeySets.length; i++) { 11694 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 11695 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 11696 return true; 11697 } 11698 } 11699 return false; 11700 } 11701 11702 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11703 UserHandle user, String installerPackageName, String volumeUuid, 11704 PackageInstalledInfo res) { 11705 final PackageParser.Package oldPackage; 11706 final String pkgName = pkg.packageName; 11707 final int[] allUsers; 11708 final boolean[] perUserInstalled; 11709 final boolean weFroze; 11710 11711 // First find the old package info and check signatures 11712 synchronized(mPackages) { 11713 oldPackage = mPackages.get(pkgName); 11714 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 11715 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11716 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 11717 if(!checkUpgradeKeySetLP(ps, pkg)) { 11718 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11719 "New package not signed by keys specified by upgrade-keysets: " 11720 + pkgName); 11721 return; 11722 } 11723 } else { 11724 // default to original signature matching 11725 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 11726 != PackageManager.SIGNATURE_MATCH) { 11727 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11728 "New package has a different signature: " + pkgName); 11729 return; 11730 } 11731 } 11732 11733 // In case of rollback, remember per-user/profile install state 11734 allUsers = sUserManager.getUserIds(); 11735 perUserInstalled = new boolean[allUsers.length]; 11736 for (int i = 0; i < allUsers.length; i++) { 11737 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11738 } 11739 11740 // Mark the app as frozen to prevent launching during the upgrade 11741 // process, and then kill all running instances 11742 if (!ps.frozen) { 11743 ps.frozen = true; 11744 weFroze = true; 11745 } else { 11746 weFroze = false; 11747 } 11748 } 11749 11750 // Now that we're guarded by frozen state, kill app during upgrade 11751 killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg"); 11752 11753 try { 11754 boolean sysPkg = (isSystemApp(oldPackage)); 11755 if (sysPkg) { 11756 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11757 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11758 } else { 11759 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11760 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11761 } 11762 } finally { 11763 // Regardless of success or failure of upgrade steps above, always 11764 // unfreeze the package if we froze it 11765 if (weFroze) { 11766 unfreezePackage(pkgName); 11767 } 11768 } 11769 } 11770 11771 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 11772 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11773 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11774 String volumeUuid, PackageInstalledInfo res) { 11775 String pkgName = deletedPackage.packageName; 11776 boolean deletedPkg = true; 11777 boolean updatedSettings = false; 11778 11779 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 11780 + deletedPackage); 11781 long origUpdateTime; 11782 if (pkg.mExtras != null) { 11783 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 11784 } else { 11785 origUpdateTime = 0; 11786 } 11787 11788 // First delete the existing package while retaining the data directory 11789 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 11790 res.removedInfo, true)) { 11791 // If the existing package wasn't successfully deleted 11792 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 11793 deletedPkg = false; 11794 } else { 11795 // Successfully deleted the old package; proceed with replace. 11796 11797 // If deleted package lived in a container, give users a chance to 11798 // relinquish resources before killing. 11799 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 11800 if (DEBUG_INSTALL) { 11801 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 11802 } 11803 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 11804 final ArrayList<String> pkgList = new ArrayList<String>(1); 11805 pkgList.add(deletedPackage.applicationInfo.packageName); 11806 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 11807 } 11808 11809 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 11810 try { 11811 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 11812 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 11813 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11814 perUserInstalled, res, user); 11815 updatedSettings = true; 11816 } catch (PackageManagerException e) { 11817 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11818 } 11819 } 11820 11821 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11822 // remove package from internal structures. Note that we want deletePackageX to 11823 // delete the package data and cache directories that it created in 11824 // scanPackageLocked, unless those directories existed before we even tried to 11825 // install. 11826 if(updatedSettings) { 11827 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 11828 deletePackageLI( 11829 pkgName, null, true, allUsers, perUserInstalled, 11830 PackageManager.DELETE_KEEP_DATA, 11831 res.removedInfo, true); 11832 } 11833 // Since we failed to install the new package we need to restore the old 11834 // package that we deleted. 11835 if (deletedPkg) { 11836 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 11837 File restoreFile = new File(deletedPackage.codePath); 11838 // Parse old package 11839 boolean oldExternal = isExternal(deletedPackage); 11840 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 11841 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 11842 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11843 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 11844 try { 11845 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 11846 } catch (PackageManagerException e) { 11847 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 11848 + e.getMessage()); 11849 return; 11850 } 11851 // Restore of old package succeeded. Update permissions. 11852 // writer 11853 synchronized (mPackages) { 11854 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 11855 UPDATE_PERMISSIONS_ALL); 11856 // can downgrade to reader 11857 mSettings.writeLPr(); 11858 } 11859 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 11860 } 11861 } 11862 } 11863 11864 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 11865 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11866 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11867 String volumeUuid, PackageInstalledInfo res) { 11868 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 11869 + ", old=" + deletedPackage); 11870 boolean disabledSystem = false; 11871 boolean updatedSettings = false; 11872 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 11873 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 11874 != 0) { 11875 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11876 } 11877 String packageName = deletedPackage.packageName; 11878 if (packageName == null) { 11879 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11880 "Attempt to delete null packageName."); 11881 return; 11882 } 11883 PackageParser.Package oldPkg; 11884 PackageSetting oldPkgSetting; 11885 // reader 11886 synchronized (mPackages) { 11887 oldPkg = mPackages.get(packageName); 11888 oldPkgSetting = mSettings.mPackages.get(packageName); 11889 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 11890 (oldPkgSetting == null)) { 11891 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11892 "Couldn't find package:" + packageName + " information"); 11893 return; 11894 } 11895 } 11896 11897 res.removedInfo.uid = oldPkg.applicationInfo.uid; 11898 res.removedInfo.removedPackage = packageName; 11899 // Remove existing system package 11900 removePackageLI(oldPkgSetting, true); 11901 // writer 11902 synchronized (mPackages) { 11903 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 11904 if (!disabledSystem && deletedPackage != null) { 11905 // We didn't need to disable the .apk as a current system package, 11906 // which means we are replacing another update that is already 11907 // installed. We need to make sure to delete the older one's .apk. 11908 res.removedInfo.args = createInstallArgsForExisting(0, 11909 deletedPackage.applicationInfo.getCodePath(), 11910 deletedPackage.applicationInfo.getResourcePath(), 11911 getAppDexInstructionSets(deletedPackage.applicationInfo)); 11912 } else { 11913 res.removedInfo.args = null; 11914 } 11915 } 11916 11917 // Successfully disabled the old package. Now proceed with re-installation 11918 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 11919 11920 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11921 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 11922 11923 PackageParser.Package newPackage = null; 11924 try { 11925 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 11926 if (newPackage.mExtras != null) { 11927 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 11928 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 11929 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 11930 11931 // is the update attempting to change shared user? that isn't going to work... 11932 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 11933 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 11934 "Forbidding shared user change from " + oldPkgSetting.sharedUser 11935 + " to " + newPkgSetting.sharedUser); 11936 updatedSettings = true; 11937 } 11938 } 11939 11940 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11941 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11942 perUserInstalled, res, user); 11943 updatedSettings = true; 11944 } 11945 11946 } catch (PackageManagerException e) { 11947 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11948 } 11949 11950 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11951 // Re installation failed. Restore old information 11952 // Remove new pkg information 11953 if (newPackage != null) { 11954 removeInstalledPackageLI(newPackage, true); 11955 } 11956 // Add back the old system package 11957 try { 11958 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 11959 } catch (PackageManagerException e) { 11960 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 11961 } 11962 // Restore the old system information in Settings 11963 synchronized (mPackages) { 11964 if (disabledSystem) { 11965 mSettings.enableSystemPackageLPw(packageName); 11966 } 11967 if (updatedSettings) { 11968 mSettings.setInstallerPackageName(packageName, 11969 oldPkgSetting.installerPackageName); 11970 } 11971 mSettings.writeLPr(); 11972 } 11973 } 11974 } 11975 11976 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 11977 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 11978 UserHandle user) { 11979 String pkgName = newPackage.packageName; 11980 synchronized (mPackages) { 11981 //write settings. the installStatus will be incomplete at this stage. 11982 //note that the new package setting would have already been 11983 //added to mPackages. It hasn't been persisted yet. 11984 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 11985 mSettings.writeLPr(); 11986 } 11987 11988 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 11989 11990 synchronized (mPackages) { 11991 updatePermissionsLPw(newPackage.packageName, newPackage, 11992 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 11993 ? UPDATE_PERMISSIONS_ALL : 0)); 11994 // For system-bundled packages, we assume that installing an upgraded version 11995 // of the package implies that the user actually wants to run that new code, 11996 // so we enable the package. 11997 PackageSetting ps = mSettings.mPackages.get(pkgName); 11998 if (ps != null) { 11999 if (isSystemApp(newPackage)) { 12000 // NB: implicit assumption that system package upgrades apply to all users 12001 if (DEBUG_INSTALL) { 12002 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 12003 } 12004 if (res.origUsers != null) { 12005 for (int userHandle : res.origUsers) { 12006 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 12007 userHandle, installerPackageName); 12008 } 12009 } 12010 // Also convey the prior install/uninstall state 12011 if (allUsers != null && perUserInstalled != null) { 12012 for (int i = 0; i < allUsers.length; i++) { 12013 if (DEBUG_INSTALL) { 12014 Slog.d(TAG, " user " + allUsers[i] 12015 + " => " + perUserInstalled[i]); 12016 } 12017 ps.setInstalled(perUserInstalled[i], allUsers[i]); 12018 } 12019 // these install state changes will be persisted in the 12020 // upcoming call to mSettings.writeLPr(). 12021 } 12022 } 12023 // It's implied that when a user requests installation, they want the app to be 12024 // installed and enabled. 12025 int userId = user.getIdentifier(); 12026 if (userId != UserHandle.USER_ALL) { 12027 ps.setInstalled(true, userId); 12028 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 12029 } 12030 } 12031 res.name = pkgName; 12032 res.uid = newPackage.applicationInfo.uid; 12033 res.pkg = newPackage; 12034 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 12035 mSettings.setInstallerPackageName(pkgName, installerPackageName); 12036 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12037 //to update install status 12038 mSettings.writeLPr(); 12039 } 12040 } 12041 12042 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 12043 final int installFlags = args.installFlags; 12044 final String installerPackageName = args.installerPackageName; 12045 final String volumeUuid = args.volumeUuid; 12046 final File tmpPackageFile = new File(args.getCodePath()); 12047 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 12048 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 12049 || (args.volumeUuid != null)); 12050 boolean replace = false; 12051 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 12052 if (args.move != null) { 12053 // moving a complete application; perfom an initial scan on the new install location 12054 scanFlags |= SCAN_INITIAL; 12055 } 12056 // Result object to be returned 12057 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12058 12059 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 12060 // Retrieve PackageSettings and parse package 12061 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 12062 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 12063 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 12064 PackageParser pp = new PackageParser(); 12065 pp.setSeparateProcesses(mSeparateProcesses); 12066 pp.setDisplayMetrics(mMetrics); 12067 12068 final PackageParser.Package pkg; 12069 try { 12070 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 12071 } catch (PackageParserException e) { 12072 res.setError("Failed parse during installPackageLI", e); 12073 return; 12074 } 12075 12076 // Mark that we have an install time CPU ABI override. 12077 pkg.cpuAbiOverride = args.abiOverride; 12078 12079 String pkgName = res.name = pkg.packageName; 12080 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 12081 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 12082 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 12083 return; 12084 } 12085 } 12086 12087 try { 12088 pp.collectCertificates(pkg, parseFlags); 12089 pp.collectManifestDigest(pkg); 12090 } catch (PackageParserException e) { 12091 res.setError("Failed collect during installPackageLI", e); 12092 return; 12093 } 12094 12095 /* If the installer passed in a manifest digest, compare it now. */ 12096 if (args.manifestDigest != null) { 12097 if (DEBUG_INSTALL) { 12098 final String parsedManifest = pkg.manifestDigest == null ? "null" 12099 : pkg.manifestDigest.toString(); 12100 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 12101 + parsedManifest); 12102 } 12103 12104 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 12105 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 12106 return; 12107 } 12108 } else if (DEBUG_INSTALL) { 12109 final String parsedManifest = pkg.manifestDigest == null 12110 ? "null" : pkg.manifestDigest.toString(); 12111 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 12112 } 12113 12114 // Get rid of all references to package scan path via parser. 12115 pp = null; 12116 String oldCodePath = null; 12117 boolean systemApp = false; 12118 synchronized (mPackages) { 12119 // Check if installing already existing package 12120 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12121 String oldName = mSettings.mRenamedPackages.get(pkgName); 12122 if (pkg.mOriginalPackages != null 12123 && pkg.mOriginalPackages.contains(oldName) 12124 && mPackages.containsKey(oldName)) { 12125 // This package is derived from an original package, 12126 // and this device has been updating from that original 12127 // name. We must continue using the original name, so 12128 // rename the new package here. 12129 pkg.setPackageName(oldName); 12130 pkgName = pkg.packageName; 12131 replace = true; 12132 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 12133 + oldName + " pkgName=" + pkgName); 12134 } else if (mPackages.containsKey(pkgName)) { 12135 // This package, under its official name, already exists 12136 // on the device; we should replace it. 12137 replace = true; 12138 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 12139 } 12140 12141 // Prevent apps opting out from runtime permissions 12142 if (replace) { 12143 PackageParser.Package oldPackage = mPackages.get(pkgName); 12144 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 12145 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 12146 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 12147 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 12148 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 12149 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 12150 + " doesn't support runtime permissions but the old" 12151 + " target SDK " + oldTargetSdk + " does."); 12152 return; 12153 } 12154 } 12155 } 12156 12157 PackageSetting ps = mSettings.mPackages.get(pkgName); 12158 if (ps != null) { 12159 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 12160 12161 // Quick sanity check that we're signed correctly if updating; 12162 // we'll check this again later when scanning, but we want to 12163 // bail early here before tripping over redefined permissions. 12164 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12165 if (!checkUpgradeKeySetLP(ps, pkg)) { 12166 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 12167 + pkg.packageName + " upgrade keys do not match the " 12168 + "previously installed version"); 12169 return; 12170 } 12171 } else { 12172 try { 12173 verifySignaturesLP(ps, pkg); 12174 } catch (PackageManagerException e) { 12175 res.setError(e.error, e.getMessage()); 12176 return; 12177 } 12178 } 12179 12180 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 12181 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 12182 systemApp = (ps.pkg.applicationInfo.flags & 12183 ApplicationInfo.FLAG_SYSTEM) != 0; 12184 } 12185 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12186 } 12187 12188 // Check whether the newly-scanned package wants to define an already-defined perm 12189 int N = pkg.permissions.size(); 12190 for (int i = N-1; i >= 0; i--) { 12191 PackageParser.Permission perm = pkg.permissions.get(i); 12192 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 12193 if (bp != null) { 12194 // If the defining package is signed with our cert, it's okay. This 12195 // also includes the "updating the same package" case, of course. 12196 // "updating same package" could also involve key-rotation. 12197 final boolean sigsOk; 12198 if (bp.sourcePackage.equals(pkg.packageName) 12199 && (bp.packageSetting instanceof PackageSetting) 12200 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 12201 scanFlags))) { 12202 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 12203 } else { 12204 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 12205 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 12206 } 12207 if (!sigsOk) { 12208 // If the owning package is the system itself, we log but allow 12209 // install to proceed; we fail the install on all other permission 12210 // redefinitions. 12211 if (!bp.sourcePackage.equals("android")) { 12212 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 12213 + pkg.packageName + " attempting to redeclare permission " 12214 + perm.info.name + " already owned by " + bp.sourcePackage); 12215 res.origPermission = perm.info.name; 12216 res.origPackage = bp.sourcePackage; 12217 return; 12218 } else { 12219 Slog.w(TAG, "Package " + pkg.packageName 12220 + " attempting to redeclare system permission " 12221 + perm.info.name + "; ignoring new declaration"); 12222 pkg.permissions.remove(i); 12223 } 12224 } 12225 } 12226 } 12227 12228 } 12229 12230 if (systemApp && onExternal) { 12231 // Disable updates to system apps on sdcard 12232 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 12233 "Cannot install updates to system apps on sdcard"); 12234 return; 12235 } 12236 12237 if (args.move != null) { 12238 // We did an in-place move, so dex is ready to roll 12239 scanFlags |= SCAN_NO_DEX; 12240 scanFlags |= SCAN_MOVE; 12241 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 12242 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 12243 scanFlags |= SCAN_NO_DEX; 12244 12245 try { 12246 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 12247 true /* extract libs */); 12248 } catch (PackageManagerException pme) { 12249 Slog.e(TAG, "Error deriving application ABI", pme); 12250 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 12251 return; 12252 } 12253 12254 // Run dexopt before old package gets removed, to minimize time when app is unavailable 12255 int result = mPackageDexOptimizer 12256 .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */, 12257 false /* defer */, false /* inclDependencies */); 12258 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 12259 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 12260 return; 12261 } 12262 } 12263 12264 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 12265 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 12266 return; 12267 } 12268 12269 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 12270 12271 if (replace) { 12272 replacePackageLI(pkg, parseFlags, scanFlags, args.user, 12273 installerPackageName, volumeUuid, res); 12274 } else { 12275 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 12276 args.user, installerPackageName, volumeUuid, res); 12277 } 12278 synchronized (mPackages) { 12279 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12280 if (ps != null) { 12281 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12282 } 12283 } 12284 } 12285 12286 private void startIntentFilterVerifications(int userId, boolean replacing, 12287 PackageParser.Package pkg) { 12288 if (mIntentFilterVerifierComponent == null) { 12289 Slog.w(TAG, "No IntentFilter verification will not be done as " 12290 + "there is no IntentFilterVerifier available!"); 12291 return; 12292 } 12293 12294 final int verifierUid = getPackageUid( 12295 mIntentFilterVerifierComponent.getPackageName(), 12296 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 12297 12298 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 12299 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 12300 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 12301 mHandler.sendMessage(msg); 12302 } 12303 12304 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 12305 PackageParser.Package pkg) { 12306 int size = pkg.activities.size(); 12307 if (size == 0) { 12308 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12309 "No activity, so no need to verify any IntentFilter!"); 12310 return; 12311 } 12312 12313 final boolean hasDomainURLs = hasDomainURLs(pkg); 12314 if (!hasDomainURLs) { 12315 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12316 "No domain URLs, so no need to verify any IntentFilter!"); 12317 return; 12318 } 12319 12320 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 12321 + " if any IntentFilter from the " + size 12322 + " Activities needs verification ..."); 12323 12324 int count = 0; 12325 final String packageName = pkg.packageName; 12326 12327 synchronized (mPackages) { 12328 // If this is a new install and we see that we've already run verification for this 12329 // package, we have nothing to do: it means the state was restored from backup. 12330 if (!replacing) { 12331 IntentFilterVerificationInfo ivi = 12332 mSettings.getIntentFilterVerificationLPr(packageName); 12333 if (ivi != null) { 12334 if (DEBUG_DOMAIN_VERIFICATION) { 12335 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 12336 + ivi.getStatusString()); 12337 } 12338 return; 12339 } 12340 } 12341 12342 // If any filters need to be verified, then all need to be. 12343 boolean needToVerify = false; 12344 for (PackageParser.Activity a : pkg.activities) { 12345 for (ActivityIntentInfo filter : a.intents) { 12346 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 12347 if (DEBUG_DOMAIN_VERIFICATION) { 12348 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 12349 } 12350 needToVerify = true; 12351 break; 12352 } 12353 } 12354 } 12355 12356 if (needToVerify) { 12357 final int verificationId = mIntentFilterVerificationToken++; 12358 for (PackageParser.Activity a : pkg.activities) { 12359 for (ActivityIntentInfo filter : a.intents) { 12360 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 12361 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12362 "Verification needed for IntentFilter:" + filter.toString()); 12363 mIntentFilterVerifier.addOneIntentFilterVerification( 12364 verifierUid, userId, verificationId, filter, packageName); 12365 count++; 12366 } 12367 } 12368 } 12369 } 12370 } 12371 12372 if (count > 0) { 12373 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 12374 + " IntentFilter verification" + (count > 1 ? "s" : "") 12375 + " for userId:" + userId); 12376 mIntentFilterVerifier.startVerifications(userId); 12377 } else { 12378 if (DEBUG_DOMAIN_VERIFICATION) { 12379 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 12380 } 12381 } 12382 } 12383 12384 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 12385 final ComponentName cn = filter.activity.getComponentName(); 12386 final String packageName = cn.getPackageName(); 12387 12388 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 12389 packageName); 12390 if (ivi == null) { 12391 return true; 12392 } 12393 int status = ivi.getStatus(); 12394 switch (status) { 12395 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 12396 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 12397 return true; 12398 12399 default: 12400 // Nothing to do 12401 return false; 12402 } 12403 } 12404 12405 private static boolean isMultiArch(PackageSetting ps) { 12406 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12407 } 12408 12409 private static boolean isMultiArch(ApplicationInfo info) { 12410 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12411 } 12412 12413 private static boolean isExternal(PackageParser.Package pkg) { 12414 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12415 } 12416 12417 private static boolean isExternal(PackageSetting ps) { 12418 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12419 } 12420 12421 private static boolean isExternal(ApplicationInfo info) { 12422 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12423 } 12424 12425 private static boolean isSystemApp(PackageParser.Package pkg) { 12426 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 12427 } 12428 12429 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 12430 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 12431 } 12432 12433 private static boolean hasDomainURLs(PackageParser.Package pkg) { 12434 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 12435 } 12436 12437 private static boolean isSystemApp(PackageSetting ps) { 12438 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 12439 } 12440 12441 private static boolean isUpdatedSystemApp(PackageSetting ps) { 12442 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 12443 } 12444 12445 private int packageFlagsToInstallFlags(PackageSetting ps) { 12446 int installFlags = 0; 12447 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 12448 // This existing package was an external ASEC install when we have 12449 // the external flag without a UUID 12450 installFlags |= PackageManager.INSTALL_EXTERNAL; 12451 } 12452 if (ps.isForwardLocked()) { 12453 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12454 } 12455 return installFlags; 12456 } 12457 12458 private void deleteTempPackageFiles() { 12459 final FilenameFilter filter = new FilenameFilter() { 12460 public boolean accept(File dir, String name) { 12461 return name.startsWith("vmdl") && name.endsWith(".tmp"); 12462 } 12463 }; 12464 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 12465 file.delete(); 12466 } 12467 } 12468 12469 @Override 12470 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 12471 int flags) { 12472 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 12473 flags); 12474 } 12475 12476 @Override 12477 public void deletePackage(final String packageName, 12478 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 12479 mContext.enforceCallingOrSelfPermission( 12480 android.Manifest.permission.DELETE_PACKAGES, null); 12481 Preconditions.checkNotNull(packageName); 12482 Preconditions.checkNotNull(observer); 12483 final int uid = Binder.getCallingUid(); 12484 if (UserHandle.getUserId(uid) != userId) { 12485 mContext.enforceCallingPermission( 12486 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 12487 "deletePackage for user " + userId); 12488 } 12489 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 12490 try { 12491 observer.onPackageDeleted(packageName, 12492 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 12493 } catch (RemoteException re) { 12494 } 12495 return; 12496 } 12497 12498 boolean uninstallBlocked = false; 12499 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 12500 int[] users = sUserManager.getUserIds(); 12501 for (int i = 0; i < users.length; ++i) { 12502 if (getBlockUninstallForUser(packageName, users[i])) { 12503 uninstallBlocked = true; 12504 break; 12505 } 12506 } 12507 } else { 12508 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 12509 } 12510 if (uninstallBlocked) { 12511 try { 12512 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 12513 null); 12514 } catch (RemoteException re) { 12515 } 12516 return; 12517 } 12518 12519 if (DEBUG_REMOVE) { 12520 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 12521 } 12522 // Queue up an async operation since the package deletion may take a little while. 12523 mHandler.post(new Runnable() { 12524 public void run() { 12525 mHandler.removeCallbacks(this); 12526 final int returnCode = deletePackageX(packageName, userId, flags); 12527 if (observer != null) { 12528 try { 12529 observer.onPackageDeleted(packageName, returnCode, null); 12530 } catch (RemoteException e) { 12531 Log.i(TAG, "Observer no longer exists."); 12532 } //end catch 12533 } //end if 12534 } //end run 12535 }); 12536 } 12537 12538 private boolean isPackageDeviceAdmin(String packageName, int userId) { 12539 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 12540 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 12541 try { 12542 if (dpm != null) { 12543 if (dpm.isDeviceOwner(packageName)) { 12544 return true; 12545 } 12546 int[] users; 12547 if (userId == UserHandle.USER_ALL) { 12548 users = sUserManager.getUserIds(); 12549 } else { 12550 users = new int[]{userId}; 12551 } 12552 for (int i = 0; i < users.length; ++i) { 12553 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 12554 return true; 12555 } 12556 } 12557 } 12558 } catch (RemoteException e) { 12559 } 12560 return false; 12561 } 12562 12563 /** 12564 * This method is an internal method that could be get invoked either 12565 * to delete an installed package or to clean up a failed installation. 12566 * After deleting an installed package, a broadcast is sent to notify any 12567 * listeners that the package has been installed. For cleaning up a failed 12568 * installation, the broadcast is not necessary since the package's 12569 * installation wouldn't have sent the initial broadcast either 12570 * The key steps in deleting a package are 12571 * deleting the package information in internal structures like mPackages, 12572 * deleting the packages base directories through installd 12573 * updating mSettings to reflect current status 12574 * persisting settings for later use 12575 * sending a broadcast if necessary 12576 */ 12577 private int deletePackageX(String packageName, int userId, int flags) { 12578 final PackageRemovedInfo info = new PackageRemovedInfo(); 12579 final boolean res; 12580 12581 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 12582 ? UserHandle.ALL : new UserHandle(userId); 12583 12584 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 12585 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 12586 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 12587 } 12588 12589 boolean removedForAllUsers = false; 12590 boolean systemUpdate = false; 12591 12592 // for the uninstall-updates case and restricted profiles, remember the per- 12593 // userhandle installed state 12594 int[] allUsers; 12595 boolean[] perUserInstalled; 12596 synchronized (mPackages) { 12597 PackageSetting ps = mSettings.mPackages.get(packageName); 12598 allUsers = sUserManager.getUserIds(); 12599 perUserInstalled = new boolean[allUsers.length]; 12600 for (int i = 0; i < allUsers.length; i++) { 12601 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12602 } 12603 } 12604 12605 synchronized (mInstallLock) { 12606 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 12607 res = deletePackageLI(packageName, removeForUser, 12608 true, allUsers, perUserInstalled, 12609 flags | REMOVE_CHATTY, info, true); 12610 systemUpdate = info.isRemovedPackageSystemUpdate; 12611 if (res && !systemUpdate && mPackages.get(packageName) == null) { 12612 removedForAllUsers = true; 12613 } 12614 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 12615 + " removedForAllUsers=" + removedForAllUsers); 12616 } 12617 12618 if (res) { 12619 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 12620 12621 // If the removed package was a system update, the old system package 12622 // was re-enabled; we need to broadcast this information 12623 if (systemUpdate) { 12624 Bundle extras = new Bundle(1); 12625 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 12626 ? info.removedAppId : info.uid); 12627 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12628 12629 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 12630 extras, null, null, null); 12631 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 12632 extras, null, null, null); 12633 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 12634 null, packageName, null, null); 12635 } 12636 } 12637 // Force a gc here. 12638 Runtime.getRuntime().gc(); 12639 // Delete the resources here after sending the broadcast to let 12640 // other processes clean up before deleting resources. 12641 if (info.args != null) { 12642 synchronized (mInstallLock) { 12643 info.args.doPostDeleteLI(true); 12644 } 12645 } 12646 12647 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 12648 } 12649 12650 class PackageRemovedInfo { 12651 String removedPackage; 12652 int uid = -1; 12653 int removedAppId = -1; 12654 int[] removedUsers = null; 12655 boolean isRemovedPackageSystemUpdate = false; 12656 // Clean up resources deleted packages. 12657 InstallArgs args = null; 12658 12659 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 12660 Bundle extras = new Bundle(1); 12661 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 12662 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 12663 if (replacing) { 12664 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12665 } 12666 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 12667 if (removedPackage != null) { 12668 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 12669 extras, null, null, removedUsers); 12670 if (fullRemove && !replacing) { 12671 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 12672 extras, null, null, removedUsers); 12673 } 12674 } 12675 if (removedAppId >= 0) { 12676 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 12677 removedUsers); 12678 } 12679 } 12680 } 12681 12682 /* 12683 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 12684 * flag is not set, the data directory is removed as well. 12685 * make sure this flag is set for partially installed apps. If not its meaningless to 12686 * delete a partially installed application. 12687 */ 12688 private void removePackageDataLI(PackageSetting ps, 12689 int[] allUserHandles, boolean[] perUserInstalled, 12690 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 12691 String packageName = ps.name; 12692 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 12693 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 12694 // Retrieve object to delete permissions for shared user later on 12695 final PackageSetting deletedPs; 12696 // reader 12697 synchronized (mPackages) { 12698 deletedPs = mSettings.mPackages.get(packageName); 12699 if (outInfo != null) { 12700 outInfo.removedPackage = packageName; 12701 outInfo.removedUsers = deletedPs != null 12702 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 12703 : null; 12704 } 12705 } 12706 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12707 removeDataDirsLI(ps.volumeUuid, packageName); 12708 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 12709 } 12710 // writer 12711 synchronized (mPackages) { 12712 if (deletedPs != null) { 12713 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12714 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 12715 clearDefaultBrowserIfNeeded(packageName); 12716 if (outInfo != null) { 12717 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 12718 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 12719 } 12720 updatePermissionsLPw(deletedPs.name, null, 0); 12721 if (deletedPs.sharedUser != null) { 12722 // Remove permissions associated with package. Since runtime 12723 // permissions are per user we have to kill the removed package 12724 // or packages running under the shared user of the removed 12725 // package if revoking the permissions requested only by the removed 12726 // package is successful and this causes a change in gids. 12727 for (int userId : UserManagerService.getInstance().getUserIds()) { 12728 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 12729 userId); 12730 if (userIdToKill == UserHandle.USER_ALL 12731 || userIdToKill >= UserHandle.USER_OWNER) { 12732 // If gids changed for this user, kill all affected packages. 12733 mHandler.post(new Runnable() { 12734 @Override 12735 public void run() { 12736 // This has to happen with no lock held. 12737 killSettingPackagesForUser(deletedPs, userIdToKill, 12738 KILL_APP_REASON_GIDS_CHANGED); 12739 } 12740 }); 12741 break; 12742 } 12743 } 12744 } 12745 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 12746 } 12747 // make sure to preserve per-user disabled state if this removal was just 12748 // a downgrade of a system app to the factory package 12749 if (allUserHandles != null && perUserInstalled != null) { 12750 if (DEBUG_REMOVE) { 12751 Slog.d(TAG, "Propagating install state across downgrade"); 12752 } 12753 for (int i = 0; i < allUserHandles.length; i++) { 12754 if (DEBUG_REMOVE) { 12755 Slog.d(TAG, " user " + allUserHandles[i] 12756 + " => " + perUserInstalled[i]); 12757 } 12758 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12759 } 12760 } 12761 } 12762 // can downgrade to reader 12763 if (writeSettings) { 12764 // Save settings now 12765 mSettings.writeLPr(); 12766 } 12767 } 12768 if (outInfo != null) { 12769 // A user ID was deleted here. Go through all users and remove it 12770 // from KeyStore. 12771 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 12772 } 12773 } 12774 12775 static boolean locationIsPrivileged(File path) { 12776 try { 12777 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 12778 .getCanonicalPath(); 12779 return path.getCanonicalPath().startsWith(privilegedAppDir); 12780 } catch (IOException e) { 12781 Slog.e(TAG, "Unable to access code path " + path); 12782 } 12783 return false; 12784 } 12785 12786 /* 12787 * Tries to delete system package. 12788 */ 12789 private boolean deleteSystemPackageLI(PackageSetting newPs, 12790 int[] allUserHandles, boolean[] perUserInstalled, 12791 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 12792 final boolean applyUserRestrictions 12793 = (allUserHandles != null) && (perUserInstalled != null); 12794 PackageSetting disabledPs = null; 12795 // Confirm if the system package has been updated 12796 // An updated system app can be deleted. This will also have to restore 12797 // the system pkg from system partition 12798 // reader 12799 synchronized (mPackages) { 12800 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 12801 } 12802 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 12803 + " disabledPs=" + disabledPs); 12804 if (disabledPs == null) { 12805 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 12806 return false; 12807 } else if (DEBUG_REMOVE) { 12808 Slog.d(TAG, "Deleting system pkg from data partition"); 12809 } 12810 if (DEBUG_REMOVE) { 12811 if (applyUserRestrictions) { 12812 Slog.d(TAG, "Remembering install states:"); 12813 for (int i = 0; i < allUserHandles.length; i++) { 12814 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 12815 } 12816 } 12817 } 12818 // Delete the updated package 12819 outInfo.isRemovedPackageSystemUpdate = true; 12820 if (disabledPs.versionCode < newPs.versionCode) { 12821 // Delete data for downgrades 12822 flags &= ~PackageManager.DELETE_KEEP_DATA; 12823 } else { 12824 // Preserve data by setting flag 12825 flags |= PackageManager.DELETE_KEEP_DATA; 12826 } 12827 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 12828 allUserHandles, perUserInstalled, outInfo, writeSettings); 12829 if (!ret) { 12830 return false; 12831 } 12832 // writer 12833 synchronized (mPackages) { 12834 // Reinstate the old system package 12835 mSettings.enableSystemPackageLPw(newPs.name); 12836 // Remove any native libraries from the upgraded package. 12837 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 12838 } 12839 // Install the system package 12840 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 12841 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 12842 if (locationIsPrivileged(disabledPs.codePath)) { 12843 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12844 } 12845 12846 final PackageParser.Package newPkg; 12847 try { 12848 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 12849 } catch (PackageManagerException e) { 12850 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 12851 return false; 12852 } 12853 12854 // writer 12855 synchronized (mPackages) { 12856 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 12857 12858 // Propagate the permissions state as we do want to drop on the floor 12859 // runtime permissions. The update permissions method below will take 12860 // care of removing obsolete permissions and grant install permissions. 12861 ps.getPermissionsState().copyFrom(disabledPs.getPermissionsState()); 12862 updatePermissionsLPw(newPkg.packageName, newPkg, 12863 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 12864 12865 if (applyUserRestrictions) { 12866 if (DEBUG_REMOVE) { 12867 Slog.d(TAG, "Propagating install state across reinstall"); 12868 } 12869 for (int i = 0; i < allUserHandles.length; i++) { 12870 if (DEBUG_REMOVE) { 12871 Slog.d(TAG, " user " + allUserHandles[i] 12872 + " => " + perUserInstalled[i]); 12873 } 12874 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12875 } 12876 // Regardless of writeSettings we need to ensure that this restriction 12877 // state propagation is persisted 12878 mSettings.writeAllUsersPackageRestrictionsLPr(); 12879 } 12880 // can downgrade to reader here 12881 if (writeSettings) { 12882 mSettings.writeLPr(); 12883 } 12884 } 12885 return true; 12886 } 12887 12888 private boolean deleteInstalledPackageLI(PackageSetting ps, 12889 boolean deleteCodeAndResources, int flags, 12890 int[] allUserHandles, boolean[] perUserInstalled, 12891 PackageRemovedInfo outInfo, boolean writeSettings) { 12892 if (outInfo != null) { 12893 outInfo.uid = ps.appId; 12894 } 12895 12896 // Delete package data from internal structures and also remove data if flag is set 12897 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 12898 12899 // Delete application code and resources 12900 if (deleteCodeAndResources && (outInfo != null)) { 12901 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 12902 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 12903 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 12904 } 12905 return true; 12906 } 12907 12908 @Override 12909 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 12910 int userId) { 12911 mContext.enforceCallingOrSelfPermission( 12912 android.Manifest.permission.DELETE_PACKAGES, null); 12913 synchronized (mPackages) { 12914 PackageSetting ps = mSettings.mPackages.get(packageName); 12915 if (ps == null) { 12916 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 12917 return false; 12918 } 12919 if (!ps.getInstalled(userId)) { 12920 // Can't block uninstall for an app that is not installed or enabled. 12921 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 12922 return false; 12923 } 12924 ps.setBlockUninstall(blockUninstall, userId); 12925 mSettings.writePackageRestrictionsLPr(userId); 12926 } 12927 return true; 12928 } 12929 12930 @Override 12931 public boolean getBlockUninstallForUser(String packageName, int userId) { 12932 synchronized (mPackages) { 12933 PackageSetting ps = mSettings.mPackages.get(packageName); 12934 if (ps == null) { 12935 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 12936 return false; 12937 } 12938 return ps.getBlockUninstall(userId); 12939 } 12940 } 12941 12942 /* 12943 * This method handles package deletion in general 12944 */ 12945 private boolean deletePackageLI(String packageName, UserHandle user, 12946 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 12947 int flags, PackageRemovedInfo outInfo, 12948 boolean writeSettings) { 12949 if (packageName == null) { 12950 Slog.w(TAG, "Attempt to delete null packageName."); 12951 return false; 12952 } 12953 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 12954 PackageSetting ps; 12955 boolean dataOnly = false; 12956 int removeUser = -1; 12957 int appId = -1; 12958 synchronized (mPackages) { 12959 ps = mSettings.mPackages.get(packageName); 12960 if (ps == null) { 12961 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12962 return false; 12963 } 12964 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 12965 && user.getIdentifier() != UserHandle.USER_ALL) { 12966 // The caller is asking that the package only be deleted for a single 12967 // user. To do this, we just mark its uninstalled state and delete 12968 // its data. If this is a system app, we only allow this to happen if 12969 // they have set the special DELETE_SYSTEM_APP which requests different 12970 // semantics than normal for uninstalling system apps. 12971 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 12972 ps.setUserState(user.getIdentifier(), 12973 COMPONENT_ENABLED_STATE_DEFAULT, 12974 false, //installed 12975 true, //stopped 12976 true, //notLaunched 12977 false, //hidden 12978 null, null, null, 12979 false, // blockUninstall 12980 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED, 0); 12981 if (!isSystemApp(ps)) { 12982 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 12983 // Other user still have this package installed, so all 12984 // we need to do is clear this user's data and save that 12985 // it is uninstalled. 12986 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 12987 removeUser = user.getIdentifier(); 12988 appId = ps.appId; 12989 scheduleWritePackageRestrictionsLocked(removeUser); 12990 } else { 12991 // We need to set it back to 'installed' so the uninstall 12992 // broadcasts will be sent correctly. 12993 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 12994 ps.setInstalled(true, user.getIdentifier()); 12995 } 12996 } else { 12997 // This is a system app, so we assume that the 12998 // other users still have this package installed, so all 12999 // we need to do is clear this user's data and save that 13000 // it is uninstalled. 13001 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 13002 removeUser = user.getIdentifier(); 13003 appId = ps.appId; 13004 scheduleWritePackageRestrictionsLocked(removeUser); 13005 } 13006 } 13007 } 13008 13009 if (removeUser >= 0) { 13010 // From above, we determined that we are deleting this only 13011 // for a single user. Continue the work here. 13012 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 13013 if (outInfo != null) { 13014 outInfo.removedPackage = packageName; 13015 outInfo.removedAppId = appId; 13016 outInfo.removedUsers = new int[] {removeUser}; 13017 } 13018 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 13019 removeKeystoreDataIfNeeded(removeUser, appId); 13020 schedulePackageCleaning(packageName, removeUser, false); 13021 synchronized (mPackages) { 13022 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 13023 scheduleWritePackageRestrictionsLocked(removeUser); 13024 } 13025 resetUserChangesToRuntimePermissionsAndFlagsLocked(ps, removeUser); 13026 } 13027 return true; 13028 } 13029 13030 if (dataOnly) { 13031 // Delete application data first 13032 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 13033 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 13034 return true; 13035 } 13036 13037 boolean ret = false; 13038 if (isSystemApp(ps)) { 13039 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 13040 // When an updated system application is deleted we delete the existing resources as well and 13041 // fall back to existing code in system partition 13042 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 13043 flags, outInfo, writeSettings); 13044 } else { 13045 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 13046 // Kill application pre-emptively especially for apps on sd. 13047 killApplication(packageName, ps.appId, "uninstall pkg"); 13048 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 13049 allUserHandles, perUserInstalled, 13050 outInfo, writeSettings); 13051 } 13052 13053 return ret; 13054 } 13055 13056 private final class ClearStorageConnection implements ServiceConnection { 13057 IMediaContainerService mContainerService; 13058 13059 @Override 13060 public void onServiceConnected(ComponentName name, IBinder service) { 13061 synchronized (this) { 13062 mContainerService = IMediaContainerService.Stub.asInterface(service); 13063 notifyAll(); 13064 } 13065 } 13066 13067 @Override 13068 public void onServiceDisconnected(ComponentName name) { 13069 } 13070 } 13071 13072 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 13073 final boolean mounted; 13074 if (Environment.isExternalStorageEmulated()) { 13075 mounted = true; 13076 } else { 13077 final String status = Environment.getExternalStorageState(); 13078 13079 mounted = status.equals(Environment.MEDIA_MOUNTED) 13080 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 13081 } 13082 13083 if (!mounted) { 13084 return; 13085 } 13086 13087 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 13088 int[] users; 13089 if (userId == UserHandle.USER_ALL) { 13090 users = sUserManager.getUserIds(); 13091 } else { 13092 users = new int[] { userId }; 13093 } 13094 final ClearStorageConnection conn = new ClearStorageConnection(); 13095 if (mContext.bindServiceAsUser( 13096 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 13097 try { 13098 for (int curUser : users) { 13099 long timeout = SystemClock.uptimeMillis() + 5000; 13100 synchronized (conn) { 13101 long now = SystemClock.uptimeMillis(); 13102 while (conn.mContainerService == null && now < timeout) { 13103 try { 13104 conn.wait(timeout - now); 13105 } catch (InterruptedException e) { 13106 } 13107 } 13108 } 13109 if (conn.mContainerService == null) { 13110 return; 13111 } 13112 13113 final UserEnvironment userEnv = new UserEnvironment(curUser); 13114 clearDirectory(conn.mContainerService, 13115 userEnv.buildExternalStorageAppCacheDirs(packageName)); 13116 if (allData) { 13117 clearDirectory(conn.mContainerService, 13118 userEnv.buildExternalStorageAppDataDirs(packageName)); 13119 clearDirectory(conn.mContainerService, 13120 userEnv.buildExternalStorageAppMediaDirs(packageName)); 13121 } 13122 } 13123 } finally { 13124 mContext.unbindService(conn); 13125 } 13126 } 13127 } 13128 13129 @Override 13130 public void clearApplicationUserData(final String packageName, 13131 final IPackageDataObserver observer, final int userId) { 13132 mContext.enforceCallingOrSelfPermission( 13133 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 13134 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 13135 // Queue up an async operation since the package deletion may take a little while. 13136 mHandler.post(new Runnable() { 13137 public void run() { 13138 mHandler.removeCallbacks(this); 13139 final boolean succeeded; 13140 synchronized (mInstallLock) { 13141 succeeded = clearApplicationUserDataLI(packageName, userId); 13142 } 13143 clearExternalStorageDataSync(packageName, userId, true); 13144 if (succeeded) { 13145 // invoke DeviceStorageMonitor's update method to clear any notifications 13146 DeviceStorageMonitorInternal 13147 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13148 if (dsm != null) { 13149 dsm.checkMemory(); 13150 } 13151 } 13152 if(observer != null) { 13153 try { 13154 observer.onRemoveCompleted(packageName, succeeded); 13155 } catch (RemoteException e) { 13156 Log.i(TAG, "Observer no longer exists."); 13157 } 13158 } //end if observer 13159 } //end run 13160 }); 13161 } 13162 13163 private boolean clearApplicationUserDataLI(String packageName, int userId) { 13164 if (packageName == null) { 13165 Slog.w(TAG, "Attempt to delete null packageName."); 13166 return false; 13167 } 13168 13169 // Try finding details about the requested package 13170 PackageParser.Package pkg; 13171 synchronized (mPackages) { 13172 pkg = mPackages.get(packageName); 13173 if (pkg == null) { 13174 final PackageSetting ps = mSettings.mPackages.get(packageName); 13175 if (ps != null) { 13176 pkg = ps.pkg; 13177 } 13178 } 13179 13180 if (pkg == null) { 13181 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13182 return false; 13183 } 13184 13185 PackageSetting ps = (PackageSetting) pkg.mExtras; 13186 resetUserChangesToRuntimePermissionsAndFlagsLocked(ps, userId); 13187 } 13188 13189 // Always delete data directories for package, even if we found no other 13190 // record of app. This helps users recover from UID mismatches without 13191 // resorting to a full data wipe. 13192 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 13193 if (retCode < 0) { 13194 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 13195 return false; 13196 } 13197 13198 final int appId = pkg.applicationInfo.uid; 13199 removeKeystoreDataIfNeeded(userId, appId); 13200 13201 // Create a native library symlink only if we have native libraries 13202 // and if the native libraries are 32 bit libraries. We do not provide 13203 // this symlink for 64 bit libraries. 13204 if (pkg.applicationInfo.primaryCpuAbi != null && 13205 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 13206 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 13207 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 13208 nativeLibPath, userId) < 0) { 13209 Slog.w(TAG, "Failed linking native library dir"); 13210 return false; 13211 } 13212 } 13213 13214 return true; 13215 } 13216 13217 /** 13218 * Reverts user permission state changes (permissions and flags). 13219 * 13220 * @param ps The package for which to reset. 13221 * @param userId The device user for which to do a reset. 13222 */ 13223 private void resetUserChangesToRuntimePermissionsAndFlagsLocked( 13224 final PackageSetting ps, final int userId) { 13225 if (ps.pkg == null) { 13226 return; 13227 } 13228 13229 final int userSettableFlags = FLAG_PERMISSION_USER_SET 13230 | FLAG_PERMISSION_USER_FIXED 13231 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 13232 13233 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 13234 | FLAG_PERMISSION_POLICY_FIXED; 13235 13236 boolean writeInstallPermissions = false; 13237 boolean writeRuntimePermissions = false; 13238 13239 final int permissionCount = ps.pkg.requestedPermissions.size(); 13240 for (int i = 0; i < permissionCount; i++) { 13241 String permission = ps.pkg.requestedPermissions.get(i); 13242 13243 BasePermission bp = mSettings.mPermissions.get(permission); 13244 if (bp == null) { 13245 continue; 13246 } 13247 13248 // If shared user we just reset the state to which only this app contributed. 13249 if (ps.sharedUser != null) { 13250 boolean used = false; 13251 final int packageCount = ps.sharedUser.packages.size(); 13252 for (int j = 0; j < packageCount; j++) { 13253 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 13254 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 13255 && pkg.pkg.requestedPermissions.contains(permission)) { 13256 used = true; 13257 break; 13258 } 13259 } 13260 if (used) { 13261 continue; 13262 } 13263 } 13264 13265 PermissionsState permissionsState = ps.getPermissionsState(); 13266 13267 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 13268 13269 // Always clear the user settable flags. 13270 final boolean hasInstallState = permissionsState.getInstallPermissionState( 13271 bp.name) != null; 13272 if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) { 13273 if (hasInstallState) { 13274 writeInstallPermissions = true; 13275 } else { 13276 writeRuntimePermissions = true; 13277 } 13278 } 13279 13280 // Below is only runtime permission handling. 13281 if (!bp.isRuntime()) { 13282 continue; 13283 } 13284 13285 // Never clobber system or policy. 13286 if ((oldFlags & policyOrSystemFlags) != 0) { 13287 continue; 13288 } 13289 13290 // If this permission was granted by default, make sure it is. 13291 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 13292 if (permissionsState.grantRuntimePermission(bp, userId) 13293 != PERMISSION_OPERATION_FAILURE) { 13294 writeRuntimePermissions = true; 13295 } 13296 } else { 13297 // Otherwise, reset the permission. 13298 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 13299 switch (revokeResult) { 13300 case PERMISSION_OPERATION_SUCCESS: { 13301 writeRuntimePermissions = true; 13302 } break; 13303 13304 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 13305 writeRuntimePermissions = true; 13306 // If gids changed for this user, kill all affected packages. 13307 mHandler.post(new Runnable() { 13308 @Override 13309 public void run() { 13310 // This has to happen with no lock held. 13311 killSettingPackagesForUser(ps, userId, 13312 KILL_APP_REASON_GIDS_CHANGED); 13313 } 13314 }); 13315 } break; 13316 } 13317 } 13318 } 13319 13320 // Synchronously write as we are taking permissions away. 13321 if (writeRuntimePermissions) { 13322 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 13323 } 13324 13325 // Synchronously write as we are taking permissions away. 13326 if (writeInstallPermissions) { 13327 mSettings.writeLPr(); 13328 } 13329 } 13330 13331 /** 13332 * Remove entries from the keystore daemon. Will only remove it if the 13333 * {@code appId} is valid. 13334 */ 13335 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 13336 if (appId < 0) { 13337 return; 13338 } 13339 13340 final KeyStore keyStore = KeyStore.getInstance(); 13341 if (keyStore != null) { 13342 if (userId == UserHandle.USER_ALL) { 13343 for (final int individual : sUserManager.getUserIds()) { 13344 keyStore.clearUid(UserHandle.getUid(individual, appId)); 13345 } 13346 } else { 13347 keyStore.clearUid(UserHandle.getUid(userId, appId)); 13348 } 13349 } else { 13350 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 13351 } 13352 } 13353 13354 @Override 13355 public void deleteApplicationCacheFiles(final String packageName, 13356 final IPackageDataObserver observer) { 13357 mContext.enforceCallingOrSelfPermission( 13358 android.Manifest.permission.DELETE_CACHE_FILES, null); 13359 // Queue up an async operation since the package deletion may take a little while. 13360 final int userId = UserHandle.getCallingUserId(); 13361 mHandler.post(new Runnable() { 13362 public void run() { 13363 mHandler.removeCallbacks(this); 13364 final boolean succeded; 13365 synchronized (mInstallLock) { 13366 succeded = deleteApplicationCacheFilesLI(packageName, userId); 13367 } 13368 clearExternalStorageDataSync(packageName, userId, false); 13369 if (observer != null) { 13370 try { 13371 observer.onRemoveCompleted(packageName, succeded); 13372 } catch (RemoteException e) { 13373 Log.i(TAG, "Observer no longer exists."); 13374 } 13375 } //end if observer 13376 } //end run 13377 }); 13378 } 13379 13380 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 13381 if (packageName == null) { 13382 Slog.w(TAG, "Attempt to delete null packageName."); 13383 return false; 13384 } 13385 PackageParser.Package p; 13386 synchronized (mPackages) { 13387 p = mPackages.get(packageName); 13388 } 13389 if (p == null) { 13390 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13391 return false; 13392 } 13393 final ApplicationInfo applicationInfo = p.applicationInfo; 13394 if (applicationInfo == null) { 13395 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13396 return false; 13397 } 13398 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 13399 if (retCode < 0) { 13400 Slog.w(TAG, "Couldn't remove cache files for package: " 13401 + packageName + " u" + userId); 13402 return false; 13403 } 13404 return true; 13405 } 13406 13407 @Override 13408 public void getPackageSizeInfo(final String packageName, int userHandle, 13409 final IPackageStatsObserver observer) { 13410 mContext.enforceCallingOrSelfPermission( 13411 android.Manifest.permission.GET_PACKAGE_SIZE, null); 13412 if (packageName == null) { 13413 throw new IllegalArgumentException("Attempt to get size of null packageName"); 13414 } 13415 13416 PackageStats stats = new PackageStats(packageName, userHandle); 13417 13418 /* 13419 * Queue up an async operation since the package measurement may take a 13420 * little while. 13421 */ 13422 Message msg = mHandler.obtainMessage(INIT_COPY); 13423 msg.obj = new MeasureParams(stats, observer); 13424 mHandler.sendMessage(msg); 13425 } 13426 13427 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 13428 PackageStats pStats) { 13429 if (packageName == null) { 13430 Slog.w(TAG, "Attempt to get size of null packageName."); 13431 return false; 13432 } 13433 PackageParser.Package p; 13434 boolean dataOnly = false; 13435 String libDirRoot = null; 13436 String asecPath = null; 13437 PackageSetting ps = null; 13438 synchronized (mPackages) { 13439 p = mPackages.get(packageName); 13440 ps = mSettings.mPackages.get(packageName); 13441 if(p == null) { 13442 dataOnly = true; 13443 if((ps == null) || (ps.pkg == null)) { 13444 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13445 return false; 13446 } 13447 p = ps.pkg; 13448 } 13449 if (ps != null) { 13450 libDirRoot = ps.legacyNativeLibraryPathString; 13451 } 13452 if (p != null && (isExternal(p) || p.isForwardLocked())) { 13453 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 13454 if (secureContainerId != null) { 13455 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 13456 } 13457 } 13458 } 13459 String publicSrcDir = null; 13460 if(!dataOnly) { 13461 final ApplicationInfo applicationInfo = p.applicationInfo; 13462 if (applicationInfo == null) { 13463 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13464 return false; 13465 } 13466 if (p.isForwardLocked()) { 13467 publicSrcDir = applicationInfo.getBaseResourcePath(); 13468 } 13469 } 13470 // TODO: extend to measure size of split APKs 13471 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 13472 // not just the first level. 13473 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 13474 // just the primary. 13475 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 13476 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath, 13477 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 13478 if (res < 0) { 13479 return false; 13480 } 13481 13482 // Fix-up for forward-locked applications in ASEC containers. 13483 if (!isExternal(p)) { 13484 pStats.codeSize += pStats.externalCodeSize; 13485 pStats.externalCodeSize = 0L; 13486 } 13487 13488 return true; 13489 } 13490 13491 13492 @Override 13493 public void addPackageToPreferred(String packageName) { 13494 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 13495 } 13496 13497 @Override 13498 public void removePackageFromPreferred(String packageName) { 13499 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 13500 } 13501 13502 @Override 13503 public List<PackageInfo> getPreferredPackages(int flags) { 13504 return new ArrayList<PackageInfo>(); 13505 } 13506 13507 private int getUidTargetSdkVersionLockedLPr(int uid) { 13508 Object obj = mSettings.getUserIdLPr(uid); 13509 if (obj instanceof SharedUserSetting) { 13510 final SharedUserSetting sus = (SharedUserSetting) obj; 13511 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 13512 final Iterator<PackageSetting> it = sus.packages.iterator(); 13513 while (it.hasNext()) { 13514 final PackageSetting ps = it.next(); 13515 if (ps.pkg != null) { 13516 int v = ps.pkg.applicationInfo.targetSdkVersion; 13517 if (v < vers) vers = v; 13518 } 13519 } 13520 return vers; 13521 } else if (obj instanceof PackageSetting) { 13522 final PackageSetting ps = (PackageSetting) obj; 13523 if (ps.pkg != null) { 13524 return ps.pkg.applicationInfo.targetSdkVersion; 13525 } 13526 } 13527 return Build.VERSION_CODES.CUR_DEVELOPMENT; 13528 } 13529 13530 @Override 13531 public void addPreferredActivity(IntentFilter filter, int match, 13532 ComponentName[] set, ComponentName activity, int userId) { 13533 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13534 "Adding preferred"); 13535 } 13536 13537 private void addPreferredActivityInternal(IntentFilter filter, int match, 13538 ComponentName[] set, ComponentName activity, boolean always, int userId, 13539 String opname) { 13540 // writer 13541 int callingUid = Binder.getCallingUid(); 13542 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 13543 if (filter.countActions() == 0) { 13544 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13545 return; 13546 } 13547 synchronized (mPackages) { 13548 if (mContext.checkCallingOrSelfPermission( 13549 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13550 != PackageManager.PERMISSION_GRANTED) { 13551 if (getUidTargetSdkVersionLockedLPr(callingUid) 13552 < Build.VERSION_CODES.FROYO) { 13553 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 13554 + callingUid); 13555 return; 13556 } 13557 mContext.enforceCallingOrSelfPermission( 13558 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13559 } 13560 13561 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 13562 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 13563 + userId + ":"); 13564 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13565 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 13566 scheduleWritePackageRestrictionsLocked(userId); 13567 } 13568 } 13569 13570 @Override 13571 public void replacePreferredActivity(IntentFilter filter, int match, 13572 ComponentName[] set, ComponentName activity, int userId) { 13573 if (filter.countActions() != 1) { 13574 throw new IllegalArgumentException( 13575 "replacePreferredActivity expects filter to have only 1 action."); 13576 } 13577 if (filter.countDataAuthorities() != 0 13578 || filter.countDataPaths() != 0 13579 || filter.countDataSchemes() > 1 13580 || filter.countDataTypes() != 0) { 13581 throw new IllegalArgumentException( 13582 "replacePreferredActivity expects filter to have no data authorities, " + 13583 "paths, or types; and at most one scheme."); 13584 } 13585 13586 final int callingUid = Binder.getCallingUid(); 13587 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 13588 synchronized (mPackages) { 13589 if (mContext.checkCallingOrSelfPermission( 13590 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13591 != PackageManager.PERMISSION_GRANTED) { 13592 if (getUidTargetSdkVersionLockedLPr(callingUid) 13593 < Build.VERSION_CODES.FROYO) { 13594 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 13595 + Binder.getCallingUid()); 13596 return; 13597 } 13598 mContext.enforceCallingOrSelfPermission( 13599 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13600 } 13601 13602 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13603 if (pir != null) { 13604 // Get all of the existing entries that exactly match this filter. 13605 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 13606 if (existing != null && existing.size() == 1) { 13607 PreferredActivity cur = existing.get(0); 13608 if (DEBUG_PREFERRED) { 13609 Slog.i(TAG, "Checking replace of preferred:"); 13610 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13611 if (!cur.mPref.mAlways) { 13612 Slog.i(TAG, " -- CUR; not mAlways!"); 13613 } else { 13614 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 13615 Slog.i(TAG, " -- CUR: mSet=" 13616 + Arrays.toString(cur.mPref.mSetComponents)); 13617 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 13618 Slog.i(TAG, " -- NEW: mMatch=" 13619 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 13620 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 13621 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 13622 } 13623 } 13624 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 13625 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 13626 && cur.mPref.sameSet(set)) { 13627 // Setting the preferred activity to what it happens to be already 13628 if (DEBUG_PREFERRED) { 13629 Slog.i(TAG, "Replacing with same preferred activity " 13630 + cur.mPref.mShortComponent + " for user " 13631 + userId + ":"); 13632 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13633 } 13634 return; 13635 } 13636 } 13637 13638 if (existing != null) { 13639 if (DEBUG_PREFERRED) { 13640 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 13641 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13642 } 13643 for (int i = 0; i < existing.size(); i++) { 13644 PreferredActivity pa = existing.get(i); 13645 if (DEBUG_PREFERRED) { 13646 Slog.i(TAG, "Removing existing preferred activity " 13647 + pa.mPref.mComponent + ":"); 13648 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 13649 } 13650 pir.removeFilter(pa); 13651 } 13652 } 13653 } 13654 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13655 "Replacing preferred"); 13656 } 13657 } 13658 13659 @Override 13660 public void clearPackagePreferredActivities(String packageName) { 13661 final int uid = Binder.getCallingUid(); 13662 // writer 13663 synchronized (mPackages) { 13664 PackageParser.Package pkg = mPackages.get(packageName); 13665 if (pkg == null || pkg.applicationInfo.uid != uid) { 13666 if (mContext.checkCallingOrSelfPermission( 13667 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13668 != PackageManager.PERMISSION_GRANTED) { 13669 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 13670 < Build.VERSION_CODES.FROYO) { 13671 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 13672 + Binder.getCallingUid()); 13673 return; 13674 } 13675 mContext.enforceCallingOrSelfPermission( 13676 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13677 } 13678 } 13679 13680 int user = UserHandle.getCallingUserId(); 13681 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 13682 scheduleWritePackageRestrictionsLocked(user); 13683 } 13684 } 13685 } 13686 13687 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13688 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 13689 ArrayList<PreferredActivity> removed = null; 13690 boolean changed = false; 13691 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13692 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 13693 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13694 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 13695 continue; 13696 } 13697 Iterator<PreferredActivity> it = pir.filterIterator(); 13698 while (it.hasNext()) { 13699 PreferredActivity pa = it.next(); 13700 // Mark entry for removal only if it matches the package name 13701 // and the entry is of type "always". 13702 if (packageName == null || 13703 (pa.mPref.mComponent.getPackageName().equals(packageName) 13704 && pa.mPref.mAlways)) { 13705 if (removed == null) { 13706 removed = new ArrayList<PreferredActivity>(); 13707 } 13708 removed.add(pa); 13709 } 13710 } 13711 if (removed != null) { 13712 for (int j=0; j<removed.size(); j++) { 13713 PreferredActivity pa = removed.get(j); 13714 pir.removeFilter(pa); 13715 } 13716 changed = true; 13717 } 13718 } 13719 return changed; 13720 } 13721 13722 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13723 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 13724 if (userId == UserHandle.USER_ALL) { 13725 if (mSettings.removeIntentFilterVerificationLPw(packageName, 13726 sUserManager.getUserIds())) { 13727 for (int oneUserId : sUserManager.getUserIds()) { 13728 scheduleWritePackageRestrictionsLocked(oneUserId); 13729 } 13730 } 13731 } else { 13732 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 13733 scheduleWritePackageRestrictionsLocked(userId); 13734 } 13735 } 13736 } 13737 13738 13739 void clearDefaultBrowserIfNeeded(String packageName) { 13740 for (int oneUserId : sUserManager.getUserIds()) { 13741 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 13742 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 13743 if (packageName.equals(defaultBrowserPackageName)) { 13744 setDefaultBrowserPackageName(null, oneUserId); 13745 } 13746 } 13747 } 13748 13749 @Override 13750 public void resetPreferredActivities(int userId) { 13751 mContext.enforceCallingOrSelfPermission( 13752 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13753 // writer 13754 synchronized (mPackages) { 13755 clearPackagePreferredActivitiesLPw(null, userId); 13756 mSettings.applyDefaultPreferredAppsLPw(this, userId); 13757 applyFactoryDefaultBrowserLPw(userId); 13758 primeDomainVerificationsLPw(userId); 13759 13760 scheduleWritePackageRestrictionsLocked(userId); 13761 } 13762 } 13763 13764 @Override 13765 public int getPreferredActivities(List<IntentFilter> outFilters, 13766 List<ComponentName> outActivities, String packageName) { 13767 13768 int num = 0; 13769 final int userId = UserHandle.getCallingUserId(); 13770 // reader 13771 synchronized (mPackages) { 13772 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13773 if (pir != null) { 13774 final Iterator<PreferredActivity> it = pir.filterIterator(); 13775 while (it.hasNext()) { 13776 final PreferredActivity pa = it.next(); 13777 if (packageName == null 13778 || (pa.mPref.mComponent.getPackageName().equals(packageName) 13779 && pa.mPref.mAlways)) { 13780 if (outFilters != null) { 13781 outFilters.add(new IntentFilter(pa)); 13782 } 13783 if (outActivities != null) { 13784 outActivities.add(pa.mPref.mComponent); 13785 } 13786 } 13787 } 13788 } 13789 } 13790 13791 return num; 13792 } 13793 13794 @Override 13795 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 13796 int userId) { 13797 int callingUid = Binder.getCallingUid(); 13798 if (callingUid != Process.SYSTEM_UID) { 13799 throw new SecurityException( 13800 "addPersistentPreferredActivity can only be run by the system"); 13801 } 13802 if (filter.countActions() == 0) { 13803 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13804 return; 13805 } 13806 synchronized (mPackages) { 13807 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 13808 " :"); 13809 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13810 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 13811 new PersistentPreferredActivity(filter, activity)); 13812 scheduleWritePackageRestrictionsLocked(userId); 13813 } 13814 } 13815 13816 @Override 13817 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 13818 int callingUid = Binder.getCallingUid(); 13819 if (callingUid != Process.SYSTEM_UID) { 13820 throw new SecurityException( 13821 "clearPackagePersistentPreferredActivities can only be run by the system"); 13822 } 13823 ArrayList<PersistentPreferredActivity> removed = null; 13824 boolean changed = false; 13825 synchronized (mPackages) { 13826 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 13827 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 13828 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 13829 .valueAt(i); 13830 if (userId != thisUserId) { 13831 continue; 13832 } 13833 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 13834 while (it.hasNext()) { 13835 PersistentPreferredActivity ppa = it.next(); 13836 // Mark entry for removal only if it matches the package name. 13837 if (ppa.mComponent.getPackageName().equals(packageName)) { 13838 if (removed == null) { 13839 removed = new ArrayList<PersistentPreferredActivity>(); 13840 } 13841 removed.add(ppa); 13842 } 13843 } 13844 if (removed != null) { 13845 for (int j=0; j<removed.size(); j++) { 13846 PersistentPreferredActivity ppa = removed.get(j); 13847 ppir.removeFilter(ppa); 13848 } 13849 changed = true; 13850 } 13851 } 13852 13853 if (changed) { 13854 scheduleWritePackageRestrictionsLocked(userId); 13855 } 13856 } 13857 } 13858 13859 /** 13860 * Common machinery for picking apart a restored XML blob and passing 13861 * it to a caller-supplied functor to be applied to the running system. 13862 */ 13863 private void restoreFromXml(XmlPullParser parser, int userId, 13864 String expectedStartTag, BlobXmlRestorer functor) 13865 throws IOException, XmlPullParserException { 13866 int type; 13867 while ((type = parser.next()) != XmlPullParser.START_TAG 13868 && type != XmlPullParser.END_DOCUMENT) { 13869 } 13870 if (type != XmlPullParser.START_TAG) { 13871 // oops didn't find a start tag?! 13872 if (DEBUG_BACKUP) { 13873 Slog.e(TAG, "Didn't find start tag during restore"); 13874 } 13875 return; 13876 } 13877 13878 // this is supposed to be TAG_PREFERRED_BACKUP 13879 if (!expectedStartTag.equals(parser.getName())) { 13880 if (DEBUG_BACKUP) { 13881 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 13882 } 13883 return; 13884 } 13885 13886 // skip interfering stuff, then we're aligned with the backing implementation 13887 while ((type = parser.next()) == XmlPullParser.TEXT) { } 13888 functor.apply(parser, userId); 13889 } 13890 13891 private interface BlobXmlRestorer { 13892 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 13893 } 13894 13895 /** 13896 * Non-Binder method, support for the backup/restore mechanism: write the 13897 * full set of preferred activities in its canonical XML format. Returns the 13898 * XML output as a byte array, or null if there is none. 13899 */ 13900 @Override 13901 public byte[] getPreferredActivityBackup(int userId) { 13902 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13903 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 13904 } 13905 13906 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13907 try { 13908 final XmlSerializer serializer = new FastXmlSerializer(); 13909 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13910 serializer.startDocument(null, true); 13911 serializer.startTag(null, TAG_PREFERRED_BACKUP); 13912 13913 synchronized (mPackages) { 13914 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 13915 } 13916 13917 serializer.endTag(null, TAG_PREFERRED_BACKUP); 13918 serializer.endDocument(); 13919 serializer.flush(); 13920 } catch (Exception e) { 13921 if (DEBUG_BACKUP) { 13922 Slog.e(TAG, "Unable to write preferred activities for backup", e); 13923 } 13924 return null; 13925 } 13926 13927 return dataStream.toByteArray(); 13928 } 13929 13930 @Override 13931 public void restorePreferredActivities(byte[] backup, int userId) { 13932 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13933 throw new SecurityException("Only the system may call restorePreferredActivities()"); 13934 } 13935 13936 try { 13937 final XmlPullParser parser = Xml.newPullParser(); 13938 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13939 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 13940 new BlobXmlRestorer() { 13941 @Override 13942 public void apply(XmlPullParser parser, int userId) 13943 throws XmlPullParserException, IOException { 13944 synchronized (mPackages) { 13945 mSettings.readPreferredActivitiesLPw(parser, userId); 13946 } 13947 } 13948 } ); 13949 } catch (Exception e) { 13950 if (DEBUG_BACKUP) { 13951 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 13952 } 13953 } 13954 } 13955 13956 /** 13957 * Non-Binder method, support for the backup/restore mechanism: write the 13958 * default browser (etc) settings in its canonical XML format. Returns the default 13959 * browser XML representation as a byte array, or null if there is none. 13960 */ 13961 @Override 13962 public byte[] getDefaultAppsBackup(int userId) { 13963 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13964 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 13965 } 13966 13967 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13968 try { 13969 final XmlSerializer serializer = new FastXmlSerializer(); 13970 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13971 serializer.startDocument(null, true); 13972 serializer.startTag(null, TAG_DEFAULT_APPS); 13973 13974 synchronized (mPackages) { 13975 mSettings.writeDefaultAppsLPr(serializer, userId); 13976 } 13977 13978 serializer.endTag(null, TAG_DEFAULT_APPS); 13979 serializer.endDocument(); 13980 serializer.flush(); 13981 } catch (Exception e) { 13982 if (DEBUG_BACKUP) { 13983 Slog.e(TAG, "Unable to write default apps for backup", e); 13984 } 13985 return null; 13986 } 13987 13988 return dataStream.toByteArray(); 13989 } 13990 13991 @Override 13992 public void restoreDefaultApps(byte[] backup, int userId) { 13993 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13994 throw new SecurityException("Only the system may call restoreDefaultApps()"); 13995 } 13996 13997 try { 13998 final XmlPullParser parser = Xml.newPullParser(); 13999 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14000 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 14001 new BlobXmlRestorer() { 14002 @Override 14003 public void apply(XmlPullParser parser, int userId) 14004 throws XmlPullParserException, IOException { 14005 synchronized (mPackages) { 14006 mSettings.readDefaultAppsLPw(parser, userId); 14007 } 14008 } 14009 } ); 14010 } catch (Exception e) { 14011 if (DEBUG_BACKUP) { 14012 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 14013 } 14014 } 14015 } 14016 14017 @Override 14018 public byte[] getIntentFilterVerificationBackup(int userId) { 14019 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14020 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 14021 } 14022 14023 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14024 try { 14025 final XmlSerializer serializer = new FastXmlSerializer(); 14026 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14027 serializer.startDocument(null, true); 14028 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 14029 14030 synchronized (mPackages) { 14031 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 14032 } 14033 14034 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 14035 serializer.endDocument(); 14036 serializer.flush(); 14037 } catch (Exception e) { 14038 if (DEBUG_BACKUP) { 14039 Slog.e(TAG, "Unable to write default apps for backup", e); 14040 } 14041 return null; 14042 } 14043 14044 return dataStream.toByteArray(); 14045 } 14046 14047 @Override 14048 public void restoreIntentFilterVerification(byte[] backup, int userId) { 14049 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14050 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14051 } 14052 14053 try { 14054 final XmlPullParser parser = Xml.newPullParser(); 14055 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14056 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 14057 new BlobXmlRestorer() { 14058 @Override 14059 public void apply(XmlPullParser parser, int userId) 14060 throws XmlPullParserException, IOException { 14061 synchronized (mPackages) { 14062 mSettings.readAllDomainVerificationsLPr(parser, userId); 14063 mSettings.writeLPr(); 14064 } 14065 } 14066 } ); 14067 } catch (Exception e) { 14068 if (DEBUG_BACKUP) { 14069 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14070 } 14071 } 14072 } 14073 14074 @Override 14075 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 14076 int sourceUserId, int targetUserId, int flags) { 14077 mContext.enforceCallingOrSelfPermission( 14078 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14079 int callingUid = Binder.getCallingUid(); 14080 enforceOwnerRights(ownerPackage, callingUid); 14081 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14082 if (intentFilter.countActions() == 0) { 14083 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 14084 return; 14085 } 14086 synchronized (mPackages) { 14087 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 14088 ownerPackage, targetUserId, flags); 14089 CrossProfileIntentResolver resolver = 14090 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14091 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 14092 // We have all those whose filter is equal. Now checking if the rest is equal as well. 14093 if (existing != null) { 14094 int size = existing.size(); 14095 for (int i = 0; i < size; i++) { 14096 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 14097 return; 14098 } 14099 } 14100 } 14101 resolver.addFilter(newFilter); 14102 scheduleWritePackageRestrictionsLocked(sourceUserId); 14103 } 14104 } 14105 14106 @Override 14107 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 14108 mContext.enforceCallingOrSelfPermission( 14109 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14110 int callingUid = Binder.getCallingUid(); 14111 enforceOwnerRights(ownerPackage, callingUid); 14112 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14113 synchronized (mPackages) { 14114 CrossProfileIntentResolver resolver = 14115 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14116 ArraySet<CrossProfileIntentFilter> set = 14117 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 14118 for (CrossProfileIntentFilter filter : set) { 14119 if (filter.getOwnerPackage().equals(ownerPackage)) { 14120 resolver.removeFilter(filter); 14121 } 14122 } 14123 scheduleWritePackageRestrictionsLocked(sourceUserId); 14124 } 14125 } 14126 14127 // Enforcing that callingUid is owning pkg on userId 14128 private void enforceOwnerRights(String pkg, int callingUid) { 14129 // The system owns everything. 14130 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 14131 return; 14132 } 14133 int callingUserId = UserHandle.getUserId(callingUid); 14134 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 14135 if (pi == null) { 14136 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 14137 + callingUserId); 14138 } 14139 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 14140 throw new SecurityException("Calling uid " + callingUid 14141 + " does not own package " + pkg); 14142 } 14143 } 14144 14145 @Override 14146 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 14147 Intent intent = new Intent(Intent.ACTION_MAIN); 14148 intent.addCategory(Intent.CATEGORY_HOME); 14149 14150 final int callingUserId = UserHandle.getCallingUserId(); 14151 List<ResolveInfo> list = queryIntentActivities(intent, null, 14152 PackageManager.GET_META_DATA, callingUserId); 14153 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 14154 true, false, false, callingUserId); 14155 14156 allHomeCandidates.clear(); 14157 if (list != null) { 14158 for (ResolveInfo ri : list) { 14159 allHomeCandidates.add(ri); 14160 } 14161 } 14162 return (preferred == null || preferred.activityInfo == null) 14163 ? null 14164 : new ComponentName(preferred.activityInfo.packageName, 14165 preferred.activityInfo.name); 14166 } 14167 14168 @Override 14169 public void setApplicationEnabledSetting(String appPackageName, 14170 int newState, int flags, int userId, String callingPackage) { 14171 if (!sUserManager.exists(userId)) return; 14172 if (callingPackage == null) { 14173 callingPackage = Integer.toString(Binder.getCallingUid()); 14174 } 14175 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 14176 } 14177 14178 @Override 14179 public void setComponentEnabledSetting(ComponentName componentName, 14180 int newState, int flags, int userId) { 14181 if (!sUserManager.exists(userId)) return; 14182 setEnabledSetting(componentName.getPackageName(), 14183 componentName.getClassName(), newState, flags, userId, null); 14184 } 14185 14186 private void setEnabledSetting(final String packageName, String className, int newState, 14187 final int flags, int userId, String callingPackage) { 14188 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 14189 || newState == COMPONENT_ENABLED_STATE_ENABLED 14190 || newState == COMPONENT_ENABLED_STATE_DISABLED 14191 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 14192 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 14193 throw new IllegalArgumentException("Invalid new component state: " 14194 + newState); 14195 } 14196 PackageSetting pkgSetting; 14197 final int uid = Binder.getCallingUid(); 14198 final int permission = mContext.checkCallingOrSelfPermission( 14199 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14200 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 14201 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14202 boolean sendNow = false; 14203 boolean isApp = (className == null); 14204 String componentName = isApp ? packageName : className; 14205 int packageUid = -1; 14206 ArrayList<String> components; 14207 14208 // writer 14209 synchronized (mPackages) { 14210 pkgSetting = mSettings.mPackages.get(packageName); 14211 if (pkgSetting == null) { 14212 if (className == null) { 14213 throw new IllegalArgumentException( 14214 "Unknown package: " + packageName); 14215 } 14216 throw new IllegalArgumentException( 14217 "Unknown component: " + packageName 14218 + "/" + className); 14219 } 14220 // Allow root and verify that userId is not being specified by a different user 14221 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 14222 throw new SecurityException( 14223 "Permission Denial: attempt to change component state from pid=" 14224 + Binder.getCallingPid() 14225 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 14226 } 14227 if (className == null) { 14228 // We're dealing with an application/package level state change 14229 if (pkgSetting.getEnabled(userId) == newState) { 14230 // Nothing to do 14231 return; 14232 } 14233 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 14234 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 14235 // Don't care about who enables an app. 14236 callingPackage = null; 14237 } 14238 pkgSetting.setEnabled(newState, userId, callingPackage); 14239 // pkgSetting.pkg.mSetEnabled = newState; 14240 } else { 14241 // We're dealing with a component level state change 14242 // First, verify that this is a valid class name. 14243 PackageParser.Package pkg = pkgSetting.pkg; 14244 if (pkg == null || !pkg.hasComponentClassName(className)) { 14245 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 14246 throw new IllegalArgumentException("Component class " + className 14247 + " does not exist in " + packageName); 14248 } else { 14249 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 14250 + className + " does not exist in " + packageName); 14251 } 14252 } 14253 switch (newState) { 14254 case COMPONENT_ENABLED_STATE_ENABLED: 14255 if (!pkgSetting.enableComponentLPw(className, userId)) { 14256 return; 14257 } 14258 break; 14259 case COMPONENT_ENABLED_STATE_DISABLED: 14260 if (!pkgSetting.disableComponentLPw(className, userId)) { 14261 return; 14262 } 14263 break; 14264 case COMPONENT_ENABLED_STATE_DEFAULT: 14265 if (!pkgSetting.restoreComponentLPw(className, userId)) { 14266 return; 14267 } 14268 break; 14269 default: 14270 Slog.e(TAG, "Invalid new component state: " + newState); 14271 return; 14272 } 14273 } 14274 scheduleWritePackageRestrictionsLocked(userId); 14275 components = mPendingBroadcasts.get(userId, packageName); 14276 final boolean newPackage = components == null; 14277 if (newPackage) { 14278 components = new ArrayList<String>(); 14279 } 14280 if (!components.contains(componentName)) { 14281 components.add(componentName); 14282 } 14283 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 14284 sendNow = true; 14285 // Purge entry from pending broadcast list if another one exists already 14286 // since we are sending one right away. 14287 mPendingBroadcasts.remove(userId, packageName); 14288 } else { 14289 if (newPackage) { 14290 mPendingBroadcasts.put(userId, packageName, components); 14291 } 14292 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 14293 // Schedule a message 14294 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 14295 } 14296 } 14297 } 14298 14299 long callingId = Binder.clearCallingIdentity(); 14300 try { 14301 if (sendNow) { 14302 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 14303 sendPackageChangedBroadcast(packageName, 14304 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 14305 } 14306 } finally { 14307 Binder.restoreCallingIdentity(callingId); 14308 } 14309 } 14310 14311 private void sendPackageChangedBroadcast(String packageName, 14312 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 14313 if (DEBUG_INSTALL) 14314 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 14315 + componentNames); 14316 Bundle extras = new Bundle(4); 14317 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 14318 String nameList[] = new String[componentNames.size()]; 14319 componentNames.toArray(nameList); 14320 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 14321 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 14322 extras.putInt(Intent.EXTRA_UID, packageUid); 14323 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 14324 new int[] {UserHandle.getUserId(packageUid)}); 14325 } 14326 14327 @Override 14328 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 14329 if (!sUserManager.exists(userId)) return; 14330 final int uid = Binder.getCallingUid(); 14331 final int permission = mContext.checkCallingOrSelfPermission( 14332 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14333 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14334 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 14335 // writer 14336 synchronized (mPackages) { 14337 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 14338 allowedByPermission, uid, userId)) { 14339 scheduleWritePackageRestrictionsLocked(userId); 14340 } 14341 } 14342 } 14343 14344 @Override 14345 public String getInstallerPackageName(String packageName) { 14346 // reader 14347 synchronized (mPackages) { 14348 return mSettings.getInstallerPackageNameLPr(packageName); 14349 } 14350 } 14351 14352 @Override 14353 public int getApplicationEnabledSetting(String packageName, int userId) { 14354 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14355 int uid = Binder.getCallingUid(); 14356 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 14357 // reader 14358 synchronized (mPackages) { 14359 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 14360 } 14361 } 14362 14363 @Override 14364 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 14365 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14366 int uid = Binder.getCallingUid(); 14367 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 14368 // reader 14369 synchronized (mPackages) { 14370 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 14371 } 14372 } 14373 14374 @Override 14375 public void enterSafeMode() { 14376 enforceSystemOrRoot("Only the system can request entering safe mode"); 14377 14378 if (!mSystemReady) { 14379 mSafeMode = true; 14380 } 14381 } 14382 14383 @Override 14384 public void systemReady() { 14385 mSystemReady = true; 14386 14387 // Read the compatibilty setting when the system is ready. 14388 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 14389 mContext.getContentResolver(), 14390 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 14391 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 14392 if (DEBUG_SETTINGS) { 14393 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 14394 } 14395 14396 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 14397 14398 synchronized (mPackages) { 14399 // Verify that all of the preferred activity components actually 14400 // exist. It is possible for applications to be updated and at 14401 // that point remove a previously declared activity component that 14402 // had been set as a preferred activity. We try to clean this up 14403 // the next time we encounter that preferred activity, but it is 14404 // possible for the user flow to never be able to return to that 14405 // situation so here we do a sanity check to make sure we haven't 14406 // left any junk around. 14407 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 14408 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14409 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14410 removed.clear(); 14411 for (PreferredActivity pa : pir.filterSet()) { 14412 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 14413 removed.add(pa); 14414 } 14415 } 14416 if (removed.size() > 0) { 14417 for (int r=0; r<removed.size(); r++) { 14418 PreferredActivity pa = removed.get(r); 14419 Slog.w(TAG, "Removing dangling preferred activity: " 14420 + pa.mPref.mComponent); 14421 pir.removeFilter(pa); 14422 } 14423 mSettings.writePackageRestrictionsLPr( 14424 mSettings.mPreferredActivities.keyAt(i)); 14425 } 14426 } 14427 14428 for (int userId : UserManagerService.getInstance().getUserIds()) { 14429 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 14430 grantPermissionsUserIds = ArrayUtils.appendInt( 14431 grantPermissionsUserIds, userId); 14432 } 14433 } 14434 } 14435 sUserManager.systemReady(); 14436 14437 // If we upgraded grant all default permissions before kicking off. 14438 for (int userId : grantPermissionsUserIds) { 14439 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 14440 } 14441 14442 // Kick off any messages waiting for system ready 14443 if (mPostSystemReadyMessages != null) { 14444 for (Message msg : mPostSystemReadyMessages) { 14445 msg.sendToTarget(); 14446 } 14447 mPostSystemReadyMessages = null; 14448 } 14449 14450 // Watch for external volumes that come and go over time 14451 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14452 storage.registerListener(mStorageListener); 14453 14454 mInstallerService.systemReady(); 14455 mPackageDexOptimizer.systemReady(); 14456 14457 MountServiceInternal mountServiceInternal = LocalServices.getService( 14458 MountServiceInternal.class); 14459 mountServiceInternal.addExternalStoragePolicy( 14460 new MountServiceInternal.ExternalStorageMountPolicy() { 14461 @Override 14462 public int getMountMode(int uid, String packageName) { 14463 if (Process.isIsolated(uid)) { 14464 return Zygote.MOUNT_EXTERNAL_NONE; 14465 } 14466 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 14467 return Zygote.MOUNT_EXTERNAL_DEFAULT; 14468 } 14469 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 14470 return Zygote.MOUNT_EXTERNAL_DEFAULT; 14471 } 14472 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 14473 return Zygote.MOUNT_EXTERNAL_READ; 14474 } 14475 return Zygote.MOUNT_EXTERNAL_WRITE; 14476 } 14477 14478 @Override 14479 public boolean hasExternalStorage(int uid, String packageName) { 14480 return true; 14481 } 14482 }); 14483 } 14484 14485 @Override 14486 public boolean isSafeMode() { 14487 return mSafeMode; 14488 } 14489 14490 @Override 14491 public boolean hasSystemUidErrors() { 14492 return mHasSystemUidErrors; 14493 } 14494 14495 static String arrayToString(int[] array) { 14496 StringBuffer buf = new StringBuffer(128); 14497 buf.append('['); 14498 if (array != null) { 14499 for (int i=0; i<array.length; i++) { 14500 if (i > 0) buf.append(", "); 14501 buf.append(array[i]); 14502 } 14503 } 14504 buf.append(']'); 14505 return buf.toString(); 14506 } 14507 14508 static class DumpState { 14509 public static final int DUMP_LIBS = 1 << 0; 14510 public static final int DUMP_FEATURES = 1 << 1; 14511 public static final int DUMP_RESOLVERS = 1 << 2; 14512 public static final int DUMP_PERMISSIONS = 1 << 3; 14513 public static final int DUMP_PACKAGES = 1 << 4; 14514 public static final int DUMP_SHARED_USERS = 1 << 5; 14515 public static final int DUMP_MESSAGES = 1 << 6; 14516 public static final int DUMP_PROVIDERS = 1 << 7; 14517 public static final int DUMP_VERIFIERS = 1 << 8; 14518 public static final int DUMP_PREFERRED = 1 << 9; 14519 public static final int DUMP_PREFERRED_XML = 1 << 10; 14520 public static final int DUMP_KEYSETS = 1 << 11; 14521 public static final int DUMP_VERSION = 1 << 12; 14522 public static final int DUMP_INSTALLS = 1 << 13; 14523 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 14524 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 14525 14526 public static final int OPTION_SHOW_FILTERS = 1 << 0; 14527 14528 private int mTypes; 14529 14530 private int mOptions; 14531 14532 private boolean mTitlePrinted; 14533 14534 private SharedUserSetting mSharedUser; 14535 14536 public boolean isDumping(int type) { 14537 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 14538 return true; 14539 } 14540 14541 return (mTypes & type) != 0; 14542 } 14543 14544 public void setDump(int type) { 14545 mTypes |= type; 14546 } 14547 14548 public boolean isOptionEnabled(int option) { 14549 return (mOptions & option) != 0; 14550 } 14551 14552 public void setOptionEnabled(int option) { 14553 mOptions |= option; 14554 } 14555 14556 public boolean onTitlePrinted() { 14557 final boolean printed = mTitlePrinted; 14558 mTitlePrinted = true; 14559 return printed; 14560 } 14561 14562 public boolean getTitlePrinted() { 14563 return mTitlePrinted; 14564 } 14565 14566 public void setTitlePrinted(boolean enabled) { 14567 mTitlePrinted = enabled; 14568 } 14569 14570 public SharedUserSetting getSharedUser() { 14571 return mSharedUser; 14572 } 14573 14574 public void setSharedUser(SharedUserSetting user) { 14575 mSharedUser = user; 14576 } 14577 } 14578 14579 @Override 14580 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 14581 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 14582 != PackageManager.PERMISSION_GRANTED) { 14583 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 14584 + Binder.getCallingPid() 14585 + ", uid=" + Binder.getCallingUid() 14586 + " without permission " 14587 + android.Manifest.permission.DUMP); 14588 return; 14589 } 14590 14591 DumpState dumpState = new DumpState(); 14592 boolean fullPreferred = false; 14593 boolean checkin = false; 14594 14595 String packageName = null; 14596 ArraySet<String> permissionNames = null; 14597 14598 int opti = 0; 14599 while (opti < args.length) { 14600 String opt = args[opti]; 14601 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 14602 break; 14603 } 14604 opti++; 14605 14606 if ("-a".equals(opt)) { 14607 // Right now we only know how to print all. 14608 } else if ("-h".equals(opt)) { 14609 pw.println("Package manager dump options:"); 14610 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 14611 pw.println(" --checkin: dump for a checkin"); 14612 pw.println(" -f: print details of intent filters"); 14613 pw.println(" -h: print this help"); 14614 pw.println(" cmd may be one of:"); 14615 pw.println(" l[ibraries]: list known shared libraries"); 14616 pw.println(" f[ibraries]: list device features"); 14617 pw.println(" k[eysets]: print known keysets"); 14618 pw.println(" r[esolvers]: dump intent resolvers"); 14619 pw.println(" perm[issions]: dump permissions"); 14620 pw.println(" permission [name ...]: dump declaration and use of given permission"); 14621 pw.println(" pref[erred]: print preferred package settings"); 14622 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 14623 pw.println(" prov[iders]: dump content providers"); 14624 pw.println(" p[ackages]: dump installed packages"); 14625 pw.println(" s[hared-users]: dump shared user IDs"); 14626 pw.println(" m[essages]: print collected runtime messages"); 14627 pw.println(" v[erifiers]: print package verifier info"); 14628 pw.println(" version: print database version info"); 14629 pw.println(" write: write current settings now"); 14630 pw.println(" <package.name>: info about given package"); 14631 pw.println(" installs: details about install sessions"); 14632 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 14633 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 14634 return; 14635 } else if ("--checkin".equals(opt)) { 14636 checkin = true; 14637 } else if ("-f".equals(opt)) { 14638 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14639 } else { 14640 pw.println("Unknown argument: " + opt + "; use -h for help"); 14641 } 14642 } 14643 14644 // Is the caller requesting to dump a particular piece of data? 14645 if (opti < args.length) { 14646 String cmd = args[opti]; 14647 opti++; 14648 // Is this a package name? 14649 if ("android".equals(cmd) || cmd.contains(".")) { 14650 packageName = cmd; 14651 // When dumping a single package, we always dump all of its 14652 // filter information since the amount of data will be reasonable. 14653 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14654 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 14655 dumpState.setDump(DumpState.DUMP_LIBS); 14656 } else if ("f".equals(cmd) || "features".equals(cmd)) { 14657 dumpState.setDump(DumpState.DUMP_FEATURES); 14658 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 14659 dumpState.setDump(DumpState.DUMP_RESOLVERS); 14660 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 14661 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 14662 } else if ("permission".equals(cmd)) { 14663 if (opti >= args.length) { 14664 pw.println("Error: permission requires permission name"); 14665 return; 14666 } 14667 permissionNames = new ArraySet<>(); 14668 while (opti < args.length) { 14669 permissionNames.add(args[opti]); 14670 opti++; 14671 } 14672 dumpState.setDump(DumpState.DUMP_PERMISSIONS 14673 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 14674 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 14675 dumpState.setDump(DumpState.DUMP_PREFERRED); 14676 } else if ("preferred-xml".equals(cmd)) { 14677 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 14678 if (opti < args.length && "--full".equals(args[opti])) { 14679 fullPreferred = true; 14680 opti++; 14681 } 14682 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 14683 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 14684 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 14685 dumpState.setDump(DumpState.DUMP_PACKAGES); 14686 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 14687 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 14688 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 14689 dumpState.setDump(DumpState.DUMP_PROVIDERS); 14690 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 14691 dumpState.setDump(DumpState.DUMP_MESSAGES); 14692 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 14693 dumpState.setDump(DumpState.DUMP_VERIFIERS); 14694 } else if ("i".equals(cmd) || "ifv".equals(cmd) 14695 || "intent-filter-verifiers".equals(cmd)) { 14696 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 14697 } else if ("version".equals(cmd)) { 14698 dumpState.setDump(DumpState.DUMP_VERSION); 14699 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 14700 dumpState.setDump(DumpState.DUMP_KEYSETS); 14701 } else if ("installs".equals(cmd)) { 14702 dumpState.setDump(DumpState.DUMP_INSTALLS); 14703 } else if ("write".equals(cmd)) { 14704 synchronized (mPackages) { 14705 mSettings.writeLPr(); 14706 pw.println("Settings written."); 14707 return; 14708 } 14709 } 14710 } 14711 14712 if (checkin) { 14713 pw.println("vers,1"); 14714 } 14715 14716 // reader 14717 synchronized (mPackages) { 14718 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 14719 if (!checkin) { 14720 if (dumpState.onTitlePrinted()) 14721 pw.println(); 14722 pw.println("Database versions:"); 14723 pw.print(" SDK Version:"); 14724 pw.print(" internal="); 14725 pw.print(mSettings.mInternalSdkPlatform); 14726 pw.print(" external="); 14727 pw.println(mSettings.mExternalSdkPlatform); 14728 pw.print(" DB Version:"); 14729 pw.print(" internal="); 14730 pw.print(mSettings.mInternalDatabaseVersion); 14731 pw.print(" external="); 14732 pw.println(mSettings.mExternalDatabaseVersion); 14733 } 14734 } 14735 14736 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 14737 if (!checkin) { 14738 if (dumpState.onTitlePrinted()) 14739 pw.println(); 14740 pw.println("Verifiers:"); 14741 pw.print(" Required: "); 14742 pw.print(mRequiredVerifierPackage); 14743 pw.print(" (uid="); 14744 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 14745 pw.println(")"); 14746 } else if (mRequiredVerifierPackage != null) { 14747 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 14748 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 14749 } 14750 } 14751 14752 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 14753 packageName == null) { 14754 if (mIntentFilterVerifierComponent != null) { 14755 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 14756 if (!checkin) { 14757 if (dumpState.onTitlePrinted()) 14758 pw.println(); 14759 pw.println("Intent Filter Verifier:"); 14760 pw.print(" Using: "); 14761 pw.print(verifierPackageName); 14762 pw.print(" (uid="); 14763 pw.print(getPackageUid(verifierPackageName, 0)); 14764 pw.println(")"); 14765 } else if (verifierPackageName != null) { 14766 pw.print("ifv,"); pw.print(verifierPackageName); 14767 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 14768 } 14769 } else { 14770 pw.println(); 14771 pw.println("No Intent Filter Verifier available!"); 14772 } 14773 } 14774 14775 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 14776 boolean printedHeader = false; 14777 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 14778 while (it.hasNext()) { 14779 String name = it.next(); 14780 SharedLibraryEntry ent = mSharedLibraries.get(name); 14781 if (!checkin) { 14782 if (!printedHeader) { 14783 if (dumpState.onTitlePrinted()) 14784 pw.println(); 14785 pw.println("Libraries:"); 14786 printedHeader = true; 14787 } 14788 pw.print(" "); 14789 } else { 14790 pw.print("lib,"); 14791 } 14792 pw.print(name); 14793 if (!checkin) { 14794 pw.print(" -> "); 14795 } 14796 if (ent.path != null) { 14797 if (!checkin) { 14798 pw.print("(jar) "); 14799 pw.print(ent.path); 14800 } else { 14801 pw.print(",jar,"); 14802 pw.print(ent.path); 14803 } 14804 } else { 14805 if (!checkin) { 14806 pw.print("(apk) "); 14807 pw.print(ent.apk); 14808 } else { 14809 pw.print(",apk,"); 14810 pw.print(ent.apk); 14811 } 14812 } 14813 pw.println(); 14814 } 14815 } 14816 14817 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 14818 if (dumpState.onTitlePrinted()) 14819 pw.println(); 14820 if (!checkin) { 14821 pw.println("Features:"); 14822 } 14823 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 14824 while (it.hasNext()) { 14825 String name = it.next(); 14826 if (!checkin) { 14827 pw.print(" "); 14828 } else { 14829 pw.print("feat,"); 14830 } 14831 pw.println(name); 14832 } 14833 } 14834 14835 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 14836 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 14837 : "Activity Resolver Table:", " ", packageName, 14838 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14839 dumpState.setTitlePrinted(true); 14840 } 14841 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 14842 : "Receiver Resolver Table:", " ", packageName, 14843 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14844 dumpState.setTitlePrinted(true); 14845 } 14846 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 14847 : "Service Resolver Table:", " ", packageName, 14848 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14849 dumpState.setTitlePrinted(true); 14850 } 14851 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 14852 : "Provider Resolver Table:", " ", packageName, 14853 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14854 dumpState.setTitlePrinted(true); 14855 } 14856 } 14857 14858 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 14859 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14860 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14861 int user = mSettings.mPreferredActivities.keyAt(i); 14862 if (pir.dump(pw, 14863 dumpState.getTitlePrinted() 14864 ? "\nPreferred Activities User " + user + ":" 14865 : "Preferred Activities User " + user + ":", " ", 14866 packageName, true, false)) { 14867 dumpState.setTitlePrinted(true); 14868 } 14869 } 14870 } 14871 14872 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 14873 pw.flush(); 14874 FileOutputStream fout = new FileOutputStream(fd); 14875 BufferedOutputStream str = new BufferedOutputStream(fout); 14876 XmlSerializer serializer = new FastXmlSerializer(); 14877 try { 14878 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 14879 serializer.startDocument(null, true); 14880 serializer.setFeature( 14881 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 14882 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 14883 serializer.endDocument(); 14884 serializer.flush(); 14885 } catch (IllegalArgumentException e) { 14886 pw.println("Failed writing: " + e); 14887 } catch (IllegalStateException e) { 14888 pw.println("Failed writing: " + e); 14889 } catch (IOException e) { 14890 pw.println("Failed writing: " + e); 14891 } 14892 } 14893 14894 if (!checkin 14895 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 14896 && packageName == null) { 14897 pw.println(); 14898 int count = mSettings.mPackages.size(); 14899 if (count == 0) { 14900 pw.println("No applications!"); 14901 pw.println(); 14902 } else { 14903 final String prefix = " "; 14904 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 14905 if (allPackageSettings.size() == 0) { 14906 pw.println("No domain preferred apps!"); 14907 pw.println(); 14908 } else { 14909 pw.println("App verification status:"); 14910 pw.println(); 14911 count = 0; 14912 for (PackageSetting ps : allPackageSettings) { 14913 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 14914 if (ivi == null || ivi.getPackageName() == null) continue; 14915 pw.println(prefix + "Package: " + ivi.getPackageName()); 14916 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 14917 pw.println(prefix + "Status: " + ivi.getStatusString()); 14918 pw.println(); 14919 count++; 14920 } 14921 if (count == 0) { 14922 pw.println(prefix + "No app verification established."); 14923 pw.println(); 14924 } 14925 for (int userId : sUserManager.getUserIds()) { 14926 pw.println("App linkages for user " + userId + ":"); 14927 pw.println(); 14928 count = 0; 14929 for (PackageSetting ps : allPackageSettings) { 14930 final long status = ps.getDomainVerificationStatusForUser(userId); 14931 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 14932 continue; 14933 } 14934 pw.println(prefix + "Package: " + ps.name); 14935 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 14936 String statusStr = IntentFilterVerificationInfo. 14937 getStatusStringFromValue(status); 14938 pw.println(prefix + "Status: " + statusStr); 14939 pw.println(); 14940 count++; 14941 } 14942 if (count == 0) { 14943 pw.println(prefix + "No configured app linkages."); 14944 pw.println(); 14945 } 14946 } 14947 } 14948 } 14949 } 14950 14951 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 14952 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 14953 if (packageName == null && permissionNames == null) { 14954 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 14955 if (iperm == 0) { 14956 if (dumpState.onTitlePrinted()) 14957 pw.println(); 14958 pw.println("AppOp Permissions:"); 14959 } 14960 pw.print(" AppOp Permission "); 14961 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 14962 pw.println(":"); 14963 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 14964 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 14965 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 14966 } 14967 } 14968 } 14969 } 14970 14971 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 14972 boolean printedSomething = false; 14973 for (PackageParser.Provider p : mProviders.mProviders.values()) { 14974 if (packageName != null && !packageName.equals(p.info.packageName)) { 14975 continue; 14976 } 14977 if (!printedSomething) { 14978 if (dumpState.onTitlePrinted()) 14979 pw.println(); 14980 pw.println("Registered ContentProviders:"); 14981 printedSomething = true; 14982 } 14983 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 14984 pw.print(" "); pw.println(p.toString()); 14985 } 14986 printedSomething = false; 14987 for (Map.Entry<String, PackageParser.Provider> entry : 14988 mProvidersByAuthority.entrySet()) { 14989 PackageParser.Provider p = entry.getValue(); 14990 if (packageName != null && !packageName.equals(p.info.packageName)) { 14991 continue; 14992 } 14993 if (!printedSomething) { 14994 if (dumpState.onTitlePrinted()) 14995 pw.println(); 14996 pw.println("ContentProvider Authorities:"); 14997 printedSomething = true; 14998 } 14999 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 15000 pw.print(" "); pw.println(p.toString()); 15001 if (p.info != null && p.info.applicationInfo != null) { 15002 final String appInfo = p.info.applicationInfo.toString(); 15003 pw.print(" applicationInfo="); pw.println(appInfo); 15004 } 15005 } 15006 } 15007 15008 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 15009 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 15010 } 15011 15012 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 15013 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 15014 } 15015 15016 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 15017 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 15018 } 15019 15020 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 15021 // XXX should handle packageName != null by dumping only install data that 15022 // the given package is involved with. 15023 if (dumpState.onTitlePrinted()) pw.println(); 15024 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 15025 } 15026 15027 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 15028 if (dumpState.onTitlePrinted()) pw.println(); 15029 mSettings.dumpReadMessagesLPr(pw, dumpState); 15030 15031 pw.println(); 15032 pw.println("Package warning messages:"); 15033 BufferedReader in = null; 15034 String line = null; 15035 try { 15036 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15037 while ((line = in.readLine()) != null) { 15038 if (line.contains("ignored: updated version")) continue; 15039 pw.println(line); 15040 } 15041 } catch (IOException ignored) { 15042 } finally { 15043 IoUtils.closeQuietly(in); 15044 } 15045 } 15046 15047 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 15048 BufferedReader in = null; 15049 String line = null; 15050 try { 15051 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15052 while ((line = in.readLine()) != null) { 15053 if (line.contains("ignored: updated version")) continue; 15054 pw.print("msg,"); 15055 pw.println(line); 15056 } 15057 } catch (IOException ignored) { 15058 } finally { 15059 IoUtils.closeQuietly(in); 15060 } 15061 } 15062 } 15063 } 15064 15065 private String dumpDomainString(String packageName) { 15066 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName); 15067 List<IntentFilter> filters = getAllIntentFilters(packageName); 15068 15069 ArraySet<String> result = new ArraySet<>(); 15070 if (iviList.size() > 0) { 15071 for (IntentFilterVerificationInfo ivi : iviList) { 15072 for (String host : ivi.getDomains()) { 15073 result.add(host); 15074 } 15075 } 15076 } 15077 if (filters != null && filters.size() > 0) { 15078 for (IntentFilter filter : filters) { 15079 if (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 15080 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)) { 15081 result.addAll(filter.getHostsList()); 15082 } 15083 } 15084 } 15085 15086 StringBuilder sb = new StringBuilder(result.size() * 16); 15087 for (String domain : result) { 15088 if (sb.length() > 0) sb.append(" "); 15089 sb.append(domain); 15090 } 15091 return sb.toString(); 15092 } 15093 15094 // ------- apps on sdcard specific code ------- 15095 static final boolean DEBUG_SD_INSTALL = false; 15096 15097 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 15098 15099 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 15100 15101 private boolean mMediaMounted = false; 15102 15103 static String getEncryptKey() { 15104 try { 15105 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 15106 SD_ENCRYPTION_KEYSTORE_NAME); 15107 if (sdEncKey == null) { 15108 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 15109 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 15110 if (sdEncKey == null) { 15111 Slog.e(TAG, "Failed to create encryption keys"); 15112 return null; 15113 } 15114 } 15115 return sdEncKey; 15116 } catch (NoSuchAlgorithmException nsae) { 15117 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 15118 return null; 15119 } catch (IOException ioe) { 15120 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 15121 return null; 15122 } 15123 } 15124 15125 /* 15126 * Update media status on PackageManager. 15127 */ 15128 @Override 15129 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 15130 int callingUid = Binder.getCallingUid(); 15131 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 15132 throw new SecurityException("Media status can only be updated by the system"); 15133 } 15134 // reader; this apparently protects mMediaMounted, but should probably 15135 // be a different lock in that case. 15136 synchronized (mPackages) { 15137 Log.i(TAG, "Updating external media status from " 15138 + (mMediaMounted ? "mounted" : "unmounted") + " to " 15139 + (mediaStatus ? "mounted" : "unmounted")); 15140 if (DEBUG_SD_INSTALL) 15141 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 15142 + ", mMediaMounted=" + mMediaMounted); 15143 if (mediaStatus == mMediaMounted) { 15144 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 15145 : 0, -1); 15146 mHandler.sendMessage(msg); 15147 return; 15148 } 15149 mMediaMounted = mediaStatus; 15150 } 15151 // Queue up an async operation since the package installation may take a 15152 // little while. 15153 mHandler.post(new Runnable() { 15154 public void run() { 15155 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 15156 } 15157 }); 15158 } 15159 15160 /** 15161 * Called by MountService when the initial ASECs to scan are available. 15162 * Should block until all the ASEC containers are finished being scanned. 15163 */ 15164 public void scanAvailableAsecs() { 15165 updateExternalMediaStatusInner(true, false, false); 15166 if (mShouldRestoreconData) { 15167 SELinuxMMAC.setRestoreconDone(); 15168 mShouldRestoreconData = false; 15169 } 15170 } 15171 15172 /* 15173 * Collect information of applications on external media, map them against 15174 * existing containers and update information based on current mount status. 15175 * Please note that we always have to report status if reportStatus has been 15176 * set to true especially when unloading packages. 15177 */ 15178 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 15179 boolean externalStorage) { 15180 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 15181 int[] uidArr = EmptyArray.INT; 15182 15183 final String[] list = PackageHelper.getSecureContainerList(); 15184 if (ArrayUtils.isEmpty(list)) { 15185 Log.i(TAG, "No secure containers found"); 15186 } else { 15187 // Process list of secure containers and categorize them 15188 // as active or stale based on their package internal state. 15189 15190 // reader 15191 synchronized (mPackages) { 15192 for (String cid : list) { 15193 // Leave stages untouched for now; installer service owns them 15194 if (PackageInstallerService.isStageName(cid)) continue; 15195 15196 if (DEBUG_SD_INSTALL) 15197 Log.i(TAG, "Processing container " + cid); 15198 String pkgName = getAsecPackageName(cid); 15199 if (pkgName == null) { 15200 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 15201 continue; 15202 } 15203 if (DEBUG_SD_INSTALL) 15204 Log.i(TAG, "Looking for pkg : " + pkgName); 15205 15206 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15207 if (ps == null) { 15208 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 15209 continue; 15210 } 15211 15212 /* 15213 * Skip packages that are not external if we're unmounting 15214 * external storage. 15215 */ 15216 if (externalStorage && !isMounted && !isExternal(ps)) { 15217 continue; 15218 } 15219 15220 final AsecInstallArgs args = new AsecInstallArgs(cid, 15221 getAppDexInstructionSets(ps), ps.isForwardLocked()); 15222 // The package status is changed only if the code path 15223 // matches between settings and the container id. 15224 if (ps.codePathString != null 15225 && ps.codePathString.startsWith(args.getCodePath())) { 15226 if (DEBUG_SD_INSTALL) { 15227 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 15228 + " at code path: " + ps.codePathString); 15229 } 15230 15231 // We do have a valid package installed on sdcard 15232 processCids.put(args, ps.codePathString); 15233 final int uid = ps.appId; 15234 if (uid != -1) { 15235 uidArr = ArrayUtils.appendInt(uidArr, uid); 15236 } 15237 } else { 15238 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 15239 + ps.codePathString); 15240 } 15241 } 15242 } 15243 15244 Arrays.sort(uidArr); 15245 } 15246 15247 // Process packages with valid entries. 15248 if (isMounted) { 15249 if (DEBUG_SD_INSTALL) 15250 Log.i(TAG, "Loading packages"); 15251 loadMediaPackages(processCids, uidArr); 15252 startCleaningPackages(); 15253 mInstallerService.onSecureContainersAvailable(); 15254 } else { 15255 if (DEBUG_SD_INSTALL) 15256 Log.i(TAG, "Unloading packages"); 15257 unloadMediaPackages(processCids, uidArr, reportStatus); 15258 } 15259 } 15260 15261 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15262 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 15263 final int size = infos.size(); 15264 final String[] packageNames = new String[size]; 15265 final int[] packageUids = new int[size]; 15266 for (int i = 0; i < size; i++) { 15267 final ApplicationInfo info = infos.get(i); 15268 packageNames[i] = info.packageName; 15269 packageUids[i] = info.uid; 15270 } 15271 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 15272 finishedReceiver); 15273 } 15274 15275 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15276 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15277 sendResourcesChangedBroadcast(mediaStatus, replacing, 15278 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 15279 } 15280 15281 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15282 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15283 int size = pkgList.length; 15284 if (size > 0) { 15285 // Send broadcasts here 15286 Bundle extras = new Bundle(); 15287 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 15288 if (uidArr != null) { 15289 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 15290 } 15291 if (replacing) { 15292 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 15293 } 15294 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 15295 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 15296 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 15297 } 15298 } 15299 15300 /* 15301 * Look at potentially valid container ids from processCids If package 15302 * information doesn't match the one on record or package scanning fails, 15303 * the cid is added to list of removeCids. We currently don't delete stale 15304 * containers. 15305 */ 15306 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 15307 ArrayList<String> pkgList = new ArrayList<String>(); 15308 Set<AsecInstallArgs> keys = processCids.keySet(); 15309 15310 for (AsecInstallArgs args : keys) { 15311 String codePath = processCids.get(args); 15312 if (DEBUG_SD_INSTALL) 15313 Log.i(TAG, "Loading container : " + args.cid); 15314 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15315 try { 15316 // Make sure there are no container errors first. 15317 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 15318 Slog.e(TAG, "Failed to mount cid : " + args.cid 15319 + " when installing from sdcard"); 15320 continue; 15321 } 15322 // Check code path here. 15323 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 15324 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 15325 + " does not match one in settings " + codePath); 15326 continue; 15327 } 15328 // Parse package 15329 int parseFlags = mDefParseFlags; 15330 if (args.isExternalAsec()) { 15331 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 15332 } 15333 if (args.isFwdLocked()) { 15334 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 15335 } 15336 15337 synchronized (mInstallLock) { 15338 PackageParser.Package pkg = null; 15339 try { 15340 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 15341 } catch (PackageManagerException e) { 15342 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 15343 } 15344 // Scan the package 15345 if (pkg != null) { 15346 /* 15347 * TODO why is the lock being held? doPostInstall is 15348 * called in other places without the lock. This needs 15349 * to be straightened out. 15350 */ 15351 // writer 15352 synchronized (mPackages) { 15353 retCode = PackageManager.INSTALL_SUCCEEDED; 15354 pkgList.add(pkg.packageName); 15355 // Post process args 15356 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 15357 pkg.applicationInfo.uid); 15358 } 15359 } else { 15360 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 15361 } 15362 } 15363 15364 } finally { 15365 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 15366 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 15367 } 15368 } 15369 } 15370 // writer 15371 synchronized (mPackages) { 15372 // If the platform SDK has changed since the last time we booted, 15373 // we need to re-grant app permission to catch any new ones that 15374 // appear. This is really a hack, and means that apps can in some 15375 // cases get permissions that the user didn't initially explicitly 15376 // allow... it would be nice to have some better way to handle 15377 // this situation. 15378 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 15379 if (regrantPermissions) 15380 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 15381 + mSdkVersion + "; regranting permissions for external storage"); 15382 mSettings.mExternalSdkPlatform = mSdkVersion; 15383 15384 // Make sure group IDs have been assigned, and any permission 15385 // changes in other apps are accounted for 15386 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 15387 | (regrantPermissions 15388 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 15389 : 0)); 15390 15391 mSettings.updateExternalDatabaseVersion(); 15392 15393 // can downgrade to reader 15394 // Persist settings 15395 mSettings.writeLPr(); 15396 } 15397 // Send a broadcast to let everyone know we are done processing 15398 if (pkgList.size() > 0) { 15399 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 15400 } 15401 } 15402 15403 /* 15404 * Utility method to unload a list of specified containers 15405 */ 15406 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 15407 // Just unmount all valid containers. 15408 for (AsecInstallArgs arg : cidArgs) { 15409 synchronized (mInstallLock) { 15410 arg.doPostDeleteLI(false); 15411 } 15412 } 15413 } 15414 15415 /* 15416 * Unload packages mounted on external media. This involves deleting package 15417 * data from internal structures, sending broadcasts about diabled packages, 15418 * gc'ing to free up references, unmounting all secure containers 15419 * corresponding to packages on external media, and posting a 15420 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 15421 * that we always have to post this message if status has been requested no 15422 * matter what. 15423 */ 15424 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 15425 final boolean reportStatus) { 15426 if (DEBUG_SD_INSTALL) 15427 Log.i(TAG, "unloading media packages"); 15428 ArrayList<String> pkgList = new ArrayList<String>(); 15429 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 15430 final Set<AsecInstallArgs> keys = processCids.keySet(); 15431 for (AsecInstallArgs args : keys) { 15432 String pkgName = args.getPackageName(); 15433 if (DEBUG_SD_INSTALL) 15434 Log.i(TAG, "Trying to unload pkg : " + pkgName); 15435 // Delete package internally 15436 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15437 synchronized (mInstallLock) { 15438 boolean res = deletePackageLI(pkgName, null, false, null, null, 15439 PackageManager.DELETE_KEEP_DATA, outInfo, false); 15440 if (res) { 15441 pkgList.add(pkgName); 15442 } else { 15443 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 15444 failedList.add(args); 15445 } 15446 } 15447 } 15448 15449 // reader 15450 synchronized (mPackages) { 15451 // We didn't update the settings after removing each package; 15452 // write them now for all packages. 15453 mSettings.writeLPr(); 15454 } 15455 15456 // We have to absolutely send UPDATED_MEDIA_STATUS only 15457 // after confirming that all the receivers processed the ordered 15458 // broadcast when packages get disabled, force a gc to clean things up. 15459 // and unload all the containers. 15460 if (pkgList.size() > 0) { 15461 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 15462 new IIntentReceiver.Stub() { 15463 public void performReceive(Intent intent, int resultCode, String data, 15464 Bundle extras, boolean ordered, boolean sticky, 15465 int sendingUser) throws RemoteException { 15466 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 15467 reportStatus ? 1 : 0, 1, keys); 15468 mHandler.sendMessage(msg); 15469 } 15470 }); 15471 } else { 15472 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 15473 keys); 15474 mHandler.sendMessage(msg); 15475 } 15476 } 15477 15478 private void loadPrivatePackages(VolumeInfo vol) { 15479 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 15480 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 15481 synchronized (mInstallLock) { 15482 synchronized (mPackages) { 15483 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15484 for (PackageSetting ps : packages) { 15485 final PackageParser.Package pkg; 15486 try { 15487 pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null); 15488 loaded.add(pkg.applicationInfo); 15489 } catch (PackageManagerException e) { 15490 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 15491 } 15492 } 15493 15494 // TODO: regrant any permissions that changed based since original install 15495 15496 mSettings.writeLPr(); 15497 } 15498 } 15499 15500 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 15501 sendResourcesChangedBroadcast(true, false, loaded, null); 15502 } 15503 15504 private void unloadPrivatePackages(VolumeInfo vol) { 15505 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 15506 synchronized (mInstallLock) { 15507 synchronized (mPackages) { 15508 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15509 for (PackageSetting ps : packages) { 15510 if (ps.pkg == null) continue; 15511 15512 final ApplicationInfo info = ps.pkg.applicationInfo; 15513 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15514 if (deletePackageLI(ps.name, null, false, null, null, 15515 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 15516 unloaded.add(info); 15517 } else { 15518 Slog.w(TAG, "Failed to unload " + ps.codePath); 15519 } 15520 } 15521 15522 mSettings.writeLPr(); 15523 } 15524 } 15525 15526 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 15527 sendResourcesChangedBroadcast(false, false, unloaded, null); 15528 } 15529 15530 /** 15531 * Examine all users present on given mounted volume, and destroy data 15532 * belonging to users that are no longer valid, or whose user ID has been 15533 * recycled. 15534 */ 15535 private void reconcileUsers(String volumeUuid) { 15536 final File[] files = Environment.getDataUserDirectory(volumeUuid).listFiles(); 15537 if (ArrayUtils.isEmpty(files)) { 15538 Slog.d(TAG, "No users found on " + volumeUuid); 15539 return; 15540 } 15541 15542 for (File file : files) { 15543 if (!file.isDirectory()) continue; 15544 15545 final int userId; 15546 final UserInfo info; 15547 try { 15548 userId = Integer.parseInt(file.getName()); 15549 info = sUserManager.getUserInfo(userId); 15550 } catch (NumberFormatException e) { 15551 Slog.w(TAG, "Invalid user directory " + file); 15552 continue; 15553 } 15554 15555 boolean destroyUser = false; 15556 if (info == null) { 15557 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15558 + " because no matching user was found"); 15559 destroyUser = true; 15560 } else { 15561 try { 15562 UserManagerService.enforceSerialNumber(file, info.serialNumber); 15563 } catch (IOException e) { 15564 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15565 + " because we failed to enforce serial number: " + e); 15566 destroyUser = true; 15567 } 15568 } 15569 15570 if (destroyUser) { 15571 synchronized (mInstallLock) { 15572 mInstaller.removeUserDataDirs(volumeUuid, userId); 15573 } 15574 } 15575 } 15576 15577 final UserManager um = mContext.getSystemService(UserManager.class); 15578 for (UserInfo user : um.getUsers()) { 15579 final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id); 15580 if (userDir.exists()) continue; 15581 15582 try { 15583 UserManagerService.prepareUserDirectory(mContext, volumeUuid, user.id); 15584 UserManagerService.enforceSerialNumber(userDir, user.serialNumber); 15585 } catch (IOException e) { 15586 Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e); 15587 } 15588 } 15589 } 15590 15591 /** 15592 * Examine all apps present on given mounted volume, and destroy apps that 15593 * aren't expected, either due to uninstallation or reinstallation on 15594 * another volume. 15595 */ 15596 private void reconcileApps(String volumeUuid) { 15597 final File[] files = Environment.getDataAppDirectory(volumeUuid).listFiles(); 15598 if (ArrayUtils.isEmpty(files)) { 15599 Slog.d(TAG, "No apps found on " + volumeUuid); 15600 return; 15601 } 15602 15603 for (File file : files) { 15604 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 15605 && !PackageInstallerService.isStageName(file.getName()); 15606 if (!isPackage) { 15607 // Ignore entries which are not packages 15608 continue; 15609 } 15610 15611 boolean destroyApp = false; 15612 String packageName = null; 15613 try { 15614 final PackageLite pkg = PackageParser.parsePackageLite(file, 15615 PackageParser.PARSE_MUST_BE_APK); 15616 packageName = pkg.packageName; 15617 15618 synchronized (mPackages) { 15619 final PackageSetting ps = mSettings.mPackages.get(packageName); 15620 if (ps == null) { 15621 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + " 15622 + volumeUuid + " because we found no install record"); 15623 destroyApp = true; 15624 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 15625 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on " 15626 + volumeUuid + " because we expected it on " + ps.volumeUuid); 15627 destroyApp = true; 15628 } 15629 } 15630 15631 } catch (PackageParserException e) { 15632 logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e); 15633 destroyApp = true; 15634 } 15635 15636 if (destroyApp) { 15637 synchronized (mInstallLock) { 15638 if (packageName != null) { 15639 removeDataDirsLI(volumeUuid, packageName); 15640 } 15641 if (file.isDirectory()) { 15642 mInstaller.rmPackageDir(file.getAbsolutePath()); 15643 } else { 15644 file.delete(); 15645 } 15646 } 15647 } 15648 } 15649 } 15650 15651 private void unfreezePackage(String packageName) { 15652 synchronized (mPackages) { 15653 final PackageSetting ps = mSettings.mPackages.get(packageName); 15654 if (ps != null) { 15655 ps.frozen = false; 15656 } 15657 } 15658 } 15659 15660 @Override 15661 public int movePackage(final String packageName, final String volumeUuid) { 15662 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15663 15664 final int moveId = mNextMoveId.getAndIncrement(); 15665 try { 15666 movePackageInternal(packageName, volumeUuid, moveId); 15667 } catch (PackageManagerException e) { 15668 Slog.w(TAG, "Failed to move " + packageName, e); 15669 mMoveCallbacks.notifyStatusChanged(moveId, 15670 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15671 } 15672 return moveId; 15673 } 15674 15675 private void movePackageInternal(final String packageName, final String volumeUuid, 15676 final int moveId) throws PackageManagerException { 15677 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 15678 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15679 final PackageManager pm = mContext.getPackageManager(); 15680 15681 final boolean currentAsec; 15682 final String currentVolumeUuid; 15683 final File codeFile; 15684 final String installerPackageName; 15685 final String packageAbiOverride; 15686 final int appId; 15687 final String seinfo; 15688 final String label; 15689 15690 // reader 15691 synchronized (mPackages) { 15692 final PackageParser.Package pkg = mPackages.get(packageName); 15693 final PackageSetting ps = mSettings.mPackages.get(packageName); 15694 if (pkg == null || ps == null) { 15695 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 15696 } 15697 15698 if (pkg.applicationInfo.isSystemApp()) { 15699 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 15700 "Cannot move system application"); 15701 } 15702 15703 if (Objects.equals(ps.volumeUuid, volumeUuid)) { 15704 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15705 "Package already moved to " + volumeUuid); 15706 } 15707 15708 final File probe = new File(pkg.codePath); 15709 final File probeOat = new File(probe, "oat"); 15710 if (!probe.isDirectory() || !probeOat.isDirectory()) { 15711 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15712 "Move only supported for modern cluster style installs"); 15713 } 15714 15715 if (ps.frozen) { 15716 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 15717 "Failed to move already frozen package"); 15718 } 15719 ps.frozen = true; 15720 15721 currentAsec = pkg.applicationInfo.isForwardLocked() 15722 || pkg.applicationInfo.isExternalAsec(); 15723 currentVolumeUuid = ps.volumeUuid; 15724 codeFile = new File(pkg.codePath); 15725 installerPackageName = ps.installerPackageName; 15726 packageAbiOverride = ps.cpuAbiOverrideString; 15727 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 15728 seinfo = pkg.applicationInfo.seinfo; 15729 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 15730 } 15731 15732 // Now that we're guarded by frozen state, kill app during move 15733 killApplication(packageName, appId, "move pkg"); 15734 15735 final Bundle extras = new Bundle(); 15736 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 15737 extras.putString(Intent.EXTRA_TITLE, label); 15738 mMoveCallbacks.notifyCreated(moveId, extras); 15739 15740 int installFlags; 15741 final boolean moveCompleteApp; 15742 final File measurePath; 15743 15744 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 15745 installFlags = INSTALL_INTERNAL; 15746 moveCompleteApp = !currentAsec; 15747 measurePath = Environment.getDataAppDirectory(volumeUuid); 15748 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 15749 installFlags = INSTALL_EXTERNAL; 15750 moveCompleteApp = false; 15751 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 15752 } else { 15753 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 15754 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 15755 || !volume.isMountedWritable()) { 15756 unfreezePackage(packageName); 15757 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15758 "Move location not mounted private volume"); 15759 } 15760 15761 Preconditions.checkState(!currentAsec); 15762 15763 installFlags = INSTALL_INTERNAL; 15764 moveCompleteApp = true; 15765 measurePath = Environment.getDataAppDirectory(volumeUuid); 15766 } 15767 15768 final PackageStats stats = new PackageStats(null, -1); 15769 synchronized (mInstaller) { 15770 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 15771 unfreezePackage(packageName); 15772 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15773 "Failed to measure package size"); 15774 } 15775 } 15776 15777 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 15778 + stats.dataSize); 15779 15780 final long startFreeBytes = measurePath.getFreeSpace(); 15781 final long sizeBytes; 15782 if (moveCompleteApp) { 15783 sizeBytes = stats.codeSize + stats.dataSize; 15784 } else { 15785 sizeBytes = stats.codeSize; 15786 } 15787 15788 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 15789 unfreezePackage(packageName); 15790 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15791 "Not enough free space to move"); 15792 } 15793 15794 mMoveCallbacks.notifyStatusChanged(moveId, 10); 15795 15796 final CountDownLatch installedLatch = new CountDownLatch(1); 15797 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 15798 @Override 15799 public void onUserActionRequired(Intent intent) throws RemoteException { 15800 throw new IllegalStateException(); 15801 } 15802 15803 @Override 15804 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 15805 Bundle extras) throws RemoteException { 15806 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 15807 + PackageManager.installStatusToString(returnCode, msg)); 15808 15809 installedLatch.countDown(); 15810 15811 // Regardless of success or failure of the move operation, 15812 // always unfreeze the package 15813 unfreezePackage(packageName); 15814 15815 final int status = PackageManager.installStatusToPublicStatus(returnCode); 15816 switch (status) { 15817 case PackageInstaller.STATUS_SUCCESS: 15818 mMoveCallbacks.notifyStatusChanged(moveId, 15819 PackageManager.MOVE_SUCCEEDED); 15820 break; 15821 case PackageInstaller.STATUS_FAILURE_STORAGE: 15822 mMoveCallbacks.notifyStatusChanged(moveId, 15823 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 15824 break; 15825 default: 15826 mMoveCallbacks.notifyStatusChanged(moveId, 15827 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15828 break; 15829 } 15830 } 15831 }; 15832 15833 final MoveInfo move; 15834 if (moveCompleteApp) { 15835 // Kick off a thread to report progress estimates 15836 new Thread() { 15837 @Override 15838 public void run() { 15839 while (true) { 15840 try { 15841 if (installedLatch.await(1, TimeUnit.SECONDS)) { 15842 break; 15843 } 15844 } catch (InterruptedException ignored) { 15845 } 15846 15847 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 15848 final int progress = 10 + (int) MathUtils.constrain( 15849 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 15850 mMoveCallbacks.notifyStatusChanged(moveId, progress); 15851 } 15852 } 15853 }.start(); 15854 15855 final String dataAppName = codeFile.getName(); 15856 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 15857 dataAppName, appId, seinfo); 15858 } else { 15859 move = null; 15860 } 15861 15862 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 15863 15864 final Message msg = mHandler.obtainMessage(INIT_COPY); 15865 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 15866 msg.obj = new InstallParams(origin, move, installObserver, installFlags, 15867 installerPackageName, volumeUuid, null, user, packageAbiOverride); 15868 mHandler.sendMessage(msg); 15869 } 15870 15871 @Override 15872 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 15873 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15874 15875 final int realMoveId = mNextMoveId.getAndIncrement(); 15876 final Bundle extras = new Bundle(); 15877 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 15878 mMoveCallbacks.notifyCreated(realMoveId, extras); 15879 15880 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 15881 @Override 15882 public void onCreated(int moveId, Bundle extras) { 15883 // Ignored 15884 } 15885 15886 @Override 15887 public void onStatusChanged(int moveId, int status, long estMillis) { 15888 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 15889 } 15890 }; 15891 15892 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15893 storage.setPrimaryStorageUuid(volumeUuid, callback); 15894 return realMoveId; 15895 } 15896 15897 @Override 15898 public int getMoveStatus(int moveId) { 15899 mContext.enforceCallingOrSelfPermission( 15900 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15901 return mMoveCallbacks.mLastStatus.get(moveId); 15902 } 15903 15904 @Override 15905 public void registerMoveCallback(IPackageMoveObserver callback) { 15906 mContext.enforceCallingOrSelfPermission( 15907 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15908 mMoveCallbacks.register(callback); 15909 } 15910 15911 @Override 15912 public void unregisterMoveCallback(IPackageMoveObserver callback) { 15913 mContext.enforceCallingOrSelfPermission( 15914 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15915 mMoveCallbacks.unregister(callback); 15916 } 15917 15918 @Override 15919 public boolean setInstallLocation(int loc) { 15920 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 15921 null); 15922 if (getInstallLocation() == loc) { 15923 return true; 15924 } 15925 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 15926 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 15927 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 15928 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 15929 return true; 15930 } 15931 return false; 15932 } 15933 15934 @Override 15935 public int getInstallLocation() { 15936 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 15937 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 15938 PackageHelper.APP_INSTALL_AUTO); 15939 } 15940 15941 /** Called by UserManagerService */ 15942 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 15943 mDirtyUsers.remove(userHandle); 15944 mSettings.removeUserLPw(userHandle); 15945 mPendingBroadcasts.remove(userHandle); 15946 if (mInstaller != null) { 15947 // Technically, we shouldn't be doing this with the package lock 15948 // held. However, this is very rare, and there is already so much 15949 // other disk I/O going on, that we'll let it slide for now. 15950 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15951 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 15952 final String volumeUuid = vol.getFsUuid(); 15953 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 15954 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 15955 } 15956 } 15957 mUserNeedsBadging.delete(userHandle); 15958 removeUnusedPackagesLILPw(userManager, userHandle); 15959 } 15960 15961 /** 15962 * We're removing userHandle and would like to remove any downloaded packages 15963 * that are no longer in use by any other user. 15964 * @param userHandle the user being removed 15965 */ 15966 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 15967 final boolean DEBUG_CLEAN_APKS = false; 15968 int [] users = userManager.getUserIdsLPr(); 15969 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 15970 while (psit.hasNext()) { 15971 PackageSetting ps = psit.next(); 15972 if (ps.pkg == null) { 15973 continue; 15974 } 15975 final String packageName = ps.pkg.packageName; 15976 // Skip over if system app 15977 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 15978 continue; 15979 } 15980 if (DEBUG_CLEAN_APKS) { 15981 Slog.i(TAG, "Checking package " + packageName); 15982 } 15983 boolean keep = false; 15984 for (int i = 0; i < users.length; i++) { 15985 if (users[i] != userHandle && ps.getInstalled(users[i])) { 15986 keep = true; 15987 if (DEBUG_CLEAN_APKS) { 15988 Slog.i(TAG, " Keeping package " + packageName + " for user " 15989 + users[i]); 15990 } 15991 break; 15992 } 15993 } 15994 if (!keep) { 15995 if (DEBUG_CLEAN_APKS) { 15996 Slog.i(TAG, " Removing package " + packageName); 15997 } 15998 mHandler.post(new Runnable() { 15999 public void run() { 16000 deletePackageX(packageName, userHandle, 0); 16001 } //end run 16002 }); 16003 } 16004 } 16005 } 16006 16007 /** Called by UserManagerService */ 16008 void createNewUserLILPw(int userHandle) { 16009 if (mInstaller != null) { 16010 mInstaller.createUserConfig(userHandle); 16011 mSettings.createNewUserLILPw(this, mInstaller, userHandle); 16012 applyFactoryDefaultBrowserLPw(userHandle); 16013 primeDomainVerificationsLPw(userHandle); 16014 } 16015 } 16016 16017 void newUserCreated(final int userHandle) { 16018 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 16019 } 16020 16021 @Override 16022 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 16023 mContext.enforceCallingOrSelfPermission( 16024 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 16025 "Only package verification agents can read the verifier device identity"); 16026 16027 synchronized (mPackages) { 16028 return mSettings.getVerifierDeviceIdentityLPw(); 16029 } 16030 } 16031 16032 @Override 16033 public void setPermissionEnforced(String permission, boolean enforced) { 16034 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 16035 if (READ_EXTERNAL_STORAGE.equals(permission)) { 16036 synchronized (mPackages) { 16037 if (mSettings.mReadExternalStorageEnforced == null 16038 || mSettings.mReadExternalStorageEnforced != enforced) { 16039 mSettings.mReadExternalStorageEnforced = enforced; 16040 mSettings.writeLPr(); 16041 } 16042 } 16043 // kill any non-foreground processes so we restart them and 16044 // grant/revoke the GID. 16045 final IActivityManager am = ActivityManagerNative.getDefault(); 16046 if (am != null) { 16047 final long token = Binder.clearCallingIdentity(); 16048 try { 16049 am.killProcessesBelowForeground("setPermissionEnforcement"); 16050 } catch (RemoteException e) { 16051 } finally { 16052 Binder.restoreCallingIdentity(token); 16053 } 16054 } 16055 } else { 16056 throw new IllegalArgumentException("No selective enforcement for " + permission); 16057 } 16058 } 16059 16060 @Override 16061 @Deprecated 16062 public boolean isPermissionEnforced(String permission) { 16063 return true; 16064 } 16065 16066 @Override 16067 public boolean isStorageLow() { 16068 final long token = Binder.clearCallingIdentity(); 16069 try { 16070 final DeviceStorageMonitorInternal 16071 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 16072 if (dsm != null) { 16073 return dsm.isMemoryLow(); 16074 } else { 16075 return false; 16076 } 16077 } finally { 16078 Binder.restoreCallingIdentity(token); 16079 } 16080 } 16081 16082 @Override 16083 public IPackageInstaller getPackageInstaller() { 16084 return mInstallerService; 16085 } 16086 16087 private boolean userNeedsBadging(int userId) { 16088 int index = mUserNeedsBadging.indexOfKey(userId); 16089 if (index < 0) { 16090 final UserInfo userInfo; 16091 final long token = Binder.clearCallingIdentity(); 16092 try { 16093 userInfo = sUserManager.getUserInfo(userId); 16094 } finally { 16095 Binder.restoreCallingIdentity(token); 16096 } 16097 final boolean b; 16098 if (userInfo != null && userInfo.isManagedProfile()) { 16099 b = true; 16100 } else { 16101 b = false; 16102 } 16103 mUserNeedsBadging.put(userId, b); 16104 return b; 16105 } 16106 return mUserNeedsBadging.valueAt(index); 16107 } 16108 16109 @Override 16110 public KeySet getKeySetByAlias(String packageName, String alias) { 16111 if (packageName == null || alias == null) { 16112 return null; 16113 } 16114 synchronized(mPackages) { 16115 final PackageParser.Package pkg = mPackages.get(packageName); 16116 if (pkg == null) { 16117 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16118 throw new IllegalArgumentException("Unknown package: " + packageName); 16119 } 16120 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16121 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 16122 } 16123 } 16124 16125 @Override 16126 public KeySet getSigningKeySet(String packageName) { 16127 if (packageName == null) { 16128 return null; 16129 } 16130 synchronized(mPackages) { 16131 final PackageParser.Package pkg = mPackages.get(packageName); 16132 if (pkg == null) { 16133 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16134 throw new IllegalArgumentException("Unknown package: " + packageName); 16135 } 16136 if (pkg.applicationInfo.uid != Binder.getCallingUid() 16137 && Process.SYSTEM_UID != Binder.getCallingUid()) { 16138 throw new SecurityException("May not access signing KeySet of other apps."); 16139 } 16140 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16141 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 16142 } 16143 } 16144 16145 @Override 16146 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 16147 if (packageName == null || ks == null) { 16148 return false; 16149 } 16150 synchronized(mPackages) { 16151 final PackageParser.Package pkg = mPackages.get(packageName); 16152 if (pkg == null) { 16153 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16154 throw new IllegalArgumentException("Unknown package: " + packageName); 16155 } 16156 IBinder ksh = ks.getToken(); 16157 if (ksh instanceof KeySetHandle) { 16158 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16159 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 16160 } 16161 return false; 16162 } 16163 } 16164 16165 @Override 16166 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 16167 if (packageName == null || ks == null) { 16168 return false; 16169 } 16170 synchronized(mPackages) { 16171 final PackageParser.Package pkg = mPackages.get(packageName); 16172 if (pkg == null) { 16173 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16174 throw new IllegalArgumentException("Unknown package: " + packageName); 16175 } 16176 IBinder ksh = ks.getToken(); 16177 if (ksh instanceof KeySetHandle) { 16178 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16179 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 16180 } 16181 return false; 16182 } 16183 } 16184 16185 public void getUsageStatsIfNoPackageUsageInfo() { 16186 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 16187 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 16188 if (usm == null) { 16189 throw new IllegalStateException("UsageStatsManager must be initialized"); 16190 } 16191 long now = System.currentTimeMillis(); 16192 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 16193 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 16194 String packageName = entry.getKey(); 16195 PackageParser.Package pkg = mPackages.get(packageName); 16196 if (pkg == null) { 16197 continue; 16198 } 16199 UsageStats usage = entry.getValue(); 16200 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 16201 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 16202 } 16203 } 16204 } 16205 16206 /** 16207 * Check and throw if the given before/after packages would be considered a 16208 * downgrade. 16209 */ 16210 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 16211 throws PackageManagerException { 16212 if (after.versionCode < before.mVersionCode) { 16213 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16214 "Update version code " + after.versionCode + " is older than current " 16215 + before.mVersionCode); 16216 } else if (after.versionCode == before.mVersionCode) { 16217 if (after.baseRevisionCode < before.baseRevisionCode) { 16218 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16219 "Update base revision code " + after.baseRevisionCode 16220 + " is older than current " + before.baseRevisionCode); 16221 } 16222 16223 if (!ArrayUtils.isEmpty(after.splitNames)) { 16224 for (int i = 0; i < after.splitNames.length; i++) { 16225 final String splitName = after.splitNames[i]; 16226 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 16227 if (j != -1) { 16228 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 16229 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16230 "Update split " + splitName + " revision code " 16231 + after.splitRevisionCodes[i] + " is older than current " 16232 + before.splitRevisionCodes[j]); 16233 } 16234 } 16235 } 16236 } 16237 } 16238 } 16239 16240 private static class MoveCallbacks extends Handler { 16241 private static final int MSG_CREATED = 1; 16242 private static final int MSG_STATUS_CHANGED = 2; 16243 16244 private final RemoteCallbackList<IPackageMoveObserver> 16245 mCallbacks = new RemoteCallbackList<>(); 16246 16247 private final SparseIntArray mLastStatus = new SparseIntArray(); 16248 16249 public MoveCallbacks(Looper looper) { 16250 super(looper); 16251 } 16252 16253 public void register(IPackageMoveObserver callback) { 16254 mCallbacks.register(callback); 16255 } 16256 16257 public void unregister(IPackageMoveObserver callback) { 16258 mCallbacks.unregister(callback); 16259 } 16260 16261 @Override 16262 public void handleMessage(Message msg) { 16263 final SomeArgs args = (SomeArgs) msg.obj; 16264 final int n = mCallbacks.beginBroadcast(); 16265 for (int i = 0; i < n; i++) { 16266 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 16267 try { 16268 invokeCallback(callback, msg.what, args); 16269 } catch (RemoteException ignored) { 16270 } 16271 } 16272 mCallbacks.finishBroadcast(); 16273 args.recycle(); 16274 } 16275 16276 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 16277 throws RemoteException { 16278 switch (what) { 16279 case MSG_CREATED: { 16280 callback.onCreated(args.argi1, (Bundle) args.arg2); 16281 break; 16282 } 16283 case MSG_STATUS_CHANGED: { 16284 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 16285 break; 16286 } 16287 } 16288 } 16289 16290 private void notifyCreated(int moveId, Bundle extras) { 16291 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 16292 16293 final SomeArgs args = SomeArgs.obtain(); 16294 args.argi1 = moveId; 16295 args.arg2 = extras; 16296 obtainMessage(MSG_CREATED, args).sendToTarget(); 16297 } 16298 16299 private void notifyStatusChanged(int moveId, int status) { 16300 notifyStatusChanged(moveId, status, -1); 16301 } 16302 16303 private void notifyStatusChanged(int moveId, int status, long estMillis) { 16304 Slog.v(TAG, "Move " + moveId + " status " + status); 16305 16306 final SomeArgs args = SomeArgs.obtain(); 16307 args.argi1 = moveId; 16308 args.argi2 = status; 16309 args.arg3 = estMillis; 16310 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 16311 16312 synchronized (mLastStatus) { 16313 mLastStatus.put(moveId, status); 16314 } 16315 } 16316 } 16317 16318 private final class OnPermissionChangeListeners extends Handler { 16319 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 16320 16321 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 16322 new RemoteCallbackList<>(); 16323 16324 public OnPermissionChangeListeners(Looper looper) { 16325 super(looper); 16326 } 16327 16328 @Override 16329 public void handleMessage(Message msg) { 16330 switch (msg.what) { 16331 case MSG_ON_PERMISSIONS_CHANGED: { 16332 final int uid = msg.arg1; 16333 handleOnPermissionsChanged(uid); 16334 } break; 16335 } 16336 } 16337 16338 public void addListenerLocked(IOnPermissionsChangeListener listener) { 16339 mPermissionListeners.register(listener); 16340 16341 } 16342 16343 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 16344 mPermissionListeners.unregister(listener); 16345 } 16346 16347 public void onPermissionsChanged(int uid) { 16348 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 16349 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 16350 } 16351 } 16352 16353 private void handleOnPermissionsChanged(int uid) { 16354 final int count = mPermissionListeners.beginBroadcast(); 16355 try { 16356 for (int i = 0; i < count; i++) { 16357 IOnPermissionsChangeListener callback = mPermissionListeners 16358 .getBroadcastItem(i); 16359 try { 16360 callback.onPermissionsChanged(uid); 16361 } catch (RemoteException e) { 16362 Log.e(TAG, "Permission listener is dead", e); 16363 } 16364 } 16365 } finally { 16366 mPermissionListeners.finishBroadcast(); 16367 } 16368 } 16369 } 16370 16371 private class PackageManagerInternalImpl extends PackageManagerInternal { 16372 @Override 16373 public void setLocationPackagesProvider(PackagesProvider provider) { 16374 synchronized (mPackages) { 16375 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 16376 } 16377 } 16378 16379 @Override 16380 public void setImePackagesProvider(PackagesProvider provider) { 16381 synchronized (mPackages) { 16382 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 16383 } 16384 } 16385 16386 @Override 16387 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 16388 synchronized (mPackages) { 16389 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 16390 } 16391 } 16392 16393 @Override 16394 public void setSmsAppPackagesProvider(PackagesProvider provider) { 16395 synchronized (mPackages) { 16396 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 16397 } 16398 } 16399 16400 @Override 16401 public void setDialerAppPackagesProvider(PackagesProvider provider) { 16402 synchronized (mPackages) { 16403 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 16404 } 16405 } 16406 16407 @Override 16408 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 16409 synchronized (mPackages) { 16410 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderrLPw(provider); 16411 } 16412 } 16413 16414 @Override 16415 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 16416 synchronized (mPackages) { 16417 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 16418 packageName, userId); 16419 } 16420 } 16421 16422 @Override 16423 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 16424 synchronized (mPackages) { 16425 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 16426 packageName, userId); 16427 } 16428 } 16429 } 16430 16431 @Override 16432 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 16433 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 16434 synchronized (mPackages) { 16435 final long identity = Binder.clearCallingIdentity(); 16436 try { 16437 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 16438 packageNames, userId); 16439 } finally { 16440 Binder.restoreCallingIdentity(identity); 16441 } 16442 } 16443 } 16444 16445 private static void enforceSystemOrPhoneCaller(String tag) { 16446 int callingUid = Binder.getCallingUid(); 16447 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 16448 throw new SecurityException( 16449 "Cannot call " + tag + " from UID " + callingUid); 16450 } 16451 } 16452} 16453