PackageManagerService.java revision 171fe6ac0aa5b0d2dd64ac1cdda25cdcb5f183f3
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_GRANTED; 66import static android.content.pm.PackageParser.isApkFile; 67import static android.os.Process.PACKAGE_INFO_GID; 68import static android.os.Process.SYSTEM_UID; 69import static android.system.OsConstants.O_CREAT; 70import static android.system.OsConstants.O_RDWR; 71import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 72import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER; 73import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 74import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 75import static com.android.internal.util.ArrayUtils.appendInt; 76import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 77import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 78import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 79import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 80import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 81import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 82import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 83import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 84 85import android.Manifest; 86import android.app.ActivityManager; 87import android.app.ActivityManagerNative; 88import android.app.AppGlobals; 89import android.app.IActivityManager; 90import android.app.admin.IDevicePolicyManager; 91import android.app.backup.IBackupManager; 92import android.app.usage.UsageStats; 93import android.app.usage.UsageStatsManager; 94import android.content.BroadcastReceiver; 95import android.content.ComponentName; 96import android.content.Context; 97import android.content.IIntentReceiver; 98import android.content.Intent; 99import android.content.IntentFilter; 100import android.content.IntentSender; 101import android.content.IntentSender.SendIntentException; 102import android.content.ServiceConnection; 103import android.content.pm.ActivityInfo; 104import android.content.pm.ApplicationInfo; 105import android.content.pm.FeatureInfo; 106import android.content.pm.IOnPermissionsChangeListener; 107import android.content.pm.IPackageDataObserver; 108import android.content.pm.IPackageDeleteObserver; 109import android.content.pm.IPackageDeleteObserver2; 110import android.content.pm.IPackageInstallObserver2; 111import android.content.pm.IPackageInstaller; 112import android.content.pm.IPackageManager; 113import android.content.pm.IPackageMoveObserver; 114import android.content.pm.IPackageStatsObserver; 115import android.content.pm.InstrumentationInfo; 116import android.content.pm.IntentFilterVerificationInfo; 117import android.content.pm.KeySet; 118import android.content.pm.ManifestDigest; 119import android.content.pm.PackageCleanItem; 120import android.content.pm.PackageInfo; 121import android.content.pm.PackageInfoLite; 122import android.content.pm.PackageInstaller; 123import android.content.pm.PackageManager; 124import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 125import android.content.pm.PackageManagerInternal; 126import android.content.pm.PackageParser; 127import android.content.pm.PackageParser.ActivityIntentInfo; 128import android.content.pm.PackageParser.PackageLite; 129import android.content.pm.PackageParser.PackageParserException; 130import android.content.pm.PackageStats; 131import android.content.pm.PackageUserState; 132import android.content.pm.ParceledListSlice; 133import android.content.pm.PermissionGroupInfo; 134import android.content.pm.PermissionInfo; 135import android.content.pm.ProviderInfo; 136import android.content.pm.ResolveInfo; 137import android.content.pm.ServiceInfo; 138import android.content.pm.Signature; 139import android.content.pm.UserInfo; 140import android.content.pm.VerificationParams; 141import android.content.pm.VerifierDeviceIdentity; 142import android.content.pm.VerifierInfo; 143import android.content.res.Resources; 144import android.hardware.display.DisplayManager; 145import android.net.Uri; 146import android.os.Binder; 147import android.os.Build; 148import android.os.Bundle; 149import android.os.Debug; 150import android.os.Environment; 151import android.os.Environment.UserEnvironment; 152import android.os.FileUtils; 153import android.os.Handler; 154import android.os.IBinder; 155import android.os.Looper; 156import android.os.Message; 157import android.os.Parcel; 158import android.os.ParcelFileDescriptor; 159import android.os.Process; 160import android.os.RemoteCallbackList; 161import android.os.RemoteException; 162import android.os.SELinux; 163import android.os.ServiceManager; 164import android.os.SystemClock; 165import android.os.SystemProperties; 166import android.os.UserHandle; 167import android.os.UserManager; 168import android.os.storage.IMountService; 169import android.os.storage.StorageEventListener; 170import android.os.storage.StorageManager; 171import android.os.storage.VolumeInfo; 172import android.os.storage.VolumeRecord; 173import android.security.KeyStore; 174import android.security.SystemKeyStore; 175import android.system.ErrnoException; 176import android.system.Os; 177import android.system.StructStat; 178import android.text.TextUtils; 179import android.text.format.DateUtils; 180import android.util.ArrayMap; 181import android.util.ArraySet; 182import android.util.AtomicFile; 183import android.util.DisplayMetrics; 184import android.util.EventLog; 185import android.util.ExceptionUtils; 186import android.util.Log; 187import android.util.LogPrinter; 188import android.util.MathUtils; 189import android.util.PrintStreamPrinter; 190import android.util.Slog; 191import android.util.SparseArray; 192import android.util.SparseBooleanArray; 193import android.util.SparseIntArray; 194import android.util.Xml; 195import android.view.Display; 196 197import dalvik.system.DexFile; 198import dalvik.system.VMRuntime; 199 200import libcore.io.IoUtils; 201import libcore.util.EmptyArray; 202 203import com.android.internal.R; 204import com.android.internal.annotations.GuardedBy; 205import com.android.internal.app.IMediaContainerService; 206import com.android.internal.app.ResolverActivity; 207import com.android.internal.content.NativeLibraryHelper; 208import com.android.internal.content.PackageHelper; 209import com.android.internal.os.IParcelFileDescriptorFactory; 210import com.android.internal.os.SomeArgs; 211import com.android.internal.os.Zygote; 212import com.android.internal.util.ArrayUtils; 213import com.android.internal.util.FastPrintWriter; 214import com.android.internal.util.FastXmlSerializer; 215import com.android.internal.util.IndentingPrintWriter; 216import com.android.internal.util.Preconditions; 217import com.android.server.EventLogTags; 218import com.android.server.FgThread; 219import com.android.server.IntentResolver; 220import com.android.server.LocalServices; 221import com.android.server.ServiceThread; 222import com.android.server.SystemConfig; 223import com.android.server.Watchdog; 224import com.android.server.pm.PermissionsState.PermissionState; 225import com.android.server.pm.Settings.DatabaseVersion; 226import com.android.server.storage.DeviceStorageMonitorInternal; 227 228import org.xmlpull.v1.XmlPullParser; 229import org.xmlpull.v1.XmlPullParserException; 230import org.xmlpull.v1.XmlSerializer; 231 232import java.io.BufferedInputStream; 233import java.io.BufferedOutputStream; 234import java.io.BufferedReader; 235import java.io.ByteArrayInputStream; 236import java.io.ByteArrayOutputStream; 237import java.io.File; 238import java.io.FileDescriptor; 239import java.io.FileNotFoundException; 240import java.io.FileOutputStream; 241import java.io.FileReader; 242import java.io.FilenameFilter; 243import java.io.IOException; 244import java.io.InputStream; 245import java.io.PrintWriter; 246import java.nio.charset.StandardCharsets; 247import java.security.NoSuchAlgorithmException; 248import java.security.PublicKey; 249import java.security.cert.CertificateEncodingException; 250import java.security.cert.CertificateException; 251import java.text.SimpleDateFormat; 252import java.util.ArrayList; 253import java.util.Arrays; 254import java.util.Collection; 255import java.util.Collections; 256import java.util.Comparator; 257import java.util.Date; 258import java.util.Iterator; 259import java.util.List; 260import java.util.Map; 261import java.util.Objects; 262import java.util.Set; 263import java.util.concurrent.CountDownLatch; 264import java.util.concurrent.TimeUnit; 265import java.util.concurrent.atomic.AtomicBoolean; 266import java.util.concurrent.atomic.AtomicInteger; 267import java.util.concurrent.atomic.AtomicLong; 268 269/** 270 * Keep track of all those .apks everywhere. 271 * 272 * This is very central to the platform's security; please run the unit 273 * tests whenever making modifications here: 274 * 275mmm frameworks/base/tests/AndroidTests 276adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 277adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 278 * 279 * {@hide} 280 */ 281public class PackageManagerService extends IPackageManager.Stub { 282 static final String TAG = "PackageManager"; 283 static final boolean DEBUG_SETTINGS = false; 284 static final boolean DEBUG_PREFERRED = false; 285 static final boolean DEBUG_UPGRADE = false; 286 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 287 private static final boolean DEBUG_BACKUP = true; 288 private static final boolean DEBUG_INSTALL = false; 289 private static final boolean DEBUG_REMOVE = false; 290 private static final boolean DEBUG_BROADCASTS = false; 291 private static final boolean DEBUG_SHOW_INFO = false; 292 private static final boolean DEBUG_PACKAGE_INFO = false; 293 private static final boolean DEBUG_INTENT_MATCHING = false; 294 private static final boolean DEBUG_PACKAGE_SCANNING = false; 295 private static final boolean DEBUG_VERIFY = false; 296 private static final boolean DEBUG_DEXOPT = false; 297 private static final boolean DEBUG_ABI_SELECTION = false; 298 299 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = Build.IS_DEBUGGABLE; 300 301 private static final int RADIO_UID = Process.PHONE_UID; 302 private static final int LOG_UID = Process.LOG_UID; 303 private static final int NFC_UID = Process.NFC_UID; 304 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 305 private static final int SHELL_UID = Process.SHELL_UID; 306 307 // Cap the size of permission trees that 3rd party apps can define 308 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 309 310 // Suffix used during package installation when copying/moving 311 // package apks to install directory. 312 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 313 314 static final int SCAN_NO_DEX = 1<<1; 315 static final int SCAN_FORCE_DEX = 1<<2; 316 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 317 static final int SCAN_NEW_INSTALL = 1<<4; 318 static final int SCAN_NO_PATHS = 1<<5; 319 static final int SCAN_UPDATE_TIME = 1<<6; 320 static final int SCAN_DEFER_DEX = 1<<7; 321 static final int SCAN_BOOTING = 1<<8; 322 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 323 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 324 static final int SCAN_REQUIRE_KNOWN = 1<<12; 325 static final int SCAN_MOVE = 1<<13; 326 static final int SCAN_INITIAL = 1<<14; 327 328 static final int REMOVE_CHATTY = 1<<16; 329 330 private static final int[] EMPTY_INT_ARRAY = new int[0]; 331 332 /** 333 * Timeout (in milliseconds) after which the watchdog should declare that 334 * our handler thread is wedged. The usual default for such things is one 335 * minute but we sometimes do very lengthy I/O operations on this thread, 336 * such as installing multi-gigabyte applications, so ours needs to be longer. 337 */ 338 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 339 340 /** 341 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 342 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 343 * settings entry if available, otherwise we use the hardcoded default. If it's been 344 * more than this long since the last fstrim, we force one during the boot sequence. 345 * 346 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 347 * one gets run at the next available charging+idle time. This final mandatory 348 * no-fstrim check kicks in only of the other scheduling criteria is never met. 349 */ 350 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 351 352 /** 353 * Whether verification is enabled by default. 354 */ 355 private static final boolean DEFAULT_VERIFY_ENABLE = true; 356 357 /** 358 * The default maximum time to wait for the verification agent to return in 359 * milliseconds. 360 */ 361 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 362 363 /** 364 * The default response for package verification timeout. 365 * 366 * This can be either PackageManager.VERIFICATION_ALLOW or 367 * PackageManager.VERIFICATION_REJECT. 368 */ 369 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 370 371 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 372 373 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 374 DEFAULT_CONTAINER_PACKAGE, 375 "com.android.defcontainer.DefaultContainerService"); 376 377 private static final String KILL_APP_REASON_GIDS_CHANGED = 378 "permission grant or revoke changed gids"; 379 380 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 381 "permissions revoked"; 382 383 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 384 385 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 386 387 /** Permission grant: not grant the permission. */ 388 private static final int GRANT_DENIED = 1; 389 390 /** Permission grant: grant the permission as an install permission. */ 391 private static final int GRANT_INSTALL = 2; 392 393 /** Permission grant: grant the permission as an install permission for a legacy app. */ 394 private static final int GRANT_INSTALL_LEGACY = 3; 395 396 /** Permission grant: grant the permission as a runtime one. */ 397 private static final int GRANT_RUNTIME = 4; 398 399 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 400 private static final int GRANT_UPGRADE = 5; 401 402 /** Canonical intent used to identify what counts as a "web browser" app */ 403 private static final Intent sBrowserIntent; 404 static { 405 sBrowserIntent = new Intent(); 406 sBrowserIntent.setAction(Intent.ACTION_VIEW); 407 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 408 sBrowserIntent.setData(Uri.parse("http:")); 409 } 410 411 final ServiceThread mHandlerThread; 412 413 final PackageHandler mHandler; 414 415 /** 416 * Messages for {@link #mHandler} that need to wait for system ready before 417 * being dispatched. 418 */ 419 private ArrayList<Message> mPostSystemReadyMessages; 420 421 final int mSdkVersion = Build.VERSION.SDK_INT; 422 423 final Context mContext; 424 final boolean mFactoryTest; 425 final boolean mOnlyCore; 426 final boolean mLazyDexOpt; 427 final long mDexOptLRUThresholdInMills; 428 final DisplayMetrics mMetrics; 429 final int mDefParseFlags; 430 final String[] mSeparateProcesses; 431 final boolean mIsUpgrade; 432 433 // This is where all application persistent data goes. 434 final File mAppDataDir; 435 436 // This is where all application persistent data goes for secondary users. 437 final File mUserAppDataDir; 438 439 /** The location for ASEC container files on internal storage. */ 440 final String mAsecInternalPath; 441 442 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 443 // LOCK HELD. Can be called with mInstallLock held. 444 @GuardedBy("mInstallLock") 445 final Installer mInstaller; 446 447 /** Directory where installed third-party apps stored */ 448 final File mAppInstallDir; 449 450 /** 451 * Directory to which applications installed internally have their 452 * 32 bit native libraries copied. 453 */ 454 private File mAppLib32InstallDir; 455 456 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 457 // apps. 458 final File mDrmAppPrivateInstallDir; 459 460 // ---------------------------------------------------------------- 461 462 // Lock for state used when installing and doing other long running 463 // operations. Methods that must be called with this lock held have 464 // the suffix "LI". 465 final Object mInstallLock = new Object(); 466 467 // ---------------------------------------------------------------- 468 469 // Keys are String (package name), values are Package. This also serves 470 // as the lock for the global state. Methods that must be called with 471 // this lock held have the prefix "LP". 472 @GuardedBy("mPackages") 473 final ArrayMap<String, PackageParser.Package> mPackages = 474 new ArrayMap<String, PackageParser.Package>(); 475 476 // Tracks available target package names -> overlay package paths. 477 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 478 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 479 480 /** 481 * Tracks new system packages [receiving in an OTA] that we expect to 482 * find updated user-installed versions. Keys are package name, values 483 * are package location. 484 */ 485 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 486 487 final Settings mSettings; 488 boolean mRestoredSettings; 489 490 // System configuration read by SystemConfig. 491 final int[] mGlobalGids; 492 final SparseArray<ArraySet<String>> mSystemPermissions; 493 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 494 495 // If mac_permissions.xml was found for seinfo labeling. 496 boolean mFoundPolicyFile; 497 498 // If a recursive restorecon of /data/data/<pkg> is needed. 499 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 500 501 public static final class SharedLibraryEntry { 502 public final String path; 503 public final String apk; 504 505 SharedLibraryEntry(String _path, String _apk) { 506 path = _path; 507 apk = _apk; 508 } 509 } 510 511 // Currently known shared libraries. 512 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 513 new ArrayMap<String, SharedLibraryEntry>(); 514 515 // All available activities, for your resolving pleasure. 516 final ActivityIntentResolver mActivities = 517 new ActivityIntentResolver(); 518 519 // All available receivers, for your resolving pleasure. 520 final ActivityIntentResolver mReceivers = 521 new ActivityIntentResolver(); 522 523 // All available services, for your resolving pleasure. 524 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 525 526 // All available providers, for your resolving pleasure. 527 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 528 529 // Mapping from provider base names (first directory in content URI codePath) 530 // to the provider information. 531 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 532 new ArrayMap<String, PackageParser.Provider>(); 533 534 // Mapping from instrumentation class names to info about them. 535 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 536 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 537 538 // Mapping from permission names to info about them. 539 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 540 new ArrayMap<String, PackageParser.PermissionGroup>(); 541 542 // Packages whose data we have transfered into another package, thus 543 // should no longer exist. 544 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 545 546 // Broadcast actions that are only available to the system. 547 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 548 549 /** List of packages waiting for verification. */ 550 final SparseArray<PackageVerificationState> mPendingVerification 551 = new SparseArray<PackageVerificationState>(); 552 553 /** Set of packages associated with each app op permission. */ 554 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 555 556 final PackageInstallerService mInstallerService; 557 558 private final PackageDexOptimizer mPackageDexOptimizer; 559 560 private AtomicInteger mNextMoveId = new AtomicInteger(); 561 private final MoveCallbacks mMoveCallbacks; 562 563 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 564 565 // Cache of users who need badging. 566 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 567 568 /** Token for keys in mPendingVerification. */ 569 private int mPendingVerificationToken = 0; 570 571 volatile boolean mSystemReady; 572 volatile boolean mSafeMode; 573 volatile boolean mHasSystemUidErrors; 574 575 ApplicationInfo mAndroidApplication; 576 final ActivityInfo mResolveActivity = new ActivityInfo(); 577 final ResolveInfo mResolveInfo = new ResolveInfo(); 578 ComponentName mResolveComponentName; 579 PackageParser.Package mPlatformPackage; 580 ComponentName mCustomResolverComponentName; 581 582 boolean mResolverReplaced = false; 583 584 private final ComponentName mIntentFilterVerifierComponent; 585 private int mIntentFilterVerificationToken = 0; 586 587 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 588 = new SparseArray<IntentFilterVerificationState>(); 589 590 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 591 new DefaultPermissionGrantPolicy(this); 592 593 private static class IFVerificationParams { 594 PackageParser.Package pkg; 595 boolean replacing; 596 int userId; 597 int verifierUid; 598 599 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 600 int _userId, int _verifierUid) { 601 pkg = _pkg; 602 replacing = _replacing; 603 userId = _userId; 604 replacing = _replacing; 605 verifierUid = _verifierUid; 606 } 607 } 608 609 private interface IntentFilterVerifier<T extends IntentFilter> { 610 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 611 T filter, String packageName); 612 void startVerifications(int userId); 613 void receiveVerificationResponse(int verificationId); 614 } 615 616 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 617 private Context mContext; 618 private ComponentName mIntentFilterVerifierComponent; 619 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 620 621 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 622 mContext = context; 623 mIntentFilterVerifierComponent = verifierComponent; 624 } 625 626 private String getDefaultScheme() { 627 return IntentFilter.SCHEME_HTTPS; 628 } 629 630 @Override 631 public void startVerifications(int userId) { 632 // Launch verifications requests 633 int count = mCurrentIntentFilterVerifications.size(); 634 for (int n=0; n<count; n++) { 635 int verificationId = mCurrentIntentFilterVerifications.get(n); 636 final IntentFilterVerificationState ivs = 637 mIntentFilterVerificationStates.get(verificationId); 638 639 String packageName = ivs.getPackageName(); 640 641 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 642 final int filterCount = filters.size(); 643 ArraySet<String> domainsSet = new ArraySet<>(); 644 for (int m=0; m<filterCount; m++) { 645 PackageParser.ActivityIntentInfo filter = filters.get(m); 646 domainsSet.addAll(filter.getHostsList()); 647 } 648 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 649 synchronized (mPackages) { 650 if (mSettings.createIntentFilterVerificationIfNeededLPw( 651 packageName, domainsList) != null) { 652 scheduleWriteSettingsLocked(); 653 } 654 } 655 sendVerificationRequest(userId, verificationId, ivs); 656 } 657 mCurrentIntentFilterVerifications.clear(); 658 } 659 660 private void sendVerificationRequest(int userId, int verificationId, 661 IntentFilterVerificationState ivs) { 662 663 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 664 verificationIntent.putExtra( 665 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 666 verificationId); 667 verificationIntent.putExtra( 668 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 669 getDefaultScheme()); 670 verificationIntent.putExtra( 671 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 672 ivs.getHostsString()); 673 verificationIntent.putExtra( 674 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 675 ivs.getPackageName()); 676 verificationIntent.setComponent(mIntentFilterVerifierComponent); 677 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 678 679 UserHandle user = new UserHandle(userId); 680 mContext.sendBroadcastAsUser(verificationIntent, user); 681 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 682 "Sending IntentFilter verification broadcast"); 683 } 684 685 public void receiveVerificationResponse(int verificationId) { 686 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 687 688 final boolean verified = ivs.isVerified(); 689 690 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 691 final int count = filters.size(); 692 if (DEBUG_DOMAIN_VERIFICATION) { 693 Slog.i(TAG, "Received verification response " + verificationId 694 + " for " + count + " filters, verified=" + verified); 695 } 696 for (int n=0; n<count; n++) { 697 PackageParser.ActivityIntentInfo filter = filters.get(n); 698 filter.setVerified(verified); 699 700 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 701 + " verified with result:" + verified + " and hosts:" 702 + ivs.getHostsString()); 703 } 704 705 mIntentFilterVerificationStates.remove(verificationId); 706 707 final String packageName = ivs.getPackageName(); 708 IntentFilterVerificationInfo ivi = null; 709 710 synchronized (mPackages) { 711 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 712 } 713 if (ivi == null) { 714 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 715 + verificationId + " packageName:" + packageName); 716 return; 717 } 718 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 719 "Updating IntentFilterVerificationInfo for package " + packageName 720 +" verificationId:" + verificationId); 721 722 synchronized (mPackages) { 723 if (verified) { 724 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 725 } else { 726 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 727 } 728 scheduleWriteSettingsLocked(); 729 730 final int userId = ivs.getUserId(); 731 if (userId != UserHandle.USER_ALL) { 732 final int userStatus = 733 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 734 735 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 736 boolean needUpdate = false; 737 738 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 739 // already been set by the User thru the Disambiguation dialog 740 switch (userStatus) { 741 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 742 if (verified) { 743 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 744 } else { 745 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 746 } 747 needUpdate = true; 748 break; 749 750 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 751 if (verified) { 752 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 753 needUpdate = true; 754 } 755 break; 756 757 default: 758 // Nothing to do 759 } 760 761 if (needUpdate) { 762 mSettings.updateIntentFilterVerificationStatusLPw( 763 packageName, updatedStatus, userId); 764 scheduleWritePackageRestrictionsLocked(userId); 765 } 766 } 767 } 768 } 769 770 @Override 771 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 772 ActivityIntentInfo filter, String packageName) { 773 if (!hasValidDomains(filter)) { 774 return false; 775 } 776 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 777 if (ivs == null) { 778 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 779 packageName); 780 } 781 if (DEBUG_DOMAIN_VERIFICATION) { 782 Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter); 783 } 784 ivs.addFilter(filter); 785 return true; 786 } 787 788 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 789 int userId, int verificationId, String packageName) { 790 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 791 verifierUid, userId, packageName); 792 ivs.setPendingState(); 793 synchronized (mPackages) { 794 mIntentFilterVerificationStates.append(verificationId, ivs); 795 mCurrentIntentFilterVerifications.add(verificationId); 796 } 797 return ivs; 798 } 799 } 800 801 private static boolean hasValidDomains(ActivityIntentInfo filter) { 802 boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 803 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS); 804 if (!hasHTTPorHTTPS) { 805 return false; 806 } 807 return true; 808 } 809 810 private IntentFilterVerifier mIntentFilterVerifier; 811 812 // Set of pending broadcasts for aggregating enable/disable of components. 813 static class PendingPackageBroadcasts { 814 // for each user id, a map of <package name -> components within that package> 815 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 816 817 public PendingPackageBroadcasts() { 818 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 819 } 820 821 public ArrayList<String> get(int userId, String packageName) { 822 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 823 return packages.get(packageName); 824 } 825 826 public void put(int userId, String packageName, ArrayList<String> components) { 827 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 828 packages.put(packageName, components); 829 } 830 831 public void remove(int userId, String packageName) { 832 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 833 if (packages != null) { 834 packages.remove(packageName); 835 } 836 } 837 838 public void remove(int userId) { 839 mUidMap.remove(userId); 840 } 841 842 public int userIdCount() { 843 return mUidMap.size(); 844 } 845 846 public int userIdAt(int n) { 847 return mUidMap.keyAt(n); 848 } 849 850 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 851 return mUidMap.get(userId); 852 } 853 854 public int size() { 855 // total number of pending broadcast entries across all userIds 856 int num = 0; 857 for (int i = 0; i< mUidMap.size(); i++) { 858 num += mUidMap.valueAt(i).size(); 859 } 860 return num; 861 } 862 863 public void clear() { 864 mUidMap.clear(); 865 } 866 867 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 868 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 869 if (map == null) { 870 map = new ArrayMap<String, ArrayList<String>>(); 871 mUidMap.put(userId, map); 872 } 873 return map; 874 } 875 } 876 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 877 878 // Service Connection to remote media container service to copy 879 // package uri's from external media onto secure containers 880 // or internal storage. 881 private IMediaContainerService mContainerService = null; 882 883 static final int SEND_PENDING_BROADCAST = 1; 884 static final int MCS_BOUND = 3; 885 static final int END_COPY = 4; 886 static final int INIT_COPY = 5; 887 static final int MCS_UNBIND = 6; 888 static final int START_CLEANING_PACKAGE = 7; 889 static final int FIND_INSTALL_LOC = 8; 890 static final int POST_INSTALL = 9; 891 static final int MCS_RECONNECT = 10; 892 static final int MCS_GIVE_UP = 11; 893 static final int UPDATED_MEDIA_STATUS = 12; 894 static final int WRITE_SETTINGS = 13; 895 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 896 static final int PACKAGE_VERIFIED = 15; 897 static final int CHECK_PENDING_VERIFICATION = 16; 898 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 899 static final int INTENT_FILTER_VERIFIED = 18; 900 901 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 902 903 // Delay time in millisecs 904 static final int BROADCAST_DELAY = 10 * 1000; 905 906 static UserManagerService sUserManager; 907 908 // Stores a list of users whose package restrictions file needs to be updated 909 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 910 911 final private DefaultContainerConnection mDefContainerConn = 912 new DefaultContainerConnection(); 913 class DefaultContainerConnection implements ServiceConnection { 914 public void onServiceConnected(ComponentName name, IBinder service) { 915 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 916 IMediaContainerService imcs = 917 IMediaContainerService.Stub.asInterface(service); 918 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 919 } 920 921 public void onServiceDisconnected(ComponentName name) { 922 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 923 } 924 } 925 926 // Recordkeeping of restore-after-install operations that are currently in flight 927 // between the Package Manager and the Backup Manager 928 class PostInstallData { 929 public InstallArgs args; 930 public PackageInstalledInfo res; 931 932 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 933 args = _a; 934 res = _r; 935 } 936 } 937 938 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 939 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 940 941 // XML tags for backup/restore of various bits of state 942 private static final String TAG_PREFERRED_BACKUP = "pa"; 943 private static final String TAG_DEFAULT_APPS = "da"; 944 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 945 946 final String mRequiredVerifierPackage; 947 final String mRequiredInstallerPackage; 948 949 private final PackageUsage mPackageUsage = new PackageUsage(); 950 951 private class PackageUsage { 952 private static final int WRITE_INTERVAL 953 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 954 955 private final Object mFileLock = new Object(); 956 private final AtomicLong mLastWritten = new AtomicLong(0); 957 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 958 959 private boolean mIsHistoricalPackageUsageAvailable = true; 960 961 boolean isHistoricalPackageUsageAvailable() { 962 return mIsHistoricalPackageUsageAvailable; 963 } 964 965 void write(boolean force) { 966 if (force) { 967 writeInternal(); 968 return; 969 } 970 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 971 && !DEBUG_DEXOPT) { 972 return; 973 } 974 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 975 new Thread("PackageUsage_DiskWriter") { 976 @Override 977 public void run() { 978 try { 979 writeInternal(); 980 } finally { 981 mBackgroundWriteRunning.set(false); 982 } 983 } 984 }.start(); 985 } 986 } 987 988 private void writeInternal() { 989 synchronized (mPackages) { 990 synchronized (mFileLock) { 991 AtomicFile file = getFile(); 992 FileOutputStream f = null; 993 try { 994 f = file.startWrite(); 995 BufferedOutputStream out = new BufferedOutputStream(f); 996 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 997 StringBuilder sb = new StringBuilder(); 998 for (PackageParser.Package pkg : mPackages.values()) { 999 if (pkg.mLastPackageUsageTimeInMills == 0) { 1000 continue; 1001 } 1002 sb.setLength(0); 1003 sb.append(pkg.packageName); 1004 sb.append(' '); 1005 sb.append((long)pkg.mLastPackageUsageTimeInMills); 1006 sb.append('\n'); 1007 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1008 } 1009 out.flush(); 1010 file.finishWrite(f); 1011 } catch (IOException e) { 1012 if (f != null) { 1013 file.failWrite(f); 1014 } 1015 Log.e(TAG, "Failed to write package usage times", e); 1016 } 1017 } 1018 } 1019 mLastWritten.set(SystemClock.elapsedRealtime()); 1020 } 1021 1022 void readLP() { 1023 synchronized (mFileLock) { 1024 AtomicFile file = getFile(); 1025 BufferedInputStream in = null; 1026 try { 1027 in = new BufferedInputStream(file.openRead()); 1028 StringBuffer sb = new StringBuffer(); 1029 while (true) { 1030 String packageName = readToken(in, sb, ' '); 1031 if (packageName == null) { 1032 break; 1033 } 1034 String timeInMillisString = readToken(in, sb, '\n'); 1035 if (timeInMillisString == null) { 1036 throw new IOException("Failed to find last usage time for package " 1037 + packageName); 1038 } 1039 PackageParser.Package pkg = mPackages.get(packageName); 1040 if (pkg == null) { 1041 continue; 1042 } 1043 long timeInMillis; 1044 try { 1045 timeInMillis = Long.parseLong(timeInMillisString.toString()); 1046 } catch (NumberFormatException e) { 1047 throw new IOException("Failed to parse " + timeInMillisString 1048 + " as a long.", e); 1049 } 1050 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1051 } 1052 } catch (FileNotFoundException expected) { 1053 mIsHistoricalPackageUsageAvailable = false; 1054 } catch (IOException e) { 1055 Log.w(TAG, "Failed to read package usage times", e); 1056 } finally { 1057 IoUtils.closeQuietly(in); 1058 } 1059 } 1060 mLastWritten.set(SystemClock.elapsedRealtime()); 1061 } 1062 1063 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1064 throws IOException { 1065 sb.setLength(0); 1066 while (true) { 1067 int ch = in.read(); 1068 if (ch == -1) { 1069 if (sb.length() == 0) { 1070 return null; 1071 } 1072 throw new IOException("Unexpected EOF"); 1073 } 1074 if (ch == endOfToken) { 1075 return sb.toString(); 1076 } 1077 sb.append((char)ch); 1078 } 1079 } 1080 1081 private AtomicFile getFile() { 1082 File dataDir = Environment.getDataDirectory(); 1083 File systemDir = new File(dataDir, "system"); 1084 File fname = new File(systemDir, "package-usage.list"); 1085 return new AtomicFile(fname); 1086 } 1087 } 1088 1089 class PackageHandler extends Handler { 1090 private boolean mBound = false; 1091 final ArrayList<HandlerParams> mPendingInstalls = 1092 new ArrayList<HandlerParams>(); 1093 1094 private boolean connectToService() { 1095 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1096 " DefaultContainerService"); 1097 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1098 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1099 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1100 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 1101 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1102 mBound = true; 1103 return true; 1104 } 1105 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1106 return false; 1107 } 1108 1109 private void disconnectService() { 1110 mContainerService = null; 1111 mBound = false; 1112 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1113 mContext.unbindService(mDefContainerConn); 1114 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1115 } 1116 1117 PackageHandler(Looper looper) { 1118 super(looper); 1119 } 1120 1121 public void handleMessage(Message msg) { 1122 try { 1123 doHandleMessage(msg); 1124 } finally { 1125 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1126 } 1127 } 1128 1129 void doHandleMessage(Message msg) { 1130 switch (msg.what) { 1131 case INIT_COPY: { 1132 HandlerParams params = (HandlerParams) msg.obj; 1133 int idx = mPendingInstalls.size(); 1134 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1135 // If a bind was already initiated we dont really 1136 // need to do anything. The pending install 1137 // will be processed later on. 1138 if (!mBound) { 1139 // If this is the only one pending we might 1140 // have to bind to the service again. 1141 if (!connectToService()) { 1142 Slog.e(TAG, "Failed to bind to media container service"); 1143 params.serviceError(); 1144 return; 1145 } else { 1146 // Once we bind to the service, the first 1147 // pending request will be processed. 1148 mPendingInstalls.add(idx, params); 1149 } 1150 } else { 1151 mPendingInstalls.add(idx, params); 1152 // Already bound to the service. Just make 1153 // sure we trigger off processing the first request. 1154 if (idx == 0) { 1155 mHandler.sendEmptyMessage(MCS_BOUND); 1156 } 1157 } 1158 break; 1159 } 1160 case MCS_BOUND: { 1161 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1162 if (msg.obj != null) { 1163 mContainerService = (IMediaContainerService) msg.obj; 1164 } 1165 if (mContainerService == null) { 1166 if (!mBound) { 1167 // Something seriously wrong since we are not bound and we are not 1168 // waiting for connection. Bail out. 1169 Slog.e(TAG, "Cannot bind to media container service"); 1170 for (HandlerParams params : mPendingInstalls) { 1171 // Indicate service bind error 1172 params.serviceError(); 1173 } 1174 mPendingInstalls.clear(); 1175 } else { 1176 Slog.w(TAG, "Waiting to connect to media container service"); 1177 } 1178 } else if (mPendingInstalls.size() > 0) { 1179 HandlerParams params = mPendingInstalls.get(0); 1180 if (params != null) { 1181 if (params.startCopy()) { 1182 // We are done... look for more work or to 1183 // go idle. 1184 if (DEBUG_SD_INSTALL) Log.i(TAG, 1185 "Checking for more work or unbind..."); 1186 // Delete pending install 1187 if (mPendingInstalls.size() > 0) { 1188 mPendingInstalls.remove(0); 1189 } 1190 if (mPendingInstalls.size() == 0) { 1191 if (mBound) { 1192 if (DEBUG_SD_INSTALL) Log.i(TAG, 1193 "Posting delayed MCS_UNBIND"); 1194 removeMessages(MCS_UNBIND); 1195 Message ubmsg = obtainMessage(MCS_UNBIND); 1196 // Unbind after a little delay, to avoid 1197 // continual thrashing. 1198 sendMessageDelayed(ubmsg, 10000); 1199 } 1200 } else { 1201 // There are more pending requests in queue. 1202 // Just post MCS_BOUND message to trigger processing 1203 // of next pending install. 1204 if (DEBUG_SD_INSTALL) Log.i(TAG, 1205 "Posting MCS_BOUND for next work"); 1206 mHandler.sendEmptyMessage(MCS_BOUND); 1207 } 1208 } 1209 } 1210 } else { 1211 // Should never happen ideally. 1212 Slog.w(TAG, "Empty queue"); 1213 } 1214 break; 1215 } 1216 case MCS_RECONNECT: { 1217 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1218 if (mPendingInstalls.size() > 0) { 1219 if (mBound) { 1220 disconnectService(); 1221 } 1222 if (!connectToService()) { 1223 Slog.e(TAG, "Failed to bind to media container service"); 1224 for (HandlerParams params : mPendingInstalls) { 1225 // Indicate service bind error 1226 params.serviceError(); 1227 } 1228 mPendingInstalls.clear(); 1229 } 1230 } 1231 break; 1232 } 1233 case MCS_UNBIND: { 1234 // If there is no actual work left, then time to unbind. 1235 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1236 1237 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1238 if (mBound) { 1239 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1240 1241 disconnectService(); 1242 } 1243 } else if (mPendingInstalls.size() > 0) { 1244 // There are more pending requests in queue. 1245 // Just post MCS_BOUND message to trigger processing 1246 // of next pending install. 1247 mHandler.sendEmptyMessage(MCS_BOUND); 1248 } 1249 1250 break; 1251 } 1252 case MCS_GIVE_UP: { 1253 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1254 mPendingInstalls.remove(0); 1255 break; 1256 } 1257 case SEND_PENDING_BROADCAST: { 1258 String packages[]; 1259 ArrayList<String> components[]; 1260 int size = 0; 1261 int uids[]; 1262 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1263 synchronized (mPackages) { 1264 if (mPendingBroadcasts == null) { 1265 return; 1266 } 1267 size = mPendingBroadcasts.size(); 1268 if (size <= 0) { 1269 // Nothing to be done. Just return 1270 return; 1271 } 1272 packages = new String[size]; 1273 components = new ArrayList[size]; 1274 uids = new int[size]; 1275 int i = 0; // filling out the above arrays 1276 1277 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1278 int packageUserId = mPendingBroadcasts.userIdAt(n); 1279 Iterator<Map.Entry<String, ArrayList<String>>> it 1280 = mPendingBroadcasts.packagesForUserId(packageUserId) 1281 .entrySet().iterator(); 1282 while (it.hasNext() && i < size) { 1283 Map.Entry<String, ArrayList<String>> ent = it.next(); 1284 packages[i] = ent.getKey(); 1285 components[i] = ent.getValue(); 1286 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1287 uids[i] = (ps != null) 1288 ? UserHandle.getUid(packageUserId, ps.appId) 1289 : -1; 1290 i++; 1291 } 1292 } 1293 size = i; 1294 mPendingBroadcasts.clear(); 1295 } 1296 // Send broadcasts 1297 for (int i = 0; i < size; i++) { 1298 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1299 } 1300 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1301 break; 1302 } 1303 case START_CLEANING_PACKAGE: { 1304 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1305 final String packageName = (String)msg.obj; 1306 final int userId = msg.arg1; 1307 final boolean andCode = msg.arg2 != 0; 1308 synchronized (mPackages) { 1309 if (userId == UserHandle.USER_ALL) { 1310 int[] users = sUserManager.getUserIds(); 1311 for (int user : users) { 1312 mSettings.addPackageToCleanLPw( 1313 new PackageCleanItem(user, packageName, andCode)); 1314 } 1315 } else { 1316 mSettings.addPackageToCleanLPw( 1317 new PackageCleanItem(userId, packageName, andCode)); 1318 } 1319 } 1320 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1321 startCleaningPackages(); 1322 } break; 1323 case POST_INSTALL: { 1324 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1325 PostInstallData data = mRunningInstalls.get(msg.arg1); 1326 mRunningInstalls.delete(msg.arg1); 1327 boolean deleteOld = false; 1328 1329 if (data != null) { 1330 InstallArgs args = data.args; 1331 PackageInstalledInfo res = data.res; 1332 1333 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1334 final String packageName = res.pkg.applicationInfo.packageName; 1335 res.removedInfo.sendBroadcast(false, true, false); 1336 Bundle extras = new Bundle(1); 1337 extras.putInt(Intent.EXTRA_UID, res.uid); 1338 1339 // Now that we successfully installed the package, grant runtime 1340 // permissions if requested before broadcasting the install. 1341 if ((args.installFlags 1342 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1343 grantRequestedRuntimePermissions(res.pkg, 1344 args.user.getIdentifier()); 1345 } 1346 1347 // Determine the set of users who are adding this 1348 // package for the first time vs. those who are seeing 1349 // an update. 1350 int[] firstUsers; 1351 int[] updateUsers = new int[0]; 1352 if (res.origUsers == null || res.origUsers.length == 0) { 1353 firstUsers = res.newUsers; 1354 } else { 1355 firstUsers = new int[0]; 1356 for (int i=0; i<res.newUsers.length; i++) { 1357 int user = res.newUsers[i]; 1358 boolean isNew = true; 1359 for (int j=0; j<res.origUsers.length; j++) { 1360 if (res.origUsers[j] == user) { 1361 isNew = false; 1362 break; 1363 } 1364 } 1365 if (isNew) { 1366 int[] newFirst = new int[firstUsers.length+1]; 1367 System.arraycopy(firstUsers, 0, newFirst, 0, 1368 firstUsers.length); 1369 newFirst[firstUsers.length] = user; 1370 firstUsers = newFirst; 1371 } else { 1372 int[] newUpdate = new int[updateUsers.length+1]; 1373 System.arraycopy(updateUsers, 0, newUpdate, 0, 1374 updateUsers.length); 1375 newUpdate[updateUsers.length] = user; 1376 updateUsers = newUpdate; 1377 } 1378 } 1379 } 1380 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1381 packageName, extras, null, null, firstUsers); 1382 final boolean update = res.removedInfo.removedPackage != null; 1383 if (update) { 1384 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1385 } 1386 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1387 packageName, extras, null, null, updateUsers); 1388 if (update) { 1389 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1390 packageName, extras, null, null, updateUsers); 1391 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1392 null, null, packageName, null, updateUsers); 1393 1394 // treat asec-hosted packages like removable media on upgrade 1395 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1396 if (DEBUG_INSTALL) { 1397 Slog.i(TAG, "upgrading pkg " + res.pkg 1398 + " is ASEC-hosted -> AVAILABLE"); 1399 } 1400 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1401 ArrayList<String> pkgList = new ArrayList<String>(1); 1402 pkgList.add(packageName); 1403 sendResourcesChangedBroadcast(true, true, 1404 pkgList,uidArray, null); 1405 } 1406 } 1407 if (res.removedInfo.args != null) { 1408 // Remove the replaced package's older resources safely now 1409 deleteOld = true; 1410 } 1411 1412 // If this app is a browser and it's newly-installed for some 1413 // users, clear any default-browser state in those users 1414 if (firstUsers.length > 0) { 1415 // the app's nature doesn't depend on the user, so we can just 1416 // check its browser nature in any user and generalize. 1417 if (packageIsBrowser(packageName, firstUsers[0])) { 1418 synchronized (mPackages) { 1419 for (int userId : firstUsers) { 1420 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1421 } 1422 } 1423 } 1424 } 1425 // Log current value of "unknown sources" setting 1426 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1427 getUnknownSourcesSettings()); 1428 } 1429 // Force a gc to clear up things 1430 Runtime.getRuntime().gc(); 1431 // We delete after a gc for applications on sdcard. 1432 if (deleteOld) { 1433 synchronized (mInstallLock) { 1434 res.removedInfo.args.doPostDeleteLI(true); 1435 } 1436 } 1437 if (args.observer != null) { 1438 try { 1439 Bundle extras = extrasForInstallResult(res); 1440 args.observer.onPackageInstalled(res.name, res.returnCode, 1441 res.returnMsg, extras); 1442 } catch (RemoteException e) { 1443 Slog.i(TAG, "Observer no longer exists."); 1444 } 1445 } 1446 } else { 1447 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1448 } 1449 } break; 1450 case UPDATED_MEDIA_STATUS: { 1451 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1452 boolean reportStatus = msg.arg1 == 1; 1453 boolean doGc = msg.arg2 == 1; 1454 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1455 if (doGc) { 1456 // Force a gc to clear up stale containers. 1457 Runtime.getRuntime().gc(); 1458 } 1459 if (msg.obj != null) { 1460 @SuppressWarnings("unchecked") 1461 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1462 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1463 // Unload containers 1464 unloadAllContainers(args); 1465 } 1466 if (reportStatus) { 1467 try { 1468 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1469 PackageHelper.getMountService().finishMediaUpdate(); 1470 } catch (RemoteException e) { 1471 Log.e(TAG, "MountService not running?"); 1472 } 1473 } 1474 } break; 1475 case WRITE_SETTINGS: { 1476 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1477 synchronized (mPackages) { 1478 removeMessages(WRITE_SETTINGS); 1479 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1480 mSettings.writeLPr(); 1481 mDirtyUsers.clear(); 1482 } 1483 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1484 } break; 1485 case WRITE_PACKAGE_RESTRICTIONS: { 1486 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1487 synchronized (mPackages) { 1488 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1489 for (int userId : mDirtyUsers) { 1490 mSettings.writePackageRestrictionsLPr(userId); 1491 } 1492 mDirtyUsers.clear(); 1493 } 1494 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1495 } break; 1496 case CHECK_PENDING_VERIFICATION: { 1497 final int verificationId = msg.arg1; 1498 final PackageVerificationState state = mPendingVerification.get(verificationId); 1499 1500 if ((state != null) && !state.timeoutExtended()) { 1501 final InstallArgs args = state.getInstallArgs(); 1502 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1503 1504 Slog.i(TAG, "Verification timed out for " + originUri); 1505 mPendingVerification.remove(verificationId); 1506 1507 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1508 1509 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1510 Slog.i(TAG, "Continuing with installation of " + originUri); 1511 state.setVerifierResponse(Binder.getCallingUid(), 1512 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1513 broadcastPackageVerified(verificationId, originUri, 1514 PackageManager.VERIFICATION_ALLOW, 1515 state.getInstallArgs().getUser()); 1516 try { 1517 ret = args.copyApk(mContainerService, true); 1518 } catch (RemoteException e) { 1519 Slog.e(TAG, "Could not contact the ContainerService"); 1520 } 1521 } else { 1522 broadcastPackageVerified(verificationId, originUri, 1523 PackageManager.VERIFICATION_REJECT, 1524 state.getInstallArgs().getUser()); 1525 } 1526 1527 processPendingInstall(args, ret); 1528 mHandler.sendEmptyMessage(MCS_UNBIND); 1529 } 1530 break; 1531 } 1532 case PACKAGE_VERIFIED: { 1533 final int verificationId = msg.arg1; 1534 1535 final PackageVerificationState state = mPendingVerification.get(verificationId); 1536 if (state == null) { 1537 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1538 break; 1539 } 1540 1541 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1542 1543 state.setVerifierResponse(response.callerUid, response.code); 1544 1545 if (state.isVerificationComplete()) { 1546 mPendingVerification.remove(verificationId); 1547 1548 final InstallArgs args = state.getInstallArgs(); 1549 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1550 1551 int ret; 1552 if (state.isInstallAllowed()) { 1553 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1554 broadcastPackageVerified(verificationId, originUri, 1555 response.code, state.getInstallArgs().getUser()); 1556 try { 1557 ret = args.copyApk(mContainerService, true); 1558 } catch (RemoteException e) { 1559 Slog.e(TAG, "Could not contact the ContainerService"); 1560 } 1561 } else { 1562 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1563 } 1564 1565 processPendingInstall(args, ret); 1566 1567 mHandler.sendEmptyMessage(MCS_UNBIND); 1568 } 1569 1570 break; 1571 } 1572 case START_INTENT_FILTER_VERIFICATIONS: { 1573 IFVerificationParams params = (IFVerificationParams) msg.obj; 1574 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1575 params.replacing, params.pkg); 1576 break; 1577 } 1578 case INTENT_FILTER_VERIFIED: { 1579 final int verificationId = msg.arg1; 1580 1581 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1582 verificationId); 1583 if (state == null) { 1584 Slog.w(TAG, "Invalid IntentFilter verification token " 1585 + verificationId + " received"); 1586 break; 1587 } 1588 1589 final int userId = state.getUserId(); 1590 1591 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1592 "Processing IntentFilter verification with token:" 1593 + verificationId + " and userId:" + userId); 1594 1595 final IntentFilterVerificationResponse response = 1596 (IntentFilterVerificationResponse) msg.obj; 1597 1598 state.setVerifierResponse(response.callerUid, response.code); 1599 1600 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1601 "IntentFilter verification with token:" + verificationId 1602 + " and userId:" + userId 1603 + " is settings verifier response with response code:" 1604 + response.code); 1605 1606 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1607 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1608 + response.getFailedDomainsString()); 1609 } 1610 1611 if (state.isVerificationComplete()) { 1612 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1613 } else { 1614 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1615 "IntentFilter verification with token:" + verificationId 1616 + " was not said to be complete"); 1617 } 1618 1619 break; 1620 } 1621 } 1622 } 1623 } 1624 1625 private StorageEventListener mStorageListener = new StorageEventListener() { 1626 @Override 1627 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1628 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1629 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1630 final String volumeUuid = vol.getFsUuid(); 1631 1632 // Clean up any users or apps that were removed or recreated 1633 // while this volume was missing 1634 reconcileUsers(volumeUuid); 1635 reconcileApps(volumeUuid); 1636 1637 // Clean up any install sessions that expired or were 1638 // cancelled while this volume was missing 1639 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1640 1641 loadPrivatePackages(vol); 1642 1643 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1644 unloadPrivatePackages(vol); 1645 } 1646 } 1647 1648 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1649 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1650 updateExternalMediaStatus(true, false); 1651 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1652 updateExternalMediaStatus(false, false); 1653 } 1654 } 1655 } 1656 1657 @Override 1658 public void onVolumeForgotten(String fsUuid) { 1659 // Remove any apps installed on the forgotten volume 1660 synchronized (mPackages) { 1661 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1662 for (PackageSetting ps : packages) { 1663 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1664 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1665 UserHandle.USER_OWNER, PackageManager.DELETE_ALL_USERS); 1666 } 1667 1668 mSettings.writeLPr(); 1669 } 1670 } 1671 }; 1672 1673 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) { 1674 if (userId >= UserHandle.USER_OWNER) { 1675 grantRequestedRuntimePermissionsForUser(pkg, userId); 1676 } else if (userId == UserHandle.USER_ALL) { 1677 for (int someUserId : UserManagerService.getInstance().getUserIds()) { 1678 grantRequestedRuntimePermissionsForUser(pkg, someUserId); 1679 } 1680 } 1681 1682 // We could have touched GID membership, so flush out packages.list 1683 synchronized (mPackages) { 1684 mSettings.writePackageListLPr(); 1685 } 1686 } 1687 1688 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) { 1689 SettingBase sb = (SettingBase) pkg.mExtras; 1690 if (sb == null) { 1691 return; 1692 } 1693 1694 PermissionsState permissionsState = sb.getPermissionsState(); 1695 1696 for (String permission : pkg.requestedPermissions) { 1697 BasePermission bp = mSettings.mPermissions.get(permission); 1698 if (bp != null && bp.isRuntime()) { 1699 permissionsState.grantRuntimePermission(bp, userId); 1700 } 1701 } 1702 } 1703 1704 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1705 Bundle extras = null; 1706 switch (res.returnCode) { 1707 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1708 extras = new Bundle(); 1709 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1710 res.origPermission); 1711 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1712 res.origPackage); 1713 break; 1714 } 1715 case PackageManager.INSTALL_SUCCEEDED: { 1716 extras = new Bundle(); 1717 extras.putBoolean(Intent.EXTRA_REPLACING, 1718 res.removedInfo != null && res.removedInfo.removedPackage != null); 1719 break; 1720 } 1721 } 1722 return extras; 1723 } 1724 1725 void scheduleWriteSettingsLocked() { 1726 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1727 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1728 } 1729 } 1730 1731 void scheduleWritePackageRestrictionsLocked(int userId) { 1732 if (!sUserManager.exists(userId)) return; 1733 mDirtyUsers.add(userId); 1734 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1735 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1736 } 1737 } 1738 1739 public static PackageManagerService main(Context context, Installer installer, 1740 boolean factoryTest, boolean onlyCore) { 1741 PackageManagerService m = new PackageManagerService(context, installer, 1742 factoryTest, onlyCore); 1743 ServiceManager.addService("package", m); 1744 return m; 1745 } 1746 1747 static String[] splitString(String str, char sep) { 1748 int count = 1; 1749 int i = 0; 1750 while ((i=str.indexOf(sep, i)) >= 0) { 1751 count++; 1752 i++; 1753 } 1754 1755 String[] res = new String[count]; 1756 i=0; 1757 count = 0; 1758 int lastI=0; 1759 while ((i=str.indexOf(sep, i)) >= 0) { 1760 res[count] = str.substring(lastI, i); 1761 count++; 1762 i++; 1763 lastI = i; 1764 } 1765 res[count] = str.substring(lastI, str.length()); 1766 return res; 1767 } 1768 1769 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1770 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1771 Context.DISPLAY_SERVICE); 1772 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1773 } 1774 1775 public PackageManagerService(Context context, Installer installer, 1776 boolean factoryTest, boolean onlyCore) { 1777 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1778 SystemClock.uptimeMillis()); 1779 1780 if (mSdkVersion <= 0) { 1781 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1782 } 1783 1784 mContext = context; 1785 mFactoryTest = factoryTest; 1786 mOnlyCore = onlyCore; 1787 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1788 mMetrics = new DisplayMetrics(); 1789 mSettings = new Settings(mPackages); 1790 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1791 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1792 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1793 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1794 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1795 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1796 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1797 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1798 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1799 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1800 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1801 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1802 1803 // TODO: add a property to control this? 1804 long dexOptLRUThresholdInMinutes; 1805 if (mLazyDexOpt) { 1806 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1807 } else { 1808 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1809 } 1810 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1811 1812 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1813 if (separateProcesses != null && separateProcesses.length() > 0) { 1814 if ("*".equals(separateProcesses)) { 1815 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1816 mSeparateProcesses = null; 1817 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1818 } else { 1819 mDefParseFlags = 0; 1820 mSeparateProcesses = separateProcesses.split(","); 1821 Slog.w(TAG, "Running with debug.separate_processes: " 1822 + separateProcesses); 1823 } 1824 } else { 1825 mDefParseFlags = 0; 1826 mSeparateProcesses = null; 1827 } 1828 1829 mInstaller = installer; 1830 mPackageDexOptimizer = new PackageDexOptimizer(this); 1831 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1832 1833 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 1834 FgThread.get().getLooper()); 1835 1836 getDefaultDisplayMetrics(context, mMetrics); 1837 1838 SystemConfig systemConfig = SystemConfig.getInstance(); 1839 mGlobalGids = systemConfig.getGlobalGids(); 1840 mSystemPermissions = systemConfig.getSystemPermissions(); 1841 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1842 1843 synchronized (mInstallLock) { 1844 // writer 1845 synchronized (mPackages) { 1846 mHandlerThread = new ServiceThread(TAG, 1847 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1848 mHandlerThread.start(); 1849 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1850 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1851 1852 File dataDir = Environment.getDataDirectory(); 1853 mAppDataDir = new File(dataDir, "data"); 1854 mAppInstallDir = new File(dataDir, "app"); 1855 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1856 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1857 mUserAppDataDir = new File(dataDir, "user"); 1858 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1859 1860 sUserManager = new UserManagerService(context, this, 1861 mInstallLock, mPackages); 1862 1863 // Propagate permission configuration in to package manager. 1864 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1865 = systemConfig.getPermissions(); 1866 for (int i=0; i<permConfig.size(); i++) { 1867 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1868 BasePermission bp = mSettings.mPermissions.get(perm.name); 1869 if (bp == null) { 1870 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1871 mSettings.mPermissions.put(perm.name, bp); 1872 } 1873 if (perm.gids != null) { 1874 bp.setGids(perm.gids, perm.perUser); 1875 } 1876 } 1877 1878 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1879 for (int i=0; i<libConfig.size(); i++) { 1880 mSharedLibraries.put(libConfig.keyAt(i), 1881 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1882 } 1883 1884 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1885 1886 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1887 mSdkVersion, mOnlyCore); 1888 1889 String customResolverActivity = Resources.getSystem().getString( 1890 R.string.config_customResolverActivity); 1891 if (TextUtils.isEmpty(customResolverActivity)) { 1892 customResolverActivity = null; 1893 } else { 1894 mCustomResolverComponentName = ComponentName.unflattenFromString( 1895 customResolverActivity); 1896 } 1897 1898 long startTime = SystemClock.uptimeMillis(); 1899 1900 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1901 startTime); 1902 1903 // Set flag to monitor and not change apk file paths when 1904 // scanning install directories. 1905 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 1906 1907 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1908 1909 /** 1910 * Add everything in the in the boot class path to the 1911 * list of process files because dexopt will have been run 1912 * if necessary during zygote startup. 1913 */ 1914 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1915 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1916 1917 if (bootClassPath != null) { 1918 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1919 for (String element : bootClassPathElements) { 1920 alreadyDexOpted.add(element); 1921 } 1922 } else { 1923 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1924 } 1925 1926 if (systemServerClassPath != null) { 1927 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1928 for (String element : systemServerClassPathElements) { 1929 alreadyDexOpted.add(element); 1930 } 1931 } else { 1932 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1933 } 1934 1935 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1936 final String[] dexCodeInstructionSets = 1937 getDexCodeInstructionSets( 1938 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1939 1940 /** 1941 * Ensure all external libraries have had dexopt run on them. 1942 */ 1943 if (mSharedLibraries.size() > 0) { 1944 // NOTE: For now, we're compiling these system "shared libraries" 1945 // (and framework jars) into all available architectures. It's possible 1946 // to compile them only when we come across an app that uses them (there's 1947 // already logic for that in scanPackageLI) but that adds some complexity. 1948 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1949 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1950 final String lib = libEntry.path; 1951 if (lib == null) { 1952 continue; 1953 } 1954 1955 try { 1956 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 1957 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1958 alreadyDexOpted.add(lib); 1959 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1960 } 1961 } catch (FileNotFoundException e) { 1962 Slog.w(TAG, "Library not found: " + lib); 1963 } catch (IOException e) { 1964 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1965 + e.getMessage()); 1966 } 1967 } 1968 } 1969 } 1970 1971 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1972 1973 // Gross hack for now: we know this file doesn't contain any 1974 // code, so don't dexopt it to avoid the resulting log spew. 1975 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1976 1977 // Gross hack for now: we know this file is only part of 1978 // the boot class path for art, so don't dexopt it to 1979 // avoid the resulting log spew. 1980 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1981 1982 /** 1983 * There are a number of commands implemented in Java, which 1984 * we currently need to do the dexopt on so that they can be 1985 * run from a non-root shell. 1986 */ 1987 String[] frameworkFiles = frameworkDir.list(); 1988 if (frameworkFiles != null) { 1989 // TODO: We could compile these only for the most preferred ABI. We should 1990 // first double check that the dex files for these commands are not referenced 1991 // by other system apps. 1992 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1993 for (int i=0; i<frameworkFiles.length; i++) { 1994 File libPath = new File(frameworkDir, frameworkFiles[i]); 1995 String path = libPath.getPath(); 1996 // Skip the file if we already did it. 1997 if (alreadyDexOpted.contains(path)) { 1998 continue; 1999 } 2000 // Skip the file if it is not a type we want to dexopt. 2001 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 2002 continue; 2003 } 2004 try { 2005 int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false); 2006 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2007 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 2008 } 2009 } catch (FileNotFoundException e) { 2010 Slog.w(TAG, "Jar not found: " + path); 2011 } catch (IOException e) { 2012 Slog.w(TAG, "Exception reading jar: " + path, e); 2013 } 2014 } 2015 } 2016 } 2017 2018 // Collect vendor overlay packages. 2019 // (Do this before scanning any apps.) 2020 // For security and version matching reason, only consider 2021 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2022 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2023 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2024 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2025 2026 // Find base frameworks (resource packages without code). 2027 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2028 | PackageParser.PARSE_IS_SYSTEM_DIR 2029 | PackageParser.PARSE_IS_PRIVILEGED, 2030 scanFlags | SCAN_NO_DEX, 0); 2031 2032 // Collected privileged system packages. 2033 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2034 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2035 | PackageParser.PARSE_IS_SYSTEM_DIR 2036 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2037 2038 // Collect ordinary system packages. 2039 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2040 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2041 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2042 2043 // Collect all vendor packages. 2044 File vendorAppDir = new File("/vendor/app"); 2045 try { 2046 vendorAppDir = vendorAppDir.getCanonicalFile(); 2047 } catch (IOException e) { 2048 // failed to look up canonical path, continue with original one 2049 } 2050 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2051 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2052 2053 // Collect all OEM packages. 2054 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2055 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2056 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2057 2058 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 2059 mInstaller.moveFiles(); 2060 2061 // Prune any system packages that no longer exist. 2062 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2063 if (!mOnlyCore) { 2064 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2065 while (psit.hasNext()) { 2066 PackageSetting ps = psit.next(); 2067 2068 /* 2069 * If this is not a system app, it can't be a 2070 * disable system app. 2071 */ 2072 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2073 continue; 2074 } 2075 2076 /* 2077 * If the package is scanned, it's not erased. 2078 */ 2079 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2080 if (scannedPkg != null) { 2081 /* 2082 * If the system app is both scanned and in the 2083 * disabled packages list, then it must have been 2084 * added via OTA. Remove it from the currently 2085 * scanned package so the previously user-installed 2086 * application can be scanned. 2087 */ 2088 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2089 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2090 + ps.name + "; removing system app. Last known codePath=" 2091 + ps.codePathString + ", installStatus=" + ps.installStatus 2092 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2093 + scannedPkg.mVersionCode); 2094 removePackageLI(ps, true); 2095 mExpectingBetter.put(ps.name, ps.codePath); 2096 } 2097 2098 continue; 2099 } 2100 2101 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2102 psit.remove(); 2103 logCriticalInfo(Log.WARN, "System package " + ps.name 2104 + " no longer exists; wiping its data"); 2105 removeDataDirsLI(null, ps.name); 2106 } else { 2107 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2108 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2109 possiblyDeletedUpdatedSystemApps.add(ps.name); 2110 } 2111 } 2112 } 2113 } 2114 2115 //look for any incomplete package installations 2116 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2117 //clean up list 2118 for(int i = 0; i < deletePkgsList.size(); i++) { 2119 //clean up here 2120 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2121 } 2122 //delete tmp files 2123 deleteTempPackageFiles(); 2124 2125 // Remove any shared userIDs that have no associated packages 2126 mSettings.pruneSharedUsersLPw(); 2127 2128 if (!mOnlyCore) { 2129 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2130 SystemClock.uptimeMillis()); 2131 scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2132 2133 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2134 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2135 2136 /** 2137 * Remove disable package settings for any updated system 2138 * apps that were removed via an OTA. If they're not a 2139 * previously-updated app, remove them completely. 2140 * Otherwise, just revoke their system-level permissions. 2141 */ 2142 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2143 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2144 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2145 2146 String msg; 2147 if (deletedPkg == null) { 2148 msg = "Updated system package " + deletedAppName 2149 + " no longer exists; wiping its data"; 2150 removeDataDirsLI(null, deletedAppName); 2151 } else { 2152 msg = "Updated system app + " + deletedAppName 2153 + " no longer present; removing system privileges for " 2154 + deletedAppName; 2155 2156 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2157 2158 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2159 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2160 } 2161 logCriticalInfo(Log.WARN, msg); 2162 } 2163 2164 /** 2165 * Make sure all system apps that we expected to appear on 2166 * the userdata partition actually showed up. If they never 2167 * appeared, crawl back and revive the system version. 2168 */ 2169 for (int i = 0; i < mExpectingBetter.size(); i++) { 2170 final String packageName = mExpectingBetter.keyAt(i); 2171 if (!mPackages.containsKey(packageName)) { 2172 final File scanFile = mExpectingBetter.valueAt(i); 2173 2174 logCriticalInfo(Log.WARN, "Expected better " + packageName 2175 + " but never showed up; reverting to system"); 2176 2177 final int reparseFlags; 2178 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2179 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2180 | PackageParser.PARSE_IS_SYSTEM_DIR 2181 | PackageParser.PARSE_IS_PRIVILEGED; 2182 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2183 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2184 | PackageParser.PARSE_IS_SYSTEM_DIR; 2185 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2186 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2187 | PackageParser.PARSE_IS_SYSTEM_DIR; 2188 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2189 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2190 | PackageParser.PARSE_IS_SYSTEM_DIR; 2191 } else { 2192 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2193 continue; 2194 } 2195 2196 mSettings.enableSystemPackageLPw(packageName); 2197 2198 try { 2199 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 2200 } catch (PackageManagerException e) { 2201 Slog.e(TAG, "Failed to parse original system package: " 2202 + e.getMessage()); 2203 } 2204 } 2205 } 2206 } 2207 mExpectingBetter.clear(); 2208 2209 // Now that we know all of the shared libraries, update all clients to have 2210 // the correct library paths. 2211 updateAllSharedLibrariesLPw(); 2212 2213 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2214 // NOTE: We ignore potential failures here during a system scan (like 2215 // the rest of the commands above) because there's precious little we 2216 // can do about it. A settings error is reported, though. 2217 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2218 false /* force dexopt */, false /* defer dexopt */); 2219 } 2220 2221 // Now that we know all the packages we are keeping, 2222 // read and update their last usage times. 2223 mPackageUsage.readLP(); 2224 2225 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2226 SystemClock.uptimeMillis()); 2227 Slog.i(TAG, "Time to scan packages: " 2228 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2229 + " seconds"); 2230 2231 // If the platform SDK has changed since the last time we booted, 2232 // we need to re-grant app permission to catch any new ones that 2233 // appear. This is really a hack, and means that apps can in some 2234 // cases get permissions that the user didn't initially explicitly 2235 // allow... it would be nice to have some better way to handle 2236 // this situation. 2237 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 2238 != mSdkVersion; 2239 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 2240 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 2241 + "; regranting permissions for internal storage"); 2242 mSettings.mInternalSdkPlatform = mSdkVersion; 2243 2244 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 2245 | (regrantPermissions 2246 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 2247 : 0)); 2248 2249 // If this is the first boot, and it is a normal boot, then 2250 // we need to initialize the default preferred apps. 2251 if (!mRestoredSettings && !onlyCore) { 2252 mSettings.applyDefaultPreferredAppsLPw(this, UserHandle.USER_OWNER); 2253 applyFactoryDefaultBrowserLPw(UserHandle.USER_OWNER); 2254 primeDomainVerificationsLPw(UserHandle.USER_OWNER); 2255 } 2256 2257 // If this is first boot after an OTA, and a normal boot, then 2258 // we need to clear code cache directories. 2259 mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint); 2260 if (mIsUpgrade && !onlyCore) { 2261 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2262 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2263 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2264 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2265 } 2266 mSettings.mFingerprint = Build.FINGERPRINT; 2267 } 2268 2269 checkDefaultBrowser(); 2270 2271 // All the changes are done during package scanning. 2272 mSettings.updateInternalDatabaseVersion(); 2273 2274 // can downgrade to reader 2275 mSettings.writeLPr(); 2276 2277 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2278 SystemClock.uptimeMillis()); 2279 2280 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2281 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2282 2283 mInstallerService = new PackageInstallerService(context, this); 2284 2285 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2286 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2287 mIntentFilterVerifierComponent); 2288 2289 } // synchronized (mPackages) 2290 } // synchronized (mInstallLock) 2291 2292 // Now after opening every single application zip, make sure they 2293 // are all flushed. Not really needed, but keeps things nice and 2294 // tidy. 2295 Runtime.getRuntime().gc(); 2296 2297 // Expose private service for system components to use. 2298 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2299 } 2300 2301 @Override 2302 public boolean isFirstBoot() { 2303 return !mRestoredSettings; 2304 } 2305 2306 @Override 2307 public boolean isOnlyCoreApps() { 2308 return mOnlyCore; 2309 } 2310 2311 @Override 2312 public boolean isUpgrade() { 2313 return mIsUpgrade; 2314 } 2315 2316 private String getRequiredVerifierLPr() { 2317 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2318 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2319 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 2320 2321 String requiredVerifier = null; 2322 2323 final int N = receivers.size(); 2324 for (int i = 0; i < N; i++) { 2325 final ResolveInfo info = receivers.get(i); 2326 2327 if (info.activityInfo == null) { 2328 continue; 2329 } 2330 2331 final String packageName = info.activityInfo.packageName; 2332 2333 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2334 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2335 continue; 2336 } 2337 2338 if (requiredVerifier != null) { 2339 throw new RuntimeException("There can be only one required verifier"); 2340 } 2341 2342 requiredVerifier = packageName; 2343 } 2344 2345 return requiredVerifier; 2346 } 2347 2348 private String getRequiredInstallerLPr() { 2349 Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2350 installerIntent.addCategory(Intent.CATEGORY_DEFAULT); 2351 installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2352 2353 final List<ResolveInfo> installers = queryIntentActivities(installerIntent, 2354 PACKAGE_MIME_TYPE, 0, 0); 2355 2356 String requiredInstaller = null; 2357 2358 final int N = installers.size(); 2359 for (int i = 0; i < N; i++) { 2360 final ResolveInfo info = installers.get(i); 2361 final String packageName = info.activityInfo.packageName; 2362 2363 if (!info.activityInfo.applicationInfo.isSystemApp()) { 2364 continue; 2365 } 2366 2367 if (requiredInstaller != null) { 2368 throw new RuntimeException("There must be one required installer"); 2369 } 2370 2371 requiredInstaller = packageName; 2372 } 2373 2374 if (requiredInstaller == null) { 2375 throw new RuntimeException("There must be one required installer"); 2376 } 2377 2378 return requiredInstaller; 2379 } 2380 2381 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2382 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2383 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2384 PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */); 2385 2386 ComponentName verifierComponentName = null; 2387 2388 int priority = -1000; 2389 final int N = receivers.size(); 2390 for (int i = 0; i < N; i++) { 2391 final ResolveInfo info = receivers.get(i); 2392 2393 if (info.activityInfo == null) { 2394 continue; 2395 } 2396 2397 final String packageName = info.activityInfo.packageName; 2398 2399 final PackageSetting ps = mSettings.mPackages.get(packageName); 2400 if (ps == null) { 2401 continue; 2402 } 2403 2404 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2405 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2406 continue; 2407 } 2408 2409 // Select the IntentFilterVerifier with the highest priority 2410 if (priority < info.priority) { 2411 priority = info.priority; 2412 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2413 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: " 2414 + verifierComponentName + " with priority: " + info.priority); 2415 } 2416 } 2417 2418 return verifierComponentName; 2419 } 2420 2421 private void primeDomainVerificationsLPw(int userId) { 2422 if (DEBUG_DOMAIN_VERIFICATION) { 2423 Slog.d(TAG, "Priming domain verifications in user " + userId); 2424 } 2425 2426 SystemConfig systemConfig = SystemConfig.getInstance(); 2427 ArraySet<String> packages = systemConfig.getLinkedApps(); 2428 ArraySet<String> domains = new ArraySet<String>(); 2429 2430 for (String packageName : packages) { 2431 PackageParser.Package pkg = mPackages.get(packageName); 2432 if (pkg != null) { 2433 if (!pkg.isSystemApp()) { 2434 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2435 continue; 2436 } 2437 2438 domains.clear(); 2439 for (PackageParser.Activity a : pkg.activities) { 2440 for (ActivityIntentInfo filter : a.intents) { 2441 if (hasValidDomains(filter)) { 2442 domains.addAll(filter.getHostsList()); 2443 } 2444 } 2445 } 2446 2447 if (domains.size() > 0) { 2448 if (DEBUG_DOMAIN_VERIFICATION) { 2449 Slog.v(TAG, " + " + packageName); 2450 } 2451 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2452 // state w.r.t. the formal app-linkage "no verification attempted" state; 2453 // and then 'always' in the per-user state actually used for intent resolution. 2454 final IntentFilterVerificationInfo ivi; 2455 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2456 new ArrayList<String>(domains)); 2457 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2458 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2459 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2460 } else { 2461 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2462 + "' does not handle web links"); 2463 } 2464 } else { 2465 Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>"); 2466 } 2467 } 2468 2469 scheduleWritePackageRestrictionsLocked(userId); 2470 scheduleWriteSettingsLocked(); 2471 } 2472 2473 private void applyFactoryDefaultBrowserLPw(int userId) { 2474 // The default browser app's package name is stored in a string resource, 2475 // with a product-specific overlay used for vendor customization. 2476 String browserPkg = mContext.getResources().getString( 2477 com.android.internal.R.string.default_browser); 2478 if (!TextUtils.isEmpty(browserPkg)) { 2479 // non-empty string => required to be a known package 2480 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2481 if (ps == null) { 2482 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2483 browserPkg = null; 2484 } else { 2485 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2486 } 2487 } 2488 2489 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2490 // default. If there's more than one, just leave everything alone. 2491 if (browserPkg == null) { 2492 calculateDefaultBrowserLPw(userId); 2493 } 2494 } 2495 2496 private void calculateDefaultBrowserLPw(int userId) { 2497 List<String> allBrowsers = resolveAllBrowserApps(userId); 2498 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2499 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2500 } 2501 2502 private List<String> resolveAllBrowserApps(int userId) { 2503 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2504 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2505 PackageManager.MATCH_ALL, userId); 2506 2507 final int count = list.size(); 2508 List<String> result = new ArrayList<String>(count); 2509 for (int i=0; i<count; i++) { 2510 ResolveInfo info = list.get(i); 2511 if (info.activityInfo == null 2512 || !info.handleAllWebDataURI 2513 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2514 || result.contains(info.activityInfo.packageName)) { 2515 continue; 2516 } 2517 result.add(info.activityInfo.packageName); 2518 } 2519 2520 return result; 2521 } 2522 2523 private boolean packageIsBrowser(String packageName, int userId) { 2524 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2525 PackageManager.MATCH_ALL, userId); 2526 final int N = list.size(); 2527 for (int i = 0; i < N; i++) { 2528 ResolveInfo info = list.get(i); 2529 if (packageName.equals(info.activityInfo.packageName)) { 2530 return true; 2531 } 2532 } 2533 return false; 2534 } 2535 2536 private void checkDefaultBrowser() { 2537 final int myUserId = UserHandle.myUserId(); 2538 final String packageName = getDefaultBrowserPackageName(myUserId); 2539 if (packageName != null) { 2540 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2541 if (info == null) { 2542 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2543 synchronized (mPackages) { 2544 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2545 } 2546 } 2547 } 2548 } 2549 2550 @Override 2551 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2552 throws RemoteException { 2553 try { 2554 return super.onTransact(code, data, reply, flags); 2555 } catch (RuntimeException e) { 2556 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2557 Slog.wtf(TAG, "Package Manager Crash", e); 2558 } 2559 throw e; 2560 } 2561 } 2562 2563 void cleanupInstallFailedPackage(PackageSetting ps) { 2564 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2565 2566 removeDataDirsLI(ps.volumeUuid, ps.name); 2567 if (ps.codePath != null) { 2568 if (ps.codePath.isDirectory()) { 2569 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2570 } else { 2571 ps.codePath.delete(); 2572 } 2573 } 2574 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2575 if (ps.resourcePath.isDirectory()) { 2576 FileUtils.deleteContents(ps.resourcePath); 2577 } 2578 ps.resourcePath.delete(); 2579 } 2580 mSettings.removePackageLPw(ps.name); 2581 } 2582 2583 static int[] appendInts(int[] cur, int[] add) { 2584 if (add == null) return cur; 2585 if (cur == null) return add; 2586 final int N = add.length; 2587 for (int i=0; i<N; i++) { 2588 cur = appendInt(cur, add[i]); 2589 } 2590 return cur; 2591 } 2592 2593 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2594 if (!sUserManager.exists(userId)) return null; 2595 final PackageSetting ps = (PackageSetting) p.mExtras; 2596 if (ps == null) { 2597 return null; 2598 } 2599 2600 final PermissionsState permissionsState = ps.getPermissionsState(); 2601 2602 final int[] gids = permissionsState.computeGids(userId); 2603 final Set<String> permissions = permissionsState.getPermissions(userId); 2604 final PackageUserState state = ps.readUserState(userId); 2605 2606 return PackageParser.generatePackageInfo(p, gids, flags, 2607 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2608 } 2609 2610 @Override 2611 public boolean isPackageFrozen(String packageName) { 2612 synchronized (mPackages) { 2613 final PackageSetting ps = mSettings.mPackages.get(packageName); 2614 if (ps != null) { 2615 return ps.frozen; 2616 } 2617 } 2618 Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen"); 2619 return true; 2620 } 2621 2622 @Override 2623 public boolean isPackageAvailable(String packageName, int userId) { 2624 if (!sUserManager.exists(userId)) return false; 2625 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2626 synchronized (mPackages) { 2627 PackageParser.Package p = mPackages.get(packageName); 2628 if (p != null) { 2629 final PackageSetting ps = (PackageSetting) p.mExtras; 2630 if (ps != null) { 2631 final PackageUserState state = ps.readUserState(userId); 2632 if (state != null) { 2633 return PackageParser.isAvailable(state); 2634 } 2635 } 2636 } 2637 } 2638 return false; 2639 } 2640 2641 @Override 2642 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2643 if (!sUserManager.exists(userId)) return null; 2644 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2645 // reader 2646 synchronized (mPackages) { 2647 PackageParser.Package p = mPackages.get(packageName); 2648 if (DEBUG_PACKAGE_INFO) 2649 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2650 if (p != null) { 2651 return generatePackageInfo(p, flags, userId); 2652 } 2653 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2654 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2655 } 2656 } 2657 return null; 2658 } 2659 2660 @Override 2661 public String[] currentToCanonicalPackageNames(String[] names) { 2662 String[] out = new String[names.length]; 2663 // reader 2664 synchronized (mPackages) { 2665 for (int i=names.length-1; i>=0; i--) { 2666 PackageSetting ps = mSettings.mPackages.get(names[i]); 2667 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2668 } 2669 } 2670 return out; 2671 } 2672 2673 @Override 2674 public String[] canonicalToCurrentPackageNames(String[] names) { 2675 String[] out = new String[names.length]; 2676 // reader 2677 synchronized (mPackages) { 2678 for (int i=names.length-1; i>=0; i--) { 2679 String cur = mSettings.mRenamedPackages.get(names[i]); 2680 out[i] = cur != null ? cur : names[i]; 2681 } 2682 } 2683 return out; 2684 } 2685 2686 @Override 2687 public int getPackageUid(String packageName, int userId) { 2688 if (!sUserManager.exists(userId)) return -1; 2689 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2690 2691 // reader 2692 synchronized (mPackages) { 2693 PackageParser.Package p = mPackages.get(packageName); 2694 if(p != null) { 2695 return UserHandle.getUid(userId, p.applicationInfo.uid); 2696 } 2697 PackageSetting ps = mSettings.mPackages.get(packageName); 2698 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2699 return -1; 2700 } 2701 p = ps.pkg; 2702 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2703 } 2704 } 2705 2706 @Override 2707 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2708 if (!sUserManager.exists(userId)) { 2709 return null; 2710 } 2711 2712 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2713 "getPackageGids"); 2714 2715 // reader 2716 synchronized (mPackages) { 2717 PackageParser.Package p = mPackages.get(packageName); 2718 if (DEBUG_PACKAGE_INFO) { 2719 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2720 } 2721 if (p != null) { 2722 PackageSetting ps = (PackageSetting) p.mExtras; 2723 return ps.getPermissionsState().computeGids(userId); 2724 } 2725 } 2726 2727 return null; 2728 } 2729 2730 @Override 2731 public int getMountExternalMode(int uid) { 2732 if (Process.isIsolated(uid)) { 2733 return Zygote.MOUNT_EXTERNAL_NONE; 2734 } else { 2735 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 2736 return Zygote.MOUNT_EXTERNAL_DEFAULT; 2737 } else if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_GRANTED) { 2738 return Zygote.MOUNT_EXTERNAL_WRITE; 2739 } else if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_GRANTED) { 2740 return Zygote.MOUNT_EXTERNAL_READ; 2741 } else { 2742 return Zygote.MOUNT_EXTERNAL_DEFAULT; 2743 } 2744 } 2745 } 2746 2747 static PermissionInfo generatePermissionInfo( 2748 BasePermission bp, int flags) { 2749 if (bp.perm != null) { 2750 return PackageParser.generatePermissionInfo(bp.perm, flags); 2751 } 2752 PermissionInfo pi = new PermissionInfo(); 2753 pi.name = bp.name; 2754 pi.packageName = bp.sourcePackage; 2755 pi.nonLocalizedLabel = bp.name; 2756 pi.protectionLevel = bp.protectionLevel; 2757 return pi; 2758 } 2759 2760 @Override 2761 public PermissionInfo getPermissionInfo(String name, int flags) { 2762 // reader 2763 synchronized (mPackages) { 2764 final BasePermission p = mSettings.mPermissions.get(name); 2765 if (p != null) { 2766 return generatePermissionInfo(p, flags); 2767 } 2768 return null; 2769 } 2770 } 2771 2772 @Override 2773 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2774 // reader 2775 synchronized (mPackages) { 2776 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2777 for (BasePermission p : mSettings.mPermissions.values()) { 2778 if (group == null) { 2779 if (p.perm == null || p.perm.info.group == null) { 2780 out.add(generatePermissionInfo(p, flags)); 2781 } 2782 } else { 2783 if (p.perm != null && group.equals(p.perm.info.group)) { 2784 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2785 } 2786 } 2787 } 2788 2789 if (out.size() > 0) { 2790 return out; 2791 } 2792 return mPermissionGroups.containsKey(group) ? out : null; 2793 } 2794 } 2795 2796 @Override 2797 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2798 // reader 2799 synchronized (mPackages) { 2800 return PackageParser.generatePermissionGroupInfo( 2801 mPermissionGroups.get(name), flags); 2802 } 2803 } 2804 2805 @Override 2806 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2807 // reader 2808 synchronized (mPackages) { 2809 final int N = mPermissionGroups.size(); 2810 ArrayList<PermissionGroupInfo> out 2811 = new ArrayList<PermissionGroupInfo>(N); 2812 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2813 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2814 } 2815 return out; 2816 } 2817 } 2818 2819 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2820 int userId) { 2821 if (!sUserManager.exists(userId)) return null; 2822 PackageSetting ps = mSettings.mPackages.get(packageName); 2823 if (ps != null) { 2824 if (ps.pkg == null) { 2825 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2826 flags, userId); 2827 if (pInfo != null) { 2828 return pInfo.applicationInfo; 2829 } 2830 return null; 2831 } 2832 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2833 ps.readUserState(userId), userId); 2834 } 2835 return null; 2836 } 2837 2838 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2839 int userId) { 2840 if (!sUserManager.exists(userId)) return null; 2841 PackageSetting ps = mSettings.mPackages.get(packageName); 2842 if (ps != null) { 2843 PackageParser.Package pkg = ps.pkg; 2844 if (pkg == null) { 2845 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2846 return null; 2847 } 2848 // Only data remains, so we aren't worried about code paths 2849 pkg = new PackageParser.Package(packageName); 2850 pkg.applicationInfo.packageName = packageName; 2851 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2852 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2853 pkg.applicationInfo.dataDir = Environment 2854 .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName) 2855 .getAbsolutePath(); 2856 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2857 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2858 } 2859 return generatePackageInfo(pkg, flags, userId); 2860 } 2861 return null; 2862 } 2863 2864 @Override 2865 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2866 if (!sUserManager.exists(userId)) return null; 2867 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2868 // writer 2869 synchronized (mPackages) { 2870 PackageParser.Package p = mPackages.get(packageName); 2871 if (DEBUG_PACKAGE_INFO) Log.v( 2872 TAG, "getApplicationInfo " + packageName 2873 + ": " + p); 2874 if (p != null) { 2875 PackageSetting ps = mSettings.mPackages.get(packageName); 2876 if (ps == null) return null; 2877 // Note: isEnabledLP() does not apply here - always return info 2878 return PackageParser.generateApplicationInfo( 2879 p, flags, ps.readUserState(userId), userId); 2880 } 2881 if ("android".equals(packageName)||"system".equals(packageName)) { 2882 return mAndroidApplication; 2883 } 2884 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2885 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2886 } 2887 } 2888 return null; 2889 } 2890 2891 @Override 2892 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2893 final IPackageDataObserver observer) { 2894 mContext.enforceCallingOrSelfPermission( 2895 android.Manifest.permission.CLEAR_APP_CACHE, null); 2896 // Queue up an async operation since clearing cache may take a little while. 2897 mHandler.post(new Runnable() { 2898 public void run() { 2899 mHandler.removeCallbacks(this); 2900 int retCode = -1; 2901 synchronized (mInstallLock) { 2902 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2903 if (retCode < 0) { 2904 Slog.w(TAG, "Couldn't clear application caches"); 2905 } 2906 } 2907 if (observer != null) { 2908 try { 2909 observer.onRemoveCompleted(null, (retCode >= 0)); 2910 } catch (RemoteException e) { 2911 Slog.w(TAG, "RemoveException when invoking call back"); 2912 } 2913 } 2914 } 2915 }); 2916 } 2917 2918 @Override 2919 public void freeStorage(final String volumeUuid, final long freeStorageSize, 2920 final IntentSender pi) { 2921 mContext.enforceCallingOrSelfPermission( 2922 android.Manifest.permission.CLEAR_APP_CACHE, null); 2923 // Queue up an async operation since clearing cache may take a little while. 2924 mHandler.post(new Runnable() { 2925 public void run() { 2926 mHandler.removeCallbacks(this); 2927 int retCode = -1; 2928 synchronized (mInstallLock) { 2929 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2930 if (retCode < 0) { 2931 Slog.w(TAG, "Couldn't clear application caches"); 2932 } 2933 } 2934 if(pi != null) { 2935 try { 2936 // Callback via pending intent 2937 int code = (retCode >= 0) ? 1 : 0; 2938 pi.sendIntent(null, code, null, 2939 null, null); 2940 } catch (SendIntentException e1) { 2941 Slog.i(TAG, "Failed to send pending intent"); 2942 } 2943 } 2944 } 2945 }); 2946 } 2947 2948 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 2949 synchronized (mInstallLock) { 2950 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 2951 throw new IOException("Failed to free enough space"); 2952 } 2953 } 2954 } 2955 2956 @Override 2957 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2958 if (!sUserManager.exists(userId)) return null; 2959 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2960 synchronized (mPackages) { 2961 PackageParser.Activity a = mActivities.mActivities.get(component); 2962 2963 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2964 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2965 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2966 if (ps == null) return null; 2967 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2968 userId); 2969 } 2970 if (mResolveComponentName.equals(component)) { 2971 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2972 new PackageUserState(), userId); 2973 } 2974 } 2975 return null; 2976 } 2977 2978 @Override 2979 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2980 String resolvedType) { 2981 synchronized (mPackages) { 2982 PackageParser.Activity a = mActivities.mActivities.get(component); 2983 if (a == null) { 2984 return false; 2985 } 2986 for (int i=0; i<a.intents.size(); i++) { 2987 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2988 intent.getData(), intent.getCategories(), TAG) >= 0) { 2989 return true; 2990 } 2991 } 2992 return false; 2993 } 2994 } 2995 2996 @Override 2997 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2998 if (!sUserManager.exists(userId)) return null; 2999 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 3000 synchronized (mPackages) { 3001 PackageParser.Activity a = mReceivers.mActivities.get(component); 3002 if (DEBUG_PACKAGE_INFO) Log.v( 3003 TAG, "getReceiverInfo " + component + ": " + a); 3004 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 3005 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3006 if (ps == null) return null; 3007 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3008 userId); 3009 } 3010 } 3011 return null; 3012 } 3013 3014 @Override 3015 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3016 if (!sUserManager.exists(userId)) return null; 3017 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 3018 synchronized (mPackages) { 3019 PackageParser.Service s = mServices.mServices.get(component); 3020 if (DEBUG_PACKAGE_INFO) Log.v( 3021 TAG, "getServiceInfo " + component + ": " + s); 3022 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 3023 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3024 if (ps == null) return null; 3025 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3026 userId); 3027 } 3028 } 3029 return null; 3030 } 3031 3032 @Override 3033 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3034 if (!sUserManager.exists(userId)) return null; 3035 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 3036 synchronized (mPackages) { 3037 PackageParser.Provider p = mProviders.mProviders.get(component); 3038 if (DEBUG_PACKAGE_INFO) Log.v( 3039 TAG, "getProviderInfo " + component + ": " + p); 3040 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 3041 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3042 if (ps == null) return null; 3043 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3044 userId); 3045 } 3046 } 3047 return null; 3048 } 3049 3050 @Override 3051 public String[] getSystemSharedLibraryNames() { 3052 Set<String> libSet; 3053 synchronized (mPackages) { 3054 libSet = mSharedLibraries.keySet(); 3055 int size = libSet.size(); 3056 if (size > 0) { 3057 String[] libs = new String[size]; 3058 libSet.toArray(libs); 3059 return libs; 3060 } 3061 } 3062 return null; 3063 } 3064 3065 /** 3066 * @hide 3067 */ 3068 PackageParser.Package findSharedNonSystemLibrary(String libName) { 3069 synchronized (mPackages) { 3070 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 3071 if (lib != null && lib.apk != null) { 3072 return mPackages.get(lib.apk); 3073 } 3074 } 3075 return null; 3076 } 3077 3078 @Override 3079 public FeatureInfo[] getSystemAvailableFeatures() { 3080 Collection<FeatureInfo> featSet; 3081 synchronized (mPackages) { 3082 featSet = mAvailableFeatures.values(); 3083 int size = featSet.size(); 3084 if (size > 0) { 3085 FeatureInfo[] features = new FeatureInfo[size+1]; 3086 featSet.toArray(features); 3087 FeatureInfo fi = new FeatureInfo(); 3088 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3089 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3090 features[size] = fi; 3091 return features; 3092 } 3093 } 3094 return null; 3095 } 3096 3097 @Override 3098 public boolean hasSystemFeature(String name) { 3099 synchronized (mPackages) { 3100 return mAvailableFeatures.containsKey(name); 3101 } 3102 } 3103 3104 private void checkValidCaller(int uid, int userId) { 3105 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 3106 return; 3107 3108 throw new SecurityException("Caller uid=" + uid 3109 + " is not privileged to communicate with user=" + userId); 3110 } 3111 3112 @Override 3113 public int checkPermission(String permName, String pkgName, int userId) { 3114 if (!sUserManager.exists(userId)) { 3115 return PackageManager.PERMISSION_DENIED; 3116 } 3117 3118 synchronized (mPackages) { 3119 final PackageParser.Package p = mPackages.get(pkgName); 3120 if (p != null && p.mExtras != null) { 3121 final PackageSetting ps = (PackageSetting) p.mExtras; 3122 if (ps.getPermissionsState().hasPermission(permName, userId)) { 3123 return PackageManager.PERMISSION_GRANTED; 3124 } 3125 } 3126 } 3127 3128 return PackageManager.PERMISSION_DENIED; 3129 } 3130 3131 @Override 3132 public int checkUidPermission(String permName, int uid) { 3133 final int userId = UserHandle.getUserId(uid); 3134 3135 if (!sUserManager.exists(userId)) { 3136 return PackageManager.PERMISSION_DENIED; 3137 } 3138 3139 synchronized (mPackages) { 3140 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3141 if (obj != null) { 3142 final SettingBase ps = (SettingBase) obj; 3143 if (ps.getPermissionsState().hasPermission(permName, userId)) { 3144 return PackageManager.PERMISSION_GRANTED; 3145 } 3146 } else { 3147 ArraySet<String> perms = mSystemPermissions.get(uid); 3148 if (perms != null && perms.contains(permName)) { 3149 return PackageManager.PERMISSION_GRANTED; 3150 } 3151 } 3152 } 3153 3154 return PackageManager.PERMISSION_DENIED; 3155 } 3156 3157 @Override 3158 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3159 if (UserHandle.getCallingUserId() != userId) { 3160 mContext.enforceCallingPermission( 3161 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3162 "isPermissionRevokedByPolicy for user " + userId); 3163 } 3164 3165 if (checkPermission(permission, packageName, userId) 3166 == PackageManager.PERMISSION_GRANTED) { 3167 return false; 3168 } 3169 3170 final long identity = Binder.clearCallingIdentity(); 3171 try { 3172 final int flags = getPermissionFlags(permission, packageName, userId); 3173 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3174 } finally { 3175 Binder.restoreCallingIdentity(identity); 3176 } 3177 } 3178 3179 /** 3180 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3181 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3182 * @param checkShell TODO(yamasani): 3183 * @param message the message to log on security exception 3184 */ 3185 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3186 boolean checkShell, String message) { 3187 if (userId < 0) { 3188 throw new IllegalArgumentException("Invalid userId " + userId); 3189 } 3190 if (checkShell) { 3191 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3192 } 3193 if (userId == UserHandle.getUserId(callingUid)) return; 3194 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3195 if (requireFullPermission) { 3196 mContext.enforceCallingOrSelfPermission( 3197 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3198 } else { 3199 try { 3200 mContext.enforceCallingOrSelfPermission( 3201 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3202 } catch (SecurityException se) { 3203 mContext.enforceCallingOrSelfPermission( 3204 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3205 } 3206 } 3207 } 3208 } 3209 3210 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3211 if (callingUid == Process.SHELL_UID) { 3212 if (userHandle >= 0 3213 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3214 throw new SecurityException("Shell does not have permission to access user " 3215 + userHandle); 3216 } else if (userHandle < 0) { 3217 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3218 + Debug.getCallers(3)); 3219 } 3220 } 3221 } 3222 3223 private BasePermission findPermissionTreeLP(String permName) { 3224 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3225 if (permName.startsWith(bp.name) && 3226 permName.length() > bp.name.length() && 3227 permName.charAt(bp.name.length()) == '.') { 3228 return bp; 3229 } 3230 } 3231 return null; 3232 } 3233 3234 private BasePermission checkPermissionTreeLP(String permName) { 3235 if (permName != null) { 3236 BasePermission bp = findPermissionTreeLP(permName); 3237 if (bp != null) { 3238 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3239 return bp; 3240 } 3241 throw new SecurityException("Calling uid " 3242 + Binder.getCallingUid() 3243 + " is not allowed to add to permission tree " 3244 + bp.name + " owned by uid " + bp.uid); 3245 } 3246 } 3247 throw new SecurityException("No permission tree found for " + permName); 3248 } 3249 3250 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3251 if (s1 == null) { 3252 return s2 == null; 3253 } 3254 if (s2 == null) { 3255 return false; 3256 } 3257 if (s1.getClass() != s2.getClass()) { 3258 return false; 3259 } 3260 return s1.equals(s2); 3261 } 3262 3263 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3264 if (pi1.icon != pi2.icon) return false; 3265 if (pi1.logo != pi2.logo) return false; 3266 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3267 if (!compareStrings(pi1.name, pi2.name)) return false; 3268 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3269 // We'll take care of setting this one. 3270 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3271 // These are not currently stored in settings. 3272 //if (!compareStrings(pi1.group, pi2.group)) return false; 3273 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3274 //if (pi1.labelRes != pi2.labelRes) return false; 3275 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3276 return true; 3277 } 3278 3279 int permissionInfoFootprint(PermissionInfo info) { 3280 int size = info.name.length(); 3281 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3282 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3283 return size; 3284 } 3285 3286 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3287 int size = 0; 3288 for (BasePermission perm : mSettings.mPermissions.values()) { 3289 if (perm.uid == tree.uid) { 3290 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3291 } 3292 } 3293 return size; 3294 } 3295 3296 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3297 // We calculate the max size of permissions defined by this uid and throw 3298 // if that plus the size of 'info' would exceed our stated maximum. 3299 if (tree.uid != Process.SYSTEM_UID) { 3300 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3301 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3302 throw new SecurityException("Permission tree size cap exceeded"); 3303 } 3304 } 3305 } 3306 3307 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3308 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3309 throw new SecurityException("Label must be specified in permission"); 3310 } 3311 BasePermission tree = checkPermissionTreeLP(info.name); 3312 BasePermission bp = mSettings.mPermissions.get(info.name); 3313 boolean added = bp == null; 3314 boolean changed = true; 3315 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3316 if (added) { 3317 enforcePermissionCapLocked(info, tree); 3318 bp = new BasePermission(info.name, tree.sourcePackage, 3319 BasePermission.TYPE_DYNAMIC); 3320 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3321 throw new SecurityException( 3322 "Not allowed to modify non-dynamic permission " 3323 + info.name); 3324 } else { 3325 if (bp.protectionLevel == fixedLevel 3326 && bp.perm.owner.equals(tree.perm.owner) 3327 && bp.uid == tree.uid 3328 && comparePermissionInfos(bp.perm.info, info)) { 3329 changed = false; 3330 } 3331 } 3332 bp.protectionLevel = fixedLevel; 3333 info = new PermissionInfo(info); 3334 info.protectionLevel = fixedLevel; 3335 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3336 bp.perm.info.packageName = tree.perm.info.packageName; 3337 bp.uid = tree.uid; 3338 if (added) { 3339 mSettings.mPermissions.put(info.name, bp); 3340 } 3341 if (changed) { 3342 if (!async) { 3343 mSettings.writeLPr(); 3344 } else { 3345 scheduleWriteSettingsLocked(); 3346 } 3347 } 3348 return added; 3349 } 3350 3351 @Override 3352 public boolean addPermission(PermissionInfo info) { 3353 synchronized (mPackages) { 3354 return addPermissionLocked(info, false); 3355 } 3356 } 3357 3358 @Override 3359 public boolean addPermissionAsync(PermissionInfo info) { 3360 synchronized (mPackages) { 3361 return addPermissionLocked(info, true); 3362 } 3363 } 3364 3365 @Override 3366 public void removePermission(String name) { 3367 synchronized (mPackages) { 3368 checkPermissionTreeLP(name); 3369 BasePermission bp = mSettings.mPermissions.get(name); 3370 if (bp != null) { 3371 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3372 throw new SecurityException( 3373 "Not allowed to modify non-dynamic permission " 3374 + name); 3375 } 3376 mSettings.mPermissions.remove(name); 3377 mSettings.writeLPr(); 3378 } 3379 } 3380 } 3381 3382 private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg, 3383 BasePermission bp) { 3384 int index = pkg.requestedPermissions.indexOf(bp.name); 3385 if (index == -1) { 3386 throw new SecurityException("Package " + pkg.packageName 3387 + " has not requested permission " + bp.name); 3388 } 3389 if (!bp.isRuntime()) { 3390 throw new SecurityException("Permission " + bp.name 3391 + " is not a changeable permission type"); 3392 } 3393 } 3394 3395 @Override 3396 public void grantRuntimePermission(String packageName, String name, final int userId) { 3397 if (!sUserManager.exists(userId)) { 3398 Log.e(TAG, "No such user:" + userId); 3399 return; 3400 } 3401 3402 mContext.enforceCallingOrSelfPermission( 3403 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3404 "grantRuntimePermission"); 3405 3406 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3407 "grantRuntimePermission"); 3408 3409 final int uid; 3410 final SettingBase sb; 3411 3412 synchronized (mPackages) { 3413 final PackageParser.Package pkg = mPackages.get(packageName); 3414 if (pkg == null) { 3415 throw new IllegalArgumentException("Unknown package: " + packageName); 3416 } 3417 3418 final BasePermission bp = mSettings.mPermissions.get(name); 3419 if (bp == null) { 3420 throw new IllegalArgumentException("Unknown permission: " + name); 3421 } 3422 3423 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3424 3425 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3426 sb = (SettingBase) pkg.mExtras; 3427 if (sb == null) { 3428 throw new IllegalArgumentException("Unknown package: " + packageName); 3429 } 3430 3431 final PermissionsState permissionsState = sb.getPermissionsState(); 3432 3433 final int flags = permissionsState.getPermissionFlags(name, userId); 3434 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3435 throw new SecurityException("Cannot grant system fixed permission: " 3436 + name + " for package: " + packageName); 3437 } 3438 3439 final int result = permissionsState.grantRuntimePermission(bp, userId); 3440 switch (result) { 3441 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3442 return; 3443 } 3444 3445 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3446 mHandler.post(new Runnable() { 3447 @Override 3448 public void run() { 3449 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED); 3450 } 3451 }); 3452 } break; 3453 } 3454 3455 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3456 3457 // Not critical if that is lost - app has to request again. 3458 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3459 } 3460 3461 if (READ_EXTERNAL_STORAGE.equals(name) 3462 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3463 final long token = Binder.clearCallingIdentity(); 3464 try { 3465 final StorageManager storage = mContext.getSystemService(StorageManager.class); 3466 storage.remountUid(uid); 3467 } finally { 3468 Binder.restoreCallingIdentity(token); 3469 } 3470 } 3471 } 3472 3473 @Override 3474 public void revokeRuntimePermission(String packageName, String name, int userId) { 3475 if (!sUserManager.exists(userId)) { 3476 Log.e(TAG, "No such user:" + userId); 3477 return; 3478 } 3479 3480 mContext.enforceCallingOrSelfPermission( 3481 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3482 "revokeRuntimePermission"); 3483 3484 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3485 "revokeRuntimePermission"); 3486 3487 final SettingBase sb; 3488 3489 synchronized (mPackages) { 3490 final PackageParser.Package pkg = mPackages.get(packageName); 3491 if (pkg == null) { 3492 throw new IllegalArgumentException("Unknown package: " + packageName); 3493 } 3494 3495 final BasePermission bp = mSettings.mPermissions.get(name); 3496 if (bp == null) { 3497 throw new IllegalArgumentException("Unknown permission: " + name); 3498 } 3499 3500 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3501 3502 sb = (SettingBase) pkg.mExtras; 3503 if (sb == null) { 3504 throw new IllegalArgumentException("Unknown package: " + packageName); 3505 } 3506 3507 final PermissionsState permissionsState = sb.getPermissionsState(); 3508 3509 final int flags = permissionsState.getPermissionFlags(name, userId); 3510 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3511 throw new SecurityException("Cannot revoke system fixed permission: " 3512 + name + " for package: " + packageName); 3513 } 3514 3515 if (permissionsState.revokeRuntimePermission(bp, userId) == 3516 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3517 return; 3518 } 3519 3520 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3521 3522 // Critical, after this call app should never have the permission. 3523 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3524 } 3525 3526 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3527 } 3528 3529 @Override 3530 public void resetRuntimePermissions() { 3531 mContext.enforceCallingOrSelfPermission( 3532 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3533 "revokeRuntimePermission"); 3534 3535 int callingUid = Binder.getCallingUid(); 3536 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3537 mContext.enforceCallingOrSelfPermission( 3538 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3539 "resetRuntimePermissions"); 3540 } 3541 3542 final int[] userIds; 3543 3544 synchronized (mPackages) { 3545 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 3546 final int userCount = UserManagerService.getInstance().getUserIds().length; 3547 userIds = Arrays.copyOf(UserManagerService.getInstance().getUserIds(), userCount); 3548 } 3549 3550 for (int userId : userIds) { 3551 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 3552 } 3553 } 3554 3555 @Override 3556 public int getPermissionFlags(String name, String packageName, int userId) { 3557 if (!sUserManager.exists(userId)) { 3558 return 0; 3559 } 3560 3561 mContext.enforceCallingOrSelfPermission( 3562 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3563 "getPermissionFlags"); 3564 3565 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3566 "getPermissionFlags"); 3567 3568 synchronized (mPackages) { 3569 final PackageParser.Package pkg = mPackages.get(packageName); 3570 if (pkg == null) { 3571 throw new IllegalArgumentException("Unknown package: " + packageName); 3572 } 3573 3574 final BasePermission bp = mSettings.mPermissions.get(name); 3575 if (bp == null) { 3576 throw new IllegalArgumentException("Unknown permission: " + name); 3577 } 3578 3579 SettingBase sb = (SettingBase) pkg.mExtras; 3580 if (sb == null) { 3581 throw new IllegalArgumentException("Unknown package: " + packageName); 3582 } 3583 3584 PermissionsState permissionsState = sb.getPermissionsState(); 3585 return permissionsState.getPermissionFlags(name, userId); 3586 } 3587 } 3588 3589 @Override 3590 public void updatePermissionFlags(String name, String packageName, int flagMask, 3591 int flagValues, int userId) { 3592 if (!sUserManager.exists(userId)) { 3593 return; 3594 } 3595 3596 mContext.enforceCallingOrSelfPermission( 3597 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3598 "updatePermissionFlags"); 3599 3600 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3601 "updatePermissionFlags"); 3602 3603 // Only the system can change system fixed flags. 3604 if (getCallingUid() != Process.SYSTEM_UID) { 3605 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3606 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3607 } 3608 3609 synchronized (mPackages) { 3610 final PackageParser.Package pkg = mPackages.get(packageName); 3611 if (pkg == null) { 3612 throw new IllegalArgumentException("Unknown package: " + packageName); 3613 } 3614 3615 final BasePermission bp = mSettings.mPermissions.get(name); 3616 if (bp == null) { 3617 throw new IllegalArgumentException("Unknown permission: " + name); 3618 } 3619 3620 SettingBase sb = (SettingBase) pkg.mExtras; 3621 if (sb == null) { 3622 throw new IllegalArgumentException("Unknown package: " + packageName); 3623 } 3624 3625 PermissionsState permissionsState = sb.getPermissionsState(); 3626 3627 // Only the package manager can change flags for system component permissions. 3628 final int flags = permissionsState.getPermissionFlags(bp.name, userId); 3629 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3630 return; 3631 } 3632 3633 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 3634 3635 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3636 // Install and runtime permissions are stored in different places, 3637 // so figure out what permission changed and persist the change. 3638 if (permissionsState.getInstallPermissionState(name) != null) { 3639 scheduleWriteSettingsLocked(); 3640 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 3641 || hadState) { 3642 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3643 } 3644 } 3645 } 3646 } 3647 3648 /** 3649 * Update the permission flags for all packages and runtime permissions of a user in order 3650 * to allow device or profile owner to remove POLICY_FIXED. 3651 */ 3652 @Override 3653 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 3654 if (!sUserManager.exists(userId)) { 3655 return; 3656 } 3657 3658 mContext.enforceCallingOrSelfPermission( 3659 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3660 "updatePermissionFlagsForAllApps"); 3661 3662 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3663 "updatePermissionFlagsForAllApps"); 3664 3665 // Only the system can change system fixed flags. 3666 if (getCallingUid() != Process.SYSTEM_UID) { 3667 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3668 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3669 } 3670 3671 synchronized (mPackages) { 3672 boolean changed = false; 3673 final int packageCount = mPackages.size(); 3674 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 3675 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 3676 SettingBase sb = (SettingBase) pkg.mExtras; 3677 if (sb == null) { 3678 continue; 3679 } 3680 PermissionsState permissionsState = sb.getPermissionsState(); 3681 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 3682 userId, flagMask, flagValues); 3683 } 3684 if (changed) { 3685 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3686 } 3687 } 3688 } 3689 3690 @Override 3691 public boolean shouldShowRequestPermissionRationale(String permissionName, 3692 String packageName, int userId) { 3693 if (UserHandle.getCallingUserId() != userId) { 3694 mContext.enforceCallingPermission( 3695 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3696 "canShowRequestPermissionRationale for user " + userId); 3697 } 3698 3699 final int uid = getPackageUid(packageName, userId); 3700 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 3701 return false; 3702 } 3703 3704 if (checkPermission(permissionName, packageName, userId) 3705 == PackageManager.PERMISSION_GRANTED) { 3706 return false; 3707 } 3708 3709 final int flags; 3710 3711 final long identity = Binder.clearCallingIdentity(); 3712 try { 3713 flags = getPermissionFlags(permissionName, 3714 packageName, userId); 3715 } finally { 3716 Binder.restoreCallingIdentity(identity); 3717 } 3718 3719 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 3720 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 3721 | PackageManager.FLAG_PERMISSION_USER_FIXED; 3722 3723 if ((flags & fixedFlags) != 0) { 3724 return false; 3725 } 3726 3727 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 3728 } 3729 3730 void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) { 3731 BasePermission bp = mSettings.mPermissions.get(permission); 3732 if (bp == null) { 3733 throw new SecurityException("Missing " + permission + " permission"); 3734 } 3735 3736 SettingBase sb = (SettingBase) pkg.mExtras; 3737 PermissionsState permissionsState = sb.getPermissionsState(); 3738 3739 if (permissionsState.grantInstallPermission(bp) != 3740 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3741 scheduleWriteSettingsLocked(); 3742 } 3743 } 3744 3745 @Override 3746 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3747 mContext.enforceCallingOrSelfPermission( 3748 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 3749 "addOnPermissionsChangeListener"); 3750 3751 synchronized (mPackages) { 3752 mOnPermissionChangeListeners.addListenerLocked(listener); 3753 } 3754 } 3755 3756 @Override 3757 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3758 synchronized (mPackages) { 3759 mOnPermissionChangeListeners.removeListenerLocked(listener); 3760 } 3761 } 3762 3763 @Override 3764 public boolean isProtectedBroadcast(String actionName) { 3765 synchronized (mPackages) { 3766 return mProtectedBroadcasts.contains(actionName); 3767 } 3768 } 3769 3770 @Override 3771 public int checkSignatures(String pkg1, String pkg2) { 3772 synchronized (mPackages) { 3773 final PackageParser.Package p1 = mPackages.get(pkg1); 3774 final PackageParser.Package p2 = mPackages.get(pkg2); 3775 if (p1 == null || p1.mExtras == null 3776 || p2 == null || p2.mExtras == null) { 3777 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3778 } 3779 return compareSignatures(p1.mSignatures, p2.mSignatures); 3780 } 3781 } 3782 3783 @Override 3784 public int checkUidSignatures(int uid1, int uid2) { 3785 // Map to base uids. 3786 uid1 = UserHandle.getAppId(uid1); 3787 uid2 = UserHandle.getAppId(uid2); 3788 // reader 3789 synchronized (mPackages) { 3790 Signature[] s1; 3791 Signature[] s2; 3792 Object obj = mSettings.getUserIdLPr(uid1); 3793 if (obj != null) { 3794 if (obj instanceof SharedUserSetting) { 3795 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3796 } else if (obj instanceof PackageSetting) { 3797 s1 = ((PackageSetting)obj).signatures.mSignatures; 3798 } else { 3799 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3800 } 3801 } else { 3802 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3803 } 3804 obj = mSettings.getUserIdLPr(uid2); 3805 if (obj != null) { 3806 if (obj instanceof SharedUserSetting) { 3807 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3808 } else if (obj instanceof PackageSetting) { 3809 s2 = ((PackageSetting)obj).signatures.mSignatures; 3810 } else { 3811 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3812 } 3813 } else { 3814 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3815 } 3816 return compareSignatures(s1, s2); 3817 } 3818 } 3819 3820 private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) { 3821 final long identity = Binder.clearCallingIdentity(); 3822 try { 3823 if (sb instanceof SharedUserSetting) { 3824 SharedUserSetting sus = (SharedUserSetting) sb; 3825 final int packageCount = sus.packages.size(); 3826 for (int i = 0; i < packageCount; i++) { 3827 PackageSetting susPs = sus.packages.valueAt(i); 3828 if (userId == UserHandle.USER_ALL) { 3829 killApplication(susPs.pkg.packageName, susPs.appId, reason); 3830 } else { 3831 final int uid = UserHandle.getUid(userId, susPs.appId); 3832 killUid(uid, reason); 3833 } 3834 } 3835 } else if (sb instanceof PackageSetting) { 3836 PackageSetting ps = (PackageSetting) sb; 3837 if (userId == UserHandle.USER_ALL) { 3838 killApplication(ps.pkg.packageName, ps.appId, reason); 3839 } else { 3840 final int uid = UserHandle.getUid(userId, ps.appId); 3841 killUid(uid, reason); 3842 } 3843 } 3844 } finally { 3845 Binder.restoreCallingIdentity(identity); 3846 } 3847 } 3848 3849 private static void killUid(int uid, String reason) { 3850 IActivityManager am = ActivityManagerNative.getDefault(); 3851 if (am != null) { 3852 try { 3853 am.killUid(uid, reason); 3854 } catch (RemoteException e) { 3855 /* ignore - same process */ 3856 } 3857 } 3858 } 3859 3860 /** 3861 * Compares two sets of signatures. Returns: 3862 * <br /> 3863 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3864 * <br /> 3865 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3866 * <br /> 3867 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3868 * <br /> 3869 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3870 * <br /> 3871 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3872 */ 3873 static int compareSignatures(Signature[] s1, Signature[] s2) { 3874 if (s1 == null) { 3875 return s2 == null 3876 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3877 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3878 } 3879 3880 if (s2 == null) { 3881 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3882 } 3883 3884 if (s1.length != s2.length) { 3885 return PackageManager.SIGNATURE_NO_MATCH; 3886 } 3887 3888 // Since both signature sets are of size 1, we can compare without HashSets. 3889 if (s1.length == 1) { 3890 return s1[0].equals(s2[0]) ? 3891 PackageManager.SIGNATURE_MATCH : 3892 PackageManager.SIGNATURE_NO_MATCH; 3893 } 3894 3895 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3896 for (Signature sig : s1) { 3897 set1.add(sig); 3898 } 3899 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3900 for (Signature sig : s2) { 3901 set2.add(sig); 3902 } 3903 // Make sure s2 contains all signatures in s1. 3904 if (set1.equals(set2)) { 3905 return PackageManager.SIGNATURE_MATCH; 3906 } 3907 return PackageManager.SIGNATURE_NO_MATCH; 3908 } 3909 3910 /** 3911 * If the database version for this type of package (internal storage or 3912 * external storage) is less than the version where package signatures 3913 * were updated, return true. 3914 */ 3915 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3916 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 3917 DatabaseVersion.SIGNATURE_END_ENTITY)) 3918 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 3919 DatabaseVersion.SIGNATURE_END_ENTITY)); 3920 } 3921 3922 /** 3923 * Used for backward compatibility to make sure any packages with 3924 * certificate chains get upgraded to the new style. {@code existingSigs} 3925 * will be in the old format (since they were stored on disk from before the 3926 * system upgrade) and {@code scannedSigs} will be in the newer format. 3927 */ 3928 private int compareSignaturesCompat(PackageSignatures existingSigs, 3929 PackageParser.Package scannedPkg) { 3930 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 3931 return PackageManager.SIGNATURE_NO_MATCH; 3932 } 3933 3934 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 3935 for (Signature sig : existingSigs.mSignatures) { 3936 existingSet.add(sig); 3937 } 3938 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 3939 for (Signature sig : scannedPkg.mSignatures) { 3940 try { 3941 Signature[] chainSignatures = sig.getChainSignatures(); 3942 for (Signature chainSig : chainSignatures) { 3943 scannedCompatSet.add(chainSig); 3944 } 3945 } catch (CertificateEncodingException e) { 3946 scannedCompatSet.add(sig); 3947 } 3948 } 3949 /* 3950 * Make sure the expanded scanned set contains all signatures in the 3951 * existing one. 3952 */ 3953 if (scannedCompatSet.equals(existingSet)) { 3954 // Migrate the old signatures to the new scheme. 3955 existingSigs.assignSignatures(scannedPkg.mSignatures); 3956 // The new KeySets will be re-added later in the scanning process. 3957 synchronized (mPackages) { 3958 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 3959 } 3960 return PackageManager.SIGNATURE_MATCH; 3961 } 3962 return PackageManager.SIGNATURE_NO_MATCH; 3963 } 3964 3965 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3966 if (isExternal(scannedPkg)) { 3967 return mSettings.isExternalDatabaseVersionOlderThan( 3968 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3969 } else { 3970 return mSettings.isInternalDatabaseVersionOlderThan( 3971 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3972 } 3973 } 3974 3975 private int compareSignaturesRecover(PackageSignatures existingSigs, 3976 PackageParser.Package scannedPkg) { 3977 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 3978 return PackageManager.SIGNATURE_NO_MATCH; 3979 } 3980 3981 String msg = null; 3982 try { 3983 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 3984 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 3985 + scannedPkg.packageName); 3986 return PackageManager.SIGNATURE_MATCH; 3987 } 3988 } catch (CertificateException e) { 3989 msg = e.getMessage(); 3990 } 3991 3992 logCriticalInfo(Log.INFO, 3993 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 3994 return PackageManager.SIGNATURE_NO_MATCH; 3995 } 3996 3997 @Override 3998 public String[] getPackagesForUid(int uid) { 3999 uid = UserHandle.getAppId(uid); 4000 // reader 4001 synchronized (mPackages) { 4002 Object obj = mSettings.getUserIdLPr(uid); 4003 if (obj instanceof SharedUserSetting) { 4004 final SharedUserSetting sus = (SharedUserSetting) obj; 4005 final int N = sus.packages.size(); 4006 final String[] res = new String[N]; 4007 final Iterator<PackageSetting> it = sus.packages.iterator(); 4008 int i = 0; 4009 while (it.hasNext()) { 4010 res[i++] = it.next().name; 4011 } 4012 return res; 4013 } else if (obj instanceof PackageSetting) { 4014 final PackageSetting ps = (PackageSetting) obj; 4015 return new String[] { ps.name }; 4016 } 4017 } 4018 return null; 4019 } 4020 4021 @Override 4022 public String getNameForUid(int uid) { 4023 // reader 4024 synchronized (mPackages) { 4025 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4026 if (obj instanceof SharedUserSetting) { 4027 final SharedUserSetting sus = (SharedUserSetting) obj; 4028 return sus.name + ":" + sus.userId; 4029 } else if (obj instanceof PackageSetting) { 4030 final PackageSetting ps = (PackageSetting) obj; 4031 return ps.name; 4032 } 4033 } 4034 return null; 4035 } 4036 4037 @Override 4038 public int getUidForSharedUser(String sharedUserName) { 4039 if(sharedUserName == null) { 4040 return -1; 4041 } 4042 // reader 4043 synchronized (mPackages) { 4044 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4045 if (suid == null) { 4046 return -1; 4047 } 4048 return suid.userId; 4049 } 4050 } 4051 4052 @Override 4053 public int getFlagsForUid(int uid) { 4054 synchronized (mPackages) { 4055 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4056 if (obj instanceof SharedUserSetting) { 4057 final SharedUserSetting sus = (SharedUserSetting) obj; 4058 return sus.pkgFlags; 4059 } else if (obj instanceof PackageSetting) { 4060 final PackageSetting ps = (PackageSetting) obj; 4061 return ps.pkgFlags; 4062 } 4063 } 4064 return 0; 4065 } 4066 4067 @Override 4068 public int getPrivateFlagsForUid(int uid) { 4069 synchronized (mPackages) { 4070 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4071 if (obj instanceof SharedUserSetting) { 4072 final SharedUserSetting sus = (SharedUserSetting) obj; 4073 return sus.pkgPrivateFlags; 4074 } else if (obj instanceof PackageSetting) { 4075 final PackageSetting ps = (PackageSetting) obj; 4076 return ps.pkgPrivateFlags; 4077 } 4078 } 4079 return 0; 4080 } 4081 4082 @Override 4083 public boolean isUidPrivileged(int uid) { 4084 uid = UserHandle.getAppId(uid); 4085 // reader 4086 synchronized (mPackages) { 4087 Object obj = mSettings.getUserIdLPr(uid); 4088 if (obj instanceof SharedUserSetting) { 4089 final SharedUserSetting sus = (SharedUserSetting) obj; 4090 final Iterator<PackageSetting> it = sus.packages.iterator(); 4091 while (it.hasNext()) { 4092 if (it.next().isPrivileged()) { 4093 return true; 4094 } 4095 } 4096 } else if (obj instanceof PackageSetting) { 4097 final PackageSetting ps = (PackageSetting) obj; 4098 return ps.isPrivileged(); 4099 } 4100 } 4101 return false; 4102 } 4103 4104 @Override 4105 public String[] getAppOpPermissionPackages(String permissionName) { 4106 synchronized (mPackages) { 4107 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4108 if (pkgs == null) { 4109 return null; 4110 } 4111 return pkgs.toArray(new String[pkgs.size()]); 4112 } 4113 } 4114 4115 @Override 4116 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4117 int flags, int userId) { 4118 if (!sUserManager.exists(userId)) return null; 4119 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 4120 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4121 return chooseBestActivity(intent, resolvedType, flags, query, userId); 4122 } 4123 4124 @Override 4125 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4126 IntentFilter filter, int match, ComponentName activity) { 4127 final int userId = UserHandle.getCallingUserId(); 4128 if (DEBUG_PREFERRED) { 4129 Log.v(TAG, "setLastChosenActivity intent=" + intent 4130 + " resolvedType=" + resolvedType 4131 + " flags=" + flags 4132 + " filter=" + filter 4133 + " match=" + match 4134 + " activity=" + activity); 4135 filter.dump(new PrintStreamPrinter(System.out), " "); 4136 } 4137 intent.setComponent(null); 4138 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4139 // Find any earlier preferred or last chosen entries and nuke them 4140 findPreferredActivity(intent, resolvedType, 4141 flags, query, 0, false, true, false, userId); 4142 // Add the new activity as the last chosen for this filter 4143 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4144 "Setting last chosen"); 4145 } 4146 4147 @Override 4148 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4149 final int userId = UserHandle.getCallingUserId(); 4150 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4151 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4152 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4153 false, false, false, userId); 4154 } 4155 4156 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4157 int flags, List<ResolveInfo> query, int userId) { 4158 if (query != null) { 4159 final int N = query.size(); 4160 if (N == 1) { 4161 return query.get(0); 4162 } else if (N > 1) { 4163 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4164 // If there is more than one activity with the same priority, 4165 // then let the user decide between them. 4166 ResolveInfo r0 = query.get(0); 4167 ResolveInfo r1 = query.get(1); 4168 if (DEBUG_INTENT_MATCHING || debug) { 4169 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4170 + r1.activityInfo.name + "=" + r1.priority); 4171 } 4172 // If the first activity has a higher priority, or a different 4173 // default, then it is always desireable to pick it. 4174 if (r0.priority != r1.priority 4175 || r0.preferredOrder != r1.preferredOrder 4176 || r0.isDefault != r1.isDefault) { 4177 return query.get(0); 4178 } 4179 // If we have saved a preference for a preferred activity for 4180 // this Intent, use that. 4181 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4182 flags, query, r0.priority, true, false, debug, userId); 4183 if (ri != null) { 4184 return ri; 4185 } 4186 if (userId != 0) { 4187 ri = new ResolveInfo(mResolveInfo); 4188 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4189 ri.activityInfo.applicationInfo = new ApplicationInfo( 4190 ri.activityInfo.applicationInfo); 4191 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4192 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4193 return ri; 4194 } 4195 return mResolveInfo; 4196 } 4197 } 4198 return null; 4199 } 4200 4201 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4202 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4203 final int N = query.size(); 4204 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4205 .get(userId); 4206 // Get the list of persistent preferred activities that handle the intent 4207 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4208 List<PersistentPreferredActivity> pprefs = ppir != null 4209 ? ppir.queryIntent(intent, resolvedType, 4210 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4211 : null; 4212 if (pprefs != null && pprefs.size() > 0) { 4213 final int M = pprefs.size(); 4214 for (int i=0; i<M; i++) { 4215 final PersistentPreferredActivity ppa = pprefs.get(i); 4216 if (DEBUG_PREFERRED || debug) { 4217 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4218 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4219 + "\n component=" + ppa.mComponent); 4220 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4221 } 4222 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4223 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4224 if (DEBUG_PREFERRED || debug) { 4225 Slog.v(TAG, "Found persistent preferred activity:"); 4226 if (ai != null) { 4227 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4228 } else { 4229 Slog.v(TAG, " null"); 4230 } 4231 } 4232 if (ai == null) { 4233 // This previously registered persistent preferred activity 4234 // component is no longer known. Ignore it and do NOT remove it. 4235 continue; 4236 } 4237 for (int j=0; j<N; j++) { 4238 final ResolveInfo ri = query.get(j); 4239 if (!ri.activityInfo.applicationInfo.packageName 4240 .equals(ai.applicationInfo.packageName)) { 4241 continue; 4242 } 4243 if (!ri.activityInfo.name.equals(ai.name)) { 4244 continue; 4245 } 4246 // Found a persistent preference that can handle the intent. 4247 if (DEBUG_PREFERRED || debug) { 4248 Slog.v(TAG, "Returning persistent preferred activity: " + 4249 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4250 } 4251 return ri; 4252 } 4253 } 4254 } 4255 return null; 4256 } 4257 4258 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4259 List<ResolveInfo> query, int priority, boolean always, 4260 boolean removeMatches, boolean debug, int userId) { 4261 if (!sUserManager.exists(userId)) return null; 4262 // writer 4263 synchronized (mPackages) { 4264 if (intent.getSelector() != null) { 4265 intent = intent.getSelector(); 4266 } 4267 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4268 4269 // Try to find a matching persistent preferred activity. 4270 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4271 debug, userId); 4272 4273 // If a persistent preferred activity matched, use it. 4274 if (pri != null) { 4275 return pri; 4276 } 4277 4278 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4279 // Get the list of preferred activities that handle the intent 4280 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4281 List<PreferredActivity> prefs = pir != null 4282 ? pir.queryIntent(intent, resolvedType, 4283 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4284 : null; 4285 if (prefs != null && prefs.size() > 0) { 4286 boolean changed = false; 4287 try { 4288 // First figure out how good the original match set is. 4289 // We will only allow preferred activities that came 4290 // from the same match quality. 4291 int match = 0; 4292 4293 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4294 4295 final int N = query.size(); 4296 for (int j=0; j<N; j++) { 4297 final ResolveInfo ri = query.get(j); 4298 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4299 + ": 0x" + Integer.toHexString(match)); 4300 if (ri.match > match) { 4301 match = ri.match; 4302 } 4303 } 4304 4305 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4306 + Integer.toHexString(match)); 4307 4308 match &= IntentFilter.MATCH_CATEGORY_MASK; 4309 final int M = prefs.size(); 4310 for (int i=0; i<M; i++) { 4311 final PreferredActivity pa = prefs.get(i); 4312 if (DEBUG_PREFERRED || debug) { 4313 Slog.v(TAG, "Checking PreferredActivity ds=" 4314 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4315 + "\n component=" + pa.mPref.mComponent); 4316 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4317 } 4318 if (pa.mPref.mMatch != match) { 4319 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4320 + Integer.toHexString(pa.mPref.mMatch)); 4321 continue; 4322 } 4323 // If it's not an "always" type preferred activity and that's what we're 4324 // looking for, skip it. 4325 if (always && !pa.mPref.mAlways) { 4326 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4327 continue; 4328 } 4329 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4330 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4331 if (DEBUG_PREFERRED || debug) { 4332 Slog.v(TAG, "Found preferred activity:"); 4333 if (ai != null) { 4334 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4335 } else { 4336 Slog.v(TAG, " null"); 4337 } 4338 } 4339 if (ai == null) { 4340 // This previously registered preferred activity 4341 // component is no longer known. Most likely an update 4342 // to the app was installed and in the new version this 4343 // component no longer exists. Clean it up by removing 4344 // it from the preferred activities list, and skip it. 4345 Slog.w(TAG, "Removing dangling preferred activity: " 4346 + pa.mPref.mComponent); 4347 pir.removeFilter(pa); 4348 changed = true; 4349 continue; 4350 } 4351 for (int j=0; j<N; j++) { 4352 final ResolveInfo ri = query.get(j); 4353 if (!ri.activityInfo.applicationInfo.packageName 4354 .equals(ai.applicationInfo.packageName)) { 4355 continue; 4356 } 4357 if (!ri.activityInfo.name.equals(ai.name)) { 4358 continue; 4359 } 4360 4361 if (removeMatches) { 4362 pir.removeFilter(pa); 4363 changed = true; 4364 if (DEBUG_PREFERRED) { 4365 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4366 } 4367 break; 4368 } 4369 4370 // Okay we found a previously set preferred or last chosen app. 4371 // If the result set is different from when this 4372 // was created, we need to clear it and re-ask the 4373 // user their preference, if we're looking for an "always" type entry. 4374 if (always && !pa.mPref.sameSet(query)) { 4375 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4376 + intent + " type " + resolvedType); 4377 if (DEBUG_PREFERRED) { 4378 Slog.v(TAG, "Removing preferred activity since set changed " 4379 + pa.mPref.mComponent); 4380 } 4381 pir.removeFilter(pa); 4382 // Re-add the filter as a "last chosen" entry (!always) 4383 PreferredActivity lastChosen = new PreferredActivity( 4384 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4385 pir.addFilter(lastChosen); 4386 changed = true; 4387 return null; 4388 } 4389 4390 // Yay! Either the set matched or we're looking for the last chosen 4391 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4392 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4393 return ri; 4394 } 4395 } 4396 } finally { 4397 if (changed) { 4398 if (DEBUG_PREFERRED) { 4399 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4400 } 4401 scheduleWritePackageRestrictionsLocked(userId); 4402 } 4403 } 4404 } 4405 } 4406 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4407 return null; 4408 } 4409 4410 /* 4411 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4412 */ 4413 @Override 4414 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4415 int targetUserId) { 4416 mContext.enforceCallingOrSelfPermission( 4417 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4418 List<CrossProfileIntentFilter> matches = 4419 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4420 if (matches != null) { 4421 int size = matches.size(); 4422 for (int i = 0; i < size; i++) { 4423 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4424 } 4425 } 4426 if (hasWebURI(intent)) { 4427 // cross-profile app linking works only towards the parent. 4428 final UserInfo parent = getProfileParent(sourceUserId); 4429 synchronized(mPackages) { 4430 return getCrossProfileDomainPreferredLpr(intent, resolvedType, 0, sourceUserId, 4431 parent.id) != null; 4432 } 4433 } 4434 return false; 4435 } 4436 4437 private UserInfo getProfileParent(int userId) { 4438 final long identity = Binder.clearCallingIdentity(); 4439 try { 4440 return sUserManager.getProfileParent(userId); 4441 } finally { 4442 Binder.restoreCallingIdentity(identity); 4443 } 4444 } 4445 4446 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4447 String resolvedType, int userId) { 4448 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4449 if (resolver != null) { 4450 return resolver.queryIntent(intent, resolvedType, false, userId); 4451 } 4452 return null; 4453 } 4454 4455 @Override 4456 public List<ResolveInfo> queryIntentActivities(Intent intent, 4457 String resolvedType, int flags, int userId) { 4458 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4459 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4460 ComponentName comp = intent.getComponent(); 4461 if (comp == null) { 4462 if (intent.getSelector() != null) { 4463 intent = intent.getSelector(); 4464 comp = intent.getComponent(); 4465 } 4466 } 4467 4468 if (comp != null) { 4469 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4470 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4471 if (ai != null) { 4472 final ResolveInfo ri = new ResolveInfo(); 4473 ri.activityInfo = ai; 4474 list.add(ri); 4475 } 4476 return list; 4477 } 4478 4479 // reader 4480 synchronized (mPackages) { 4481 final String pkgName = intent.getPackage(); 4482 if (pkgName == null) { 4483 List<CrossProfileIntentFilter> matchingFilters = 4484 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4485 // Check for results that need to skip the current profile. 4486 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4487 resolvedType, flags, userId); 4488 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4489 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4490 result.add(xpResolveInfo); 4491 return filterIfNotPrimaryUser(result, userId); 4492 } 4493 4494 // Check for results in the current profile. 4495 List<ResolveInfo> result = mActivities.queryIntent( 4496 intent, resolvedType, flags, userId); 4497 4498 // Check for cross profile results. 4499 xpResolveInfo = queryCrossProfileIntents( 4500 matchingFilters, intent, resolvedType, flags, userId); 4501 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4502 result.add(xpResolveInfo); 4503 Collections.sort(result, mResolvePrioritySorter); 4504 } 4505 result = filterIfNotPrimaryUser(result, userId); 4506 if (hasWebURI(intent)) { 4507 CrossProfileDomainInfo xpDomainInfo = null; 4508 final UserInfo parent = getProfileParent(userId); 4509 if (parent != null) { 4510 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 4511 flags, userId, parent.id); 4512 } 4513 if (xpDomainInfo != null) { 4514 if (xpResolveInfo != null) { 4515 // If we didn't remove it, the cross-profile ResolveInfo would be twice 4516 // in the result. 4517 result.remove(xpResolveInfo); 4518 } 4519 if (result.size() == 0) { 4520 result.add(xpDomainInfo.resolveInfo); 4521 return result; 4522 } 4523 } else if (result.size() <= 1) { 4524 return result; 4525 } 4526 result = filterCandidatesWithDomainPreferredActivitiesLPr(flags, result, 4527 xpDomainInfo); 4528 Collections.sort(result, mResolvePrioritySorter); 4529 } 4530 return result; 4531 } 4532 final PackageParser.Package pkg = mPackages.get(pkgName); 4533 if (pkg != null) { 4534 return filterIfNotPrimaryUser( 4535 mActivities.queryIntentForPackage( 4536 intent, resolvedType, flags, pkg.activities, userId), 4537 userId); 4538 } 4539 return new ArrayList<ResolveInfo>(); 4540 } 4541 } 4542 4543 private static class CrossProfileDomainInfo { 4544 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 4545 ResolveInfo resolveInfo; 4546 /* Best domain verification status of the activities found in the other profile */ 4547 int bestDomainVerificationStatus; 4548 } 4549 4550 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 4551 String resolvedType, int flags, int sourceUserId, int parentUserId) { 4552 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 4553 sourceUserId)) { 4554 return null; 4555 } 4556 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4557 resolvedType, flags, parentUserId); 4558 4559 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 4560 return null; 4561 } 4562 CrossProfileDomainInfo result = null; 4563 int size = resultTargetUser.size(); 4564 for (int i = 0; i < size; i++) { 4565 ResolveInfo riTargetUser = resultTargetUser.get(i); 4566 // Intent filter verification is only for filters that specify a host. So don't return 4567 // those that handle all web uris. 4568 if (riTargetUser.handleAllWebDataURI) { 4569 continue; 4570 } 4571 String packageName = riTargetUser.activityInfo.packageName; 4572 PackageSetting ps = mSettings.mPackages.get(packageName); 4573 if (ps == null) { 4574 continue; 4575 } 4576 int status = getDomainVerificationStatusLPr(ps, parentUserId); 4577 if (result == null) { 4578 result = new CrossProfileDomainInfo(); 4579 result.resolveInfo = 4580 createForwardingResolveInfo(null, sourceUserId, parentUserId); 4581 result.bestDomainVerificationStatus = status; 4582 } else { 4583 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 4584 result.bestDomainVerificationStatus); 4585 } 4586 } 4587 return result; 4588 } 4589 4590 /** 4591 * Verification statuses are ordered from the worse to the best, except for 4592 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 4593 */ 4594 private int bestDomainVerificationStatus(int status1, int status2) { 4595 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4596 return status2; 4597 } 4598 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4599 return status1; 4600 } 4601 return (int) MathUtils.max(status1, status2); 4602 } 4603 4604 private boolean isUserEnabled(int userId) { 4605 long callingId = Binder.clearCallingIdentity(); 4606 try { 4607 UserInfo userInfo = sUserManager.getUserInfo(userId); 4608 return userInfo != null && userInfo.isEnabled(); 4609 } finally { 4610 Binder.restoreCallingIdentity(callingId); 4611 } 4612 } 4613 4614 /** 4615 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 4616 * 4617 * @return filtered list 4618 */ 4619 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 4620 if (userId == UserHandle.USER_OWNER) { 4621 return resolveInfos; 4622 } 4623 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 4624 ResolveInfo info = resolveInfos.get(i); 4625 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 4626 resolveInfos.remove(i); 4627 } 4628 } 4629 return resolveInfos; 4630 } 4631 4632 private static boolean hasWebURI(Intent intent) { 4633 if (intent.getData() == null) { 4634 return false; 4635 } 4636 final String scheme = intent.getScheme(); 4637 if (TextUtils.isEmpty(scheme)) { 4638 return false; 4639 } 4640 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4641 } 4642 4643 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr( 4644 int flags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo) { 4645 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4646 Slog.v("TAG", "Filtering results with preferred activities. Candidates count: " + 4647 candidates.size()); 4648 } 4649 4650 final int userId = UserHandle.getCallingUserId(); 4651 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4652 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 4653 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4654 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4655 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4656 4657 synchronized (mPackages) { 4658 final int count = candidates.size(); 4659 // First, try to use linked apps. Partition the candidates into four lists: 4660 // one for the final results, one for the "do not use ever", one for "undefined status" 4661 // and finally one for "browser app type". 4662 for (int n=0; n<count; n++) { 4663 ResolveInfo info = candidates.get(n); 4664 String packageName = info.activityInfo.packageName; 4665 PackageSetting ps = mSettings.mPackages.get(packageName); 4666 if (ps != null) { 4667 // Add to the special match all list (Browser use case) 4668 if (info.handleAllWebDataURI) { 4669 matchAllList.add(info); 4670 continue; 4671 } 4672 // Try to get the status from User settings first 4673 int status = getDomainVerificationStatusLPr(ps, userId); 4674 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4675 if (DEBUG_DOMAIN_VERIFICATION) { 4676 Slog.i(TAG, " + always: " + info.activityInfo.packageName); 4677 } 4678 alwaysList.add(info); 4679 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4680 if (DEBUG_DOMAIN_VERIFICATION) { 4681 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 4682 } 4683 neverList.add(info); 4684 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 4685 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 4686 if (DEBUG_DOMAIN_VERIFICATION) { 4687 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 4688 } 4689 undefinedList.add(info); 4690 } 4691 } 4692 } 4693 // First try to add the "always" resolution for the current user if there is any 4694 if (alwaysList.size() > 0) { 4695 result.addAll(alwaysList); 4696 // if there is an "always" for the parent user, add it. 4697 } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus 4698 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4699 result.add(xpDomainInfo.resolveInfo); 4700 } else { 4701 // Add all undefined Apps as we want them to appear in the Disambiguation dialog. 4702 result.addAll(undefinedList); 4703 if (xpDomainInfo != null && ( 4704 xpDomainInfo.bestDomainVerificationStatus 4705 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 4706 || xpDomainInfo.bestDomainVerificationStatus 4707 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) { 4708 result.add(xpDomainInfo.resolveInfo); 4709 } 4710 // Also add Browsers (all of them or only the default one) 4711 if ((flags & MATCH_ALL) != 0) { 4712 result.addAll(matchAllList); 4713 } else { 4714 // Try to add the Default Browser if we can 4715 final String defaultBrowserPackageName = getDefaultBrowserPackageName( 4716 UserHandle.myUserId()); 4717 if (!TextUtils.isEmpty(defaultBrowserPackageName)) { 4718 boolean defaultBrowserFound = false; 4719 final int browserCount = matchAllList.size(); 4720 for (int n=0; n<browserCount; n++) { 4721 ResolveInfo browser = matchAllList.get(n); 4722 if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4723 result.add(browser); 4724 defaultBrowserFound = true; 4725 break; 4726 } 4727 } 4728 if (!defaultBrowserFound) { 4729 result.addAll(matchAllList); 4730 } 4731 } else { 4732 result.addAll(matchAllList); 4733 } 4734 } 4735 4736 // If there is nothing selected, add all candidates and remove the ones that the user 4737 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 4738 if (result.size() == 0) { 4739 result.addAll(candidates); 4740 result.removeAll(neverList); 4741 } 4742 } 4743 } 4744 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4745 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 4746 result.size()); 4747 for (ResolveInfo info : result) { 4748 Slog.v(TAG, " + " + info.activityInfo); 4749 } 4750 } 4751 return result; 4752 } 4753 4754 private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4755 int status = ps.getDomainVerificationStatusForUser(userId); 4756 // if none available, get the master status 4757 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4758 if (ps.getIntentFilterVerificationInfo() != null) { 4759 status = ps.getIntentFilterVerificationInfo().getStatus(); 4760 } 4761 } 4762 return status; 4763 } 4764 4765 private ResolveInfo querySkipCurrentProfileIntents( 4766 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4767 int flags, int sourceUserId) { 4768 if (matchingFilters != null) { 4769 int size = matchingFilters.size(); 4770 for (int i = 0; i < size; i ++) { 4771 CrossProfileIntentFilter filter = matchingFilters.get(i); 4772 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4773 // Checking if there are activities in the target user that can handle the 4774 // intent. 4775 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4776 flags, sourceUserId); 4777 if (resolveInfo != null) { 4778 return resolveInfo; 4779 } 4780 } 4781 } 4782 } 4783 return null; 4784 } 4785 4786 // Return matching ResolveInfo if any for skip current profile intent filters. 4787 private ResolveInfo queryCrossProfileIntents( 4788 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4789 int flags, int sourceUserId) { 4790 if (matchingFilters != null) { 4791 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4792 // match the same intent. For performance reasons, it is better not to 4793 // run queryIntent twice for the same userId 4794 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4795 int size = matchingFilters.size(); 4796 for (int i = 0; i < size; i++) { 4797 CrossProfileIntentFilter filter = matchingFilters.get(i); 4798 int targetUserId = filter.getTargetUserId(); 4799 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4800 && !alreadyTriedUserIds.get(targetUserId)) { 4801 // Checking if there are activities in the target user that can handle the 4802 // intent. 4803 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4804 flags, sourceUserId); 4805 if (resolveInfo != null) return resolveInfo; 4806 alreadyTriedUserIds.put(targetUserId, true); 4807 } 4808 } 4809 } 4810 return null; 4811 } 4812 4813 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 4814 String resolvedType, int flags, int sourceUserId) { 4815 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4816 resolvedType, flags, filter.getTargetUserId()); 4817 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4818 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4819 } 4820 return null; 4821 } 4822 4823 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4824 int sourceUserId, int targetUserId) { 4825 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4826 String className; 4827 if (targetUserId == UserHandle.USER_OWNER) { 4828 className = FORWARD_INTENT_TO_USER_OWNER; 4829 } else { 4830 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4831 } 4832 ComponentName forwardingActivityComponentName = new ComponentName( 4833 mAndroidApplication.packageName, className); 4834 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4835 sourceUserId); 4836 if (targetUserId == UserHandle.USER_OWNER) { 4837 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 4838 forwardingResolveInfo.noResourceId = true; 4839 } 4840 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4841 forwardingResolveInfo.priority = 0; 4842 forwardingResolveInfo.preferredOrder = 0; 4843 forwardingResolveInfo.match = 0; 4844 forwardingResolveInfo.isDefault = true; 4845 forwardingResolveInfo.filter = filter; 4846 forwardingResolveInfo.targetUserId = targetUserId; 4847 return forwardingResolveInfo; 4848 } 4849 4850 @Override 4851 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4852 Intent[] specifics, String[] specificTypes, Intent intent, 4853 String resolvedType, int flags, int userId) { 4854 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4855 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4856 false, "query intent activity options"); 4857 final String resultsAction = intent.getAction(); 4858 4859 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4860 | PackageManager.GET_RESOLVED_FILTER, userId); 4861 4862 if (DEBUG_INTENT_MATCHING) { 4863 Log.v(TAG, "Query " + intent + ": " + results); 4864 } 4865 4866 int specificsPos = 0; 4867 int N; 4868 4869 // todo: note that the algorithm used here is O(N^2). This 4870 // isn't a problem in our current environment, but if we start running 4871 // into situations where we have more than 5 or 10 matches then this 4872 // should probably be changed to something smarter... 4873 4874 // First we go through and resolve each of the specific items 4875 // that were supplied, taking care of removing any corresponding 4876 // duplicate items in the generic resolve list. 4877 if (specifics != null) { 4878 for (int i=0; i<specifics.length; i++) { 4879 final Intent sintent = specifics[i]; 4880 if (sintent == null) { 4881 continue; 4882 } 4883 4884 if (DEBUG_INTENT_MATCHING) { 4885 Log.v(TAG, "Specific #" + i + ": " + sintent); 4886 } 4887 4888 String action = sintent.getAction(); 4889 if (resultsAction != null && resultsAction.equals(action)) { 4890 // If this action was explicitly requested, then don't 4891 // remove things that have it. 4892 action = null; 4893 } 4894 4895 ResolveInfo ri = null; 4896 ActivityInfo ai = null; 4897 4898 ComponentName comp = sintent.getComponent(); 4899 if (comp == null) { 4900 ri = resolveIntent( 4901 sintent, 4902 specificTypes != null ? specificTypes[i] : null, 4903 flags, userId); 4904 if (ri == null) { 4905 continue; 4906 } 4907 if (ri == mResolveInfo) { 4908 // ACK! Must do something better with this. 4909 } 4910 ai = ri.activityInfo; 4911 comp = new ComponentName(ai.applicationInfo.packageName, 4912 ai.name); 4913 } else { 4914 ai = getActivityInfo(comp, flags, userId); 4915 if (ai == null) { 4916 continue; 4917 } 4918 } 4919 4920 // Look for any generic query activities that are duplicates 4921 // of this specific one, and remove them from the results. 4922 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 4923 N = results.size(); 4924 int j; 4925 for (j=specificsPos; j<N; j++) { 4926 ResolveInfo sri = results.get(j); 4927 if ((sri.activityInfo.name.equals(comp.getClassName()) 4928 && sri.activityInfo.applicationInfo.packageName.equals( 4929 comp.getPackageName())) 4930 || (action != null && sri.filter.matchAction(action))) { 4931 results.remove(j); 4932 if (DEBUG_INTENT_MATCHING) Log.v( 4933 TAG, "Removing duplicate item from " + j 4934 + " due to specific " + specificsPos); 4935 if (ri == null) { 4936 ri = sri; 4937 } 4938 j--; 4939 N--; 4940 } 4941 } 4942 4943 // Add this specific item to its proper place. 4944 if (ri == null) { 4945 ri = new ResolveInfo(); 4946 ri.activityInfo = ai; 4947 } 4948 results.add(specificsPos, ri); 4949 ri.specificIndex = i; 4950 specificsPos++; 4951 } 4952 } 4953 4954 // Now we go through the remaining generic results and remove any 4955 // duplicate actions that are found here. 4956 N = results.size(); 4957 for (int i=specificsPos; i<N-1; i++) { 4958 final ResolveInfo rii = results.get(i); 4959 if (rii.filter == null) { 4960 continue; 4961 } 4962 4963 // Iterate over all of the actions of this result's intent 4964 // filter... typically this should be just one. 4965 final Iterator<String> it = rii.filter.actionsIterator(); 4966 if (it == null) { 4967 continue; 4968 } 4969 while (it.hasNext()) { 4970 final String action = it.next(); 4971 if (resultsAction != null && resultsAction.equals(action)) { 4972 // If this action was explicitly requested, then don't 4973 // remove things that have it. 4974 continue; 4975 } 4976 for (int j=i+1; j<N; j++) { 4977 final ResolveInfo rij = results.get(j); 4978 if (rij.filter != null && rij.filter.hasAction(action)) { 4979 results.remove(j); 4980 if (DEBUG_INTENT_MATCHING) Log.v( 4981 TAG, "Removing duplicate item from " + j 4982 + " due to action " + action + " at " + i); 4983 j--; 4984 N--; 4985 } 4986 } 4987 } 4988 4989 // If the caller didn't request filter information, drop it now 4990 // so we don't have to marshall/unmarshall it. 4991 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4992 rii.filter = null; 4993 } 4994 } 4995 4996 // Filter out the caller activity if so requested. 4997 if (caller != null) { 4998 N = results.size(); 4999 for (int i=0; i<N; i++) { 5000 ActivityInfo ainfo = results.get(i).activityInfo; 5001 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5002 && caller.getClassName().equals(ainfo.name)) { 5003 results.remove(i); 5004 break; 5005 } 5006 } 5007 } 5008 5009 // If the caller didn't request filter information, 5010 // drop them now so we don't have to 5011 // marshall/unmarshall it. 5012 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5013 N = results.size(); 5014 for (int i=0; i<N; i++) { 5015 results.get(i).filter = null; 5016 } 5017 } 5018 5019 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5020 return results; 5021 } 5022 5023 @Override 5024 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 5025 int userId) { 5026 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5027 ComponentName comp = intent.getComponent(); 5028 if (comp == null) { 5029 if (intent.getSelector() != null) { 5030 intent = intent.getSelector(); 5031 comp = intent.getComponent(); 5032 } 5033 } 5034 if (comp != null) { 5035 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5036 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5037 if (ai != null) { 5038 ResolveInfo ri = new ResolveInfo(); 5039 ri.activityInfo = ai; 5040 list.add(ri); 5041 } 5042 return list; 5043 } 5044 5045 // reader 5046 synchronized (mPackages) { 5047 String pkgName = intent.getPackage(); 5048 if (pkgName == null) { 5049 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5050 } 5051 final PackageParser.Package pkg = mPackages.get(pkgName); 5052 if (pkg != null) { 5053 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5054 userId); 5055 } 5056 return null; 5057 } 5058 } 5059 5060 @Override 5061 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5062 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 5063 if (!sUserManager.exists(userId)) return null; 5064 if (query != null) { 5065 if (query.size() >= 1) { 5066 // If there is more than one service with the same priority, 5067 // just arbitrarily pick the first one. 5068 return query.get(0); 5069 } 5070 } 5071 return null; 5072 } 5073 5074 @Override 5075 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 5076 int userId) { 5077 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5078 ComponentName comp = intent.getComponent(); 5079 if (comp == null) { 5080 if (intent.getSelector() != null) { 5081 intent = intent.getSelector(); 5082 comp = intent.getComponent(); 5083 } 5084 } 5085 if (comp != null) { 5086 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5087 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5088 if (si != null) { 5089 final ResolveInfo ri = new ResolveInfo(); 5090 ri.serviceInfo = si; 5091 list.add(ri); 5092 } 5093 return list; 5094 } 5095 5096 // reader 5097 synchronized (mPackages) { 5098 String pkgName = intent.getPackage(); 5099 if (pkgName == null) { 5100 return mServices.queryIntent(intent, resolvedType, flags, userId); 5101 } 5102 final PackageParser.Package pkg = mPackages.get(pkgName); 5103 if (pkg != null) { 5104 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5105 userId); 5106 } 5107 return null; 5108 } 5109 } 5110 5111 @Override 5112 public List<ResolveInfo> queryIntentContentProviders( 5113 Intent intent, String resolvedType, int flags, int userId) { 5114 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5115 ComponentName comp = intent.getComponent(); 5116 if (comp == null) { 5117 if (intent.getSelector() != null) { 5118 intent = intent.getSelector(); 5119 comp = intent.getComponent(); 5120 } 5121 } 5122 if (comp != null) { 5123 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5124 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5125 if (pi != null) { 5126 final ResolveInfo ri = new ResolveInfo(); 5127 ri.providerInfo = pi; 5128 list.add(ri); 5129 } 5130 return list; 5131 } 5132 5133 // reader 5134 synchronized (mPackages) { 5135 String pkgName = intent.getPackage(); 5136 if (pkgName == null) { 5137 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5138 } 5139 final PackageParser.Package pkg = mPackages.get(pkgName); 5140 if (pkg != null) { 5141 return mProviders.queryIntentForPackage( 5142 intent, resolvedType, flags, pkg.providers, userId); 5143 } 5144 return null; 5145 } 5146 } 5147 5148 @Override 5149 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5150 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5151 5152 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 5153 5154 // writer 5155 synchronized (mPackages) { 5156 ArrayList<PackageInfo> list; 5157 if (listUninstalled) { 5158 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5159 for (PackageSetting ps : mSettings.mPackages.values()) { 5160 PackageInfo pi; 5161 if (ps.pkg != null) { 5162 pi = generatePackageInfo(ps.pkg, flags, userId); 5163 } else { 5164 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5165 } 5166 if (pi != null) { 5167 list.add(pi); 5168 } 5169 } 5170 } else { 5171 list = new ArrayList<PackageInfo>(mPackages.size()); 5172 for (PackageParser.Package p : mPackages.values()) { 5173 PackageInfo pi = generatePackageInfo(p, flags, userId); 5174 if (pi != null) { 5175 list.add(pi); 5176 } 5177 } 5178 } 5179 5180 return new ParceledListSlice<PackageInfo>(list); 5181 } 5182 } 5183 5184 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5185 String[] permissions, boolean[] tmp, int flags, int userId) { 5186 int numMatch = 0; 5187 final PermissionsState permissionsState = ps.getPermissionsState(); 5188 for (int i=0; i<permissions.length; i++) { 5189 final String permission = permissions[i]; 5190 if (permissionsState.hasPermission(permission, userId)) { 5191 tmp[i] = true; 5192 numMatch++; 5193 } else { 5194 tmp[i] = false; 5195 } 5196 } 5197 if (numMatch == 0) { 5198 return; 5199 } 5200 PackageInfo pi; 5201 if (ps.pkg != null) { 5202 pi = generatePackageInfo(ps.pkg, flags, userId); 5203 } else { 5204 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5205 } 5206 // The above might return null in cases of uninstalled apps or install-state 5207 // skew across users/profiles. 5208 if (pi != null) { 5209 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5210 if (numMatch == permissions.length) { 5211 pi.requestedPermissions = permissions; 5212 } else { 5213 pi.requestedPermissions = new String[numMatch]; 5214 numMatch = 0; 5215 for (int i=0; i<permissions.length; i++) { 5216 if (tmp[i]) { 5217 pi.requestedPermissions[numMatch] = permissions[i]; 5218 numMatch++; 5219 } 5220 } 5221 } 5222 } 5223 list.add(pi); 5224 } 5225 } 5226 5227 @Override 5228 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5229 String[] permissions, int flags, int userId) { 5230 if (!sUserManager.exists(userId)) return null; 5231 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5232 5233 // writer 5234 synchronized (mPackages) { 5235 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5236 boolean[] tmpBools = new boolean[permissions.length]; 5237 if (listUninstalled) { 5238 for (PackageSetting ps : mSettings.mPackages.values()) { 5239 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5240 } 5241 } else { 5242 for (PackageParser.Package pkg : mPackages.values()) { 5243 PackageSetting ps = (PackageSetting)pkg.mExtras; 5244 if (ps != null) { 5245 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5246 userId); 5247 } 5248 } 5249 } 5250 5251 return new ParceledListSlice<PackageInfo>(list); 5252 } 5253 } 5254 5255 @Override 5256 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5257 if (!sUserManager.exists(userId)) return null; 5258 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5259 5260 // writer 5261 synchronized (mPackages) { 5262 ArrayList<ApplicationInfo> list; 5263 if (listUninstalled) { 5264 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5265 for (PackageSetting ps : mSettings.mPackages.values()) { 5266 ApplicationInfo ai; 5267 if (ps.pkg != null) { 5268 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5269 ps.readUserState(userId), userId); 5270 } else { 5271 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5272 } 5273 if (ai != null) { 5274 list.add(ai); 5275 } 5276 } 5277 } else { 5278 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5279 for (PackageParser.Package p : mPackages.values()) { 5280 if (p.mExtras != null) { 5281 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5282 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5283 if (ai != null) { 5284 list.add(ai); 5285 } 5286 } 5287 } 5288 } 5289 5290 return new ParceledListSlice<ApplicationInfo>(list); 5291 } 5292 } 5293 5294 public List<ApplicationInfo> getPersistentApplications(int flags) { 5295 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 5296 5297 // reader 5298 synchronized (mPackages) { 5299 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 5300 final int userId = UserHandle.getCallingUserId(); 5301 while (i.hasNext()) { 5302 final PackageParser.Package p = i.next(); 5303 if (p.applicationInfo != null 5304 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 5305 && (!mSafeMode || isSystemApp(p))) { 5306 PackageSetting ps = mSettings.mPackages.get(p.packageName); 5307 if (ps != null) { 5308 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5309 ps.readUserState(userId), userId); 5310 if (ai != null) { 5311 finalList.add(ai); 5312 } 5313 } 5314 } 5315 } 5316 } 5317 5318 return finalList; 5319 } 5320 5321 @Override 5322 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 5323 if (!sUserManager.exists(userId)) return null; 5324 // reader 5325 synchronized (mPackages) { 5326 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 5327 PackageSetting ps = provider != null 5328 ? mSettings.mPackages.get(provider.owner.packageName) 5329 : null; 5330 return ps != null 5331 && mSettings.isEnabledLPr(provider.info, flags, userId) 5332 && (!mSafeMode || (provider.info.applicationInfo.flags 5333 &ApplicationInfo.FLAG_SYSTEM) != 0) 5334 ? PackageParser.generateProviderInfo(provider, flags, 5335 ps.readUserState(userId), userId) 5336 : null; 5337 } 5338 } 5339 5340 /** 5341 * @deprecated 5342 */ 5343 @Deprecated 5344 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 5345 // reader 5346 synchronized (mPackages) { 5347 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 5348 .entrySet().iterator(); 5349 final int userId = UserHandle.getCallingUserId(); 5350 while (i.hasNext()) { 5351 Map.Entry<String, PackageParser.Provider> entry = i.next(); 5352 PackageParser.Provider p = entry.getValue(); 5353 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5354 5355 if (ps != null && p.syncable 5356 && (!mSafeMode || (p.info.applicationInfo.flags 5357 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 5358 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 5359 ps.readUserState(userId), userId); 5360 if (info != null) { 5361 outNames.add(entry.getKey()); 5362 outInfo.add(info); 5363 } 5364 } 5365 } 5366 } 5367 } 5368 5369 @Override 5370 public List<ProviderInfo> queryContentProviders(String processName, 5371 int uid, int flags) { 5372 ArrayList<ProviderInfo> finalList = null; 5373 // reader 5374 synchronized (mPackages) { 5375 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 5376 final int userId = processName != null ? 5377 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 5378 while (i.hasNext()) { 5379 final PackageParser.Provider p = i.next(); 5380 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5381 if (ps != null && p.info.authority != null 5382 && (processName == null 5383 || (p.info.processName.equals(processName) 5384 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 5385 && mSettings.isEnabledLPr(p.info, flags, userId) 5386 && (!mSafeMode 5387 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 5388 if (finalList == null) { 5389 finalList = new ArrayList<ProviderInfo>(3); 5390 } 5391 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 5392 ps.readUserState(userId), userId); 5393 if (info != null) { 5394 finalList.add(info); 5395 } 5396 } 5397 } 5398 } 5399 5400 if (finalList != null) { 5401 Collections.sort(finalList, mProviderInitOrderSorter); 5402 } 5403 5404 return finalList; 5405 } 5406 5407 @Override 5408 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 5409 int flags) { 5410 // reader 5411 synchronized (mPackages) { 5412 final PackageParser.Instrumentation i = mInstrumentation.get(name); 5413 return PackageParser.generateInstrumentationInfo(i, flags); 5414 } 5415 } 5416 5417 @Override 5418 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 5419 int flags) { 5420 ArrayList<InstrumentationInfo> finalList = 5421 new ArrayList<InstrumentationInfo>(); 5422 5423 // reader 5424 synchronized (mPackages) { 5425 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 5426 while (i.hasNext()) { 5427 final PackageParser.Instrumentation p = i.next(); 5428 if (targetPackage == null 5429 || targetPackage.equals(p.info.targetPackage)) { 5430 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 5431 flags); 5432 if (ii != null) { 5433 finalList.add(ii); 5434 } 5435 } 5436 } 5437 } 5438 5439 return finalList; 5440 } 5441 5442 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 5443 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 5444 if (overlays == null) { 5445 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 5446 return; 5447 } 5448 for (PackageParser.Package opkg : overlays.values()) { 5449 // Not much to do if idmap fails: we already logged the error 5450 // and we certainly don't want to abort installation of pkg simply 5451 // because an overlay didn't fit properly. For these reasons, 5452 // ignore the return value of createIdmapForPackagePairLI. 5453 createIdmapForPackagePairLI(pkg, opkg); 5454 } 5455 } 5456 5457 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 5458 PackageParser.Package opkg) { 5459 if (!opkg.mTrustedOverlay) { 5460 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 5461 opkg.baseCodePath + ": overlay not trusted"); 5462 return false; 5463 } 5464 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 5465 if (overlaySet == null) { 5466 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 5467 opkg.baseCodePath + " but target package has no known overlays"); 5468 return false; 5469 } 5470 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 5471 // TODO: generate idmap for split APKs 5472 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 5473 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 5474 + opkg.baseCodePath); 5475 return false; 5476 } 5477 PackageParser.Package[] overlayArray = 5478 overlaySet.values().toArray(new PackageParser.Package[0]); 5479 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 5480 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 5481 return p1.mOverlayPriority - p2.mOverlayPriority; 5482 } 5483 }; 5484 Arrays.sort(overlayArray, cmp); 5485 5486 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 5487 int i = 0; 5488 for (PackageParser.Package p : overlayArray) { 5489 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 5490 } 5491 return true; 5492 } 5493 5494 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5495 final File[] files = dir.listFiles(); 5496 if (ArrayUtils.isEmpty(files)) { 5497 Log.d(TAG, "No files in app dir " + dir); 5498 return; 5499 } 5500 5501 if (DEBUG_PACKAGE_SCANNING) { 5502 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 5503 + " flags=0x" + Integer.toHexString(parseFlags)); 5504 } 5505 5506 for (File file : files) { 5507 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 5508 && !PackageInstallerService.isStageName(file.getName()); 5509 if (!isPackage) { 5510 // Ignore entries which are not packages 5511 continue; 5512 } 5513 try { 5514 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 5515 scanFlags, currentTime, null); 5516 } catch (PackageManagerException e) { 5517 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 5518 5519 // Delete invalid userdata apps 5520 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 5521 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 5522 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 5523 if (file.isDirectory()) { 5524 mInstaller.rmPackageDir(file.getAbsolutePath()); 5525 } else { 5526 file.delete(); 5527 } 5528 } 5529 } 5530 } 5531 } 5532 5533 private static File getSettingsProblemFile() { 5534 File dataDir = Environment.getDataDirectory(); 5535 File systemDir = new File(dataDir, "system"); 5536 File fname = new File(systemDir, "uiderrors.txt"); 5537 return fname; 5538 } 5539 5540 static void reportSettingsProblem(int priority, String msg) { 5541 logCriticalInfo(priority, msg); 5542 } 5543 5544 static void logCriticalInfo(int priority, String msg) { 5545 Slog.println(priority, TAG, msg); 5546 EventLogTags.writePmCriticalInfo(msg); 5547 try { 5548 File fname = getSettingsProblemFile(); 5549 FileOutputStream out = new FileOutputStream(fname, true); 5550 PrintWriter pw = new FastPrintWriter(out); 5551 SimpleDateFormat formatter = new SimpleDateFormat(); 5552 String dateString = formatter.format(new Date(System.currentTimeMillis())); 5553 pw.println(dateString + ": " + msg); 5554 pw.close(); 5555 FileUtils.setPermissions( 5556 fname.toString(), 5557 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 5558 -1, -1); 5559 } catch (java.io.IOException e) { 5560 } 5561 } 5562 5563 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 5564 PackageParser.Package pkg, File srcFile, int parseFlags) 5565 throws PackageManagerException { 5566 if (ps != null 5567 && ps.codePath.equals(srcFile) 5568 && ps.timeStamp == srcFile.lastModified() 5569 && !isCompatSignatureUpdateNeeded(pkg) 5570 && !isRecoverSignatureUpdateNeeded(pkg)) { 5571 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 5572 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5573 ArraySet<PublicKey> signingKs; 5574 synchronized (mPackages) { 5575 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 5576 } 5577 if (ps.signatures.mSignatures != null 5578 && ps.signatures.mSignatures.length != 0 5579 && signingKs != null) { 5580 // Optimization: reuse the existing cached certificates 5581 // if the package appears to be unchanged. 5582 pkg.mSignatures = ps.signatures.mSignatures; 5583 pkg.mSigningKeys = signingKs; 5584 return; 5585 } 5586 5587 Slog.w(TAG, "PackageSetting for " + ps.name 5588 + " is missing signatures. Collecting certs again to recover them."); 5589 } else { 5590 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 5591 } 5592 5593 try { 5594 pp.collectCertificates(pkg, parseFlags); 5595 pp.collectManifestDigest(pkg); 5596 } catch (PackageParserException e) { 5597 throw PackageManagerException.from(e); 5598 } 5599 } 5600 5601 /* 5602 * Scan a package and return the newly parsed package. 5603 * Returns null in case of errors and the error code is stored in mLastScanError 5604 */ 5605 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 5606 long currentTime, UserHandle user) throws PackageManagerException { 5607 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 5608 parseFlags |= mDefParseFlags; 5609 PackageParser pp = new PackageParser(); 5610 pp.setSeparateProcesses(mSeparateProcesses); 5611 pp.setOnlyCoreApps(mOnlyCore); 5612 pp.setDisplayMetrics(mMetrics); 5613 5614 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 5615 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 5616 } 5617 5618 final PackageParser.Package pkg; 5619 try { 5620 pkg = pp.parsePackage(scanFile, parseFlags); 5621 } catch (PackageParserException e) { 5622 throw PackageManagerException.from(e); 5623 } 5624 5625 PackageSetting ps = null; 5626 PackageSetting updatedPkg; 5627 // reader 5628 synchronized (mPackages) { 5629 // Look to see if we already know about this package. 5630 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 5631 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 5632 // This package has been renamed to its original name. Let's 5633 // use that. 5634 ps = mSettings.peekPackageLPr(oldName); 5635 } 5636 // If there was no original package, see one for the real package name. 5637 if (ps == null) { 5638 ps = mSettings.peekPackageLPr(pkg.packageName); 5639 } 5640 // Check to see if this package could be hiding/updating a system 5641 // package. Must look for it either under the original or real 5642 // package name depending on our state. 5643 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 5644 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 5645 } 5646 boolean updatedPkgBetter = false; 5647 // First check if this is a system package that may involve an update 5648 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5649 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5650 // it needs to drop FLAG_PRIVILEGED. 5651 if (locationIsPrivileged(scanFile)) { 5652 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5653 } else { 5654 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5655 } 5656 5657 if (ps != null && !ps.codePath.equals(scanFile)) { 5658 // The path has changed from what was last scanned... check the 5659 // version of the new path against what we have stored to determine 5660 // what to do. 5661 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5662 if (pkg.mVersionCode <= ps.versionCode) { 5663 // The system package has been updated and the code path does not match 5664 // Ignore entry. Skip it. 5665 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5666 + " ignored: updated version " + ps.versionCode 5667 + " better than this " + pkg.mVersionCode); 5668 if (!updatedPkg.codePath.equals(scanFile)) { 5669 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5670 + ps.name + " changing from " + updatedPkg.codePathString 5671 + " to " + scanFile); 5672 updatedPkg.codePath = scanFile; 5673 updatedPkg.codePathString = scanFile.toString(); 5674 updatedPkg.resourcePath = scanFile; 5675 updatedPkg.resourcePathString = scanFile.toString(); 5676 } 5677 updatedPkg.pkg = pkg; 5678 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5679 "Package " + ps.name + " at " + scanFile 5680 + " ignored: updated version " + ps.versionCode 5681 + " better than this " + pkg.mVersionCode); 5682 } else { 5683 // The current app on the system partition is better than 5684 // what we have updated to on the data partition; switch 5685 // back to the system partition version. 5686 // At this point, its safely assumed that package installation for 5687 // apps in system partition will go through. If not there won't be a working 5688 // version of the app 5689 // writer 5690 synchronized (mPackages) { 5691 // Just remove the loaded entries from package lists. 5692 mPackages.remove(ps.name); 5693 } 5694 5695 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5696 + " reverting from " + ps.codePathString 5697 + ": new version " + pkg.mVersionCode 5698 + " better than installed " + ps.versionCode); 5699 5700 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5701 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5702 synchronized (mInstallLock) { 5703 args.cleanUpResourcesLI(); 5704 } 5705 synchronized (mPackages) { 5706 mSettings.enableSystemPackageLPw(ps.name); 5707 } 5708 updatedPkgBetter = true; 5709 } 5710 } 5711 } 5712 5713 if (updatedPkg != null) { 5714 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5715 // initially 5716 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5717 5718 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5719 // flag set initially 5720 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5721 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5722 } 5723 } 5724 5725 // Verify certificates against what was last scanned 5726 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5727 5728 /* 5729 * A new system app appeared, but we already had a non-system one of the 5730 * same name installed earlier. 5731 */ 5732 boolean shouldHideSystemApp = false; 5733 if (updatedPkg == null && ps != null 5734 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5735 /* 5736 * Check to make sure the signatures match first. If they don't, 5737 * wipe the installed application and its data. 5738 */ 5739 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5740 != PackageManager.SIGNATURE_MATCH) { 5741 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5742 + " signatures don't match existing userdata copy; removing"); 5743 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5744 ps = null; 5745 } else { 5746 /* 5747 * If the newly-added system app is an older version than the 5748 * already installed version, hide it. It will be scanned later 5749 * and re-added like an update. 5750 */ 5751 if (pkg.mVersionCode <= ps.versionCode) { 5752 shouldHideSystemApp = true; 5753 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5754 + " but new version " + pkg.mVersionCode + " better than installed " 5755 + ps.versionCode + "; hiding system"); 5756 } else { 5757 /* 5758 * The newly found system app is a newer version that the 5759 * one previously installed. Simply remove the 5760 * already-installed application and replace it with our own 5761 * while keeping the application data. 5762 */ 5763 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5764 + " reverting from " + ps.codePathString + ": new version " 5765 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5766 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5767 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5768 synchronized (mInstallLock) { 5769 args.cleanUpResourcesLI(); 5770 } 5771 } 5772 } 5773 } 5774 5775 // The apk is forward locked (not public) if its code and resources 5776 // are kept in different files. (except for app in either system or 5777 // vendor path). 5778 // TODO grab this value from PackageSettings 5779 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5780 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5781 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5782 } 5783 } 5784 5785 // TODO: extend to support forward-locked splits 5786 String resourcePath = null; 5787 String baseResourcePath = null; 5788 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5789 if (ps != null && ps.resourcePathString != null) { 5790 resourcePath = ps.resourcePathString; 5791 baseResourcePath = ps.resourcePathString; 5792 } else { 5793 // Should not happen at all. Just log an error. 5794 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5795 } 5796 } else { 5797 resourcePath = pkg.codePath; 5798 baseResourcePath = pkg.baseCodePath; 5799 } 5800 5801 // Set application objects path explicitly. 5802 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5803 pkg.applicationInfo.setCodePath(pkg.codePath); 5804 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5805 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5806 pkg.applicationInfo.setResourcePath(resourcePath); 5807 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5808 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5809 5810 // Note that we invoke the following method only if we are about to unpack an application 5811 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5812 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5813 5814 /* 5815 * If the system app should be overridden by a previously installed 5816 * data, hide the system app now and let the /data/app scan pick it up 5817 * again. 5818 */ 5819 if (shouldHideSystemApp) { 5820 synchronized (mPackages) { 5821 /* 5822 * We have to grant systems permissions before we hide, because 5823 * grantPermissions will assume the package update is trying to 5824 * expand its permissions. 5825 */ 5826 grantPermissionsLPw(pkg, true, pkg.packageName); 5827 mSettings.disableSystemPackageLPw(pkg.packageName); 5828 } 5829 } 5830 5831 return scannedPkg; 5832 } 5833 5834 private static String fixProcessName(String defProcessName, 5835 String processName, int uid) { 5836 if (processName == null) { 5837 return defProcessName; 5838 } 5839 return processName; 5840 } 5841 5842 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 5843 throws PackageManagerException { 5844 if (pkgSetting.signatures.mSignatures != null) { 5845 // Already existing package. Make sure signatures match 5846 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 5847 == PackageManager.SIGNATURE_MATCH; 5848 if (!match) { 5849 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 5850 == PackageManager.SIGNATURE_MATCH; 5851 } 5852 if (!match) { 5853 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 5854 == PackageManager.SIGNATURE_MATCH; 5855 } 5856 if (!match) { 5857 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5858 + pkg.packageName + " signatures do not match the " 5859 + "previously installed version; ignoring!"); 5860 } 5861 } 5862 5863 // Check for shared user signatures 5864 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 5865 // Already existing package. Make sure signatures match 5866 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5867 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 5868 if (!match) { 5869 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 5870 == PackageManager.SIGNATURE_MATCH; 5871 } 5872 if (!match) { 5873 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 5874 == PackageManager.SIGNATURE_MATCH; 5875 } 5876 if (!match) { 5877 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 5878 "Package " + pkg.packageName 5879 + " has no signatures that match those in shared user " 5880 + pkgSetting.sharedUser.name + "; ignoring!"); 5881 } 5882 } 5883 } 5884 5885 /** 5886 * Enforces that only the system UID or root's UID can call a method exposed 5887 * via Binder. 5888 * 5889 * @param message used as message if SecurityException is thrown 5890 * @throws SecurityException if the caller is not system or root 5891 */ 5892 private static final void enforceSystemOrRoot(String message) { 5893 final int uid = Binder.getCallingUid(); 5894 if (uid != Process.SYSTEM_UID && uid != 0) { 5895 throw new SecurityException(message); 5896 } 5897 } 5898 5899 @Override 5900 public void performBootDexOpt() { 5901 enforceSystemOrRoot("Only the system can request dexopt be performed"); 5902 5903 // Before everything else, see whether we need to fstrim. 5904 try { 5905 IMountService ms = PackageHelper.getMountService(); 5906 if (ms != null) { 5907 final boolean isUpgrade = isUpgrade(); 5908 boolean doTrim = isUpgrade; 5909 if (doTrim) { 5910 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 5911 } else { 5912 final long interval = android.provider.Settings.Global.getLong( 5913 mContext.getContentResolver(), 5914 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 5915 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 5916 if (interval > 0) { 5917 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 5918 if (timeSinceLast > interval) { 5919 doTrim = true; 5920 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 5921 + "; running immediately"); 5922 } 5923 } 5924 } 5925 if (doTrim) { 5926 if (!isFirstBoot()) { 5927 try { 5928 ActivityManagerNative.getDefault().showBootMessage( 5929 mContext.getResources().getString( 5930 R.string.android_upgrading_fstrim), true); 5931 } catch (RemoteException e) { 5932 } 5933 } 5934 ms.runMaintenance(); 5935 } 5936 } else { 5937 Slog.e(TAG, "Mount service unavailable!"); 5938 } 5939 } catch (RemoteException e) { 5940 // Can't happen; MountService is local 5941 } 5942 5943 final ArraySet<PackageParser.Package> pkgs; 5944 synchronized (mPackages) { 5945 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 5946 } 5947 5948 if (pkgs != null) { 5949 // Sort apps by importance for dexopt ordering. Important apps are given more priority 5950 // in case the device runs out of space. 5951 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 5952 // Give priority to core apps. 5953 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5954 PackageParser.Package pkg = it.next(); 5955 if (pkg.coreApp) { 5956 if (DEBUG_DEXOPT) { 5957 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 5958 } 5959 sortedPkgs.add(pkg); 5960 it.remove(); 5961 } 5962 } 5963 // Give priority to system apps that listen for pre boot complete. 5964 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 5965 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 5966 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5967 PackageParser.Package pkg = it.next(); 5968 if (pkgNames.contains(pkg.packageName)) { 5969 if (DEBUG_DEXOPT) { 5970 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 5971 } 5972 sortedPkgs.add(pkg); 5973 it.remove(); 5974 } 5975 } 5976 // Give priority to system apps. 5977 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5978 PackageParser.Package pkg = it.next(); 5979 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 5980 if (DEBUG_DEXOPT) { 5981 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 5982 } 5983 sortedPkgs.add(pkg); 5984 it.remove(); 5985 } 5986 } 5987 // Give priority to updated system apps. 5988 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5989 PackageParser.Package pkg = it.next(); 5990 if (pkg.isUpdatedSystemApp()) { 5991 if (DEBUG_DEXOPT) { 5992 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 5993 } 5994 sortedPkgs.add(pkg); 5995 it.remove(); 5996 } 5997 } 5998 // Give priority to apps that listen for boot complete. 5999 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 6000 pkgNames = getPackageNamesForIntent(intent); 6001 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6002 PackageParser.Package pkg = it.next(); 6003 if (pkgNames.contains(pkg.packageName)) { 6004 if (DEBUG_DEXOPT) { 6005 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 6006 } 6007 sortedPkgs.add(pkg); 6008 it.remove(); 6009 } 6010 } 6011 // Filter out packages that aren't recently used. 6012 filterRecentlyUsedApps(pkgs); 6013 // Add all remaining apps. 6014 for (PackageParser.Package pkg : pkgs) { 6015 if (DEBUG_DEXOPT) { 6016 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 6017 } 6018 sortedPkgs.add(pkg); 6019 } 6020 6021 // If we want to be lazy, filter everything that wasn't recently used. 6022 if (mLazyDexOpt) { 6023 filterRecentlyUsedApps(sortedPkgs); 6024 } 6025 6026 int i = 0; 6027 int total = sortedPkgs.size(); 6028 File dataDir = Environment.getDataDirectory(); 6029 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 6030 if (lowThreshold == 0) { 6031 throw new IllegalStateException("Invalid low memory threshold"); 6032 } 6033 for (PackageParser.Package pkg : sortedPkgs) { 6034 long usableSpace = dataDir.getUsableSpace(); 6035 if (usableSpace < lowThreshold) { 6036 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 6037 break; 6038 } 6039 performBootDexOpt(pkg, ++i, total); 6040 } 6041 } 6042 } 6043 6044 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 6045 // Filter out packages that aren't recently used. 6046 // 6047 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 6048 // should do a full dexopt. 6049 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 6050 int total = pkgs.size(); 6051 int skipped = 0; 6052 long now = System.currentTimeMillis(); 6053 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 6054 PackageParser.Package pkg = i.next(); 6055 long then = pkg.mLastPackageUsageTimeInMills; 6056 if (then + mDexOptLRUThresholdInMills < now) { 6057 if (DEBUG_DEXOPT) { 6058 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 6059 ((then == 0) ? "never" : new Date(then))); 6060 } 6061 i.remove(); 6062 skipped++; 6063 } 6064 } 6065 if (DEBUG_DEXOPT) { 6066 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 6067 } 6068 } 6069 } 6070 6071 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 6072 List<ResolveInfo> ris = null; 6073 try { 6074 ris = AppGlobals.getPackageManager().queryIntentReceivers( 6075 intent, null, 0, UserHandle.USER_OWNER); 6076 } catch (RemoteException e) { 6077 } 6078 ArraySet<String> pkgNames = new ArraySet<String>(); 6079 if (ris != null) { 6080 for (ResolveInfo ri : ris) { 6081 pkgNames.add(ri.activityInfo.packageName); 6082 } 6083 } 6084 return pkgNames; 6085 } 6086 6087 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 6088 if (DEBUG_DEXOPT) { 6089 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 6090 } 6091 if (!isFirstBoot()) { 6092 try { 6093 ActivityManagerNative.getDefault().showBootMessage( 6094 mContext.getResources().getString(R.string.android_upgrading_apk, 6095 curr, total), true); 6096 } catch (RemoteException e) { 6097 } 6098 } 6099 PackageParser.Package p = pkg; 6100 synchronized (mInstallLock) { 6101 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 6102 false /* force dex */, false /* defer */, true /* include dependencies */); 6103 } 6104 } 6105 6106 @Override 6107 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6108 return performDexOpt(packageName, instructionSet, false); 6109 } 6110 6111 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 6112 boolean dexopt = mLazyDexOpt || backgroundDexopt; 6113 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 6114 if (!dexopt && !updateUsage) { 6115 // We aren't going to dexopt or update usage, so bail early. 6116 return false; 6117 } 6118 PackageParser.Package p; 6119 final String targetInstructionSet; 6120 synchronized (mPackages) { 6121 p = mPackages.get(packageName); 6122 if (p == null) { 6123 return false; 6124 } 6125 if (updateUsage) { 6126 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6127 } 6128 mPackageUsage.write(false); 6129 if (!dexopt) { 6130 // We aren't going to dexopt, so bail early. 6131 return false; 6132 } 6133 6134 targetInstructionSet = instructionSet != null ? instructionSet : 6135 getPrimaryInstructionSet(p.applicationInfo); 6136 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 6137 return false; 6138 } 6139 } 6140 6141 synchronized (mInstallLock) { 6142 final String[] instructionSets = new String[] { targetInstructionSet }; 6143 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 6144 false /* forceDex */, false /* defer */, true /* inclDependencies */); 6145 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6146 } 6147 } 6148 6149 public ArraySet<String> getPackagesThatNeedDexOpt() { 6150 ArraySet<String> pkgs = null; 6151 synchronized (mPackages) { 6152 for (PackageParser.Package p : mPackages.values()) { 6153 if (DEBUG_DEXOPT) { 6154 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 6155 } 6156 if (!p.mDexOptPerformed.isEmpty()) { 6157 continue; 6158 } 6159 if (pkgs == null) { 6160 pkgs = new ArraySet<String>(); 6161 } 6162 pkgs.add(p.packageName); 6163 } 6164 } 6165 return pkgs; 6166 } 6167 6168 public void shutdown() { 6169 mPackageUsage.write(true); 6170 } 6171 6172 @Override 6173 public void forceDexOpt(String packageName) { 6174 enforceSystemOrRoot("forceDexOpt"); 6175 6176 PackageParser.Package pkg; 6177 synchronized (mPackages) { 6178 pkg = mPackages.get(packageName); 6179 if (pkg == null) { 6180 throw new IllegalArgumentException("Missing package: " + packageName); 6181 } 6182 } 6183 6184 synchronized (mInstallLock) { 6185 final String[] instructionSets = new String[] { 6186 getPrimaryInstructionSet(pkg.applicationInfo) }; 6187 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 6188 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 6189 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 6190 throw new IllegalStateException("Failed to dexopt: " + res); 6191 } 6192 } 6193 } 6194 6195 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 6196 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 6197 Slog.w(TAG, "Unable to update from " + oldPkg.name 6198 + " to " + newPkg.packageName 6199 + ": old package not in system partition"); 6200 return false; 6201 } else if (mPackages.get(oldPkg.name) != null) { 6202 Slog.w(TAG, "Unable to update from " + oldPkg.name 6203 + " to " + newPkg.packageName 6204 + ": old package still exists"); 6205 return false; 6206 } 6207 return true; 6208 } 6209 6210 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 6211 int[] users = sUserManager.getUserIds(); 6212 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 6213 if (res < 0) { 6214 return res; 6215 } 6216 for (int user : users) { 6217 if (user != 0) { 6218 res = mInstaller.createUserData(volumeUuid, packageName, 6219 UserHandle.getUid(user, uid), user, seinfo); 6220 if (res < 0) { 6221 return res; 6222 } 6223 } 6224 } 6225 return res; 6226 } 6227 6228 private int removeDataDirsLI(String volumeUuid, String packageName) { 6229 int[] users = sUserManager.getUserIds(); 6230 int res = 0; 6231 for (int user : users) { 6232 int resInner = mInstaller.remove(volumeUuid, packageName, user); 6233 if (resInner < 0) { 6234 res = resInner; 6235 } 6236 } 6237 6238 return res; 6239 } 6240 6241 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 6242 int[] users = sUserManager.getUserIds(); 6243 int res = 0; 6244 for (int user : users) { 6245 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 6246 if (resInner < 0) { 6247 res = resInner; 6248 } 6249 } 6250 return res; 6251 } 6252 6253 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 6254 PackageParser.Package changingLib) { 6255 if (file.path != null) { 6256 usesLibraryFiles.add(file.path); 6257 return; 6258 } 6259 PackageParser.Package p = mPackages.get(file.apk); 6260 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 6261 // If we are doing this while in the middle of updating a library apk, 6262 // then we need to make sure to use that new apk for determining the 6263 // dependencies here. (We haven't yet finished committing the new apk 6264 // to the package manager state.) 6265 if (p == null || p.packageName.equals(changingLib.packageName)) { 6266 p = changingLib; 6267 } 6268 } 6269 if (p != null) { 6270 usesLibraryFiles.addAll(p.getAllCodePaths()); 6271 } 6272 } 6273 6274 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 6275 PackageParser.Package changingLib) throws PackageManagerException { 6276 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 6277 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 6278 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 6279 for (int i=0; i<N; i++) { 6280 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 6281 if (file == null) { 6282 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 6283 "Package " + pkg.packageName + " requires unavailable shared library " 6284 + pkg.usesLibraries.get(i) + "; failing!"); 6285 } 6286 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6287 } 6288 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 6289 for (int i=0; i<N; i++) { 6290 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 6291 if (file == null) { 6292 Slog.w(TAG, "Package " + pkg.packageName 6293 + " desires unavailable shared library " 6294 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 6295 } else { 6296 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6297 } 6298 } 6299 N = usesLibraryFiles.size(); 6300 if (N > 0) { 6301 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 6302 } else { 6303 pkg.usesLibraryFiles = null; 6304 } 6305 } 6306 } 6307 6308 private static boolean hasString(List<String> list, List<String> which) { 6309 if (list == null) { 6310 return false; 6311 } 6312 for (int i=list.size()-1; i>=0; i--) { 6313 for (int j=which.size()-1; j>=0; j--) { 6314 if (which.get(j).equals(list.get(i))) { 6315 return true; 6316 } 6317 } 6318 } 6319 return false; 6320 } 6321 6322 private void updateAllSharedLibrariesLPw() { 6323 for (PackageParser.Package pkg : mPackages.values()) { 6324 try { 6325 updateSharedLibrariesLPw(pkg, null); 6326 } catch (PackageManagerException e) { 6327 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6328 } 6329 } 6330 } 6331 6332 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 6333 PackageParser.Package changingPkg) { 6334 ArrayList<PackageParser.Package> res = null; 6335 for (PackageParser.Package pkg : mPackages.values()) { 6336 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 6337 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 6338 if (res == null) { 6339 res = new ArrayList<PackageParser.Package>(); 6340 } 6341 res.add(pkg); 6342 try { 6343 updateSharedLibrariesLPw(pkg, changingPkg); 6344 } catch (PackageManagerException e) { 6345 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6346 } 6347 } 6348 } 6349 return res; 6350 } 6351 6352 /** 6353 * Derive the value of the {@code cpuAbiOverride} based on the provided 6354 * value and an optional stored value from the package settings. 6355 */ 6356 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 6357 String cpuAbiOverride = null; 6358 6359 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 6360 cpuAbiOverride = null; 6361 } else if (abiOverride != null) { 6362 cpuAbiOverride = abiOverride; 6363 } else if (settings != null) { 6364 cpuAbiOverride = settings.cpuAbiOverrideString; 6365 } 6366 6367 return cpuAbiOverride; 6368 } 6369 6370 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 6371 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6372 boolean success = false; 6373 try { 6374 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 6375 currentTime, user); 6376 success = true; 6377 return res; 6378 } finally { 6379 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 6380 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 6381 } 6382 } 6383 } 6384 6385 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 6386 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6387 final File scanFile = new File(pkg.codePath); 6388 if (pkg.applicationInfo.getCodePath() == null || 6389 pkg.applicationInfo.getResourcePath() == null) { 6390 // Bail out. The resource and code paths haven't been set. 6391 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 6392 "Code and resource paths haven't been set correctly"); 6393 } 6394 6395 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 6396 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 6397 } else { 6398 // Only allow system apps to be flagged as core apps. 6399 pkg.coreApp = false; 6400 } 6401 6402 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 6403 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6404 } 6405 6406 if (mCustomResolverComponentName != null && 6407 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 6408 setUpCustomResolverActivity(pkg); 6409 } 6410 6411 if (pkg.packageName.equals("android")) { 6412 synchronized (mPackages) { 6413 if (mAndroidApplication != null) { 6414 Slog.w(TAG, "*************************************************"); 6415 Slog.w(TAG, "Core android package being redefined. Skipping."); 6416 Slog.w(TAG, " file=" + scanFile); 6417 Slog.w(TAG, "*************************************************"); 6418 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6419 "Core android package being redefined. Skipping."); 6420 } 6421 6422 // Set up information for our fall-back user intent resolution activity. 6423 mPlatformPackage = pkg; 6424 pkg.mVersionCode = mSdkVersion; 6425 mAndroidApplication = pkg.applicationInfo; 6426 6427 if (!mResolverReplaced) { 6428 mResolveActivity.applicationInfo = mAndroidApplication; 6429 mResolveActivity.name = ResolverActivity.class.getName(); 6430 mResolveActivity.packageName = mAndroidApplication.packageName; 6431 mResolveActivity.processName = "system:ui"; 6432 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6433 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 6434 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 6435 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 6436 mResolveActivity.exported = true; 6437 mResolveActivity.enabled = true; 6438 mResolveInfo.activityInfo = mResolveActivity; 6439 mResolveInfo.priority = 0; 6440 mResolveInfo.preferredOrder = 0; 6441 mResolveInfo.match = 0; 6442 mResolveComponentName = new ComponentName( 6443 mAndroidApplication.packageName, mResolveActivity.name); 6444 } 6445 } 6446 } 6447 6448 if (DEBUG_PACKAGE_SCANNING) { 6449 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6450 Log.d(TAG, "Scanning package " + pkg.packageName); 6451 } 6452 6453 if (mPackages.containsKey(pkg.packageName) 6454 || mSharedLibraries.containsKey(pkg.packageName)) { 6455 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6456 "Application package " + pkg.packageName 6457 + " already installed. Skipping duplicate."); 6458 } 6459 6460 // If we're only installing presumed-existing packages, require that the 6461 // scanned APK is both already known and at the path previously established 6462 // for it. Previously unknown packages we pick up normally, but if we have an 6463 // a priori expectation about this package's install presence, enforce it. 6464 // With a singular exception for new system packages. When an OTA contains 6465 // a new system package, we allow the codepath to change from a system location 6466 // to the user-installed location. If we don't allow this change, any newer, 6467 // user-installed version of the application will be ignored. 6468 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 6469 if (mExpectingBetter.containsKey(pkg.packageName)) { 6470 logCriticalInfo(Log.WARN, 6471 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 6472 } else { 6473 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 6474 if (known != null) { 6475 if (DEBUG_PACKAGE_SCANNING) { 6476 Log.d(TAG, "Examining " + pkg.codePath 6477 + " and requiring known paths " + known.codePathString 6478 + " & " + known.resourcePathString); 6479 } 6480 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6481 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6482 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6483 "Application package " + pkg.packageName 6484 + " found at " + pkg.applicationInfo.getCodePath() 6485 + " but expected at " + known.codePathString + "; ignoring."); 6486 } 6487 } 6488 } 6489 } 6490 6491 // Initialize package source and resource directories 6492 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6493 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6494 6495 SharedUserSetting suid = null; 6496 PackageSetting pkgSetting = null; 6497 6498 if (!isSystemApp(pkg)) { 6499 // Only system apps can use these features. 6500 pkg.mOriginalPackages = null; 6501 pkg.mRealPackage = null; 6502 pkg.mAdoptPermissions = null; 6503 } 6504 6505 // writer 6506 synchronized (mPackages) { 6507 if (pkg.mSharedUserId != null) { 6508 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 6509 if (suid == null) { 6510 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6511 "Creating application package " + pkg.packageName 6512 + " for shared user failed"); 6513 } 6514 if (DEBUG_PACKAGE_SCANNING) { 6515 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6516 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 6517 + "): packages=" + suid.packages); 6518 } 6519 } 6520 6521 // Check if we are renaming from an original package name. 6522 PackageSetting origPackage = null; 6523 String realName = null; 6524 if (pkg.mOriginalPackages != null) { 6525 // This package may need to be renamed to a previously 6526 // installed name. Let's check on that... 6527 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 6528 if (pkg.mOriginalPackages.contains(renamed)) { 6529 // This package had originally been installed as the 6530 // original name, and we have already taken care of 6531 // transitioning to the new one. Just update the new 6532 // one to continue using the old name. 6533 realName = pkg.mRealPackage; 6534 if (!pkg.packageName.equals(renamed)) { 6535 // Callers into this function may have already taken 6536 // care of renaming the package; only do it here if 6537 // it is not already done. 6538 pkg.setPackageName(renamed); 6539 } 6540 6541 } else { 6542 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 6543 if ((origPackage = mSettings.peekPackageLPr( 6544 pkg.mOriginalPackages.get(i))) != null) { 6545 // We do have the package already installed under its 6546 // original name... should we use it? 6547 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 6548 // New package is not compatible with original. 6549 origPackage = null; 6550 continue; 6551 } else if (origPackage.sharedUser != null) { 6552 // Make sure uid is compatible between packages. 6553 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 6554 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 6555 + " to " + pkg.packageName + ": old uid " 6556 + origPackage.sharedUser.name 6557 + " differs from " + pkg.mSharedUserId); 6558 origPackage = null; 6559 continue; 6560 } 6561 } else { 6562 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6563 + pkg.packageName + " to old name " + origPackage.name); 6564 } 6565 break; 6566 } 6567 } 6568 } 6569 } 6570 6571 if (mTransferedPackages.contains(pkg.packageName)) { 6572 Slog.w(TAG, "Package " + pkg.packageName 6573 + " was transferred to another, but its .apk remains"); 6574 } 6575 6576 // Just create the setting, don't add it yet. For already existing packages 6577 // the PkgSetting exists already and doesn't have to be created. 6578 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6579 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6580 pkg.applicationInfo.primaryCpuAbi, 6581 pkg.applicationInfo.secondaryCpuAbi, 6582 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6583 user, false); 6584 if (pkgSetting == null) { 6585 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6586 "Creating application package " + pkg.packageName + " failed"); 6587 } 6588 6589 if (pkgSetting.origPackage != null) { 6590 // If we are first transitioning from an original package, 6591 // fix up the new package's name now. We need to do this after 6592 // looking up the package under its new name, so getPackageLP 6593 // can take care of fiddling things correctly. 6594 pkg.setPackageName(origPackage.name); 6595 6596 // File a report about this. 6597 String msg = "New package " + pkgSetting.realName 6598 + " renamed to replace old package " + pkgSetting.name; 6599 reportSettingsProblem(Log.WARN, msg); 6600 6601 // Make a note of it. 6602 mTransferedPackages.add(origPackage.name); 6603 6604 // No longer need to retain this. 6605 pkgSetting.origPackage = null; 6606 } 6607 6608 if (realName != null) { 6609 // Make a note of it. 6610 mTransferedPackages.add(pkg.packageName); 6611 } 6612 6613 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6614 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6615 } 6616 6617 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6618 // Check all shared libraries and map to their actual file path. 6619 // We only do this here for apps not on a system dir, because those 6620 // are the only ones that can fail an install due to this. We 6621 // will take care of the system apps by updating all of their 6622 // library paths after the scan is done. 6623 updateSharedLibrariesLPw(pkg, null); 6624 } 6625 6626 if (mFoundPolicyFile) { 6627 SELinuxMMAC.assignSeinfoValue(pkg); 6628 } 6629 6630 pkg.applicationInfo.uid = pkgSetting.appId; 6631 pkg.mExtras = pkgSetting; 6632 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 6633 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 6634 // We just determined the app is signed correctly, so bring 6635 // over the latest parsed certs. 6636 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6637 } else { 6638 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6639 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6640 "Package " + pkg.packageName + " upgrade keys do not match the " 6641 + "previously installed version"); 6642 } else { 6643 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6644 String msg = "System package " + pkg.packageName 6645 + " signature changed; retaining data."; 6646 reportSettingsProblem(Log.WARN, msg); 6647 } 6648 } 6649 } else { 6650 try { 6651 verifySignaturesLP(pkgSetting, pkg); 6652 // We just determined the app is signed correctly, so bring 6653 // over the latest parsed certs. 6654 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6655 } catch (PackageManagerException e) { 6656 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6657 throw e; 6658 } 6659 // The signature has changed, but this package is in the system 6660 // image... let's recover! 6661 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6662 // However... if this package is part of a shared user, but it 6663 // doesn't match the signature of the shared user, let's fail. 6664 // What this means is that you can't change the signatures 6665 // associated with an overall shared user, which doesn't seem all 6666 // that unreasonable. 6667 if (pkgSetting.sharedUser != null) { 6668 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6669 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 6670 throw new PackageManagerException( 6671 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6672 "Signature mismatch for shared user : " 6673 + pkgSetting.sharedUser); 6674 } 6675 } 6676 // File a report about this. 6677 String msg = "System package " + pkg.packageName 6678 + " signature changed; retaining data."; 6679 reportSettingsProblem(Log.WARN, msg); 6680 } 6681 } 6682 // Verify that this new package doesn't have any content providers 6683 // that conflict with existing packages. Only do this if the 6684 // package isn't already installed, since we don't want to break 6685 // things that are installed. 6686 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6687 final int N = pkg.providers.size(); 6688 int i; 6689 for (i=0; i<N; i++) { 6690 PackageParser.Provider p = pkg.providers.get(i); 6691 if (p.info.authority != null) { 6692 String names[] = p.info.authority.split(";"); 6693 for (int j = 0; j < names.length; j++) { 6694 if (mProvidersByAuthority.containsKey(names[j])) { 6695 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6696 final String otherPackageName = 6697 ((other != null && other.getComponentName() != null) ? 6698 other.getComponentName().getPackageName() : "?"); 6699 throw new PackageManagerException( 6700 INSTALL_FAILED_CONFLICTING_PROVIDER, 6701 "Can't install because provider name " + names[j] 6702 + " (in package " + pkg.applicationInfo.packageName 6703 + ") is already used by " + otherPackageName); 6704 } 6705 } 6706 } 6707 } 6708 } 6709 6710 if (pkg.mAdoptPermissions != null) { 6711 // This package wants to adopt ownership of permissions from 6712 // another package. 6713 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6714 final String origName = pkg.mAdoptPermissions.get(i); 6715 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6716 if (orig != null) { 6717 if (verifyPackageUpdateLPr(orig, pkg)) { 6718 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6719 + pkg.packageName); 6720 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6721 } 6722 } 6723 } 6724 } 6725 } 6726 6727 final String pkgName = pkg.packageName; 6728 6729 final long scanFileTime = scanFile.lastModified(); 6730 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6731 pkg.applicationInfo.processName = fixProcessName( 6732 pkg.applicationInfo.packageName, 6733 pkg.applicationInfo.processName, 6734 pkg.applicationInfo.uid); 6735 6736 File dataPath; 6737 if (mPlatformPackage == pkg) { 6738 // The system package is special. 6739 dataPath = new File(Environment.getDataDirectory(), "system"); 6740 6741 pkg.applicationInfo.dataDir = dataPath.getPath(); 6742 6743 } else { 6744 // This is a normal package, need to make its data directory. 6745 dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid, 6746 UserHandle.USER_OWNER, pkg.packageName); 6747 6748 boolean uidError = false; 6749 if (dataPath.exists()) { 6750 int currentUid = 0; 6751 try { 6752 StructStat stat = Os.stat(dataPath.getPath()); 6753 currentUid = stat.st_uid; 6754 } catch (ErrnoException e) { 6755 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6756 } 6757 6758 // If we have mismatched owners for the data path, we have a problem. 6759 if (currentUid != pkg.applicationInfo.uid) { 6760 boolean recovered = false; 6761 if (currentUid == 0) { 6762 // The directory somehow became owned by root. Wow. 6763 // This is probably because the system was stopped while 6764 // installd was in the middle of messing with its libs 6765 // directory. Ask installd to fix that. 6766 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6767 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6768 if (ret >= 0) { 6769 recovered = true; 6770 String msg = "Package " + pkg.packageName 6771 + " unexpectedly changed to uid 0; recovered to " + 6772 + pkg.applicationInfo.uid; 6773 reportSettingsProblem(Log.WARN, msg); 6774 } 6775 } 6776 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6777 || (scanFlags&SCAN_BOOTING) != 0)) { 6778 // If this is a system app, we can at least delete its 6779 // current data so the application will still work. 6780 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6781 if (ret >= 0) { 6782 // TODO: Kill the processes first 6783 // Old data gone! 6784 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6785 ? "System package " : "Third party package "; 6786 String msg = prefix + pkg.packageName 6787 + " has changed from uid: " 6788 + currentUid + " to " 6789 + pkg.applicationInfo.uid + "; old data erased"; 6790 reportSettingsProblem(Log.WARN, msg); 6791 recovered = true; 6792 6793 // And now re-install the app. 6794 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6795 pkg.applicationInfo.seinfo); 6796 if (ret == -1) { 6797 // Ack should not happen! 6798 msg = prefix + pkg.packageName 6799 + " could not have data directory re-created after delete."; 6800 reportSettingsProblem(Log.WARN, msg); 6801 throw new PackageManagerException( 6802 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6803 } 6804 } 6805 if (!recovered) { 6806 mHasSystemUidErrors = true; 6807 } 6808 } else if (!recovered) { 6809 // If we allow this install to proceed, we will be broken. 6810 // Abort, abort! 6811 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6812 "scanPackageLI"); 6813 } 6814 if (!recovered) { 6815 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6816 + pkg.applicationInfo.uid + "/fs_" 6817 + currentUid; 6818 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6819 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6820 String msg = "Package " + pkg.packageName 6821 + " has mismatched uid: " 6822 + currentUid + " on disk, " 6823 + pkg.applicationInfo.uid + " in settings"; 6824 // writer 6825 synchronized (mPackages) { 6826 mSettings.mReadMessages.append(msg); 6827 mSettings.mReadMessages.append('\n'); 6828 uidError = true; 6829 if (!pkgSetting.uidError) { 6830 reportSettingsProblem(Log.ERROR, msg); 6831 } 6832 } 6833 } 6834 } 6835 pkg.applicationInfo.dataDir = dataPath.getPath(); 6836 if (mShouldRestoreconData) { 6837 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6838 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 6839 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 6840 } 6841 } else { 6842 if (DEBUG_PACKAGE_SCANNING) { 6843 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6844 Log.v(TAG, "Want this data dir: " + dataPath); 6845 } 6846 //invoke installer to do the actual installation 6847 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6848 pkg.applicationInfo.seinfo); 6849 if (ret < 0) { 6850 // Error from installer 6851 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6852 "Unable to create data dirs [errorCode=" + ret + "]"); 6853 } 6854 6855 if (dataPath.exists()) { 6856 pkg.applicationInfo.dataDir = dataPath.getPath(); 6857 } else { 6858 Slog.w(TAG, "Unable to create data directory: " + dataPath); 6859 pkg.applicationInfo.dataDir = null; 6860 } 6861 } 6862 6863 pkgSetting.uidError = uidError; 6864 } 6865 6866 final String path = scanFile.getPath(); 6867 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6868 6869 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 6870 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 6871 6872 // Some system apps still use directory structure for native libraries 6873 // in which case we might end up not detecting abi solely based on apk 6874 // structure. Try to detect abi based on directory structure. 6875 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 6876 pkg.applicationInfo.primaryCpuAbi == null) { 6877 setBundledAppAbisAndRoots(pkg, pkgSetting); 6878 setNativeLibraryPaths(pkg); 6879 } 6880 6881 } else { 6882 if ((scanFlags & SCAN_MOVE) != 0) { 6883 // We haven't run dex-opt for this move (since we've moved the compiled output too) 6884 // but we already have this packages package info in the PackageSetting. We just 6885 // use that and derive the native library path based on the new codepath. 6886 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 6887 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 6888 } 6889 6890 // Set native library paths again. For moves, the path will be updated based on the 6891 // ABIs we've determined above. For non-moves, the path will be updated based on the 6892 // ABIs we determined during compilation, but the path will depend on the final 6893 // package path (after the rename away from the stage path). 6894 setNativeLibraryPaths(pkg); 6895 } 6896 6897 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 6898 final int[] userIds = sUserManager.getUserIds(); 6899 synchronized (mInstallLock) { 6900 // Make sure all user data directories are ready to roll; we're okay 6901 // if they already exist 6902 if (!TextUtils.isEmpty(pkg.volumeUuid)) { 6903 for (int userId : userIds) { 6904 if (userId != 0) { 6905 mInstaller.createUserData(pkg.volumeUuid, pkg.packageName, 6906 UserHandle.getUid(userId, pkg.applicationInfo.uid), userId, 6907 pkg.applicationInfo.seinfo); 6908 } 6909 } 6910 } 6911 6912 // Create a native library symlink only if we have native libraries 6913 // and if the native libraries are 32 bit libraries. We do not provide 6914 // this symlink for 64 bit libraries. 6915 if (pkg.applicationInfo.primaryCpuAbi != null && 6916 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 6917 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 6918 for (int userId : userIds) { 6919 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 6920 nativeLibPath, userId) < 0) { 6921 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6922 "Failed linking native library dir (user=" + userId + ")"); 6923 } 6924 } 6925 } 6926 } 6927 6928 // This is a special case for the "system" package, where the ABI is 6929 // dictated by the zygote configuration (and init.rc). We should keep track 6930 // of this ABI so that we can deal with "normal" applications that run under 6931 // the same UID correctly. 6932 if (mPlatformPackage == pkg) { 6933 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 6934 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 6935 } 6936 6937 // If there's a mismatch between the abi-override in the package setting 6938 // and the abiOverride specified for the install. Warn about this because we 6939 // would've already compiled the app without taking the package setting into 6940 // account. 6941 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 6942 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 6943 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 6944 " for package: " + pkg.packageName); 6945 } 6946 } 6947 6948 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6949 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6950 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 6951 6952 // Copy the derived override back to the parsed package, so that we can 6953 // update the package settings accordingly. 6954 pkg.cpuAbiOverride = cpuAbiOverride; 6955 6956 if (DEBUG_ABI_SELECTION) { 6957 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 6958 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 6959 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 6960 } 6961 6962 // Push the derived path down into PackageSettings so we know what to 6963 // clean up at uninstall time. 6964 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 6965 6966 if (DEBUG_ABI_SELECTION) { 6967 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 6968 " primary=" + pkg.applicationInfo.primaryCpuAbi + 6969 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 6970 } 6971 6972 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 6973 // We don't do this here during boot because we can do it all 6974 // at once after scanning all existing packages. 6975 // 6976 // We also do this *before* we perform dexopt on this package, so that 6977 // we can avoid redundant dexopts, and also to make sure we've got the 6978 // code and package path correct. 6979 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 6980 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 6981 } 6982 6983 if ((scanFlags & SCAN_NO_DEX) == 0) { 6984 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 6985 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 6986 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6987 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 6988 } 6989 } 6990 if (mFactoryTest && pkg.requestedPermissions.contains( 6991 android.Manifest.permission.FACTORY_TEST)) { 6992 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 6993 } 6994 6995 ArrayList<PackageParser.Package> clientLibPkgs = null; 6996 6997 // writer 6998 synchronized (mPackages) { 6999 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7000 // Only system apps can add new shared libraries. 7001 if (pkg.libraryNames != null) { 7002 for (int i=0; i<pkg.libraryNames.size(); i++) { 7003 String name = pkg.libraryNames.get(i); 7004 boolean allowed = false; 7005 if (pkg.isUpdatedSystemApp()) { 7006 // New library entries can only be added through the 7007 // system image. This is important to get rid of a lot 7008 // of nasty edge cases: for example if we allowed a non- 7009 // system update of the app to add a library, then uninstalling 7010 // the update would make the library go away, and assumptions 7011 // we made such as through app install filtering would now 7012 // have allowed apps on the device which aren't compatible 7013 // with it. Better to just have the restriction here, be 7014 // conservative, and create many fewer cases that can negatively 7015 // impact the user experience. 7016 final PackageSetting sysPs = mSettings 7017 .getDisabledSystemPkgLPr(pkg.packageName); 7018 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 7019 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 7020 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 7021 allowed = true; 7022 allowed = true; 7023 break; 7024 } 7025 } 7026 } 7027 } else { 7028 allowed = true; 7029 } 7030 if (allowed) { 7031 if (!mSharedLibraries.containsKey(name)) { 7032 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 7033 } else if (!name.equals(pkg.packageName)) { 7034 Slog.w(TAG, "Package " + pkg.packageName + " library " 7035 + name + " already exists; skipping"); 7036 } 7037 } else { 7038 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 7039 + name + " that is not declared on system image; skipping"); 7040 } 7041 } 7042 if ((scanFlags&SCAN_BOOTING) == 0) { 7043 // If we are not booting, we need to update any applications 7044 // that are clients of our shared library. If we are booting, 7045 // this will all be done once the scan is complete. 7046 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 7047 } 7048 } 7049 } 7050 } 7051 7052 // We also need to dexopt any apps that are dependent on this library. Note that 7053 // if these fail, we should abort the install since installing the library will 7054 // result in some apps being broken. 7055 if (clientLibPkgs != null) { 7056 if ((scanFlags & SCAN_NO_DEX) == 0) { 7057 for (int i = 0; i < clientLibPkgs.size(); i++) { 7058 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7059 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 7060 null /* instruction sets */, forceDex, 7061 (scanFlags & SCAN_DEFER_DEX) != 0, false); 7062 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7063 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 7064 "scanPackageLI failed to dexopt clientLibPkgs"); 7065 } 7066 } 7067 } 7068 } 7069 7070 // Also need to kill any apps that are dependent on the library. 7071 if (clientLibPkgs != null) { 7072 for (int i=0; i<clientLibPkgs.size(); i++) { 7073 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7074 killApplication(clientPkg.applicationInfo.packageName, 7075 clientPkg.applicationInfo.uid, "update lib"); 7076 } 7077 } 7078 7079 // Make sure we're not adding any bogus keyset info 7080 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7081 ksms.assertScannedPackageValid(pkg); 7082 7083 // writer 7084 synchronized (mPackages) { 7085 // We don't expect installation to fail beyond this point 7086 7087 // Add the new setting to mSettings 7088 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 7089 // Add the new setting to mPackages 7090 mPackages.put(pkg.applicationInfo.packageName, pkg); 7091 // Make sure we don't accidentally delete its data. 7092 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 7093 while (iter.hasNext()) { 7094 PackageCleanItem item = iter.next(); 7095 if (pkgName.equals(item.packageName)) { 7096 iter.remove(); 7097 } 7098 } 7099 7100 // Take care of first install / last update times. 7101 if (currentTime != 0) { 7102 if (pkgSetting.firstInstallTime == 0) { 7103 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7104 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7105 pkgSetting.lastUpdateTime = currentTime; 7106 } 7107 } else if (pkgSetting.firstInstallTime == 0) { 7108 // We need *something*. Take time time stamp of the file. 7109 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7110 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7111 if (scanFileTime != pkgSetting.timeStamp) { 7112 // A package on the system image has changed; consider this 7113 // to be an update. 7114 pkgSetting.lastUpdateTime = scanFileTime; 7115 } 7116 } 7117 7118 // Add the package's KeySets to the global KeySetManagerService 7119 ksms.addScannedPackageLPw(pkg); 7120 7121 int N = pkg.providers.size(); 7122 StringBuilder r = null; 7123 int i; 7124 for (i=0; i<N; i++) { 7125 PackageParser.Provider p = pkg.providers.get(i); 7126 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7127 p.info.processName, pkg.applicationInfo.uid); 7128 mProviders.addProvider(p); 7129 p.syncable = p.info.isSyncable; 7130 if (p.info.authority != null) { 7131 String names[] = p.info.authority.split(";"); 7132 p.info.authority = null; 7133 for (int j = 0; j < names.length; j++) { 7134 if (j == 1 && p.syncable) { 7135 // We only want the first authority for a provider to possibly be 7136 // syncable, so if we already added this provider using a different 7137 // authority clear the syncable flag. We copy the provider before 7138 // changing it because the mProviders object contains a reference 7139 // to a provider that we don't want to change. 7140 // Only do this for the second authority since the resulting provider 7141 // object can be the same for all future authorities for this provider. 7142 p = new PackageParser.Provider(p); 7143 p.syncable = false; 7144 } 7145 if (!mProvidersByAuthority.containsKey(names[j])) { 7146 mProvidersByAuthority.put(names[j], p); 7147 if (p.info.authority == null) { 7148 p.info.authority = names[j]; 7149 } else { 7150 p.info.authority = p.info.authority + ";" + names[j]; 7151 } 7152 if (DEBUG_PACKAGE_SCANNING) { 7153 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7154 Log.d(TAG, "Registered content provider: " + names[j] 7155 + ", className = " + p.info.name + ", isSyncable = " 7156 + p.info.isSyncable); 7157 } 7158 } else { 7159 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7160 Slog.w(TAG, "Skipping provider name " + names[j] + 7161 " (in package " + pkg.applicationInfo.packageName + 7162 "): name already used by " 7163 + ((other != null && other.getComponentName() != null) 7164 ? other.getComponentName().getPackageName() : "?")); 7165 } 7166 } 7167 } 7168 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7169 if (r == null) { 7170 r = new StringBuilder(256); 7171 } else { 7172 r.append(' '); 7173 } 7174 r.append(p.info.name); 7175 } 7176 } 7177 if (r != null) { 7178 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7179 } 7180 7181 N = pkg.services.size(); 7182 r = null; 7183 for (i=0; i<N; i++) { 7184 PackageParser.Service s = pkg.services.get(i); 7185 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 7186 s.info.processName, pkg.applicationInfo.uid); 7187 mServices.addService(s); 7188 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7189 if (r == null) { 7190 r = new StringBuilder(256); 7191 } else { 7192 r.append(' '); 7193 } 7194 r.append(s.info.name); 7195 } 7196 } 7197 if (r != null) { 7198 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 7199 } 7200 7201 N = pkg.receivers.size(); 7202 r = null; 7203 for (i=0; i<N; i++) { 7204 PackageParser.Activity a = pkg.receivers.get(i); 7205 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7206 a.info.processName, pkg.applicationInfo.uid); 7207 mReceivers.addActivity(a, "receiver"); 7208 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7209 if (r == null) { 7210 r = new StringBuilder(256); 7211 } else { 7212 r.append(' '); 7213 } 7214 r.append(a.info.name); 7215 } 7216 } 7217 if (r != null) { 7218 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 7219 } 7220 7221 N = pkg.activities.size(); 7222 r = null; 7223 for (i=0; i<N; i++) { 7224 PackageParser.Activity a = pkg.activities.get(i); 7225 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7226 a.info.processName, pkg.applicationInfo.uid); 7227 mActivities.addActivity(a, "activity"); 7228 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7229 if (r == null) { 7230 r = new StringBuilder(256); 7231 } else { 7232 r.append(' '); 7233 } 7234 r.append(a.info.name); 7235 } 7236 } 7237 if (r != null) { 7238 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 7239 } 7240 7241 N = pkg.permissionGroups.size(); 7242 r = null; 7243 for (i=0; i<N; i++) { 7244 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 7245 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 7246 if (cur == null) { 7247 mPermissionGroups.put(pg.info.name, pg); 7248 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7249 if (r == null) { 7250 r = new StringBuilder(256); 7251 } else { 7252 r.append(' '); 7253 } 7254 r.append(pg.info.name); 7255 } 7256 } else { 7257 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 7258 + pg.info.packageName + " ignored: original from " 7259 + cur.info.packageName); 7260 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7261 if (r == null) { 7262 r = new StringBuilder(256); 7263 } else { 7264 r.append(' '); 7265 } 7266 r.append("DUP:"); 7267 r.append(pg.info.name); 7268 } 7269 } 7270 } 7271 if (r != null) { 7272 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 7273 } 7274 7275 N = pkg.permissions.size(); 7276 r = null; 7277 for (i=0; i<N; i++) { 7278 PackageParser.Permission p = pkg.permissions.get(i); 7279 7280 // Now that permission groups have a special meaning, we ignore permission 7281 // groups for legacy apps to prevent unexpected behavior. In particular, 7282 // permissions for one app being granted to someone just becuase they happen 7283 // to be in a group defined by another app (before this had no implications). 7284 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 7285 p.group = mPermissionGroups.get(p.info.group); 7286 // Warn for a permission in an unknown group. 7287 if (p.info.group != null && p.group == null) { 7288 Slog.w(TAG, "Permission " + p.info.name + " from package " 7289 + p.info.packageName + " in an unknown group " + p.info.group); 7290 } 7291 } 7292 7293 ArrayMap<String, BasePermission> permissionMap = 7294 p.tree ? mSettings.mPermissionTrees 7295 : mSettings.mPermissions; 7296 BasePermission bp = permissionMap.get(p.info.name); 7297 7298 // Allow system apps to redefine non-system permissions 7299 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 7300 final boolean currentOwnerIsSystem = (bp.perm != null 7301 && isSystemApp(bp.perm.owner)); 7302 if (isSystemApp(p.owner)) { 7303 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 7304 // It's a built-in permission and no owner, take ownership now 7305 bp.packageSetting = pkgSetting; 7306 bp.perm = p; 7307 bp.uid = pkg.applicationInfo.uid; 7308 bp.sourcePackage = p.info.packageName; 7309 } else if (!currentOwnerIsSystem) { 7310 String msg = "New decl " + p.owner + " of permission " 7311 + p.info.name + " is system; overriding " + bp.sourcePackage; 7312 reportSettingsProblem(Log.WARN, msg); 7313 bp = null; 7314 } 7315 } 7316 } 7317 7318 if (bp == null) { 7319 bp = new BasePermission(p.info.name, p.info.packageName, 7320 BasePermission.TYPE_NORMAL); 7321 permissionMap.put(p.info.name, bp); 7322 } 7323 7324 if (bp.perm == null) { 7325 if (bp.sourcePackage == null 7326 || bp.sourcePackage.equals(p.info.packageName)) { 7327 BasePermission tree = findPermissionTreeLP(p.info.name); 7328 if (tree == null 7329 || tree.sourcePackage.equals(p.info.packageName)) { 7330 bp.packageSetting = pkgSetting; 7331 bp.perm = p; 7332 bp.uid = pkg.applicationInfo.uid; 7333 bp.sourcePackage = p.info.packageName; 7334 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7335 if (r == null) { 7336 r = new StringBuilder(256); 7337 } else { 7338 r.append(' '); 7339 } 7340 r.append(p.info.name); 7341 } 7342 } else { 7343 Slog.w(TAG, "Permission " + p.info.name + " from package " 7344 + p.info.packageName + " ignored: base tree " 7345 + tree.name + " is from package " 7346 + tree.sourcePackage); 7347 } 7348 } else { 7349 Slog.w(TAG, "Permission " + p.info.name + " from package " 7350 + p.info.packageName + " ignored: original from " 7351 + bp.sourcePackage); 7352 } 7353 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7354 if (r == null) { 7355 r = new StringBuilder(256); 7356 } else { 7357 r.append(' '); 7358 } 7359 r.append("DUP:"); 7360 r.append(p.info.name); 7361 } 7362 if (bp.perm == p) { 7363 bp.protectionLevel = p.info.protectionLevel; 7364 } 7365 } 7366 7367 if (r != null) { 7368 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 7369 } 7370 7371 N = pkg.instrumentation.size(); 7372 r = null; 7373 for (i=0; i<N; i++) { 7374 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7375 a.info.packageName = pkg.applicationInfo.packageName; 7376 a.info.sourceDir = pkg.applicationInfo.sourceDir; 7377 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 7378 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 7379 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 7380 a.info.dataDir = pkg.applicationInfo.dataDir; 7381 7382 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 7383 // need other information about the application, like the ABI and what not ? 7384 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 7385 mInstrumentation.put(a.getComponentName(), a); 7386 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7387 if (r == null) { 7388 r = new StringBuilder(256); 7389 } else { 7390 r.append(' '); 7391 } 7392 r.append(a.info.name); 7393 } 7394 } 7395 if (r != null) { 7396 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 7397 } 7398 7399 if (pkg.protectedBroadcasts != null) { 7400 N = pkg.protectedBroadcasts.size(); 7401 for (i=0; i<N; i++) { 7402 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 7403 } 7404 } 7405 7406 pkgSetting.setTimeStamp(scanFileTime); 7407 7408 // Create idmap files for pairs of (packages, overlay packages). 7409 // Note: "android", ie framework-res.apk, is handled by native layers. 7410 if (pkg.mOverlayTarget != null) { 7411 // This is an overlay package. 7412 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 7413 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 7414 mOverlays.put(pkg.mOverlayTarget, 7415 new ArrayMap<String, PackageParser.Package>()); 7416 } 7417 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 7418 map.put(pkg.packageName, pkg); 7419 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 7420 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 7421 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7422 "scanPackageLI failed to createIdmap"); 7423 } 7424 } 7425 } else if (mOverlays.containsKey(pkg.packageName) && 7426 !pkg.packageName.equals("android")) { 7427 // This is a regular package, with one or more known overlay packages. 7428 createIdmapsForPackageLI(pkg); 7429 } 7430 } 7431 7432 return pkg; 7433 } 7434 7435 /** 7436 * Derive the ABI of a non-system package located at {@code scanFile}. This information 7437 * is derived purely on the basis of the contents of {@code scanFile} and 7438 * {@code cpuAbiOverride}. 7439 * 7440 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 7441 */ 7442 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 7443 String cpuAbiOverride, boolean extractLibs) 7444 throws PackageManagerException { 7445 // TODO: We can probably be smarter about this stuff. For installed apps, 7446 // we can calculate this information at install time once and for all. For 7447 // system apps, we can probably assume that this information doesn't change 7448 // after the first boot scan. As things stand, we do lots of unnecessary work. 7449 7450 // Give ourselves some initial paths; we'll come back for another 7451 // pass once we've determined ABI below. 7452 setNativeLibraryPaths(pkg); 7453 7454 // We would never need to extract libs for forward-locked and external packages, 7455 // since the container service will do it for us. We shouldn't attempt to 7456 // extract libs from system app when it was not updated. 7457 if (pkg.isForwardLocked() || isExternal(pkg) || 7458 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) { 7459 extractLibs = false; 7460 } 7461 7462 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7463 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7464 7465 NativeLibraryHelper.Handle handle = null; 7466 try { 7467 handle = NativeLibraryHelper.Handle.create(scanFile); 7468 // TODO(multiArch): This can be null for apps that didn't go through the 7469 // usual installation process. We can calculate it again, like we 7470 // do during install time. 7471 // 7472 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7473 // unnecessary. 7474 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7475 7476 // Null out the abis so that they can be recalculated. 7477 pkg.applicationInfo.primaryCpuAbi = null; 7478 pkg.applicationInfo.secondaryCpuAbi = null; 7479 if (isMultiArch(pkg.applicationInfo)) { 7480 // Warn if we've set an abiOverride for multi-lib packages.. 7481 // By definition, we need to copy both 32 and 64 bit libraries for 7482 // such packages. 7483 if (pkg.cpuAbiOverride != null 7484 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7485 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7486 } 7487 7488 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7489 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7490 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7491 if (extractLibs) { 7492 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7493 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7494 useIsaSpecificSubdirs); 7495 } else { 7496 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7497 } 7498 } 7499 7500 maybeThrowExceptionForMultiArchCopy( 7501 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7502 7503 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7504 if (extractLibs) { 7505 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7506 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7507 useIsaSpecificSubdirs); 7508 } else { 7509 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7510 } 7511 } 7512 7513 maybeThrowExceptionForMultiArchCopy( 7514 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7515 7516 if (abi64 >= 0) { 7517 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7518 } 7519 7520 if (abi32 >= 0) { 7521 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7522 if (abi64 >= 0) { 7523 pkg.applicationInfo.secondaryCpuAbi = abi; 7524 } else { 7525 pkg.applicationInfo.primaryCpuAbi = abi; 7526 } 7527 } 7528 } else { 7529 String[] abiList = (cpuAbiOverride != null) ? 7530 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7531 7532 // Enable gross and lame hacks for apps that are built with old 7533 // SDK tools. We must scan their APKs for renderscript bitcode and 7534 // not launch them if it's present. Don't bother checking on devices 7535 // that don't have 64 bit support. 7536 boolean needsRenderScriptOverride = false; 7537 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7538 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7539 abiList = Build.SUPPORTED_32_BIT_ABIS; 7540 needsRenderScriptOverride = true; 7541 } 7542 7543 final int copyRet; 7544 if (extractLibs) { 7545 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7546 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7547 } else { 7548 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7549 } 7550 7551 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7552 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7553 "Error unpackaging native libs for app, errorCode=" + copyRet); 7554 } 7555 7556 if (copyRet >= 0) { 7557 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7558 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7559 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7560 } else if (needsRenderScriptOverride) { 7561 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7562 } 7563 } 7564 } catch (IOException ioe) { 7565 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7566 } finally { 7567 IoUtils.closeQuietly(handle); 7568 } 7569 7570 // Now that we've calculated the ABIs and determined if it's an internal app, 7571 // we will go ahead and populate the nativeLibraryPath. 7572 setNativeLibraryPaths(pkg); 7573 } 7574 7575 /** 7576 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7577 * i.e, so that all packages can be run inside a single process if required. 7578 * 7579 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7580 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7581 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7582 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7583 * updating a package that belongs to a shared user. 7584 * 7585 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7586 * adds unnecessary complexity. 7587 */ 7588 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7589 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 7590 String requiredInstructionSet = null; 7591 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7592 requiredInstructionSet = VMRuntime.getInstructionSet( 7593 scannedPackage.applicationInfo.primaryCpuAbi); 7594 } 7595 7596 PackageSetting requirer = null; 7597 for (PackageSetting ps : packagesForUser) { 7598 // If packagesForUser contains scannedPackage, we skip it. This will happen 7599 // when scannedPackage is an update of an existing package. Without this check, 7600 // we will never be able to change the ABI of any package belonging to a shared 7601 // user, even if it's compatible with other packages. 7602 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7603 if (ps.primaryCpuAbiString == null) { 7604 continue; 7605 } 7606 7607 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7608 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7609 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7610 // this but there's not much we can do. 7611 String errorMessage = "Instruction set mismatch, " 7612 + ((requirer == null) ? "[caller]" : requirer) 7613 + " requires " + requiredInstructionSet + " whereas " + ps 7614 + " requires " + instructionSet; 7615 Slog.w(TAG, errorMessage); 7616 } 7617 7618 if (requiredInstructionSet == null) { 7619 requiredInstructionSet = instructionSet; 7620 requirer = ps; 7621 } 7622 } 7623 } 7624 7625 if (requiredInstructionSet != null) { 7626 String adjustedAbi; 7627 if (requirer != null) { 7628 // requirer != null implies that either scannedPackage was null or that scannedPackage 7629 // did not require an ABI, in which case we have to adjust scannedPackage to match 7630 // the ABI of the set (which is the same as requirer's ABI) 7631 adjustedAbi = requirer.primaryCpuAbiString; 7632 if (scannedPackage != null) { 7633 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7634 } 7635 } else { 7636 // requirer == null implies that we're updating all ABIs in the set to 7637 // match scannedPackage. 7638 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7639 } 7640 7641 for (PackageSetting ps : packagesForUser) { 7642 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7643 if (ps.primaryCpuAbiString != null) { 7644 continue; 7645 } 7646 7647 ps.primaryCpuAbiString = adjustedAbi; 7648 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7649 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7650 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7651 7652 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 7653 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 7654 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7655 ps.primaryCpuAbiString = null; 7656 ps.pkg.applicationInfo.primaryCpuAbi = null; 7657 return; 7658 } else { 7659 mInstaller.rmdex(ps.codePathString, 7660 getDexCodeInstructionSet(getPreferredInstructionSet())); 7661 } 7662 } 7663 } 7664 } 7665 } 7666 } 7667 7668 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7669 synchronized (mPackages) { 7670 mResolverReplaced = true; 7671 // Set up information for custom user intent resolution activity. 7672 mResolveActivity.applicationInfo = pkg.applicationInfo; 7673 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7674 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7675 mResolveActivity.processName = pkg.applicationInfo.packageName; 7676 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7677 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7678 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7679 mResolveActivity.theme = 0; 7680 mResolveActivity.exported = true; 7681 mResolveActivity.enabled = true; 7682 mResolveInfo.activityInfo = mResolveActivity; 7683 mResolveInfo.priority = 0; 7684 mResolveInfo.preferredOrder = 0; 7685 mResolveInfo.match = 0; 7686 mResolveComponentName = mCustomResolverComponentName; 7687 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7688 mResolveComponentName); 7689 } 7690 } 7691 7692 private static String calculateBundledApkRoot(final String codePathString) { 7693 final File codePath = new File(codePathString); 7694 final File codeRoot; 7695 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 7696 codeRoot = Environment.getRootDirectory(); 7697 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7698 codeRoot = Environment.getOemDirectory(); 7699 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7700 codeRoot = Environment.getVendorDirectory(); 7701 } else { 7702 // Unrecognized code path; take its top real segment as the apk root: 7703 // e.g. /something/app/blah.apk => /something 7704 try { 7705 File f = codePath.getCanonicalFile(); 7706 File parent = f.getParentFile(); // non-null because codePath is a file 7707 File tmp; 7708 while ((tmp = parent.getParentFile()) != null) { 7709 f = parent; 7710 parent = tmp; 7711 } 7712 codeRoot = f; 7713 Slog.w(TAG, "Unrecognized code path " 7714 + codePath + " - using " + codeRoot); 7715 } catch (IOException e) { 7716 // Can't canonicalize the code path -- shenanigans? 7717 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7718 return Environment.getRootDirectory().getPath(); 7719 } 7720 } 7721 return codeRoot.getPath(); 7722 } 7723 7724 /** 7725 * Derive and set the location of native libraries for the given package, 7726 * which varies depending on where and how the package was installed. 7727 */ 7728 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7729 final ApplicationInfo info = pkg.applicationInfo; 7730 final String codePath = pkg.codePath; 7731 final File codeFile = new File(codePath); 7732 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7733 final boolean asecApp = info.isForwardLocked() || isExternal(info); 7734 7735 info.nativeLibraryRootDir = null; 7736 info.nativeLibraryRootRequiresIsa = false; 7737 info.nativeLibraryDir = null; 7738 info.secondaryNativeLibraryDir = null; 7739 7740 if (isApkFile(codeFile)) { 7741 // Monolithic install 7742 if (bundledApp) { 7743 // If "/system/lib64/apkname" exists, assume that is the per-package 7744 // native library directory to use; otherwise use "/system/lib/apkname". 7745 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7746 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7747 getPrimaryInstructionSet(info)); 7748 7749 // This is a bundled system app so choose the path based on the ABI. 7750 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7751 // is just the default path. 7752 final String apkName = deriveCodePathName(codePath); 7753 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7754 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7755 apkName).getAbsolutePath(); 7756 7757 if (info.secondaryCpuAbi != null) { 7758 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7759 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7760 secondaryLibDir, apkName).getAbsolutePath(); 7761 } 7762 } else if (asecApp) { 7763 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 7764 .getAbsolutePath(); 7765 } else { 7766 final String apkName = deriveCodePathName(codePath); 7767 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 7768 .getAbsolutePath(); 7769 } 7770 7771 info.nativeLibraryRootRequiresIsa = false; 7772 info.nativeLibraryDir = info.nativeLibraryRootDir; 7773 } else { 7774 // Cluster install 7775 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 7776 info.nativeLibraryRootRequiresIsa = true; 7777 7778 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 7779 getPrimaryInstructionSet(info)).getAbsolutePath(); 7780 7781 if (info.secondaryCpuAbi != null) { 7782 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 7783 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 7784 } 7785 } 7786 } 7787 7788 /** 7789 * Calculate the abis and roots for a bundled app. These can uniquely 7790 * be determined from the contents of the system partition, i.e whether 7791 * it contains 64 or 32 bit shared libraries etc. We do not validate any 7792 * of this information, and instead assume that the system was built 7793 * sensibly. 7794 */ 7795 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 7796 PackageSetting pkgSetting) { 7797 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 7798 7799 // If "/system/lib64/apkname" exists, assume that is the per-package 7800 // native library directory to use; otherwise use "/system/lib/apkname". 7801 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 7802 setBundledAppAbi(pkg, apkRoot, apkName); 7803 // pkgSetting might be null during rescan following uninstall of updates 7804 // to a bundled app, so accommodate that possibility. The settings in 7805 // that case will be established later from the parsed package. 7806 // 7807 // If the settings aren't null, sync them up with what we've just derived. 7808 // note that apkRoot isn't stored in the package settings. 7809 if (pkgSetting != null) { 7810 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7811 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7812 } 7813 } 7814 7815 /** 7816 * Deduces the ABI of a bundled app and sets the relevant fields on the 7817 * parsed pkg object. 7818 * 7819 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 7820 * under which system libraries are installed. 7821 * @param apkName the name of the installed package. 7822 */ 7823 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 7824 final File codeFile = new File(pkg.codePath); 7825 7826 final boolean has64BitLibs; 7827 final boolean has32BitLibs; 7828 if (isApkFile(codeFile)) { 7829 // Monolithic install 7830 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 7831 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7832 } else { 7833 // Cluster install 7834 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7835 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7836 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7837 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7838 has64BitLibs = (new File(rootDir, isa)).exists(); 7839 } else { 7840 has64BitLibs = false; 7841 } 7842 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7843 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 7844 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 7845 has32BitLibs = (new File(rootDir, isa)).exists(); 7846 } else { 7847 has32BitLibs = false; 7848 } 7849 } 7850 7851 if (has64BitLibs && !has32BitLibs) { 7852 // The package has 64 bit libs, but not 32 bit libs. Its primary 7853 // ABI should be 64 bit. We can safely assume here that the bundled 7854 // native libraries correspond to the most preferred ABI in the list. 7855 7856 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7857 pkg.applicationInfo.secondaryCpuAbi = null; 7858 } else if (has32BitLibs && !has64BitLibs) { 7859 // The package has 32 bit libs but not 64 bit libs. Its primary 7860 // ABI should be 32 bit. 7861 7862 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7863 pkg.applicationInfo.secondaryCpuAbi = null; 7864 } else if (has32BitLibs && has64BitLibs) { 7865 // The application has both 64 and 32 bit bundled libraries. We check 7866 // here that the app declares multiArch support, and warn if it doesn't. 7867 // 7868 // We will be lenient here and record both ABIs. The primary will be the 7869 // ABI that's higher on the list, i.e, a device that's configured to prefer 7870 // 64 bit apps will see a 64 bit primary ABI, 7871 7872 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 7873 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 7874 } 7875 7876 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 7877 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7878 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7879 } else { 7880 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7881 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7882 } 7883 } else { 7884 pkg.applicationInfo.primaryCpuAbi = null; 7885 pkg.applicationInfo.secondaryCpuAbi = null; 7886 } 7887 } 7888 7889 private void killApplication(String pkgName, int appId, String reason) { 7890 // Request the ActivityManager to kill the process(only for existing packages) 7891 // so that we do not end up in a confused state while the user is still using the older 7892 // version of the application while the new one gets installed. 7893 IActivityManager am = ActivityManagerNative.getDefault(); 7894 if (am != null) { 7895 try { 7896 am.killApplicationWithAppId(pkgName, appId, reason); 7897 } catch (RemoteException e) { 7898 } 7899 } 7900 } 7901 7902 void removePackageLI(PackageSetting ps, boolean chatty) { 7903 if (DEBUG_INSTALL) { 7904 if (chatty) 7905 Log.d(TAG, "Removing package " + ps.name); 7906 } 7907 7908 // writer 7909 synchronized (mPackages) { 7910 mPackages.remove(ps.name); 7911 final PackageParser.Package pkg = ps.pkg; 7912 if (pkg != null) { 7913 cleanPackageDataStructuresLILPw(pkg, chatty); 7914 } 7915 } 7916 } 7917 7918 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 7919 if (DEBUG_INSTALL) { 7920 if (chatty) 7921 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 7922 } 7923 7924 // writer 7925 synchronized (mPackages) { 7926 mPackages.remove(pkg.applicationInfo.packageName); 7927 cleanPackageDataStructuresLILPw(pkg, chatty); 7928 } 7929 } 7930 7931 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 7932 int N = pkg.providers.size(); 7933 StringBuilder r = null; 7934 int i; 7935 for (i=0; i<N; i++) { 7936 PackageParser.Provider p = pkg.providers.get(i); 7937 mProviders.removeProvider(p); 7938 if (p.info.authority == null) { 7939 7940 /* There was another ContentProvider with this authority when 7941 * this app was installed so this authority is null, 7942 * Ignore it as we don't have to unregister the provider. 7943 */ 7944 continue; 7945 } 7946 String names[] = p.info.authority.split(";"); 7947 for (int j = 0; j < names.length; j++) { 7948 if (mProvidersByAuthority.get(names[j]) == p) { 7949 mProvidersByAuthority.remove(names[j]); 7950 if (DEBUG_REMOVE) { 7951 if (chatty) 7952 Log.d(TAG, "Unregistered content provider: " + names[j] 7953 + ", className = " + p.info.name + ", isSyncable = " 7954 + p.info.isSyncable); 7955 } 7956 } 7957 } 7958 if (DEBUG_REMOVE && chatty) { 7959 if (r == null) { 7960 r = new StringBuilder(256); 7961 } else { 7962 r.append(' '); 7963 } 7964 r.append(p.info.name); 7965 } 7966 } 7967 if (r != null) { 7968 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 7969 } 7970 7971 N = pkg.services.size(); 7972 r = null; 7973 for (i=0; i<N; i++) { 7974 PackageParser.Service s = pkg.services.get(i); 7975 mServices.removeService(s); 7976 if (chatty) { 7977 if (r == null) { 7978 r = new StringBuilder(256); 7979 } else { 7980 r.append(' '); 7981 } 7982 r.append(s.info.name); 7983 } 7984 } 7985 if (r != null) { 7986 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 7987 } 7988 7989 N = pkg.receivers.size(); 7990 r = null; 7991 for (i=0; i<N; i++) { 7992 PackageParser.Activity a = pkg.receivers.get(i); 7993 mReceivers.removeActivity(a, "receiver"); 7994 if (DEBUG_REMOVE && chatty) { 7995 if (r == null) { 7996 r = new StringBuilder(256); 7997 } else { 7998 r.append(' '); 7999 } 8000 r.append(a.info.name); 8001 } 8002 } 8003 if (r != null) { 8004 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 8005 } 8006 8007 N = pkg.activities.size(); 8008 r = null; 8009 for (i=0; i<N; i++) { 8010 PackageParser.Activity a = pkg.activities.get(i); 8011 mActivities.removeActivity(a, "activity"); 8012 if (DEBUG_REMOVE && chatty) { 8013 if (r == null) { 8014 r = new StringBuilder(256); 8015 } else { 8016 r.append(' '); 8017 } 8018 r.append(a.info.name); 8019 } 8020 } 8021 if (r != null) { 8022 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 8023 } 8024 8025 N = pkg.permissions.size(); 8026 r = null; 8027 for (i=0; i<N; i++) { 8028 PackageParser.Permission p = pkg.permissions.get(i); 8029 BasePermission bp = mSettings.mPermissions.get(p.info.name); 8030 if (bp == null) { 8031 bp = mSettings.mPermissionTrees.get(p.info.name); 8032 } 8033 if (bp != null && bp.perm == p) { 8034 bp.perm = null; 8035 if (DEBUG_REMOVE && chatty) { 8036 if (r == null) { 8037 r = new StringBuilder(256); 8038 } else { 8039 r.append(' '); 8040 } 8041 r.append(p.info.name); 8042 } 8043 } 8044 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8045 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 8046 if (appOpPerms != null) { 8047 appOpPerms.remove(pkg.packageName); 8048 } 8049 } 8050 } 8051 if (r != null) { 8052 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8053 } 8054 8055 N = pkg.requestedPermissions.size(); 8056 r = null; 8057 for (i=0; i<N; i++) { 8058 String perm = pkg.requestedPermissions.get(i); 8059 BasePermission bp = mSettings.mPermissions.get(perm); 8060 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8061 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 8062 if (appOpPerms != null) { 8063 appOpPerms.remove(pkg.packageName); 8064 if (appOpPerms.isEmpty()) { 8065 mAppOpPermissionPackages.remove(perm); 8066 } 8067 } 8068 } 8069 } 8070 if (r != null) { 8071 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8072 } 8073 8074 N = pkg.instrumentation.size(); 8075 r = null; 8076 for (i=0; i<N; i++) { 8077 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8078 mInstrumentation.remove(a.getComponentName()); 8079 if (DEBUG_REMOVE && chatty) { 8080 if (r == null) { 8081 r = new StringBuilder(256); 8082 } else { 8083 r.append(' '); 8084 } 8085 r.append(a.info.name); 8086 } 8087 } 8088 if (r != null) { 8089 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 8090 } 8091 8092 r = null; 8093 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8094 // Only system apps can hold shared libraries. 8095 if (pkg.libraryNames != null) { 8096 for (i=0; i<pkg.libraryNames.size(); i++) { 8097 String name = pkg.libraryNames.get(i); 8098 SharedLibraryEntry cur = mSharedLibraries.get(name); 8099 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 8100 mSharedLibraries.remove(name); 8101 if (DEBUG_REMOVE && chatty) { 8102 if (r == null) { 8103 r = new StringBuilder(256); 8104 } else { 8105 r.append(' '); 8106 } 8107 r.append(name); 8108 } 8109 } 8110 } 8111 } 8112 } 8113 if (r != null) { 8114 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 8115 } 8116 } 8117 8118 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 8119 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 8120 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 8121 return true; 8122 } 8123 } 8124 return false; 8125 } 8126 8127 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 8128 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 8129 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 8130 8131 private void updatePermissionsLPw(String changingPkg, 8132 PackageParser.Package pkgInfo, int flags) { 8133 // Make sure there are no dangling permission trees. 8134 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 8135 while (it.hasNext()) { 8136 final BasePermission bp = it.next(); 8137 if (bp.packageSetting == null) { 8138 // We may not yet have parsed the package, so just see if 8139 // we still know about its settings. 8140 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8141 } 8142 if (bp.packageSetting == null) { 8143 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 8144 + " from package " + bp.sourcePackage); 8145 it.remove(); 8146 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8147 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8148 Slog.i(TAG, "Removing old permission tree: " + bp.name 8149 + " from package " + bp.sourcePackage); 8150 flags |= UPDATE_PERMISSIONS_ALL; 8151 it.remove(); 8152 } 8153 } 8154 } 8155 8156 // Make sure all dynamic permissions have been assigned to a package, 8157 // and make sure there are no dangling permissions. 8158 it = mSettings.mPermissions.values().iterator(); 8159 while (it.hasNext()) { 8160 final BasePermission bp = it.next(); 8161 if (bp.type == BasePermission.TYPE_DYNAMIC) { 8162 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 8163 + bp.name + " pkg=" + bp.sourcePackage 8164 + " info=" + bp.pendingInfo); 8165 if (bp.packageSetting == null && bp.pendingInfo != null) { 8166 final BasePermission tree = findPermissionTreeLP(bp.name); 8167 if (tree != null && tree.perm != null) { 8168 bp.packageSetting = tree.packageSetting; 8169 bp.perm = new PackageParser.Permission(tree.perm.owner, 8170 new PermissionInfo(bp.pendingInfo)); 8171 bp.perm.info.packageName = tree.perm.info.packageName; 8172 bp.perm.info.name = bp.name; 8173 bp.uid = tree.uid; 8174 } 8175 } 8176 } 8177 if (bp.packageSetting == null) { 8178 // We may not yet have parsed the package, so just see if 8179 // we still know about its settings. 8180 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8181 } 8182 if (bp.packageSetting == null) { 8183 Slog.w(TAG, "Removing dangling permission: " + bp.name 8184 + " from package " + bp.sourcePackage); 8185 it.remove(); 8186 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8187 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8188 Slog.i(TAG, "Removing old permission: " + bp.name 8189 + " from package " + bp.sourcePackage); 8190 flags |= UPDATE_PERMISSIONS_ALL; 8191 it.remove(); 8192 } 8193 } 8194 } 8195 8196 // Now update the permissions for all packages, in particular 8197 // replace the granted permissions of the system packages. 8198 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 8199 for (PackageParser.Package pkg : mPackages.values()) { 8200 if (pkg != pkgInfo) { 8201 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 8202 changingPkg); 8203 } 8204 } 8205 } 8206 8207 if (pkgInfo != null) { 8208 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 8209 } 8210 } 8211 8212 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 8213 String packageOfInterest) { 8214 // IMPORTANT: There are two types of permissions: install and runtime. 8215 // Install time permissions are granted when the app is installed to 8216 // all device users and users added in the future. Runtime permissions 8217 // are granted at runtime explicitly to specific users. Normal and signature 8218 // protected permissions are install time permissions. Dangerous permissions 8219 // are install permissions if the app's target SDK is Lollipop MR1 or older, 8220 // otherwise they are runtime permissions. This function does not manage 8221 // runtime permissions except for the case an app targeting Lollipop MR1 8222 // being upgraded to target a newer SDK, in which case dangerous permissions 8223 // are transformed from install time to runtime ones. 8224 8225 final PackageSetting ps = (PackageSetting) pkg.mExtras; 8226 if (ps == null) { 8227 return; 8228 } 8229 8230 PermissionsState permissionsState = ps.getPermissionsState(); 8231 PermissionsState origPermissions = permissionsState; 8232 8233 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 8234 8235 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 8236 8237 boolean changedInstallPermission = false; 8238 8239 if (replace) { 8240 ps.installPermissionsFixed = false; 8241 if (!ps.isSharedUser()) { 8242 origPermissions = new PermissionsState(permissionsState); 8243 permissionsState.reset(); 8244 } 8245 } 8246 8247 permissionsState.setGlobalGids(mGlobalGids); 8248 8249 final int N = pkg.requestedPermissions.size(); 8250 for (int i=0; i<N; i++) { 8251 final String name = pkg.requestedPermissions.get(i); 8252 final BasePermission bp = mSettings.mPermissions.get(name); 8253 8254 if (DEBUG_INSTALL) { 8255 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 8256 } 8257 8258 if (bp == null || bp.packageSetting == null) { 8259 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8260 Slog.w(TAG, "Unknown permission " + name 8261 + " in package " + pkg.packageName); 8262 } 8263 continue; 8264 } 8265 8266 final String perm = bp.name; 8267 boolean allowedSig = false; 8268 int grant = GRANT_DENIED; 8269 8270 // Keep track of app op permissions. 8271 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8272 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 8273 if (pkgs == null) { 8274 pkgs = new ArraySet<>(); 8275 mAppOpPermissionPackages.put(bp.name, pkgs); 8276 } 8277 pkgs.add(pkg.packageName); 8278 } 8279 8280 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 8281 switch (level) { 8282 case PermissionInfo.PROTECTION_NORMAL: { 8283 // For all apps normal permissions are install time ones. 8284 grant = GRANT_INSTALL; 8285 } break; 8286 8287 case PermissionInfo.PROTECTION_DANGEROUS: { 8288 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 8289 // For legacy apps dangerous permissions are install time ones. 8290 grant = GRANT_INSTALL_LEGACY; 8291 } else if (origPermissions.hasInstallPermission(bp.name)) { 8292 // For legacy apps that became modern, install becomes runtime. 8293 grant = GRANT_UPGRADE; 8294 } else { 8295 // For modern apps keep runtime permissions unchanged. 8296 grant = GRANT_RUNTIME; 8297 } 8298 } break; 8299 8300 case PermissionInfo.PROTECTION_SIGNATURE: { 8301 // For all apps signature permissions are install time ones. 8302 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 8303 if (allowedSig) { 8304 grant = GRANT_INSTALL; 8305 } 8306 } break; 8307 } 8308 8309 if (DEBUG_INSTALL) { 8310 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 8311 } 8312 8313 if (grant != GRANT_DENIED) { 8314 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 8315 // If this is an existing, non-system package, then 8316 // we can't add any new permissions to it. 8317 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 8318 // Except... if this is a permission that was added 8319 // to the platform (note: need to only do this when 8320 // updating the platform). 8321 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 8322 grant = GRANT_DENIED; 8323 } 8324 } 8325 } 8326 8327 switch (grant) { 8328 case GRANT_INSTALL: { 8329 // Revoke this as runtime permission to handle the case of 8330 // a runtime permission being downgraded to an install one. 8331 for (int userId : UserManagerService.getInstance().getUserIds()) { 8332 if (origPermissions.getRuntimePermissionState( 8333 bp.name, userId) != null) { 8334 // Revoke the runtime permission and clear the flags. 8335 origPermissions.revokeRuntimePermission(bp, userId); 8336 origPermissions.updatePermissionFlags(bp, userId, 8337 PackageManager.MASK_PERMISSION_FLAGS, 0); 8338 // If we revoked a permission permission, we have to write. 8339 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8340 changedRuntimePermissionUserIds, userId); 8341 } 8342 } 8343 // Grant an install permission. 8344 if (permissionsState.grantInstallPermission(bp) != 8345 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8346 changedInstallPermission = true; 8347 } 8348 } break; 8349 8350 case GRANT_INSTALL_LEGACY: { 8351 // Grant an install permission. 8352 if (permissionsState.grantInstallPermission(bp) != 8353 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8354 changedInstallPermission = true; 8355 } 8356 } break; 8357 8358 case GRANT_RUNTIME: { 8359 // Grant previously granted runtime permissions. 8360 for (int userId : UserManagerService.getInstance().getUserIds()) { 8361 PermissionState permissionState = origPermissions 8362 .getRuntimePermissionState(bp.name, userId); 8363 final int flags = permissionState != null 8364 ? permissionState.getFlags() : 0; 8365 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8366 if (permissionsState.grantRuntimePermission(bp, userId) == 8367 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8368 // If we cannot put the permission as it was, we have to write. 8369 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8370 changedRuntimePermissionUserIds, userId); 8371 } 8372 } 8373 // Propagate the permission flags. 8374 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 8375 } 8376 } break; 8377 8378 case GRANT_UPGRADE: { 8379 // Grant runtime permissions for a previously held install permission. 8380 PermissionState permissionState = origPermissions 8381 .getInstallPermissionState(bp.name); 8382 final int flags = permissionState != null ? permissionState.getFlags() : 0; 8383 8384 if (origPermissions.revokeInstallPermission(bp) 8385 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 8386 // We will be transferring the permission flags, so clear them. 8387 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 8388 PackageManager.MASK_PERMISSION_FLAGS, 0); 8389 changedInstallPermission = true; 8390 } 8391 8392 // If the permission is not to be promoted to runtime we ignore it and 8393 // also its other flags as they are not applicable to install permissions. 8394 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 8395 for (int userId : currentUserIds) { 8396 if (permissionsState.grantRuntimePermission(bp, userId) != 8397 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8398 // Transfer the permission flags. 8399 permissionsState.updatePermissionFlags(bp, userId, 8400 flags, flags); 8401 // If we granted the permission, we have to write. 8402 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8403 changedRuntimePermissionUserIds, userId); 8404 } 8405 } 8406 } 8407 } break; 8408 8409 default: { 8410 if (packageOfInterest == null 8411 || packageOfInterest.equals(pkg.packageName)) { 8412 Slog.w(TAG, "Not granting permission " + perm 8413 + " to package " + pkg.packageName 8414 + " because it was previously installed without"); 8415 } 8416 } break; 8417 } 8418 } else { 8419 if (permissionsState.revokeInstallPermission(bp) != 8420 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8421 // Also drop the permission flags. 8422 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 8423 PackageManager.MASK_PERMISSION_FLAGS, 0); 8424 changedInstallPermission = true; 8425 Slog.i(TAG, "Un-granting permission " + perm 8426 + " from package " + pkg.packageName 8427 + " (protectionLevel=" + bp.protectionLevel 8428 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8429 + ")"); 8430 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 8431 // Don't print warning for app op permissions, since it is fine for them 8432 // not to be granted, there is a UI for the user to decide. 8433 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8434 Slog.w(TAG, "Not granting permission " + perm 8435 + " to package " + pkg.packageName 8436 + " (protectionLevel=" + bp.protectionLevel 8437 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8438 + ")"); 8439 } 8440 } 8441 } 8442 } 8443 8444 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 8445 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 8446 // This is the first that we have heard about this package, so the 8447 // permissions we have now selected are fixed until explicitly 8448 // changed. 8449 ps.installPermissionsFixed = true; 8450 } 8451 8452 // Persist the runtime permissions state for users with changes. 8453 for (int userId : changedRuntimePermissionUserIds) { 8454 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 8455 } 8456 } 8457 8458 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8459 boolean allowed = false; 8460 final int NP = PackageParser.NEW_PERMISSIONS.length; 8461 for (int ip=0; ip<NP; ip++) { 8462 final PackageParser.NewPermissionInfo npi 8463 = PackageParser.NEW_PERMISSIONS[ip]; 8464 if (npi.name.equals(perm) 8465 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8466 allowed = true; 8467 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8468 + pkg.packageName); 8469 break; 8470 } 8471 } 8472 return allowed; 8473 } 8474 8475 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 8476 BasePermission bp, PermissionsState origPermissions) { 8477 boolean allowed; 8478 allowed = (compareSignatures( 8479 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 8480 == PackageManager.SIGNATURE_MATCH) 8481 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 8482 == PackageManager.SIGNATURE_MATCH); 8483 if (!allowed && (bp.protectionLevel 8484 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 8485 if (isSystemApp(pkg)) { 8486 // For updated system applications, a system permission 8487 // is granted only if it had been defined by the original application. 8488 if (pkg.isUpdatedSystemApp()) { 8489 final PackageSetting sysPs = mSettings 8490 .getDisabledSystemPkgLPr(pkg.packageName); 8491 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 8492 // If the original was granted this permission, we take 8493 // that grant decision as read and propagate it to the 8494 // update. 8495 if (sysPs.isPrivileged()) { 8496 allowed = true; 8497 } 8498 } else { 8499 // The system apk may have been updated with an older 8500 // version of the one on the data partition, but which 8501 // granted a new system permission that it didn't have 8502 // before. In this case we do want to allow the app to 8503 // now get the new permission if the ancestral apk is 8504 // privileged to get it. 8505 if (sysPs.pkg != null && sysPs.isPrivileged()) { 8506 for (int j=0; 8507 j<sysPs.pkg.requestedPermissions.size(); j++) { 8508 if (perm.equals( 8509 sysPs.pkg.requestedPermissions.get(j))) { 8510 allowed = true; 8511 break; 8512 } 8513 } 8514 } 8515 } 8516 } else { 8517 allowed = isPrivilegedApp(pkg); 8518 } 8519 } 8520 } 8521 if (!allowed) { 8522 if (!allowed && (bp.protectionLevel 8523 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 8524 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.MNC) { 8525 // If this was a previously normal/dangerous permission that got moved 8526 // to a system permission as part of the runtime permission redesign, then 8527 // we still want to blindly grant it to old apps. 8528 allowed = true; 8529 } 8530 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 8531 && pkg.packageName.equals(mRequiredInstallerPackage)) { 8532 // If this permission is to be granted to the system installer and 8533 // this app is an installer, then it gets the permission. 8534 allowed = true; 8535 } 8536 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 8537 && pkg.packageName.equals(mRequiredVerifierPackage)) { 8538 // If this permission is to be granted to the system verifier and 8539 // this app is a verifier, then it gets the permission. 8540 allowed = true; 8541 } 8542 if (!allowed && (bp.protectionLevel 8543 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 8544 && isSystemApp(pkg)) { 8545 // Any pre-installed system app is allowed to get this permission. 8546 allowed = true; 8547 } 8548 if (!allowed && (bp.protectionLevel 8549 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 8550 // For development permissions, a development permission 8551 // is granted only if it was already granted. 8552 allowed = origPermissions.hasInstallPermission(perm); 8553 } 8554 } 8555 return allowed; 8556 } 8557 8558 final class ActivityIntentResolver 8559 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 8560 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8561 boolean defaultOnly, int userId) { 8562 if (!sUserManager.exists(userId)) return null; 8563 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8564 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8565 } 8566 8567 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8568 int userId) { 8569 if (!sUserManager.exists(userId)) return null; 8570 mFlags = flags; 8571 return super.queryIntent(intent, resolvedType, 8572 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8573 } 8574 8575 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8576 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 8577 if (!sUserManager.exists(userId)) return null; 8578 if (packageActivities == null) { 8579 return null; 8580 } 8581 mFlags = flags; 8582 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8583 final int N = packageActivities.size(); 8584 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 8585 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 8586 8587 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 8588 for (int i = 0; i < N; ++i) { 8589 intentFilters = packageActivities.get(i).intents; 8590 if (intentFilters != null && intentFilters.size() > 0) { 8591 PackageParser.ActivityIntentInfo[] array = 8592 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 8593 intentFilters.toArray(array); 8594 listCut.add(array); 8595 } 8596 } 8597 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8598 } 8599 8600 public final void addActivity(PackageParser.Activity a, String type) { 8601 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 8602 mActivities.put(a.getComponentName(), a); 8603 if (DEBUG_SHOW_INFO) 8604 Log.v( 8605 TAG, " " + type + " " + 8606 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 8607 if (DEBUG_SHOW_INFO) 8608 Log.v(TAG, " Class=" + a.info.name); 8609 final int NI = a.intents.size(); 8610 for (int j=0; j<NI; j++) { 8611 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8612 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 8613 intent.setPriority(0); 8614 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 8615 + a.className + " with priority > 0, forcing to 0"); 8616 } 8617 if (DEBUG_SHOW_INFO) { 8618 Log.v(TAG, " IntentFilter:"); 8619 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8620 } 8621 if (!intent.debugCheck()) { 8622 Log.w(TAG, "==> For Activity " + a.info.name); 8623 } 8624 addFilter(intent); 8625 } 8626 } 8627 8628 public final void removeActivity(PackageParser.Activity a, String type) { 8629 mActivities.remove(a.getComponentName()); 8630 if (DEBUG_SHOW_INFO) { 8631 Log.v(TAG, " " + type + " " 8632 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 8633 : a.info.name) + ":"); 8634 Log.v(TAG, " Class=" + a.info.name); 8635 } 8636 final int NI = a.intents.size(); 8637 for (int j=0; j<NI; j++) { 8638 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8639 if (DEBUG_SHOW_INFO) { 8640 Log.v(TAG, " IntentFilter:"); 8641 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8642 } 8643 removeFilter(intent); 8644 } 8645 } 8646 8647 @Override 8648 protected boolean allowFilterResult( 8649 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 8650 ActivityInfo filterAi = filter.activity.info; 8651 for (int i=dest.size()-1; i>=0; i--) { 8652 ActivityInfo destAi = dest.get(i).activityInfo; 8653 if (destAi.name == filterAi.name 8654 && destAi.packageName == filterAi.packageName) { 8655 return false; 8656 } 8657 } 8658 return true; 8659 } 8660 8661 @Override 8662 protected ActivityIntentInfo[] newArray(int size) { 8663 return new ActivityIntentInfo[size]; 8664 } 8665 8666 @Override 8667 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 8668 if (!sUserManager.exists(userId)) return true; 8669 PackageParser.Package p = filter.activity.owner; 8670 if (p != null) { 8671 PackageSetting ps = (PackageSetting)p.mExtras; 8672 if (ps != null) { 8673 // System apps are never considered stopped for purposes of 8674 // filtering, because there may be no way for the user to 8675 // actually re-launch them. 8676 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 8677 && ps.getStopped(userId); 8678 } 8679 } 8680 return false; 8681 } 8682 8683 @Override 8684 protected boolean isPackageForFilter(String packageName, 8685 PackageParser.ActivityIntentInfo info) { 8686 return packageName.equals(info.activity.owner.packageName); 8687 } 8688 8689 @Override 8690 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 8691 int match, int userId) { 8692 if (!sUserManager.exists(userId)) return null; 8693 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 8694 return null; 8695 } 8696 final PackageParser.Activity activity = info.activity; 8697 if (mSafeMode && (activity.info.applicationInfo.flags 8698 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8699 return null; 8700 } 8701 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 8702 if (ps == null) { 8703 return null; 8704 } 8705 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 8706 ps.readUserState(userId), userId); 8707 if (ai == null) { 8708 return null; 8709 } 8710 final ResolveInfo res = new ResolveInfo(); 8711 res.activityInfo = ai; 8712 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8713 res.filter = info; 8714 } 8715 if (info != null) { 8716 res.handleAllWebDataURI = info.handleAllWebDataURI(); 8717 } 8718 res.priority = info.getPriority(); 8719 res.preferredOrder = activity.owner.mPreferredOrder; 8720 //System.out.println("Result: " + res.activityInfo.className + 8721 // " = " + res.priority); 8722 res.match = match; 8723 res.isDefault = info.hasDefault; 8724 res.labelRes = info.labelRes; 8725 res.nonLocalizedLabel = info.nonLocalizedLabel; 8726 if (userNeedsBadging(userId)) { 8727 res.noResourceId = true; 8728 } else { 8729 res.icon = info.icon; 8730 } 8731 res.iconResourceId = info.icon; 8732 res.system = res.activityInfo.applicationInfo.isSystemApp(); 8733 return res; 8734 } 8735 8736 @Override 8737 protected void sortResults(List<ResolveInfo> results) { 8738 Collections.sort(results, mResolvePrioritySorter); 8739 } 8740 8741 @Override 8742 protected void dumpFilter(PrintWriter out, String prefix, 8743 PackageParser.ActivityIntentInfo filter) { 8744 out.print(prefix); out.print( 8745 Integer.toHexString(System.identityHashCode(filter.activity))); 8746 out.print(' '); 8747 filter.activity.printComponentShortName(out); 8748 out.print(" filter "); 8749 out.println(Integer.toHexString(System.identityHashCode(filter))); 8750 } 8751 8752 @Override 8753 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 8754 return filter.activity; 8755 } 8756 8757 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8758 PackageParser.Activity activity = (PackageParser.Activity)label; 8759 out.print(prefix); out.print( 8760 Integer.toHexString(System.identityHashCode(activity))); 8761 out.print(' '); 8762 activity.printComponentShortName(out); 8763 if (count > 1) { 8764 out.print(" ("); out.print(count); out.print(" filters)"); 8765 } 8766 out.println(); 8767 } 8768 8769// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8770// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8771// final List<ResolveInfo> retList = Lists.newArrayList(); 8772// while (i.hasNext()) { 8773// final ResolveInfo resolveInfo = i.next(); 8774// if (isEnabledLP(resolveInfo.activityInfo)) { 8775// retList.add(resolveInfo); 8776// } 8777// } 8778// return retList; 8779// } 8780 8781 // Keys are String (activity class name), values are Activity. 8782 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 8783 = new ArrayMap<ComponentName, PackageParser.Activity>(); 8784 private int mFlags; 8785 } 8786 8787 private final class ServiceIntentResolver 8788 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 8789 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8790 boolean defaultOnly, int userId) { 8791 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8792 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8793 } 8794 8795 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8796 int userId) { 8797 if (!sUserManager.exists(userId)) return null; 8798 mFlags = flags; 8799 return super.queryIntent(intent, resolvedType, 8800 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8801 } 8802 8803 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8804 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 8805 if (!sUserManager.exists(userId)) return null; 8806 if (packageServices == null) { 8807 return null; 8808 } 8809 mFlags = flags; 8810 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8811 final int N = packageServices.size(); 8812 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 8813 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 8814 8815 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 8816 for (int i = 0; i < N; ++i) { 8817 intentFilters = packageServices.get(i).intents; 8818 if (intentFilters != null && intentFilters.size() > 0) { 8819 PackageParser.ServiceIntentInfo[] array = 8820 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 8821 intentFilters.toArray(array); 8822 listCut.add(array); 8823 } 8824 } 8825 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8826 } 8827 8828 public final void addService(PackageParser.Service s) { 8829 mServices.put(s.getComponentName(), s); 8830 if (DEBUG_SHOW_INFO) { 8831 Log.v(TAG, " " 8832 + (s.info.nonLocalizedLabel != null 8833 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8834 Log.v(TAG, " Class=" + s.info.name); 8835 } 8836 final int NI = s.intents.size(); 8837 int j; 8838 for (j=0; j<NI; j++) { 8839 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8840 if (DEBUG_SHOW_INFO) { 8841 Log.v(TAG, " IntentFilter:"); 8842 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8843 } 8844 if (!intent.debugCheck()) { 8845 Log.w(TAG, "==> For Service " + s.info.name); 8846 } 8847 addFilter(intent); 8848 } 8849 } 8850 8851 public final void removeService(PackageParser.Service s) { 8852 mServices.remove(s.getComponentName()); 8853 if (DEBUG_SHOW_INFO) { 8854 Log.v(TAG, " " + (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 removeFilter(intent); 8867 } 8868 } 8869 8870 @Override 8871 protected boolean allowFilterResult( 8872 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 8873 ServiceInfo filterSi = filter.service.info; 8874 for (int i=dest.size()-1; i>=0; i--) { 8875 ServiceInfo destAi = dest.get(i).serviceInfo; 8876 if (destAi.name == filterSi.name 8877 && destAi.packageName == filterSi.packageName) { 8878 return false; 8879 } 8880 } 8881 return true; 8882 } 8883 8884 @Override 8885 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 8886 return new PackageParser.ServiceIntentInfo[size]; 8887 } 8888 8889 @Override 8890 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 8891 if (!sUserManager.exists(userId)) return true; 8892 PackageParser.Package p = filter.service.owner; 8893 if (p != null) { 8894 PackageSetting ps = (PackageSetting)p.mExtras; 8895 if (ps != null) { 8896 // System apps are never considered stopped for purposes of 8897 // filtering, because there may be no way for the user to 8898 // actually re-launch them. 8899 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8900 && ps.getStopped(userId); 8901 } 8902 } 8903 return false; 8904 } 8905 8906 @Override 8907 protected boolean isPackageForFilter(String packageName, 8908 PackageParser.ServiceIntentInfo info) { 8909 return packageName.equals(info.service.owner.packageName); 8910 } 8911 8912 @Override 8913 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 8914 int match, int userId) { 8915 if (!sUserManager.exists(userId)) return null; 8916 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 8917 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 8918 return null; 8919 } 8920 final PackageParser.Service service = info.service; 8921 if (mSafeMode && (service.info.applicationInfo.flags 8922 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8923 return null; 8924 } 8925 PackageSetting ps = (PackageSetting) service.owner.mExtras; 8926 if (ps == null) { 8927 return null; 8928 } 8929 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 8930 ps.readUserState(userId), userId); 8931 if (si == null) { 8932 return null; 8933 } 8934 final ResolveInfo res = new ResolveInfo(); 8935 res.serviceInfo = si; 8936 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8937 res.filter = filter; 8938 } 8939 res.priority = info.getPriority(); 8940 res.preferredOrder = service.owner.mPreferredOrder; 8941 res.match = match; 8942 res.isDefault = info.hasDefault; 8943 res.labelRes = info.labelRes; 8944 res.nonLocalizedLabel = info.nonLocalizedLabel; 8945 res.icon = info.icon; 8946 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 8947 return res; 8948 } 8949 8950 @Override 8951 protected void sortResults(List<ResolveInfo> results) { 8952 Collections.sort(results, mResolvePrioritySorter); 8953 } 8954 8955 @Override 8956 protected void dumpFilter(PrintWriter out, String prefix, 8957 PackageParser.ServiceIntentInfo filter) { 8958 out.print(prefix); out.print( 8959 Integer.toHexString(System.identityHashCode(filter.service))); 8960 out.print(' '); 8961 filter.service.printComponentShortName(out); 8962 out.print(" filter "); 8963 out.println(Integer.toHexString(System.identityHashCode(filter))); 8964 } 8965 8966 @Override 8967 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 8968 return filter.service; 8969 } 8970 8971 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8972 PackageParser.Service service = (PackageParser.Service)label; 8973 out.print(prefix); out.print( 8974 Integer.toHexString(System.identityHashCode(service))); 8975 out.print(' '); 8976 service.printComponentShortName(out); 8977 if (count > 1) { 8978 out.print(" ("); out.print(count); out.print(" filters)"); 8979 } 8980 out.println(); 8981 } 8982 8983// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8984// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8985// final List<ResolveInfo> retList = Lists.newArrayList(); 8986// while (i.hasNext()) { 8987// final ResolveInfo resolveInfo = (ResolveInfo) i; 8988// if (isEnabledLP(resolveInfo.serviceInfo)) { 8989// retList.add(resolveInfo); 8990// } 8991// } 8992// return retList; 8993// } 8994 8995 // Keys are String (activity class name), values are Activity. 8996 private final ArrayMap<ComponentName, PackageParser.Service> mServices 8997 = new ArrayMap<ComponentName, PackageParser.Service>(); 8998 private int mFlags; 8999 }; 9000 9001 private final class ProviderIntentResolver 9002 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 9003 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9004 boolean defaultOnly, int userId) { 9005 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9006 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9007 } 9008 9009 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9010 int userId) { 9011 if (!sUserManager.exists(userId)) 9012 return null; 9013 mFlags = flags; 9014 return super.queryIntent(intent, resolvedType, 9015 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9016 } 9017 9018 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9019 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 9020 if (!sUserManager.exists(userId)) 9021 return null; 9022 if (packageProviders == null) { 9023 return null; 9024 } 9025 mFlags = flags; 9026 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 9027 final int N = packageProviders.size(); 9028 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 9029 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 9030 9031 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 9032 for (int i = 0; i < N; ++i) { 9033 intentFilters = packageProviders.get(i).intents; 9034 if (intentFilters != null && intentFilters.size() > 0) { 9035 PackageParser.ProviderIntentInfo[] array = 9036 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 9037 intentFilters.toArray(array); 9038 listCut.add(array); 9039 } 9040 } 9041 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9042 } 9043 9044 public final void addProvider(PackageParser.Provider p) { 9045 if (mProviders.containsKey(p.getComponentName())) { 9046 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 9047 return; 9048 } 9049 9050 mProviders.put(p.getComponentName(), p); 9051 if (DEBUG_SHOW_INFO) { 9052 Log.v(TAG, " " 9053 + (p.info.nonLocalizedLabel != null 9054 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9055 Log.v(TAG, " Class=" + p.info.name); 9056 } 9057 final int NI = p.intents.size(); 9058 int j; 9059 for (j = 0; j < NI; j++) { 9060 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9061 if (DEBUG_SHOW_INFO) { 9062 Log.v(TAG, " IntentFilter:"); 9063 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9064 } 9065 if (!intent.debugCheck()) { 9066 Log.w(TAG, "==> For Provider " + p.info.name); 9067 } 9068 addFilter(intent); 9069 } 9070 } 9071 9072 public final void removeProvider(PackageParser.Provider p) { 9073 mProviders.remove(p.getComponentName()); 9074 if (DEBUG_SHOW_INFO) { 9075 Log.v(TAG, " " + (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 removeFilter(intent); 9088 } 9089 } 9090 9091 @Override 9092 protected boolean allowFilterResult( 9093 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 9094 ProviderInfo filterPi = filter.provider.info; 9095 for (int i = dest.size() - 1; i >= 0; i--) { 9096 ProviderInfo destPi = dest.get(i).providerInfo; 9097 if (destPi.name == filterPi.name 9098 && destPi.packageName == filterPi.packageName) { 9099 return false; 9100 } 9101 } 9102 return true; 9103 } 9104 9105 @Override 9106 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 9107 return new PackageParser.ProviderIntentInfo[size]; 9108 } 9109 9110 @Override 9111 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 9112 if (!sUserManager.exists(userId)) 9113 return true; 9114 PackageParser.Package p = filter.provider.owner; 9115 if (p != null) { 9116 PackageSetting ps = (PackageSetting) p.mExtras; 9117 if (ps != null) { 9118 // System apps are never considered stopped for purposes of 9119 // filtering, because there may be no way for the user to 9120 // actually re-launch them. 9121 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9122 && ps.getStopped(userId); 9123 } 9124 } 9125 return false; 9126 } 9127 9128 @Override 9129 protected boolean isPackageForFilter(String packageName, 9130 PackageParser.ProviderIntentInfo info) { 9131 return packageName.equals(info.provider.owner.packageName); 9132 } 9133 9134 @Override 9135 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 9136 int match, int userId) { 9137 if (!sUserManager.exists(userId)) 9138 return null; 9139 final PackageParser.ProviderIntentInfo info = filter; 9140 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 9141 return null; 9142 } 9143 final PackageParser.Provider provider = info.provider; 9144 if (mSafeMode && (provider.info.applicationInfo.flags 9145 & ApplicationInfo.FLAG_SYSTEM) == 0) { 9146 return null; 9147 } 9148 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 9149 if (ps == null) { 9150 return null; 9151 } 9152 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 9153 ps.readUserState(userId), userId); 9154 if (pi == null) { 9155 return null; 9156 } 9157 final ResolveInfo res = new ResolveInfo(); 9158 res.providerInfo = pi; 9159 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 9160 res.filter = filter; 9161 } 9162 res.priority = info.getPriority(); 9163 res.preferredOrder = provider.owner.mPreferredOrder; 9164 res.match = match; 9165 res.isDefault = info.hasDefault; 9166 res.labelRes = info.labelRes; 9167 res.nonLocalizedLabel = info.nonLocalizedLabel; 9168 res.icon = info.icon; 9169 res.system = res.providerInfo.applicationInfo.isSystemApp(); 9170 return res; 9171 } 9172 9173 @Override 9174 protected void sortResults(List<ResolveInfo> results) { 9175 Collections.sort(results, mResolvePrioritySorter); 9176 } 9177 9178 @Override 9179 protected void dumpFilter(PrintWriter out, String prefix, 9180 PackageParser.ProviderIntentInfo filter) { 9181 out.print(prefix); 9182 out.print( 9183 Integer.toHexString(System.identityHashCode(filter.provider))); 9184 out.print(' '); 9185 filter.provider.printComponentShortName(out); 9186 out.print(" filter "); 9187 out.println(Integer.toHexString(System.identityHashCode(filter))); 9188 } 9189 9190 @Override 9191 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 9192 return filter.provider; 9193 } 9194 9195 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9196 PackageParser.Provider provider = (PackageParser.Provider)label; 9197 out.print(prefix); out.print( 9198 Integer.toHexString(System.identityHashCode(provider))); 9199 out.print(' '); 9200 provider.printComponentShortName(out); 9201 if (count > 1) { 9202 out.print(" ("); out.print(count); out.print(" filters)"); 9203 } 9204 out.println(); 9205 } 9206 9207 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 9208 = new ArrayMap<ComponentName, PackageParser.Provider>(); 9209 private int mFlags; 9210 }; 9211 9212 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 9213 new Comparator<ResolveInfo>() { 9214 public int compare(ResolveInfo r1, ResolveInfo r2) { 9215 int v1 = r1.priority; 9216 int v2 = r2.priority; 9217 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 9218 if (v1 != v2) { 9219 return (v1 > v2) ? -1 : 1; 9220 } 9221 v1 = r1.preferredOrder; 9222 v2 = r2.preferredOrder; 9223 if (v1 != v2) { 9224 return (v1 > v2) ? -1 : 1; 9225 } 9226 if (r1.isDefault != r2.isDefault) { 9227 return r1.isDefault ? -1 : 1; 9228 } 9229 v1 = r1.match; 9230 v2 = r2.match; 9231 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 9232 if (v1 != v2) { 9233 return (v1 > v2) ? -1 : 1; 9234 } 9235 if (r1.system != r2.system) { 9236 return r1.system ? -1 : 1; 9237 } 9238 return 0; 9239 } 9240 }; 9241 9242 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 9243 new Comparator<ProviderInfo>() { 9244 public int compare(ProviderInfo p1, ProviderInfo p2) { 9245 final int v1 = p1.initOrder; 9246 final int v2 = p2.initOrder; 9247 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 9248 } 9249 }; 9250 9251 final void sendPackageBroadcast(final String action, final String pkg, 9252 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 9253 final int[] userIds) { 9254 mHandler.post(new Runnable() { 9255 @Override 9256 public void run() { 9257 try { 9258 final IActivityManager am = ActivityManagerNative.getDefault(); 9259 if (am == null) return; 9260 final int[] resolvedUserIds; 9261 if (userIds == null) { 9262 resolvedUserIds = am.getRunningUserIds(); 9263 } else { 9264 resolvedUserIds = userIds; 9265 } 9266 for (int id : resolvedUserIds) { 9267 final Intent intent = new Intent(action, 9268 pkg != null ? Uri.fromParts("package", pkg, null) : null); 9269 if (extras != null) { 9270 intent.putExtras(extras); 9271 } 9272 if (targetPkg != null) { 9273 intent.setPackage(targetPkg); 9274 } 9275 // Modify the UID when posting to other users 9276 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 9277 if (uid > 0 && UserHandle.getUserId(uid) != id) { 9278 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 9279 intent.putExtra(Intent.EXTRA_UID, uid); 9280 } 9281 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 9282 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 9283 if (DEBUG_BROADCASTS) { 9284 RuntimeException here = new RuntimeException("here"); 9285 here.fillInStackTrace(); 9286 Slog.d(TAG, "Sending to user " + id + ": " 9287 + intent.toShortString(false, true, false, false) 9288 + " " + intent.getExtras(), here); 9289 } 9290 am.broadcastIntent(null, intent, null, finishedReceiver, 9291 0, null, null, null, android.app.AppOpsManager.OP_NONE, 9292 null, finishedReceiver != null, false, id); 9293 } 9294 } catch (RemoteException ex) { 9295 } 9296 } 9297 }); 9298 } 9299 9300 /** 9301 * Check if the external storage media is available. This is true if there 9302 * is a mounted external storage medium or if the external storage is 9303 * emulated. 9304 */ 9305 private boolean isExternalMediaAvailable() { 9306 return mMediaMounted || Environment.isExternalStorageEmulated(); 9307 } 9308 9309 @Override 9310 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 9311 // writer 9312 synchronized (mPackages) { 9313 if (!isExternalMediaAvailable()) { 9314 // If the external storage is no longer mounted at this point, 9315 // the caller may not have been able to delete all of this 9316 // packages files and can not delete any more. Bail. 9317 return null; 9318 } 9319 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 9320 if (lastPackage != null) { 9321 pkgs.remove(lastPackage); 9322 } 9323 if (pkgs.size() > 0) { 9324 return pkgs.get(0); 9325 } 9326 } 9327 return null; 9328 } 9329 9330 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 9331 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 9332 userId, andCode ? 1 : 0, packageName); 9333 if (mSystemReady) { 9334 msg.sendToTarget(); 9335 } else { 9336 if (mPostSystemReadyMessages == null) { 9337 mPostSystemReadyMessages = new ArrayList<>(); 9338 } 9339 mPostSystemReadyMessages.add(msg); 9340 } 9341 } 9342 9343 void startCleaningPackages() { 9344 // reader 9345 synchronized (mPackages) { 9346 if (!isExternalMediaAvailable()) { 9347 return; 9348 } 9349 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 9350 return; 9351 } 9352 } 9353 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 9354 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 9355 IActivityManager am = ActivityManagerNative.getDefault(); 9356 if (am != null) { 9357 try { 9358 am.startService(null, intent, null, mContext.getOpPackageName(), 9359 UserHandle.USER_OWNER); 9360 } catch (RemoteException e) { 9361 } 9362 } 9363 } 9364 9365 @Override 9366 public void installPackage(String originPath, IPackageInstallObserver2 observer, 9367 int installFlags, String installerPackageName, VerificationParams verificationParams, 9368 String packageAbiOverride) { 9369 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 9370 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 9371 } 9372 9373 @Override 9374 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 9375 int installFlags, String installerPackageName, VerificationParams verificationParams, 9376 String packageAbiOverride, int userId) { 9377 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 9378 9379 final int callingUid = Binder.getCallingUid(); 9380 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 9381 9382 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9383 try { 9384 if (observer != null) { 9385 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 9386 } 9387 } catch (RemoteException re) { 9388 } 9389 return; 9390 } 9391 9392 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 9393 installFlags |= PackageManager.INSTALL_FROM_ADB; 9394 9395 } else { 9396 // Caller holds INSTALL_PACKAGES permission, so we're less strict 9397 // about installerPackageName. 9398 9399 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 9400 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 9401 } 9402 9403 UserHandle user; 9404 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 9405 user = UserHandle.ALL; 9406 } else { 9407 user = new UserHandle(userId); 9408 } 9409 9410 // Only system components can circumvent runtime permissions when installing. 9411 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 9412 && mContext.checkCallingOrSelfPermission(Manifest.permission 9413 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 9414 throw new SecurityException("You need the " 9415 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 9416 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 9417 } 9418 9419 verificationParams.setInstallerUid(callingUid); 9420 9421 final File originFile = new File(originPath); 9422 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 9423 9424 final Message msg = mHandler.obtainMessage(INIT_COPY); 9425 msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName, 9426 null, verificationParams, user, packageAbiOverride); 9427 mHandler.sendMessage(msg); 9428 } 9429 9430 void installStage(String packageName, File stagedDir, String stagedCid, 9431 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 9432 String installerPackageName, int installerUid, UserHandle user) { 9433 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 9434 params.referrerUri, installerUid, null); 9435 verifParams.setInstallerUid(installerUid); 9436 9437 final OriginInfo origin; 9438 if (stagedDir != null) { 9439 origin = OriginInfo.fromStagedFile(stagedDir); 9440 } else { 9441 origin = OriginInfo.fromStagedContainer(stagedCid); 9442 } 9443 9444 final Message msg = mHandler.obtainMessage(INIT_COPY); 9445 msg.obj = new InstallParams(origin, null, observer, params.installFlags, 9446 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride); 9447 mHandler.sendMessage(msg); 9448 } 9449 9450 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 9451 Bundle extras = new Bundle(1); 9452 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 9453 9454 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 9455 packageName, extras, null, null, new int[] {userId}); 9456 try { 9457 IActivityManager am = ActivityManagerNative.getDefault(); 9458 final boolean isSystem = 9459 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 9460 if (isSystem && am.isUserRunning(userId, false)) { 9461 // The just-installed/enabled app is bundled on the system, so presumed 9462 // to be able to run automatically without needing an explicit launch. 9463 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 9464 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 9465 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 9466 .setPackage(packageName); 9467 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 9468 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 9469 } 9470 } catch (RemoteException e) { 9471 // shouldn't happen 9472 Slog.w(TAG, "Unable to bootstrap installed package", e); 9473 } 9474 } 9475 9476 @Override 9477 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 9478 int userId) { 9479 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9480 PackageSetting pkgSetting; 9481 final int uid = Binder.getCallingUid(); 9482 enforceCrossUserPermission(uid, userId, true, true, 9483 "setApplicationHiddenSetting for user " + userId); 9484 9485 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 9486 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 9487 return false; 9488 } 9489 9490 long callingId = Binder.clearCallingIdentity(); 9491 try { 9492 boolean sendAdded = false; 9493 boolean sendRemoved = false; 9494 // writer 9495 synchronized (mPackages) { 9496 pkgSetting = mSettings.mPackages.get(packageName); 9497 if (pkgSetting == null) { 9498 return false; 9499 } 9500 if (pkgSetting.getHidden(userId) != hidden) { 9501 pkgSetting.setHidden(hidden, userId); 9502 mSettings.writePackageRestrictionsLPr(userId); 9503 if (hidden) { 9504 sendRemoved = true; 9505 } else { 9506 sendAdded = true; 9507 } 9508 } 9509 } 9510 if (sendAdded) { 9511 sendPackageAddedForUser(packageName, pkgSetting, userId); 9512 return true; 9513 } 9514 if (sendRemoved) { 9515 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 9516 "hiding pkg"); 9517 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 9518 } 9519 } finally { 9520 Binder.restoreCallingIdentity(callingId); 9521 } 9522 return false; 9523 } 9524 9525 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 9526 int userId) { 9527 final PackageRemovedInfo info = new PackageRemovedInfo(); 9528 info.removedPackage = packageName; 9529 info.removedUsers = new int[] {userId}; 9530 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 9531 info.sendBroadcast(false, false, false); 9532 } 9533 9534 /** 9535 * Returns true if application is not found or there was an error. Otherwise it returns 9536 * the hidden state of the package for the given user. 9537 */ 9538 @Override 9539 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 9540 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9541 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 9542 false, "getApplicationHidden for user " + userId); 9543 PackageSetting pkgSetting; 9544 long callingId = Binder.clearCallingIdentity(); 9545 try { 9546 // writer 9547 synchronized (mPackages) { 9548 pkgSetting = mSettings.mPackages.get(packageName); 9549 if (pkgSetting == null) { 9550 return true; 9551 } 9552 return pkgSetting.getHidden(userId); 9553 } 9554 } finally { 9555 Binder.restoreCallingIdentity(callingId); 9556 } 9557 } 9558 9559 /** 9560 * @hide 9561 */ 9562 @Override 9563 public int installExistingPackageAsUser(String packageName, int userId) { 9564 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 9565 null); 9566 PackageSetting pkgSetting; 9567 final int uid = Binder.getCallingUid(); 9568 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 9569 + userId); 9570 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9571 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 9572 } 9573 9574 long callingId = Binder.clearCallingIdentity(); 9575 try { 9576 boolean sendAdded = false; 9577 9578 // writer 9579 synchronized (mPackages) { 9580 pkgSetting = mSettings.mPackages.get(packageName); 9581 if (pkgSetting == null) { 9582 return PackageManager.INSTALL_FAILED_INVALID_URI; 9583 } 9584 if (!pkgSetting.getInstalled(userId)) { 9585 pkgSetting.setInstalled(true, userId); 9586 pkgSetting.setHidden(false, userId); 9587 mSettings.writePackageRestrictionsLPr(userId); 9588 sendAdded = true; 9589 } 9590 } 9591 9592 if (sendAdded) { 9593 sendPackageAddedForUser(packageName, pkgSetting, userId); 9594 } 9595 } finally { 9596 Binder.restoreCallingIdentity(callingId); 9597 } 9598 9599 return PackageManager.INSTALL_SUCCEEDED; 9600 } 9601 9602 boolean isUserRestricted(int userId, String restrictionKey) { 9603 Bundle restrictions = sUserManager.getUserRestrictions(userId); 9604 if (restrictions.getBoolean(restrictionKey, false)) { 9605 Log.w(TAG, "User is restricted: " + restrictionKey); 9606 return true; 9607 } 9608 return false; 9609 } 9610 9611 @Override 9612 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 9613 mContext.enforceCallingOrSelfPermission( 9614 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9615 "Only package verification agents can verify applications"); 9616 9617 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9618 final PackageVerificationResponse response = new PackageVerificationResponse( 9619 verificationCode, Binder.getCallingUid()); 9620 msg.arg1 = id; 9621 msg.obj = response; 9622 mHandler.sendMessage(msg); 9623 } 9624 9625 @Override 9626 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 9627 long millisecondsToDelay) { 9628 mContext.enforceCallingOrSelfPermission( 9629 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9630 "Only package verification agents can extend verification timeouts"); 9631 9632 final PackageVerificationState state = mPendingVerification.get(id); 9633 final PackageVerificationResponse response = new PackageVerificationResponse( 9634 verificationCodeAtTimeout, Binder.getCallingUid()); 9635 9636 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 9637 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 9638 } 9639 if (millisecondsToDelay < 0) { 9640 millisecondsToDelay = 0; 9641 } 9642 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 9643 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 9644 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 9645 } 9646 9647 if ((state != null) && !state.timeoutExtended()) { 9648 state.extendTimeout(); 9649 9650 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9651 msg.arg1 = id; 9652 msg.obj = response; 9653 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 9654 } 9655 } 9656 9657 private void broadcastPackageVerified(int verificationId, Uri packageUri, 9658 int verificationCode, UserHandle user) { 9659 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 9660 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 9661 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9662 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9663 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 9664 9665 mContext.sendBroadcastAsUser(intent, user, 9666 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 9667 } 9668 9669 private ComponentName matchComponentForVerifier(String packageName, 9670 List<ResolveInfo> receivers) { 9671 ActivityInfo targetReceiver = null; 9672 9673 final int NR = receivers.size(); 9674 for (int i = 0; i < NR; i++) { 9675 final ResolveInfo info = receivers.get(i); 9676 if (info.activityInfo == null) { 9677 continue; 9678 } 9679 9680 if (packageName.equals(info.activityInfo.packageName)) { 9681 targetReceiver = info.activityInfo; 9682 break; 9683 } 9684 } 9685 9686 if (targetReceiver == null) { 9687 return null; 9688 } 9689 9690 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 9691 } 9692 9693 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 9694 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 9695 if (pkgInfo.verifiers.length == 0) { 9696 return null; 9697 } 9698 9699 final int N = pkgInfo.verifiers.length; 9700 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 9701 for (int i = 0; i < N; i++) { 9702 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 9703 9704 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 9705 receivers); 9706 if (comp == null) { 9707 continue; 9708 } 9709 9710 final int verifierUid = getUidForVerifier(verifierInfo); 9711 if (verifierUid == -1) { 9712 continue; 9713 } 9714 9715 if (DEBUG_VERIFY) { 9716 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 9717 + " with the correct signature"); 9718 } 9719 sufficientVerifiers.add(comp); 9720 verificationState.addSufficientVerifier(verifierUid); 9721 } 9722 9723 return sufficientVerifiers; 9724 } 9725 9726 private int getUidForVerifier(VerifierInfo verifierInfo) { 9727 synchronized (mPackages) { 9728 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 9729 if (pkg == null) { 9730 return -1; 9731 } else if (pkg.mSignatures.length != 1) { 9732 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9733 + " has more than one signature; ignoring"); 9734 return -1; 9735 } 9736 9737 /* 9738 * If the public key of the package's signature does not match 9739 * our expected public key, then this is a different package and 9740 * we should skip. 9741 */ 9742 9743 final byte[] expectedPublicKey; 9744 try { 9745 final Signature verifierSig = pkg.mSignatures[0]; 9746 final PublicKey publicKey = verifierSig.getPublicKey(); 9747 expectedPublicKey = publicKey.getEncoded(); 9748 } catch (CertificateException e) { 9749 return -1; 9750 } 9751 9752 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 9753 9754 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 9755 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9756 + " does not have the expected public key; ignoring"); 9757 return -1; 9758 } 9759 9760 return pkg.applicationInfo.uid; 9761 } 9762 } 9763 9764 @Override 9765 public void finishPackageInstall(int token) { 9766 enforceSystemOrRoot("Only the system is allowed to finish installs"); 9767 9768 if (DEBUG_INSTALL) { 9769 Slog.v(TAG, "BM finishing package install for " + token); 9770 } 9771 9772 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9773 mHandler.sendMessage(msg); 9774 } 9775 9776 /** 9777 * Get the verification agent timeout. 9778 * 9779 * @return verification timeout in milliseconds 9780 */ 9781 private long getVerificationTimeout() { 9782 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 9783 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 9784 DEFAULT_VERIFICATION_TIMEOUT); 9785 } 9786 9787 /** 9788 * Get the default verification agent response code. 9789 * 9790 * @return default verification response code 9791 */ 9792 private int getDefaultVerificationResponse() { 9793 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9794 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 9795 DEFAULT_VERIFICATION_RESPONSE); 9796 } 9797 9798 /** 9799 * Check whether or not package verification has been enabled. 9800 * 9801 * @return true if verification should be performed 9802 */ 9803 private boolean isVerificationEnabled(int userId, int installFlags) { 9804 if (!DEFAULT_VERIFY_ENABLE) { 9805 return false; 9806 } 9807 9808 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 9809 9810 // Check if installing from ADB 9811 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 9812 // Do not run verification in a test harness environment 9813 if (ActivityManager.isRunningInTestHarness()) { 9814 return false; 9815 } 9816 if (ensureVerifyAppsEnabled) { 9817 return true; 9818 } 9819 // Check if the developer does not want package verification for ADB installs 9820 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9821 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 9822 return false; 9823 } 9824 } 9825 9826 if (ensureVerifyAppsEnabled) { 9827 return true; 9828 } 9829 9830 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9831 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 9832 } 9833 9834 @Override 9835 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 9836 throws RemoteException { 9837 mContext.enforceCallingOrSelfPermission( 9838 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 9839 "Only intentfilter verification agents can verify applications"); 9840 9841 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 9842 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 9843 Binder.getCallingUid(), verificationCode, failedDomains); 9844 msg.arg1 = id; 9845 msg.obj = response; 9846 mHandler.sendMessage(msg); 9847 } 9848 9849 @Override 9850 public int getIntentVerificationStatus(String packageName, int userId) { 9851 synchronized (mPackages) { 9852 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 9853 } 9854 } 9855 9856 @Override 9857 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 9858 mContext.enforceCallingOrSelfPermission( 9859 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 9860 9861 boolean result = false; 9862 synchronized (mPackages) { 9863 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 9864 } 9865 if (result) { 9866 scheduleWritePackageRestrictionsLocked(userId); 9867 } 9868 return result; 9869 } 9870 9871 @Override 9872 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 9873 synchronized (mPackages) { 9874 return mSettings.getIntentFilterVerificationsLPr(packageName); 9875 } 9876 } 9877 9878 @Override 9879 public List<IntentFilter> getAllIntentFilters(String packageName) { 9880 if (TextUtils.isEmpty(packageName)) { 9881 return Collections.<IntentFilter>emptyList(); 9882 } 9883 synchronized (mPackages) { 9884 PackageParser.Package pkg = mPackages.get(packageName); 9885 if (pkg == null || pkg.activities == null) { 9886 return Collections.<IntentFilter>emptyList(); 9887 } 9888 final int count = pkg.activities.size(); 9889 ArrayList<IntentFilter> result = new ArrayList<>(); 9890 for (int n=0; n<count; n++) { 9891 PackageParser.Activity activity = pkg.activities.get(n); 9892 if (activity.intents != null || activity.intents.size() > 0) { 9893 result.addAll(activity.intents); 9894 } 9895 } 9896 return result; 9897 } 9898 } 9899 9900 @Override 9901 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 9902 mContext.enforceCallingOrSelfPermission( 9903 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 9904 9905 synchronized (mPackages) { 9906 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 9907 if (packageName != null) { 9908 result |= updateIntentVerificationStatus(packageName, 9909 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 9910 UserHandle.myUserId()); 9911 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 9912 packageName, userId); 9913 } 9914 return result; 9915 } 9916 } 9917 9918 @Override 9919 public String getDefaultBrowserPackageName(int userId) { 9920 synchronized (mPackages) { 9921 return mSettings.getDefaultBrowserPackageNameLPw(userId); 9922 } 9923 } 9924 9925 /** 9926 * Get the "allow unknown sources" setting. 9927 * 9928 * @return the current "allow unknown sources" setting 9929 */ 9930 private int getUnknownSourcesSettings() { 9931 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9932 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 9933 -1); 9934 } 9935 9936 @Override 9937 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 9938 final int uid = Binder.getCallingUid(); 9939 // writer 9940 synchronized (mPackages) { 9941 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 9942 if (targetPackageSetting == null) { 9943 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 9944 } 9945 9946 PackageSetting installerPackageSetting; 9947 if (installerPackageName != null) { 9948 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 9949 if (installerPackageSetting == null) { 9950 throw new IllegalArgumentException("Unknown installer package: " 9951 + installerPackageName); 9952 } 9953 } else { 9954 installerPackageSetting = null; 9955 } 9956 9957 Signature[] callerSignature; 9958 Object obj = mSettings.getUserIdLPr(uid); 9959 if (obj != null) { 9960 if (obj instanceof SharedUserSetting) { 9961 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 9962 } else if (obj instanceof PackageSetting) { 9963 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 9964 } else { 9965 throw new SecurityException("Bad object " + obj + " for uid " + uid); 9966 } 9967 } else { 9968 throw new SecurityException("Unknown calling uid " + uid); 9969 } 9970 9971 // Verify: can't set installerPackageName to a package that is 9972 // not signed with the same cert as the caller. 9973 if (installerPackageSetting != null) { 9974 if (compareSignatures(callerSignature, 9975 installerPackageSetting.signatures.mSignatures) 9976 != PackageManager.SIGNATURE_MATCH) { 9977 throw new SecurityException( 9978 "Caller does not have same cert as new installer package " 9979 + installerPackageName); 9980 } 9981 } 9982 9983 // Verify: if target already has an installer package, it must 9984 // be signed with the same cert as the caller. 9985 if (targetPackageSetting.installerPackageName != null) { 9986 PackageSetting setting = mSettings.mPackages.get( 9987 targetPackageSetting.installerPackageName); 9988 // If the currently set package isn't valid, then it's always 9989 // okay to change it. 9990 if (setting != null) { 9991 if (compareSignatures(callerSignature, 9992 setting.signatures.mSignatures) 9993 != PackageManager.SIGNATURE_MATCH) { 9994 throw new SecurityException( 9995 "Caller does not have same cert as old installer package " 9996 + targetPackageSetting.installerPackageName); 9997 } 9998 } 9999 } 10000 10001 // Okay! 10002 targetPackageSetting.installerPackageName = installerPackageName; 10003 scheduleWriteSettingsLocked(); 10004 } 10005 } 10006 10007 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 10008 // Queue up an async operation since the package installation may take a little while. 10009 mHandler.post(new Runnable() { 10010 public void run() { 10011 mHandler.removeCallbacks(this); 10012 // Result object to be returned 10013 PackageInstalledInfo res = new PackageInstalledInfo(); 10014 res.returnCode = currentStatus; 10015 res.uid = -1; 10016 res.pkg = null; 10017 res.removedInfo = new PackageRemovedInfo(); 10018 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10019 args.doPreInstall(res.returnCode); 10020 synchronized (mInstallLock) { 10021 installPackageLI(args, res); 10022 } 10023 args.doPostInstall(res.returnCode, res.uid); 10024 } 10025 10026 // A restore should be performed at this point if (a) the install 10027 // succeeded, (b) the operation is not an update, and (c) the new 10028 // package has not opted out of backup participation. 10029 final boolean update = res.removedInfo.removedPackage != null; 10030 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 10031 boolean doRestore = !update 10032 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 10033 10034 // Set up the post-install work request bookkeeping. This will be used 10035 // and cleaned up by the post-install event handling regardless of whether 10036 // there's a restore pass performed. Token values are >= 1. 10037 int token; 10038 if (mNextInstallToken < 0) mNextInstallToken = 1; 10039 token = mNextInstallToken++; 10040 10041 PostInstallData data = new PostInstallData(args, res); 10042 mRunningInstalls.put(token, data); 10043 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 10044 10045 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 10046 // Pass responsibility to the Backup Manager. It will perform a 10047 // restore if appropriate, then pass responsibility back to the 10048 // Package Manager to run the post-install observer callbacks 10049 // and broadcasts. 10050 IBackupManager bm = IBackupManager.Stub.asInterface( 10051 ServiceManager.getService(Context.BACKUP_SERVICE)); 10052 if (bm != null) { 10053 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 10054 + " to BM for possible restore"); 10055 try { 10056 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 10057 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 10058 } else { 10059 doRestore = false; 10060 } 10061 } catch (RemoteException e) { 10062 // can't happen; the backup manager is local 10063 } catch (Exception e) { 10064 Slog.e(TAG, "Exception trying to enqueue restore", e); 10065 doRestore = false; 10066 } 10067 } else { 10068 Slog.e(TAG, "Backup Manager not found!"); 10069 doRestore = false; 10070 } 10071 } 10072 10073 if (!doRestore) { 10074 // No restore possible, or the Backup Manager was mysteriously not 10075 // available -- just fire the post-install work request directly. 10076 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 10077 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10078 mHandler.sendMessage(msg); 10079 } 10080 } 10081 }); 10082 } 10083 10084 private abstract class HandlerParams { 10085 private static final int MAX_RETRIES = 4; 10086 10087 /** 10088 * Number of times startCopy() has been attempted and had a non-fatal 10089 * error. 10090 */ 10091 private int mRetries = 0; 10092 10093 /** User handle for the user requesting the information or installation. */ 10094 private final UserHandle mUser; 10095 10096 HandlerParams(UserHandle user) { 10097 mUser = user; 10098 } 10099 10100 UserHandle getUser() { 10101 return mUser; 10102 } 10103 10104 final boolean startCopy() { 10105 boolean res; 10106 try { 10107 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 10108 10109 if (++mRetries > MAX_RETRIES) { 10110 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 10111 mHandler.sendEmptyMessage(MCS_GIVE_UP); 10112 handleServiceError(); 10113 return false; 10114 } else { 10115 handleStartCopy(); 10116 res = true; 10117 } 10118 } catch (RemoteException e) { 10119 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 10120 mHandler.sendEmptyMessage(MCS_RECONNECT); 10121 res = false; 10122 } 10123 handleReturnCode(); 10124 return res; 10125 } 10126 10127 final void serviceError() { 10128 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 10129 handleServiceError(); 10130 handleReturnCode(); 10131 } 10132 10133 abstract void handleStartCopy() throws RemoteException; 10134 abstract void handleServiceError(); 10135 abstract void handleReturnCode(); 10136 } 10137 10138 class MeasureParams extends HandlerParams { 10139 private final PackageStats mStats; 10140 private boolean mSuccess; 10141 10142 private final IPackageStatsObserver mObserver; 10143 10144 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 10145 super(new UserHandle(stats.userHandle)); 10146 mObserver = observer; 10147 mStats = stats; 10148 } 10149 10150 @Override 10151 public String toString() { 10152 return "MeasureParams{" 10153 + Integer.toHexString(System.identityHashCode(this)) 10154 + " " + mStats.packageName + "}"; 10155 } 10156 10157 @Override 10158 void handleStartCopy() throws RemoteException { 10159 synchronized (mInstallLock) { 10160 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 10161 } 10162 10163 if (mSuccess) { 10164 final boolean mounted; 10165 if (Environment.isExternalStorageEmulated()) { 10166 mounted = true; 10167 } else { 10168 final String status = Environment.getExternalStorageState(); 10169 mounted = (Environment.MEDIA_MOUNTED.equals(status) 10170 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 10171 } 10172 10173 if (mounted) { 10174 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 10175 10176 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 10177 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 10178 10179 mStats.externalDataSize = calculateDirectorySize(mContainerService, 10180 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 10181 10182 // Always subtract cache size, since it's a subdirectory 10183 mStats.externalDataSize -= mStats.externalCacheSize; 10184 10185 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 10186 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 10187 10188 mStats.externalObbSize = calculateDirectorySize(mContainerService, 10189 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 10190 } 10191 } 10192 } 10193 10194 @Override 10195 void handleReturnCode() { 10196 if (mObserver != null) { 10197 try { 10198 mObserver.onGetStatsCompleted(mStats, mSuccess); 10199 } catch (RemoteException e) { 10200 Slog.i(TAG, "Observer no longer exists."); 10201 } 10202 } 10203 } 10204 10205 @Override 10206 void handleServiceError() { 10207 Slog.e(TAG, "Could not measure application " + mStats.packageName 10208 + " external storage"); 10209 } 10210 } 10211 10212 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 10213 throws RemoteException { 10214 long result = 0; 10215 for (File path : paths) { 10216 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 10217 } 10218 return result; 10219 } 10220 10221 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 10222 for (File path : paths) { 10223 try { 10224 mcs.clearDirectory(path.getAbsolutePath()); 10225 } catch (RemoteException e) { 10226 } 10227 } 10228 } 10229 10230 static class OriginInfo { 10231 /** 10232 * Location where install is coming from, before it has been 10233 * copied/renamed into place. This could be a single monolithic APK 10234 * file, or a cluster directory. This location may be untrusted. 10235 */ 10236 final File file; 10237 final String cid; 10238 10239 /** 10240 * Flag indicating that {@link #file} or {@link #cid} has already been 10241 * staged, meaning downstream users don't need to defensively copy the 10242 * contents. 10243 */ 10244 final boolean staged; 10245 10246 /** 10247 * Flag indicating that {@link #file} or {@link #cid} is an already 10248 * installed app that is being moved. 10249 */ 10250 final boolean existing; 10251 10252 final String resolvedPath; 10253 final File resolvedFile; 10254 10255 static OriginInfo fromNothing() { 10256 return new OriginInfo(null, null, false, false); 10257 } 10258 10259 static OriginInfo fromUntrustedFile(File file) { 10260 return new OriginInfo(file, null, false, false); 10261 } 10262 10263 static OriginInfo fromExistingFile(File file) { 10264 return new OriginInfo(file, null, false, true); 10265 } 10266 10267 static OriginInfo fromStagedFile(File file) { 10268 return new OriginInfo(file, null, true, false); 10269 } 10270 10271 static OriginInfo fromStagedContainer(String cid) { 10272 return new OriginInfo(null, cid, true, false); 10273 } 10274 10275 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 10276 this.file = file; 10277 this.cid = cid; 10278 this.staged = staged; 10279 this.existing = existing; 10280 10281 if (cid != null) { 10282 resolvedPath = PackageHelper.getSdDir(cid); 10283 resolvedFile = new File(resolvedPath); 10284 } else if (file != null) { 10285 resolvedPath = file.getAbsolutePath(); 10286 resolvedFile = file; 10287 } else { 10288 resolvedPath = null; 10289 resolvedFile = null; 10290 } 10291 } 10292 } 10293 10294 class MoveInfo { 10295 final int moveId; 10296 final String fromUuid; 10297 final String toUuid; 10298 final String packageName; 10299 final String dataAppName; 10300 final int appId; 10301 final String seinfo; 10302 10303 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 10304 String dataAppName, int appId, String seinfo) { 10305 this.moveId = moveId; 10306 this.fromUuid = fromUuid; 10307 this.toUuid = toUuid; 10308 this.packageName = packageName; 10309 this.dataAppName = dataAppName; 10310 this.appId = appId; 10311 this.seinfo = seinfo; 10312 } 10313 } 10314 10315 class InstallParams extends HandlerParams { 10316 final OriginInfo origin; 10317 final MoveInfo move; 10318 final IPackageInstallObserver2 observer; 10319 int installFlags; 10320 final String installerPackageName; 10321 final String volumeUuid; 10322 final VerificationParams verificationParams; 10323 private InstallArgs mArgs; 10324 private int mRet; 10325 final String packageAbiOverride; 10326 10327 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10328 int installFlags, String installerPackageName, String volumeUuid, 10329 VerificationParams verificationParams, UserHandle user, String packageAbiOverride) { 10330 super(user); 10331 this.origin = origin; 10332 this.move = move; 10333 this.observer = observer; 10334 this.installFlags = installFlags; 10335 this.installerPackageName = installerPackageName; 10336 this.volumeUuid = volumeUuid; 10337 this.verificationParams = verificationParams; 10338 this.packageAbiOverride = packageAbiOverride; 10339 } 10340 10341 @Override 10342 public String toString() { 10343 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 10344 + " file=" + origin.file + " cid=" + origin.cid + "}"; 10345 } 10346 10347 public ManifestDigest getManifestDigest() { 10348 if (verificationParams == null) { 10349 return null; 10350 } 10351 return verificationParams.getManifestDigest(); 10352 } 10353 10354 private int installLocationPolicy(PackageInfoLite pkgLite) { 10355 String packageName = pkgLite.packageName; 10356 int installLocation = pkgLite.installLocation; 10357 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10358 // reader 10359 synchronized (mPackages) { 10360 PackageParser.Package pkg = mPackages.get(packageName); 10361 if (pkg != null) { 10362 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10363 // Check for downgrading. 10364 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 10365 try { 10366 checkDowngrade(pkg, pkgLite); 10367 } catch (PackageManagerException e) { 10368 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 10369 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 10370 } 10371 } 10372 // Check for updated system application. 10373 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10374 if (onSd) { 10375 Slog.w(TAG, "Cannot install update to system app on sdcard"); 10376 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 10377 } 10378 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10379 } else { 10380 if (onSd) { 10381 // Install flag overrides everything. 10382 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10383 } 10384 // If current upgrade specifies particular preference 10385 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 10386 // Application explicitly specified internal. 10387 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10388 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 10389 // App explictly prefers external. Let policy decide 10390 } else { 10391 // Prefer previous location 10392 if (isExternal(pkg)) { 10393 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10394 } 10395 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10396 } 10397 } 10398 } else { 10399 // Invalid install. Return error code 10400 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 10401 } 10402 } 10403 } 10404 // All the special cases have been taken care of. 10405 // Return result based on recommended install location. 10406 if (onSd) { 10407 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10408 } 10409 return pkgLite.recommendedInstallLocation; 10410 } 10411 10412 /* 10413 * Invoke remote method to get package information and install 10414 * location values. Override install location based on default 10415 * policy if needed and then create install arguments based 10416 * on the install location. 10417 */ 10418 public void handleStartCopy() throws RemoteException { 10419 int ret = PackageManager.INSTALL_SUCCEEDED; 10420 10421 // If we're already staged, we've firmly committed to an install location 10422 if (origin.staged) { 10423 if (origin.file != null) { 10424 installFlags |= PackageManager.INSTALL_INTERNAL; 10425 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10426 } else if (origin.cid != null) { 10427 installFlags |= PackageManager.INSTALL_EXTERNAL; 10428 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10429 } else { 10430 throw new IllegalStateException("Invalid stage location"); 10431 } 10432 } 10433 10434 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10435 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 10436 10437 PackageInfoLite pkgLite = null; 10438 10439 if (onInt && onSd) { 10440 // Check if both bits are set. 10441 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 10442 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10443 } else { 10444 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 10445 packageAbiOverride); 10446 10447 /* 10448 * If we have too little free space, try to free cache 10449 * before giving up. 10450 */ 10451 if (!origin.staged && pkgLite.recommendedInstallLocation 10452 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10453 // TODO: focus freeing disk space on the target device 10454 final StorageManager storage = StorageManager.from(mContext); 10455 final long lowThreshold = storage.getStorageLowBytes( 10456 Environment.getDataDirectory()); 10457 10458 final long sizeBytes = mContainerService.calculateInstalledSize( 10459 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 10460 10461 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 10462 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 10463 installFlags, packageAbiOverride); 10464 } 10465 10466 /* 10467 * The cache free must have deleted the file we 10468 * downloaded to install. 10469 * 10470 * TODO: fix the "freeCache" call to not delete 10471 * the file we care about. 10472 */ 10473 if (pkgLite.recommendedInstallLocation 10474 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10475 pkgLite.recommendedInstallLocation 10476 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 10477 } 10478 } 10479 } 10480 10481 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10482 int loc = pkgLite.recommendedInstallLocation; 10483 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 10484 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10485 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 10486 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 10487 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10488 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10489 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 10490 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 10491 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10492 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 10493 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 10494 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 10495 } else { 10496 // Override with defaults if needed. 10497 loc = installLocationPolicy(pkgLite); 10498 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 10499 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 10500 } else if (!onSd && !onInt) { 10501 // Override install location with flags 10502 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 10503 // Set the flag to install on external media. 10504 installFlags |= PackageManager.INSTALL_EXTERNAL; 10505 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10506 } else { 10507 // Make sure the flag for installing on external 10508 // media is unset 10509 installFlags |= PackageManager.INSTALL_INTERNAL; 10510 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10511 } 10512 } 10513 } 10514 } 10515 10516 final InstallArgs args = createInstallArgs(this); 10517 mArgs = args; 10518 10519 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10520 /* 10521 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 10522 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 10523 */ 10524 int userIdentifier = getUser().getIdentifier(); 10525 if (userIdentifier == UserHandle.USER_ALL 10526 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 10527 userIdentifier = UserHandle.USER_OWNER; 10528 } 10529 10530 /* 10531 * Determine if we have any installed package verifiers. If we 10532 * do, then we'll defer to them to verify the packages. 10533 */ 10534 final int requiredUid = mRequiredVerifierPackage == null ? -1 10535 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 10536 if (!origin.existing && requiredUid != -1 10537 && isVerificationEnabled(userIdentifier, installFlags)) { 10538 final Intent verification = new Intent( 10539 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 10540 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 10541 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 10542 PACKAGE_MIME_TYPE); 10543 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10544 10545 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 10546 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 10547 0 /* TODO: Which userId? */); 10548 10549 if (DEBUG_VERIFY) { 10550 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 10551 + verification.toString() + " with " + pkgLite.verifiers.length 10552 + " optional verifiers"); 10553 } 10554 10555 final int verificationId = mPendingVerificationToken++; 10556 10557 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10558 10559 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 10560 installerPackageName); 10561 10562 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 10563 installFlags); 10564 10565 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 10566 pkgLite.packageName); 10567 10568 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 10569 pkgLite.versionCode); 10570 10571 if (verificationParams != null) { 10572 if (verificationParams.getVerificationURI() != null) { 10573 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 10574 verificationParams.getVerificationURI()); 10575 } 10576 if (verificationParams.getOriginatingURI() != null) { 10577 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 10578 verificationParams.getOriginatingURI()); 10579 } 10580 if (verificationParams.getReferrer() != null) { 10581 verification.putExtra(Intent.EXTRA_REFERRER, 10582 verificationParams.getReferrer()); 10583 } 10584 if (verificationParams.getOriginatingUid() >= 0) { 10585 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 10586 verificationParams.getOriginatingUid()); 10587 } 10588 if (verificationParams.getInstallerUid() >= 0) { 10589 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 10590 verificationParams.getInstallerUid()); 10591 } 10592 } 10593 10594 final PackageVerificationState verificationState = new PackageVerificationState( 10595 requiredUid, args); 10596 10597 mPendingVerification.append(verificationId, verificationState); 10598 10599 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 10600 receivers, verificationState); 10601 10602 /* 10603 * If any sufficient verifiers were listed in the package 10604 * manifest, attempt to ask them. 10605 */ 10606 if (sufficientVerifiers != null) { 10607 final int N = sufficientVerifiers.size(); 10608 if (N == 0) { 10609 Slog.i(TAG, "Additional verifiers required, but none installed."); 10610 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 10611 } else { 10612 for (int i = 0; i < N; i++) { 10613 final ComponentName verifierComponent = sufficientVerifiers.get(i); 10614 10615 final Intent sufficientIntent = new Intent(verification); 10616 sufficientIntent.setComponent(verifierComponent); 10617 10618 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 10619 } 10620 } 10621 } 10622 10623 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 10624 mRequiredVerifierPackage, receivers); 10625 if (ret == PackageManager.INSTALL_SUCCEEDED 10626 && mRequiredVerifierPackage != null) { 10627 /* 10628 * Send the intent to the required verification agent, 10629 * but only start the verification timeout after the 10630 * target BroadcastReceivers have run. 10631 */ 10632 verification.setComponent(requiredVerifierComponent); 10633 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 10634 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10635 new BroadcastReceiver() { 10636 @Override 10637 public void onReceive(Context context, Intent intent) { 10638 final Message msg = mHandler 10639 .obtainMessage(CHECK_PENDING_VERIFICATION); 10640 msg.arg1 = verificationId; 10641 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 10642 } 10643 }, null, 0, null, null); 10644 10645 /* 10646 * We don't want the copy to proceed until verification 10647 * succeeds, so null out this field. 10648 */ 10649 mArgs = null; 10650 } 10651 } else { 10652 /* 10653 * No package verification is enabled, so immediately start 10654 * the remote call to initiate copy using temporary file. 10655 */ 10656 ret = args.copyApk(mContainerService, true); 10657 } 10658 } 10659 10660 mRet = ret; 10661 } 10662 10663 @Override 10664 void handleReturnCode() { 10665 // If mArgs is null, then MCS couldn't be reached. When it 10666 // reconnects, it will try again to install. At that point, this 10667 // will succeed. 10668 if (mArgs != null) { 10669 processPendingInstall(mArgs, mRet); 10670 } 10671 } 10672 10673 @Override 10674 void handleServiceError() { 10675 mArgs = createInstallArgs(this); 10676 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10677 } 10678 10679 public boolean isForwardLocked() { 10680 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10681 } 10682 } 10683 10684 /** 10685 * Used during creation of InstallArgs 10686 * 10687 * @param installFlags package installation flags 10688 * @return true if should be installed on external storage 10689 */ 10690 private static boolean installOnExternalAsec(int installFlags) { 10691 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 10692 return false; 10693 } 10694 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 10695 return true; 10696 } 10697 return false; 10698 } 10699 10700 /** 10701 * Used during creation of InstallArgs 10702 * 10703 * @param installFlags package installation flags 10704 * @return true if should be installed as forward locked 10705 */ 10706 private static boolean installForwardLocked(int installFlags) { 10707 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10708 } 10709 10710 private InstallArgs createInstallArgs(InstallParams params) { 10711 if (params.move != null) { 10712 return new MoveInstallArgs(params); 10713 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 10714 return new AsecInstallArgs(params); 10715 } else { 10716 return new FileInstallArgs(params); 10717 } 10718 } 10719 10720 /** 10721 * Create args that describe an existing installed package. Typically used 10722 * when cleaning up old installs, or used as a move source. 10723 */ 10724 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 10725 String resourcePath, String[] instructionSets) { 10726 final boolean isInAsec; 10727 if (installOnExternalAsec(installFlags)) { 10728 /* Apps on SD card are always in ASEC containers. */ 10729 isInAsec = true; 10730 } else if (installForwardLocked(installFlags) 10731 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 10732 /* 10733 * Forward-locked apps are only in ASEC containers if they're the 10734 * new style 10735 */ 10736 isInAsec = true; 10737 } else { 10738 isInAsec = false; 10739 } 10740 10741 if (isInAsec) { 10742 return new AsecInstallArgs(codePath, instructionSets, 10743 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 10744 } else { 10745 return new FileInstallArgs(codePath, resourcePath, instructionSets); 10746 } 10747 } 10748 10749 static abstract class InstallArgs { 10750 /** @see InstallParams#origin */ 10751 final OriginInfo origin; 10752 /** @see InstallParams#move */ 10753 final MoveInfo move; 10754 10755 final IPackageInstallObserver2 observer; 10756 // Always refers to PackageManager flags only 10757 final int installFlags; 10758 final String installerPackageName; 10759 final String volumeUuid; 10760 final ManifestDigest manifestDigest; 10761 final UserHandle user; 10762 final String abiOverride; 10763 10764 // The list of instruction sets supported by this app. This is currently 10765 // only used during the rmdex() phase to clean up resources. We can get rid of this 10766 // if we move dex files under the common app path. 10767 /* nullable */ String[] instructionSets; 10768 10769 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10770 int installFlags, String installerPackageName, String volumeUuid, 10771 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 10772 String abiOverride) { 10773 this.origin = origin; 10774 this.move = move; 10775 this.installFlags = installFlags; 10776 this.observer = observer; 10777 this.installerPackageName = installerPackageName; 10778 this.volumeUuid = volumeUuid; 10779 this.manifestDigest = manifestDigest; 10780 this.user = user; 10781 this.instructionSets = instructionSets; 10782 this.abiOverride = abiOverride; 10783 } 10784 10785 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 10786 abstract int doPreInstall(int status); 10787 10788 /** 10789 * Rename package into final resting place. All paths on the given 10790 * scanned package should be updated to reflect the rename. 10791 */ 10792 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 10793 abstract int doPostInstall(int status, int uid); 10794 10795 /** @see PackageSettingBase#codePathString */ 10796 abstract String getCodePath(); 10797 /** @see PackageSettingBase#resourcePathString */ 10798 abstract String getResourcePath(); 10799 10800 // Need installer lock especially for dex file removal. 10801 abstract void cleanUpResourcesLI(); 10802 abstract boolean doPostDeleteLI(boolean delete); 10803 10804 /** 10805 * Called before the source arguments are copied. This is used mostly 10806 * for MoveParams when it needs to read the source file to put it in the 10807 * destination. 10808 */ 10809 int doPreCopy() { 10810 return PackageManager.INSTALL_SUCCEEDED; 10811 } 10812 10813 /** 10814 * Called after the source arguments are copied. This is used mostly for 10815 * MoveParams when it needs to read the source file to put it in the 10816 * destination. 10817 * 10818 * @return 10819 */ 10820 int doPostCopy(int uid) { 10821 return PackageManager.INSTALL_SUCCEEDED; 10822 } 10823 10824 protected boolean isFwdLocked() { 10825 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10826 } 10827 10828 protected boolean isExternalAsec() { 10829 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10830 } 10831 10832 UserHandle getUser() { 10833 return user; 10834 } 10835 } 10836 10837 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 10838 if (!allCodePaths.isEmpty()) { 10839 if (instructionSets == null) { 10840 throw new IllegalStateException("instructionSet == null"); 10841 } 10842 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 10843 for (String codePath : allCodePaths) { 10844 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 10845 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 10846 if (retCode < 0) { 10847 Slog.w(TAG, "Couldn't remove dex file for package: " 10848 + " at location " + codePath + ", retcode=" + retCode); 10849 // we don't consider this to be a failure of the core package deletion 10850 } 10851 } 10852 } 10853 } 10854 } 10855 10856 /** 10857 * Logic to handle installation of non-ASEC applications, including copying 10858 * and renaming logic. 10859 */ 10860 class FileInstallArgs extends InstallArgs { 10861 private File codeFile; 10862 private File resourceFile; 10863 10864 // Example topology: 10865 // /data/app/com.example/base.apk 10866 // /data/app/com.example/split_foo.apk 10867 // /data/app/com.example/lib/arm/libfoo.so 10868 // /data/app/com.example/lib/arm64/libfoo.so 10869 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 10870 10871 /** New install */ 10872 FileInstallArgs(InstallParams params) { 10873 super(params.origin, params.move, params.observer, params.installFlags, 10874 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10875 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10876 if (isFwdLocked()) { 10877 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 10878 } 10879 } 10880 10881 /** Existing install */ 10882 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 10883 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 10884 null); 10885 this.codeFile = (codePath != null) ? new File(codePath) : null; 10886 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 10887 } 10888 10889 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10890 if (origin.staged) { 10891 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 10892 codeFile = origin.file; 10893 resourceFile = origin.file; 10894 return PackageManager.INSTALL_SUCCEEDED; 10895 } 10896 10897 try { 10898 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 10899 codeFile = tempDir; 10900 resourceFile = tempDir; 10901 } catch (IOException e) { 10902 Slog.w(TAG, "Failed to create copy file: " + e); 10903 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10904 } 10905 10906 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 10907 @Override 10908 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 10909 if (!FileUtils.isValidExtFilename(name)) { 10910 throw new IllegalArgumentException("Invalid filename: " + name); 10911 } 10912 try { 10913 final File file = new File(codeFile, name); 10914 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 10915 O_RDWR | O_CREAT, 0644); 10916 Os.chmod(file.getAbsolutePath(), 0644); 10917 return new ParcelFileDescriptor(fd); 10918 } catch (ErrnoException e) { 10919 throw new RemoteException("Failed to open: " + e.getMessage()); 10920 } 10921 } 10922 }; 10923 10924 int ret = PackageManager.INSTALL_SUCCEEDED; 10925 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 10926 if (ret != PackageManager.INSTALL_SUCCEEDED) { 10927 Slog.e(TAG, "Failed to copy package"); 10928 return ret; 10929 } 10930 10931 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 10932 NativeLibraryHelper.Handle handle = null; 10933 try { 10934 handle = NativeLibraryHelper.Handle.create(codeFile); 10935 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 10936 abiOverride); 10937 } catch (IOException e) { 10938 Slog.e(TAG, "Copying native libraries failed", e); 10939 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10940 } finally { 10941 IoUtils.closeQuietly(handle); 10942 } 10943 10944 return ret; 10945 } 10946 10947 int doPreInstall(int status) { 10948 if (status != PackageManager.INSTALL_SUCCEEDED) { 10949 cleanUp(); 10950 } 10951 return status; 10952 } 10953 10954 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10955 if (status != PackageManager.INSTALL_SUCCEEDED) { 10956 cleanUp(); 10957 return false; 10958 } 10959 10960 final File targetDir = codeFile.getParentFile(); 10961 final File beforeCodeFile = codeFile; 10962 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 10963 10964 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 10965 try { 10966 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 10967 } catch (ErrnoException e) { 10968 Slog.w(TAG, "Failed to rename", e); 10969 return false; 10970 } 10971 10972 if (!SELinux.restoreconRecursive(afterCodeFile)) { 10973 Slog.w(TAG, "Failed to restorecon"); 10974 return false; 10975 } 10976 10977 // Reflect the rename internally 10978 codeFile = afterCodeFile; 10979 resourceFile = afterCodeFile; 10980 10981 // Reflect the rename in scanned details 10982 pkg.codePath = afterCodeFile.getAbsolutePath(); 10983 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10984 pkg.baseCodePath); 10985 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10986 pkg.splitCodePaths); 10987 10988 // Reflect the rename in app info 10989 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10990 pkg.applicationInfo.setCodePath(pkg.codePath); 10991 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10992 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10993 pkg.applicationInfo.setResourcePath(pkg.codePath); 10994 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10995 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10996 10997 return true; 10998 } 10999 11000 int doPostInstall(int status, int uid) { 11001 if (status != PackageManager.INSTALL_SUCCEEDED) { 11002 cleanUp(); 11003 } 11004 return status; 11005 } 11006 11007 @Override 11008 String getCodePath() { 11009 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11010 } 11011 11012 @Override 11013 String getResourcePath() { 11014 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11015 } 11016 11017 private boolean cleanUp() { 11018 if (codeFile == null || !codeFile.exists()) { 11019 return false; 11020 } 11021 11022 if (codeFile.isDirectory()) { 11023 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11024 } else { 11025 codeFile.delete(); 11026 } 11027 11028 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 11029 resourceFile.delete(); 11030 } 11031 11032 return true; 11033 } 11034 11035 void cleanUpResourcesLI() { 11036 // Try enumerating all code paths before deleting 11037 List<String> allCodePaths = Collections.EMPTY_LIST; 11038 if (codeFile != null && codeFile.exists()) { 11039 try { 11040 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11041 allCodePaths = pkg.getAllCodePaths(); 11042 } catch (PackageParserException e) { 11043 // Ignored; we tried our best 11044 } 11045 } 11046 11047 cleanUp(); 11048 removeDexFiles(allCodePaths, instructionSets); 11049 } 11050 11051 boolean doPostDeleteLI(boolean delete) { 11052 // XXX err, shouldn't we respect the delete flag? 11053 cleanUpResourcesLI(); 11054 return true; 11055 } 11056 } 11057 11058 private boolean isAsecExternal(String cid) { 11059 final String asecPath = PackageHelper.getSdFilesystem(cid); 11060 return !asecPath.startsWith(mAsecInternalPath); 11061 } 11062 11063 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 11064 PackageManagerException { 11065 if (copyRet < 0) { 11066 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 11067 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 11068 throw new PackageManagerException(copyRet, message); 11069 } 11070 } 11071 } 11072 11073 /** 11074 * Extract the MountService "container ID" from the full code path of an 11075 * .apk. 11076 */ 11077 static String cidFromCodePath(String fullCodePath) { 11078 int eidx = fullCodePath.lastIndexOf("/"); 11079 String subStr1 = fullCodePath.substring(0, eidx); 11080 int sidx = subStr1.lastIndexOf("/"); 11081 return subStr1.substring(sidx+1, eidx); 11082 } 11083 11084 /** 11085 * Logic to handle installation of ASEC applications, including copying and 11086 * renaming logic. 11087 */ 11088 class AsecInstallArgs extends InstallArgs { 11089 static final String RES_FILE_NAME = "pkg.apk"; 11090 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 11091 11092 String cid; 11093 String packagePath; 11094 String resourcePath; 11095 11096 /** New install */ 11097 AsecInstallArgs(InstallParams params) { 11098 super(params.origin, params.move, params.observer, params.installFlags, 11099 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11100 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 11101 } 11102 11103 /** Existing install */ 11104 AsecInstallArgs(String fullCodePath, String[] instructionSets, 11105 boolean isExternal, boolean isForwardLocked) { 11106 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 11107 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11108 instructionSets, null); 11109 // Hackily pretend we're still looking at a full code path 11110 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 11111 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 11112 } 11113 11114 // Extract cid from fullCodePath 11115 int eidx = fullCodePath.lastIndexOf("/"); 11116 String subStr1 = fullCodePath.substring(0, eidx); 11117 int sidx = subStr1.lastIndexOf("/"); 11118 cid = subStr1.substring(sidx+1, eidx); 11119 setMountPath(subStr1); 11120 } 11121 11122 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 11123 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 11124 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11125 instructionSets, null); 11126 this.cid = cid; 11127 setMountPath(PackageHelper.getSdDir(cid)); 11128 } 11129 11130 void createCopyFile() { 11131 cid = mInstallerService.allocateExternalStageCidLegacy(); 11132 } 11133 11134 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11135 if (origin.staged) { 11136 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 11137 cid = origin.cid; 11138 setMountPath(PackageHelper.getSdDir(cid)); 11139 return PackageManager.INSTALL_SUCCEEDED; 11140 } 11141 11142 if (temp) { 11143 createCopyFile(); 11144 } else { 11145 /* 11146 * Pre-emptively destroy the container since it's destroyed if 11147 * copying fails due to it existing anyway. 11148 */ 11149 PackageHelper.destroySdDir(cid); 11150 } 11151 11152 final String newMountPath = imcs.copyPackageToContainer( 11153 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 11154 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 11155 11156 if (newMountPath != null) { 11157 setMountPath(newMountPath); 11158 return PackageManager.INSTALL_SUCCEEDED; 11159 } else { 11160 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11161 } 11162 } 11163 11164 @Override 11165 String getCodePath() { 11166 return packagePath; 11167 } 11168 11169 @Override 11170 String getResourcePath() { 11171 return resourcePath; 11172 } 11173 11174 int doPreInstall(int status) { 11175 if (status != PackageManager.INSTALL_SUCCEEDED) { 11176 // Destroy container 11177 PackageHelper.destroySdDir(cid); 11178 } else { 11179 boolean mounted = PackageHelper.isContainerMounted(cid); 11180 if (!mounted) { 11181 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 11182 Process.SYSTEM_UID); 11183 if (newMountPath != null) { 11184 setMountPath(newMountPath); 11185 } else { 11186 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11187 } 11188 } 11189 } 11190 return status; 11191 } 11192 11193 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11194 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 11195 String newMountPath = null; 11196 if (PackageHelper.isContainerMounted(cid)) { 11197 // Unmount the container 11198 if (!PackageHelper.unMountSdDir(cid)) { 11199 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 11200 return false; 11201 } 11202 } 11203 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11204 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 11205 " which might be stale. Will try to clean up."); 11206 // Clean up the stale container and proceed to recreate. 11207 if (!PackageHelper.destroySdDir(newCacheId)) { 11208 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 11209 return false; 11210 } 11211 // Successfully cleaned up stale container. Try to rename again. 11212 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11213 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 11214 + " inspite of cleaning it up."); 11215 return false; 11216 } 11217 } 11218 if (!PackageHelper.isContainerMounted(newCacheId)) { 11219 Slog.w(TAG, "Mounting container " + newCacheId); 11220 newMountPath = PackageHelper.mountSdDir(newCacheId, 11221 getEncryptKey(), Process.SYSTEM_UID); 11222 } else { 11223 newMountPath = PackageHelper.getSdDir(newCacheId); 11224 } 11225 if (newMountPath == null) { 11226 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 11227 return false; 11228 } 11229 Log.i(TAG, "Succesfully renamed " + cid + 11230 " to " + newCacheId + 11231 " at new path: " + newMountPath); 11232 cid = newCacheId; 11233 11234 final File beforeCodeFile = new File(packagePath); 11235 setMountPath(newMountPath); 11236 final File afterCodeFile = new File(packagePath); 11237 11238 // Reflect the rename in scanned details 11239 pkg.codePath = afterCodeFile.getAbsolutePath(); 11240 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11241 pkg.baseCodePath); 11242 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11243 pkg.splitCodePaths); 11244 11245 // Reflect the rename in app info 11246 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11247 pkg.applicationInfo.setCodePath(pkg.codePath); 11248 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11249 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11250 pkg.applicationInfo.setResourcePath(pkg.codePath); 11251 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11252 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11253 11254 return true; 11255 } 11256 11257 private void setMountPath(String mountPath) { 11258 final File mountFile = new File(mountPath); 11259 11260 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 11261 if (monolithicFile.exists()) { 11262 packagePath = monolithicFile.getAbsolutePath(); 11263 if (isFwdLocked()) { 11264 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 11265 } else { 11266 resourcePath = packagePath; 11267 } 11268 } else { 11269 packagePath = mountFile.getAbsolutePath(); 11270 resourcePath = packagePath; 11271 } 11272 } 11273 11274 int doPostInstall(int status, int uid) { 11275 if (status != PackageManager.INSTALL_SUCCEEDED) { 11276 cleanUp(); 11277 } else { 11278 final int groupOwner; 11279 final String protectedFile; 11280 if (isFwdLocked()) { 11281 groupOwner = UserHandle.getSharedAppGid(uid); 11282 protectedFile = RES_FILE_NAME; 11283 } else { 11284 groupOwner = -1; 11285 protectedFile = null; 11286 } 11287 11288 if (uid < Process.FIRST_APPLICATION_UID 11289 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 11290 Slog.e(TAG, "Failed to finalize " + cid); 11291 PackageHelper.destroySdDir(cid); 11292 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11293 } 11294 11295 boolean mounted = PackageHelper.isContainerMounted(cid); 11296 if (!mounted) { 11297 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 11298 } 11299 } 11300 return status; 11301 } 11302 11303 private void cleanUp() { 11304 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 11305 11306 // Destroy secure container 11307 PackageHelper.destroySdDir(cid); 11308 } 11309 11310 private List<String> getAllCodePaths() { 11311 final File codeFile = new File(getCodePath()); 11312 if (codeFile != null && codeFile.exists()) { 11313 try { 11314 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11315 return pkg.getAllCodePaths(); 11316 } catch (PackageParserException e) { 11317 // Ignored; we tried our best 11318 } 11319 } 11320 return Collections.EMPTY_LIST; 11321 } 11322 11323 void cleanUpResourcesLI() { 11324 // Enumerate all code paths before deleting 11325 cleanUpResourcesLI(getAllCodePaths()); 11326 } 11327 11328 private void cleanUpResourcesLI(List<String> allCodePaths) { 11329 cleanUp(); 11330 removeDexFiles(allCodePaths, instructionSets); 11331 } 11332 11333 String getPackageName() { 11334 return getAsecPackageName(cid); 11335 } 11336 11337 boolean doPostDeleteLI(boolean delete) { 11338 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 11339 final List<String> allCodePaths = getAllCodePaths(); 11340 boolean mounted = PackageHelper.isContainerMounted(cid); 11341 if (mounted) { 11342 // Unmount first 11343 if (PackageHelper.unMountSdDir(cid)) { 11344 mounted = false; 11345 } 11346 } 11347 if (!mounted && delete) { 11348 cleanUpResourcesLI(allCodePaths); 11349 } 11350 return !mounted; 11351 } 11352 11353 @Override 11354 int doPreCopy() { 11355 if (isFwdLocked()) { 11356 if (!PackageHelper.fixSdPermissions(cid, 11357 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 11358 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11359 } 11360 } 11361 11362 return PackageManager.INSTALL_SUCCEEDED; 11363 } 11364 11365 @Override 11366 int doPostCopy(int uid) { 11367 if (isFwdLocked()) { 11368 if (uid < Process.FIRST_APPLICATION_UID 11369 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 11370 RES_FILE_NAME)) { 11371 Slog.e(TAG, "Failed to finalize " + cid); 11372 PackageHelper.destroySdDir(cid); 11373 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11374 } 11375 } 11376 11377 return PackageManager.INSTALL_SUCCEEDED; 11378 } 11379 } 11380 11381 /** 11382 * Logic to handle movement of existing installed applications. 11383 */ 11384 class MoveInstallArgs extends InstallArgs { 11385 private File codeFile; 11386 private File resourceFile; 11387 11388 /** New install */ 11389 MoveInstallArgs(InstallParams params) { 11390 super(params.origin, params.move, params.observer, params.installFlags, 11391 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11392 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 11393 } 11394 11395 int copyApk(IMediaContainerService imcs, boolean temp) { 11396 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 11397 + move.fromUuid + " to " + move.toUuid); 11398 synchronized (mInstaller) { 11399 if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName, 11400 move.dataAppName, move.appId, move.seinfo) != 0) { 11401 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11402 } 11403 } 11404 11405 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 11406 resourceFile = codeFile; 11407 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 11408 11409 return PackageManager.INSTALL_SUCCEEDED; 11410 } 11411 11412 int doPreInstall(int status) { 11413 if (status != PackageManager.INSTALL_SUCCEEDED) { 11414 cleanUp(move.toUuid); 11415 } 11416 return status; 11417 } 11418 11419 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11420 if (status != PackageManager.INSTALL_SUCCEEDED) { 11421 cleanUp(move.toUuid); 11422 return false; 11423 } 11424 11425 // Reflect the move in app info 11426 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11427 pkg.applicationInfo.setCodePath(pkg.codePath); 11428 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11429 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11430 pkg.applicationInfo.setResourcePath(pkg.codePath); 11431 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11432 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11433 11434 return true; 11435 } 11436 11437 int doPostInstall(int status, int uid) { 11438 if (status == PackageManager.INSTALL_SUCCEEDED) { 11439 cleanUp(move.fromUuid); 11440 } else { 11441 cleanUp(move.toUuid); 11442 } 11443 return status; 11444 } 11445 11446 @Override 11447 String getCodePath() { 11448 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11449 } 11450 11451 @Override 11452 String getResourcePath() { 11453 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11454 } 11455 11456 private boolean cleanUp(String volumeUuid) { 11457 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 11458 move.dataAppName); 11459 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 11460 synchronized (mInstallLock) { 11461 // Clean up both app data and code 11462 removeDataDirsLI(volumeUuid, move.packageName); 11463 if (codeFile.isDirectory()) { 11464 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11465 } else { 11466 codeFile.delete(); 11467 } 11468 } 11469 return true; 11470 } 11471 11472 void cleanUpResourcesLI() { 11473 throw new UnsupportedOperationException(); 11474 } 11475 11476 boolean doPostDeleteLI(boolean delete) { 11477 throw new UnsupportedOperationException(); 11478 } 11479 } 11480 11481 static String getAsecPackageName(String packageCid) { 11482 int idx = packageCid.lastIndexOf("-"); 11483 if (idx == -1) { 11484 return packageCid; 11485 } 11486 return packageCid.substring(0, idx); 11487 } 11488 11489 // Utility method used to create code paths based on package name and available index. 11490 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 11491 String idxStr = ""; 11492 int idx = 1; 11493 // Fall back to default value of idx=1 if prefix is not 11494 // part of oldCodePath 11495 if (oldCodePath != null) { 11496 String subStr = oldCodePath; 11497 // Drop the suffix right away 11498 if (suffix != null && subStr.endsWith(suffix)) { 11499 subStr = subStr.substring(0, subStr.length() - suffix.length()); 11500 } 11501 // If oldCodePath already contains prefix find out the 11502 // ending index to either increment or decrement. 11503 int sidx = subStr.lastIndexOf(prefix); 11504 if (sidx != -1) { 11505 subStr = subStr.substring(sidx + prefix.length()); 11506 if (subStr != null) { 11507 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 11508 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 11509 } 11510 try { 11511 idx = Integer.parseInt(subStr); 11512 if (idx <= 1) { 11513 idx++; 11514 } else { 11515 idx--; 11516 } 11517 } catch(NumberFormatException e) { 11518 } 11519 } 11520 } 11521 } 11522 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 11523 return prefix + idxStr; 11524 } 11525 11526 private File getNextCodePath(File targetDir, String packageName) { 11527 int suffix = 1; 11528 File result; 11529 do { 11530 result = new File(targetDir, packageName + "-" + suffix); 11531 suffix++; 11532 } while (result.exists()); 11533 return result; 11534 } 11535 11536 // Utility method that returns the relative package path with respect 11537 // to the installation directory. Like say for /data/data/com.test-1.apk 11538 // string com.test-1 is returned. 11539 static String deriveCodePathName(String codePath) { 11540 if (codePath == null) { 11541 return null; 11542 } 11543 final File codeFile = new File(codePath); 11544 final String name = codeFile.getName(); 11545 if (codeFile.isDirectory()) { 11546 return name; 11547 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 11548 final int lastDot = name.lastIndexOf('.'); 11549 return name.substring(0, lastDot); 11550 } else { 11551 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 11552 return null; 11553 } 11554 } 11555 11556 class PackageInstalledInfo { 11557 String name; 11558 int uid; 11559 // The set of users that originally had this package installed. 11560 int[] origUsers; 11561 // The set of users that now have this package installed. 11562 int[] newUsers; 11563 PackageParser.Package pkg; 11564 int returnCode; 11565 String returnMsg; 11566 PackageRemovedInfo removedInfo; 11567 11568 public void setError(int code, String msg) { 11569 returnCode = code; 11570 returnMsg = msg; 11571 Slog.w(TAG, msg); 11572 } 11573 11574 public void setError(String msg, PackageParserException e) { 11575 returnCode = e.error; 11576 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11577 Slog.w(TAG, msg, e); 11578 } 11579 11580 public void setError(String msg, PackageManagerException e) { 11581 returnCode = e.error; 11582 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11583 Slog.w(TAG, msg, e); 11584 } 11585 11586 // In some error cases we want to convey more info back to the observer 11587 String origPackage; 11588 String origPermission; 11589 } 11590 11591 /* 11592 * Install a non-existing package. 11593 */ 11594 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11595 UserHandle user, String installerPackageName, String volumeUuid, 11596 PackageInstalledInfo res) { 11597 // Remember this for later, in case we need to rollback this install 11598 String pkgName = pkg.packageName; 11599 11600 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 11601 final boolean dataDirExists = Environment 11602 .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists(); 11603 synchronized(mPackages) { 11604 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 11605 // A package with the same name is already installed, though 11606 // it has been renamed to an older name. The package we 11607 // are trying to install should be installed as an update to 11608 // the existing one, but that has not been requested, so bail. 11609 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11610 + " without first uninstalling package running as " 11611 + mSettings.mRenamedPackages.get(pkgName)); 11612 return; 11613 } 11614 if (mPackages.containsKey(pkgName)) { 11615 // Don't allow installation over an existing package with the same name. 11616 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11617 + " without first uninstalling."); 11618 return; 11619 } 11620 } 11621 11622 try { 11623 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 11624 System.currentTimeMillis(), user); 11625 11626 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 11627 // delete the partially installed application. the data directory will have to be 11628 // restored if it was already existing 11629 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11630 // remove package from internal structures. Note that we want deletePackageX to 11631 // delete the package data and cache directories that it created in 11632 // scanPackageLocked, unless those directories existed before we even tried to 11633 // install. 11634 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 11635 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 11636 res.removedInfo, true); 11637 } 11638 11639 } catch (PackageManagerException e) { 11640 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11641 } 11642 } 11643 11644 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 11645 // Can't rotate keys during boot or if sharedUser. 11646 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 11647 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 11648 return false; 11649 } 11650 // app is using upgradeKeySets; make sure all are valid 11651 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11652 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 11653 for (int i = 0; i < upgradeKeySets.length; i++) { 11654 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 11655 Slog.wtf(TAG, "Package " 11656 + (oldPs.name != null ? oldPs.name : "<null>") 11657 + " contains upgrade-key-set reference to unknown key-set: " 11658 + upgradeKeySets[i] 11659 + " reverting to signatures check."); 11660 return false; 11661 } 11662 } 11663 return true; 11664 } 11665 11666 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 11667 // Upgrade keysets are being used. Determine if new package has a superset of the 11668 // required keys. 11669 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 11670 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11671 for (int i = 0; i < upgradeKeySets.length; i++) { 11672 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 11673 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 11674 return true; 11675 } 11676 } 11677 return false; 11678 } 11679 11680 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11681 UserHandle user, String installerPackageName, String volumeUuid, 11682 PackageInstalledInfo res) { 11683 final PackageParser.Package oldPackage; 11684 final String pkgName = pkg.packageName; 11685 final int[] allUsers; 11686 final boolean[] perUserInstalled; 11687 final boolean weFroze; 11688 11689 // First find the old package info and check signatures 11690 synchronized(mPackages) { 11691 oldPackage = mPackages.get(pkgName); 11692 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 11693 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11694 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 11695 if(!checkUpgradeKeySetLP(ps, pkg)) { 11696 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11697 "New package not signed by keys specified by upgrade-keysets: " 11698 + pkgName); 11699 return; 11700 } 11701 } else { 11702 // default to original signature matching 11703 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 11704 != PackageManager.SIGNATURE_MATCH) { 11705 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11706 "New package has a different signature: " + pkgName); 11707 return; 11708 } 11709 } 11710 11711 // In case of rollback, remember per-user/profile install state 11712 allUsers = sUserManager.getUserIds(); 11713 perUserInstalled = new boolean[allUsers.length]; 11714 for (int i = 0; i < allUsers.length; i++) { 11715 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11716 } 11717 11718 // Mark the app as frozen to prevent launching during the upgrade 11719 // process, and then kill all running instances 11720 if (!ps.frozen) { 11721 ps.frozen = true; 11722 weFroze = true; 11723 } else { 11724 weFroze = false; 11725 } 11726 } 11727 11728 // Now that we're guarded by frozen state, kill app during upgrade 11729 killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg"); 11730 11731 try { 11732 boolean sysPkg = (isSystemApp(oldPackage)); 11733 if (sysPkg) { 11734 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11735 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11736 } else { 11737 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11738 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11739 } 11740 } finally { 11741 // Regardless of success or failure of upgrade steps above, always 11742 // unfreeze the package if we froze it 11743 if (weFroze) { 11744 unfreezePackage(pkgName); 11745 } 11746 } 11747 } 11748 11749 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 11750 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11751 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11752 String volumeUuid, PackageInstalledInfo res) { 11753 String pkgName = deletedPackage.packageName; 11754 boolean deletedPkg = true; 11755 boolean updatedSettings = false; 11756 11757 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 11758 + deletedPackage); 11759 long origUpdateTime; 11760 if (pkg.mExtras != null) { 11761 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 11762 } else { 11763 origUpdateTime = 0; 11764 } 11765 11766 // First delete the existing package while retaining the data directory 11767 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 11768 res.removedInfo, true)) { 11769 // If the existing package wasn't successfully deleted 11770 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 11771 deletedPkg = false; 11772 } else { 11773 // Successfully deleted the old package; proceed with replace. 11774 11775 // If deleted package lived in a container, give users a chance to 11776 // relinquish resources before killing. 11777 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 11778 if (DEBUG_INSTALL) { 11779 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 11780 } 11781 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 11782 final ArrayList<String> pkgList = new ArrayList<String>(1); 11783 pkgList.add(deletedPackage.applicationInfo.packageName); 11784 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 11785 } 11786 11787 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 11788 try { 11789 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 11790 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 11791 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11792 perUserInstalled, res, user); 11793 updatedSettings = true; 11794 } catch (PackageManagerException e) { 11795 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11796 } 11797 } 11798 11799 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11800 // remove package from internal structures. Note that we want deletePackageX to 11801 // delete the package data and cache directories that it created in 11802 // scanPackageLocked, unless those directories existed before we even tried to 11803 // install. 11804 if(updatedSettings) { 11805 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 11806 deletePackageLI( 11807 pkgName, null, true, allUsers, perUserInstalled, 11808 PackageManager.DELETE_KEEP_DATA, 11809 res.removedInfo, true); 11810 } 11811 // Since we failed to install the new package we need to restore the old 11812 // package that we deleted. 11813 if (deletedPkg) { 11814 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 11815 File restoreFile = new File(deletedPackage.codePath); 11816 // Parse old package 11817 boolean oldExternal = isExternal(deletedPackage); 11818 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 11819 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 11820 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11821 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 11822 try { 11823 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 11824 } catch (PackageManagerException e) { 11825 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 11826 + e.getMessage()); 11827 return; 11828 } 11829 // Restore of old package succeeded. Update permissions. 11830 // writer 11831 synchronized (mPackages) { 11832 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 11833 UPDATE_PERMISSIONS_ALL); 11834 // can downgrade to reader 11835 mSettings.writeLPr(); 11836 } 11837 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 11838 } 11839 } 11840 } 11841 11842 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 11843 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11844 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11845 String volumeUuid, PackageInstalledInfo res) { 11846 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 11847 + ", old=" + deletedPackage); 11848 boolean disabledSystem = false; 11849 boolean updatedSettings = false; 11850 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 11851 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 11852 != 0) { 11853 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11854 } 11855 String packageName = deletedPackage.packageName; 11856 if (packageName == null) { 11857 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11858 "Attempt to delete null packageName."); 11859 return; 11860 } 11861 PackageParser.Package oldPkg; 11862 PackageSetting oldPkgSetting; 11863 // reader 11864 synchronized (mPackages) { 11865 oldPkg = mPackages.get(packageName); 11866 oldPkgSetting = mSettings.mPackages.get(packageName); 11867 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 11868 (oldPkgSetting == null)) { 11869 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11870 "Couldn't find package:" + packageName + " information"); 11871 return; 11872 } 11873 } 11874 11875 res.removedInfo.uid = oldPkg.applicationInfo.uid; 11876 res.removedInfo.removedPackage = packageName; 11877 // Remove existing system package 11878 removePackageLI(oldPkgSetting, true); 11879 // writer 11880 synchronized (mPackages) { 11881 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 11882 if (!disabledSystem && deletedPackage != null) { 11883 // We didn't need to disable the .apk as a current system package, 11884 // which means we are replacing another update that is already 11885 // installed. We need to make sure to delete the older one's .apk. 11886 res.removedInfo.args = createInstallArgsForExisting(0, 11887 deletedPackage.applicationInfo.getCodePath(), 11888 deletedPackage.applicationInfo.getResourcePath(), 11889 getAppDexInstructionSets(deletedPackage.applicationInfo)); 11890 } else { 11891 res.removedInfo.args = null; 11892 } 11893 } 11894 11895 // Successfully disabled the old package. Now proceed with re-installation 11896 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 11897 11898 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11899 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 11900 11901 PackageParser.Package newPackage = null; 11902 try { 11903 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 11904 if (newPackage.mExtras != null) { 11905 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 11906 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 11907 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 11908 11909 // is the update attempting to change shared user? that isn't going to work... 11910 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 11911 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 11912 "Forbidding shared user change from " + oldPkgSetting.sharedUser 11913 + " to " + newPkgSetting.sharedUser); 11914 updatedSettings = true; 11915 } 11916 } 11917 11918 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11919 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11920 perUserInstalled, res, user); 11921 updatedSettings = true; 11922 } 11923 11924 } catch (PackageManagerException e) { 11925 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11926 } 11927 11928 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11929 // Re installation failed. Restore old information 11930 // Remove new pkg information 11931 if (newPackage != null) { 11932 removeInstalledPackageLI(newPackage, true); 11933 } 11934 // Add back the old system package 11935 try { 11936 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 11937 } catch (PackageManagerException e) { 11938 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 11939 } 11940 // Restore the old system information in Settings 11941 synchronized (mPackages) { 11942 if (disabledSystem) { 11943 mSettings.enableSystemPackageLPw(packageName); 11944 } 11945 if (updatedSettings) { 11946 mSettings.setInstallerPackageName(packageName, 11947 oldPkgSetting.installerPackageName); 11948 } 11949 mSettings.writeLPr(); 11950 } 11951 } 11952 } 11953 11954 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 11955 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 11956 UserHandle user) { 11957 String pkgName = newPackage.packageName; 11958 synchronized (mPackages) { 11959 //write settings. the installStatus will be incomplete at this stage. 11960 //note that the new package setting would have already been 11961 //added to mPackages. It hasn't been persisted yet. 11962 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 11963 mSettings.writeLPr(); 11964 } 11965 11966 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 11967 11968 synchronized (mPackages) { 11969 updatePermissionsLPw(newPackage.packageName, newPackage, 11970 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 11971 ? UPDATE_PERMISSIONS_ALL : 0)); 11972 // For system-bundled packages, we assume that installing an upgraded version 11973 // of the package implies that the user actually wants to run that new code, 11974 // so we enable the package. 11975 PackageSetting ps = mSettings.mPackages.get(pkgName); 11976 if (ps != null) { 11977 if (isSystemApp(newPackage)) { 11978 // NB: implicit assumption that system package upgrades apply to all users 11979 if (DEBUG_INSTALL) { 11980 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 11981 } 11982 if (res.origUsers != null) { 11983 for (int userHandle : res.origUsers) { 11984 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 11985 userHandle, installerPackageName); 11986 } 11987 } 11988 // Also convey the prior install/uninstall state 11989 if (allUsers != null && perUserInstalled != null) { 11990 for (int i = 0; i < allUsers.length; i++) { 11991 if (DEBUG_INSTALL) { 11992 Slog.d(TAG, " user " + allUsers[i] 11993 + " => " + perUserInstalled[i]); 11994 } 11995 ps.setInstalled(perUserInstalled[i], allUsers[i]); 11996 } 11997 // these install state changes will be persisted in the 11998 // upcoming call to mSettings.writeLPr(). 11999 } 12000 } 12001 // It's implied that when a user requests installation, they want the app to be 12002 // installed and enabled. 12003 int userId = user.getIdentifier(); 12004 if (userId != UserHandle.USER_ALL) { 12005 ps.setInstalled(true, userId); 12006 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 12007 } 12008 } 12009 res.name = pkgName; 12010 res.uid = newPackage.applicationInfo.uid; 12011 res.pkg = newPackage; 12012 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 12013 mSettings.setInstallerPackageName(pkgName, installerPackageName); 12014 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12015 //to update install status 12016 mSettings.writeLPr(); 12017 } 12018 } 12019 12020 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 12021 final int installFlags = args.installFlags; 12022 final String installerPackageName = args.installerPackageName; 12023 final String volumeUuid = args.volumeUuid; 12024 final File tmpPackageFile = new File(args.getCodePath()); 12025 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 12026 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 12027 || (args.volumeUuid != null)); 12028 boolean replace = false; 12029 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 12030 if (args.move != null) { 12031 // moving a complete application; perfom an initial scan on the new install location 12032 scanFlags |= SCAN_INITIAL; 12033 } 12034 // Result object to be returned 12035 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12036 12037 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 12038 // Retrieve PackageSettings and parse package 12039 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 12040 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 12041 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 12042 PackageParser pp = new PackageParser(); 12043 pp.setSeparateProcesses(mSeparateProcesses); 12044 pp.setDisplayMetrics(mMetrics); 12045 12046 final PackageParser.Package pkg; 12047 try { 12048 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 12049 } catch (PackageParserException e) { 12050 res.setError("Failed parse during installPackageLI", e); 12051 return; 12052 } 12053 12054 // Mark that we have an install time CPU ABI override. 12055 pkg.cpuAbiOverride = args.abiOverride; 12056 12057 String pkgName = res.name = pkg.packageName; 12058 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 12059 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 12060 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 12061 return; 12062 } 12063 } 12064 12065 try { 12066 pp.collectCertificates(pkg, parseFlags); 12067 pp.collectManifestDigest(pkg); 12068 } catch (PackageParserException e) { 12069 res.setError("Failed collect during installPackageLI", e); 12070 return; 12071 } 12072 12073 /* If the installer passed in a manifest digest, compare it now. */ 12074 if (args.manifestDigest != null) { 12075 if (DEBUG_INSTALL) { 12076 final String parsedManifest = pkg.manifestDigest == null ? "null" 12077 : pkg.manifestDigest.toString(); 12078 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 12079 + parsedManifest); 12080 } 12081 12082 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 12083 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 12084 return; 12085 } 12086 } else if (DEBUG_INSTALL) { 12087 final String parsedManifest = pkg.manifestDigest == null 12088 ? "null" : pkg.manifestDigest.toString(); 12089 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 12090 } 12091 12092 // Get rid of all references to package scan path via parser. 12093 pp = null; 12094 String oldCodePath = null; 12095 boolean systemApp = false; 12096 synchronized (mPackages) { 12097 // Check if installing already existing package 12098 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12099 String oldName = mSettings.mRenamedPackages.get(pkgName); 12100 if (pkg.mOriginalPackages != null 12101 && pkg.mOriginalPackages.contains(oldName) 12102 && mPackages.containsKey(oldName)) { 12103 // This package is derived from an original package, 12104 // and this device has been updating from that original 12105 // name. We must continue using the original name, so 12106 // rename the new package here. 12107 pkg.setPackageName(oldName); 12108 pkgName = pkg.packageName; 12109 replace = true; 12110 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 12111 + oldName + " pkgName=" + pkgName); 12112 } else if (mPackages.containsKey(pkgName)) { 12113 // This package, under its official name, already exists 12114 // on the device; we should replace it. 12115 replace = true; 12116 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 12117 } 12118 12119 // Prevent apps opting out from runtime permissions 12120 if (replace) { 12121 PackageParser.Package oldPackage = mPackages.get(pkgName); 12122 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 12123 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 12124 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 12125 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 12126 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 12127 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 12128 + " doesn't support runtime permissions but the old" 12129 + " target SDK " + oldTargetSdk + " does."); 12130 return; 12131 } 12132 } 12133 } 12134 12135 PackageSetting ps = mSettings.mPackages.get(pkgName); 12136 if (ps != null) { 12137 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 12138 12139 // Quick sanity check that we're signed correctly if updating; 12140 // we'll check this again later when scanning, but we want to 12141 // bail early here before tripping over redefined permissions. 12142 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12143 if (!checkUpgradeKeySetLP(ps, pkg)) { 12144 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 12145 + pkg.packageName + " upgrade keys do not match the " 12146 + "previously installed version"); 12147 return; 12148 } 12149 } else { 12150 try { 12151 verifySignaturesLP(ps, pkg); 12152 } catch (PackageManagerException e) { 12153 res.setError(e.error, e.getMessage()); 12154 return; 12155 } 12156 } 12157 12158 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 12159 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 12160 systemApp = (ps.pkg.applicationInfo.flags & 12161 ApplicationInfo.FLAG_SYSTEM) != 0; 12162 } 12163 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12164 } 12165 12166 // Check whether the newly-scanned package wants to define an already-defined perm 12167 int N = pkg.permissions.size(); 12168 for (int i = N-1; i >= 0; i--) { 12169 PackageParser.Permission perm = pkg.permissions.get(i); 12170 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 12171 if (bp != null) { 12172 // If the defining package is signed with our cert, it's okay. This 12173 // also includes the "updating the same package" case, of course. 12174 // "updating same package" could also involve key-rotation. 12175 final boolean sigsOk; 12176 if (bp.sourcePackage.equals(pkg.packageName) 12177 && (bp.packageSetting instanceof PackageSetting) 12178 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 12179 scanFlags))) { 12180 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 12181 } else { 12182 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 12183 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 12184 } 12185 if (!sigsOk) { 12186 // If the owning package is the system itself, we log but allow 12187 // install to proceed; we fail the install on all other permission 12188 // redefinitions. 12189 if (!bp.sourcePackage.equals("android")) { 12190 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 12191 + pkg.packageName + " attempting to redeclare permission " 12192 + perm.info.name + " already owned by " + bp.sourcePackage); 12193 res.origPermission = perm.info.name; 12194 res.origPackage = bp.sourcePackage; 12195 return; 12196 } else { 12197 Slog.w(TAG, "Package " + pkg.packageName 12198 + " attempting to redeclare system permission " 12199 + perm.info.name + "; ignoring new declaration"); 12200 pkg.permissions.remove(i); 12201 } 12202 } 12203 } 12204 } 12205 12206 } 12207 12208 if (systemApp && onExternal) { 12209 // Disable updates to system apps on sdcard 12210 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 12211 "Cannot install updates to system apps on sdcard"); 12212 return; 12213 } 12214 12215 if (args.move != null) { 12216 // We did an in-place move, so dex is ready to roll 12217 scanFlags |= SCAN_NO_DEX; 12218 scanFlags |= SCAN_MOVE; 12219 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 12220 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 12221 scanFlags |= SCAN_NO_DEX; 12222 12223 try { 12224 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 12225 true /* extract libs */); 12226 } catch (PackageManagerException pme) { 12227 Slog.e(TAG, "Error deriving application ABI", pme); 12228 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 12229 return; 12230 } 12231 12232 // Run dexopt before old package gets removed, to minimize time when app is unavailable 12233 int result = mPackageDexOptimizer 12234 .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */, 12235 false /* defer */, false /* inclDependencies */); 12236 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 12237 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 12238 return; 12239 } 12240 } 12241 12242 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 12243 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 12244 return; 12245 } 12246 12247 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 12248 12249 if (replace) { 12250 replacePackageLI(pkg, parseFlags, scanFlags, args.user, 12251 installerPackageName, volumeUuid, res); 12252 } else { 12253 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 12254 args.user, installerPackageName, volumeUuid, res); 12255 } 12256 synchronized (mPackages) { 12257 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12258 if (ps != null) { 12259 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12260 } 12261 } 12262 } 12263 12264 private void startIntentFilterVerifications(int userId, boolean replacing, 12265 PackageParser.Package pkg) { 12266 if (mIntentFilterVerifierComponent == null) { 12267 Slog.w(TAG, "No IntentFilter verification will not be done as " 12268 + "there is no IntentFilterVerifier available!"); 12269 return; 12270 } 12271 12272 final int verifierUid = getPackageUid( 12273 mIntentFilterVerifierComponent.getPackageName(), 12274 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 12275 12276 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 12277 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 12278 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 12279 mHandler.sendMessage(msg); 12280 } 12281 12282 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 12283 PackageParser.Package pkg) { 12284 int size = pkg.activities.size(); 12285 if (size == 0) { 12286 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12287 "No activity, so no need to verify any IntentFilter!"); 12288 return; 12289 } 12290 12291 final boolean hasDomainURLs = hasDomainURLs(pkg); 12292 if (!hasDomainURLs) { 12293 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12294 "No domain URLs, so no need to verify any IntentFilter!"); 12295 return; 12296 } 12297 12298 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 12299 + " if any IntentFilter from the " + size 12300 + " Activities needs verification ..."); 12301 12302 int count = 0; 12303 final String packageName = pkg.packageName; 12304 12305 synchronized (mPackages) { 12306 // If this is a new install and we see that we've already run verification for this 12307 // package, we have nothing to do: it means the state was restored from backup. 12308 if (!replacing) { 12309 IntentFilterVerificationInfo ivi = 12310 mSettings.getIntentFilterVerificationLPr(packageName); 12311 if (ivi != null) { 12312 if (DEBUG_DOMAIN_VERIFICATION) { 12313 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 12314 + ivi.getStatusString()); 12315 } 12316 return; 12317 } 12318 } 12319 12320 // If any filters need to be verified, then all need to be. 12321 boolean needToVerify = false; 12322 for (PackageParser.Activity a : pkg.activities) { 12323 for (ActivityIntentInfo filter : a.intents) { 12324 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 12325 if (DEBUG_DOMAIN_VERIFICATION) { 12326 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 12327 } 12328 needToVerify = true; 12329 break; 12330 } 12331 } 12332 } 12333 12334 if (needToVerify) { 12335 final int verificationId = mIntentFilterVerificationToken++; 12336 for (PackageParser.Activity a : pkg.activities) { 12337 for (ActivityIntentInfo filter : a.intents) { 12338 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 12339 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12340 "Verification needed for IntentFilter:" + filter.toString()); 12341 mIntentFilterVerifier.addOneIntentFilterVerification( 12342 verifierUid, userId, verificationId, filter, packageName); 12343 count++; 12344 } 12345 } 12346 } 12347 } 12348 } 12349 12350 if (count > 0) { 12351 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 12352 + " IntentFilter verification" + (count > 1 ? "s" : "") 12353 + " for userId:" + userId); 12354 mIntentFilterVerifier.startVerifications(userId); 12355 } else { 12356 if (DEBUG_DOMAIN_VERIFICATION) { 12357 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 12358 } 12359 } 12360 } 12361 12362 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 12363 final ComponentName cn = filter.activity.getComponentName(); 12364 final String packageName = cn.getPackageName(); 12365 12366 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 12367 packageName); 12368 if (ivi == null) { 12369 return true; 12370 } 12371 int status = ivi.getStatus(); 12372 switch (status) { 12373 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 12374 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 12375 return true; 12376 12377 default: 12378 // Nothing to do 12379 return false; 12380 } 12381 } 12382 12383 private static boolean isMultiArch(PackageSetting ps) { 12384 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12385 } 12386 12387 private static boolean isMultiArch(ApplicationInfo info) { 12388 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12389 } 12390 12391 private static boolean isExternal(PackageParser.Package pkg) { 12392 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12393 } 12394 12395 private static boolean isExternal(PackageSetting ps) { 12396 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12397 } 12398 12399 private static boolean isExternal(ApplicationInfo info) { 12400 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12401 } 12402 12403 private static boolean isSystemApp(PackageParser.Package pkg) { 12404 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 12405 } 12406 12407 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 12408 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 12409 } 12410 12411 private static boolean hasDomainURLs(PackageParser.Package pkg) { 12412 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 12413 } 12414 12415 private static boolean isSystemApp(PackageSetting ps) { 12416 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 12417 } 12418 12419 private static boolean isUpdatedSystemApp(PackageSetting ps) { 12420 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 12421 } 12422 12423 private int packageFlagsToInstallFlags(PackageSetting ps) { 12424 int installFlags = 0; 12425 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 12426 // This existing package was an external ASEC install when we have 12427 // the external flag without a UUID 12428 installFlags |= PackageManager.INSTALL_EXTERNAL; 12429 } 12430 if (ps.isForwardLocked()) { 12431 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12432 } 12433 return installFlags; 12434 } 12435 12436 private void deleteTempPackageFiles() { 12437 final FilenameFilter filter = new FilenameFilter() { 12438 public boolean accept(File dir, String name) { 12439 return name.startsWith("vmdl") && name.endsWith(".tmp"); 12440 } 12441 }; 12442 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 12443 file.delete(); 12444 } 12445 } 12446 12447 @Override 12448 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 12449 int flags) { 12450 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 12451 flags); 12452 } 12453 12454 @Override 12455 public void deletePackage(final String packageName, 12456 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 12457 mContext.enforceCallingOrSelfPermission( 12458 android.Manifest.permission.DELETE_PACKAGES, null); 12459 Preconditions.checkNotNull(packageName); 12460 Preconditions.checkNotNull(observer); 12461 final int uid = Binder.getCallingUid(); 12462 if (UserHandle.getUserId(uid) != userId) { 12463 mContext.enforceCallingPermission( 12464 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 12465 "deletePackage for user " + userId); 12466 } 12467 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 12468 try { 12469 observer.onPackageDeleted(packageName, 12470 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 12471 } catch (RemoteException re) { 12472 } 12473 return; 12474 } 12475 12476 boolean uninstallBlocked = false; 12477 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 12478 int[] users = sUserManager.getUserIds(); 12479 for (int i = 0; i < users.length; ++i) { 12480 if (getBlockUninstallForUser(packageName, users[i])) { 12481 uninstallBlocked = true; 12482 break; 12483 } 12484 } 12485 } else { 12486 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 12487 } 12488 if (uninstallBlocked) { 12489 try { 12490 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 12491 null); 12492 } catch (RemoteException re) { 12493 } 12494 return; 12495 } 12496 12497 if (DEBUG_REMOVE) { 12498 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 12499 } 12500 // Queue up an async operation since the package deletion may take a little while. 12501 mHandler.post(new Runnable() { 12502 public void run() { 12503 mHandler.removeCallbacks(this); 12504 final int returnCode = deletePackageX(packageName, userId, flags); 12505 if (observer != null) { 12506 try { 12507 observer.onPackageDeleted(packageName, returnCode, null); 12508 } catch (RemoteException e) { 12509 Log.i(TAG, "Observer no longer exists."); 12510 } //end catch 12511 } //end if 12512 } //end run 12513 }); 12514 } 12515 12516 private boolean isPackageDeviceAdmin(String packageName, int userId) { 12517 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 12518 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 12519 try { 12520 if (dpm != null) { 12521 if (dpm.isDeviceOwner(packageName)) { 12522 return true; 12523 } 12524 int[] users; 12525 if (userId == UserHandle.USER_ALL) { 12526 users = sUserManager.getUserIds(); 12527 } else { 12528 users = new int[]{userId}; 12529 } 12530 for (int i = 0; i < users.length; ++i) { 12531 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 12532 return true; 12533 } 12534 } 12535 } 12536 } catch (RemoteException e) { 12537 } 12538 return false; 12539 } 12540 12541 /** 12542 * This method is an internal method that could be get invoked either 12543 * to delete an installed package or to clean up a failed installation. 12544 * After deleting an installed package, a broadcast is sent to notify any 12545 * listeners that the package has been installed. For cleaning up a failed 12546 * installation, the broadcast is not necessary since the package's 12547 * installation wouldn't have sent the initial broadcast either 12548 * The key steps in deleting a package are 12549 * deleting the package information in internal structures like mPackages, 12550 * deleting the packages base directories through installd 12551 * updating mSettings to reflect current status 12552 * persisting settings for later use 12553 * sending a broadcast if necessary 12554 */ 12555 private int deletePackageX(String packageName, int userId, int flags) { 12556 final PackageRemovedInfo info = new PackageRemovedInfo(); 12557 final boolean res; 12558 12559 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 12560 ? UserHandle.ALL : new UserHandle(userId); 12561 12562 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 12563 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 12564 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 12565 } 12566 12567 boolean removedForAllUsers = false; 12568 boolean systemUpdate = false; 12569 12570 // for the uninstall-updates case and restricted profiles, remember the per- 12571 // userhandle installed state 12572 int[] allUsers; 12573 boolean[] perUserInstalled; 12574 synchronized (mPackages) { 12575 PackageSetting ps = mSettings.mPackages.get(packageName); 12576 allUsers = sUserManager.getUserIds(); 12577 perUserInstalled = new boolean[allUsers.length]; 12578 for (int i = 0; i < allUsers.length; i++) { 12579 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12580 } 12581 } 12582 12583 synchronized (mInstallLock) { 12584 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 12585 res = deletePackageLI(packageName, removeForUser, 12586 true, allUsers, perUserInstalled, 12587 flags | REMOVE_CHATTY, info, true); 12588 systemUpdate = info.isRemovedPackageSystemUpdate; 12589 if (res && !systemUpdate && mPackages.get(packageName) == null) { 12590 removedForAllUsers = true; 12591 } 12592 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 12593 + " removedForAllUsers=" + removedForAllUsers); 12594 } 12595 12596 if (res) { 12597 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 12598 12599 // If the removed package was a system update, the old system package 12600 // was re-enabled; we need to broadcast this information 12601 if (systemUpdate) { 12602 Bundle extras = new Bundle(1); 12603 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 12604 ? info.removedAppId : info.uid); 12605 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12606 12607 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 12608 extras, null, null, null); 12609 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 12610 extras, null, null, null); 12611 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 12612 null, packageName, null, null); 12613 } 12614 } 12615 // Force a gc here. 12616 Runtime.getRuntime().gc(); 12617 // Delete the resources here after sending the broadcast to let 12618 // other processes clean up before deleting resources. 12619 if (info.args != null) { 12620 synchronized (mInstallLock) { 12621 info.args.doPostDeleteLI(true); 12622 } 12623 } 12624 12625 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 12626 } 12627 12628 class PackageRemovedInfo { 12629 String removedPackage; 12630 int uid = -1; 12631 int removedAppId = -1; 12632 int[] removedUsers = null; 12633 boolean isRemovedPackageSystemUpdate = false; 12634 // Clean up resources deleted packages. 12635 InstallArgs args = null; 12636 12637 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 12638 Bundle extras = new Bundle(1); 12639 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 12640 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 12641 if (replacing) { 12642 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12643 } 12644 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 12645 if (removedPackage != null) { 12646 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 12647 extras, null, null, removedUsers); 12648 if (fullRemove && !replacing) { 12649 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 12650 extras, null, null, removedUsers); 12651 } 12652 } 12653 if (removedAppId >= 0) { 12654 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 12655 removedUsers); 12656 } 12657 } 12658 } 12659 12660 /* 12661 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 12662 * flag is not set, the data directory is removed as well. 12663 * make sure this flag is set for partially installed apps. If not its meaningless to 12664 * delete a partially installed application. 12665 */ 12666 private void removePackageDataLI(PackageSetting ps, 12667 int[] allUserHandles, boolean[] perUserInstalled, 12668 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 12669 String packageName = ps.name; 12670 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 12671 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 12672 // Retrieve object to delete permissions for shared user later on 12673 final PackageSetting deletedPs; 12674 // reader 12675 synchronized (mPackages) { 12676 deletedPs = mSettings.mPackages.get(packageName); 12677 if (outInfo != null) { 12678 outInfo.removedPackage = packageName; 12679 outInfo.removedUsers = deletedPs != null 12680 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 12681 : null; 12682 } 12683 } 12684 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12685 removeDataDirsLI(ps.volumeUuid, packageName); 12686 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 12687 } 12688 // writer 12689 synchronized (mPackages) { 12690 if (deletedPs != null) { 12691 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12692 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 12693 clearDefaultBrowserIfNeeded(packageName); 12694 if (outInfo != null) { 12695 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 12696 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 12697 } 12698 updatePermissionsLPw(deletedPs.name, null, 0); 12699 if (deletedPs.sharedUser != null) { 12700 // Remove permissions associated with package. Since runtime 12701 // permissions are per user we have to kill the removed package 12702 // or packages running under the shared user of the removed 12703 // package if revoking the permissions requested only by the removed 12704 // package is successful and this causes a change in gids. 12705 for (int userId : UserManagerService.getInstance().getUserIds()) { 12706 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 12707 userId); 12708 if (userIdToKill == UserHandle.USER_ALL 12709 || userIdToKill >= UserHandle.USER_OWNER) { 12710 // If gids changed for this user, kill all affected packages. 12711 mHandler.post(new Runnable() { 12712 @Override 12713 public void run() { 12714 // This has to happen with no lock held. 12715 killSettingPackagesForUser(deletedPs, userIdToKill, 12716 KILL_APP_REASON_GIDS_CHANGED); 12717 } 12718 }); 12719 break; 12720 } 12721 } 12722 } 12723 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 12724 } 12725 // make sure to preserve per-user disabled state if this removal was just 12726 // a downgrade of a system app to the factory package 12727 if (allUserHandles != null && perUserInstalled != null) { 12728 if (DEBUG_REMOVE) { 12729 Slog.d(TAG, "Propagating install state across downgrade"); 12730 } 12731 for (int i = 0; i < allUserHandles.length; i++) { 12732 if (DEBUG_REMOVE) { 12733 Slog.d(TAG, " user " + allUserHandles[i] 12734 + " => " + perUserInstalled[i]); 12735 } 12736 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12737 } 12738 } 12739 } 12740 // can downgrade to reader 12741 if (writeSettings) { 12742 // Save settings now 12743 mSettings.writeLPr(); 12744 } 12745 } 12746 if (outInfo != null) { 12747 // A user ID was deleted here. Go through all users and remove it 12748 // from KeyStore. 12749 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 12750 } 12751 } 12752 12753 static boolean locationIsPrivileged(File path) { 12754 try { 12755 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 12756 .getCanonicalPath(); 12757 return path.getCanonicalPath().startsWith(privilegedAppDir); 12758 } catch (IOException e) { 12759 Slog.e(TAG, "Unable to access code path " + path); 12760 } 12761 return false; 12762 } 12763 12764 /* 12765 * Tries to delete system package. 12766 */ 12767 private boolean deleteSystemPackageLI(PackageSetting newPs, 12768 int[] allUserHandles, boolean[] perUserInstalled, 12769 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 12770 final boolean applyUserRestrictions 12771 = (allUserHandles != null) && (perUserInstalled != null); 12772 PackageSetting disabledPs = null; 12773 // Confirm if the system package has been updated 12774 // An updated system app can be deleted. This will also have to restore 12775 // the system pkg from system partition 12776 // reader 12777 synchronized (mPackages) { 12778 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 12779 } 12780 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 12781 + " disabledPs=" + disabledPs); 12782 if (disabledPs == null) { 12783 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 12784 return false; 12785 } else if (DEBUG_REMOVE) { 12786 Slog.d(TAG, "Deleting system pkg from data partition"); 12787 } 12788 if (DEBUG_REMOVE) { 12789 if (applyUserRestrictions) { 12790 Slog.d(TAG, "Remembering install states:"); 12791 for (int i = 0; i < allUserHandles.length; i++) { 12792 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 12793 } 12794 } 12795 } 12796 // Delete the updated package 12797 outInfo.isRemovedPackageSystemUpdate = true; 12798 if (disabledPs.versionCode < newPs.versionCode) { 12799 // Delete data for downgrades 12800 flags &= ~PackageManager.DELETE_KEEP_DATA; 12801 } else { 12802 // Preserve data by setting flag 12803 flags |= PackageManager.DELETE_KEEP_DATA; 12804 } 12805 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 12806 allUserHandles, perUserInstalled, outInfo, writeSettings); 12807 if (!ret) { 12808 return false; 12809 } 12810 // writer 12811 synchronized (mPackages) { 12812 // Reinstate the old system package 12813 mSettings.enableSystemPackageLPw(newPs.name); 12814 // Remove any native libraries from the upgraded package. 12815 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 12816 } 12817 // Install the system package 12818 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 12819 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 12820 if (locationIsPrivileged(disabledPs.codePath)) { 12821 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12822 } 12823 12824 final PackageParser.Package newPkg; 12825 try { 12826 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 12827 } catch (PackageManagerException e) { 12828 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 12829 return false; 12830 } 12831 12832 // writer 12833 synchronized (mPackages) { 12834 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 12835 12836 // Propagate the permissions state as we do want to drop on the floor 12837 // runtime permissions. The update permissions method below will take 12838 // care of removing obsolete permissions and grant install permissions. 12839 ps.getPermissionsState().copyFrom(disabledPs.getPermissionsState()); 12840 updatePermissionsLPw(newPkg.packageName, newPkg, 12841 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 12842 12843 if (applyUserRestrictions) { 12844 if (DEBUG_REMOVE) { 12845 Slog.d(TAG, "Propagating install state across reinstall"); 12846 } 12847 for (int i = 0; i < allUserHandles.length; i++) { 12848 if (DEBUG_REMOVE) { 12849 Slog.d(TAG, " user " + allUserHandles[i] 12850 + " => " + perUserInstalled[i]); 12851 } 12852 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12853 } 12854 // Regardless of writeSettings we need to ensure that this restriction 12855 // state propagation is persisted 12856 mSettings.writeAllUsersPackageRestrictionsLPr(); 12857 } 12858 // can downgrade to reader here 12859 if (writeSettings) { 12860 mSettings.writeLPr(); 12861 } 12862 } 12863 return true; 12864 } 12865 12866 private boolean deleteInstalledPackageLI(PackageSetting ps, 12867 boolean deleteCodeAndResources, int flags, 12868 int[] allUserHandles, boolean[] perUserInstalled, 12869 PackageRemovedInfo outInfo, boolean writeSettings) { 12870 if (outInfo != null) { 12871 outInfo.uid = ps.appId; 12872 } 12873 12874 // Delete package data from internal structures and also remove data if flag is set 12875 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 12876 12877 // Delete application code and resources 12878 if (deleteCodeAndResources && (outInfo != null)) { 12879 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 12880 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 12881 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 12882 } 12883 return true; 12884 } 12885 12886 @Override 12887 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 12888 int userId) { 12889 mContext.enforceCallingOrSelfPermission( 12890 android.Manifest.permission.DELETE_PACKAGES, null); 12891 synchronized (mPackages) { 12892 PackageSetting ps = mSettings.mPackages.get(packageName); 12893 if (ps == null) { 12894 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 12895 return false; 12896 } 12897 if (!ps.getInstalled(userId)) { 12898 // Can't block uninstall for an app that is not installed or enabled. 12899 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 12900 return false; 12901 } 12902 ps.setBlockUninstall(blockUninstall, userId); 12903 mSettings.writePackageRestrictionsLPr(userId); 12904 } 12905 return true; 12906 } 12907 12908 @Override 12909 public boolean getBlockUninstallForUser(String packageName, int userId) { 12910 synchronized (mPackages) { 12911 PackageSetting ps = mSettings.mPackages.get(packageName); 12912 if (ps == null) { 12913 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 12914 return false; 12915 } 12916 return ps.getBlockUninstall(userId); 12917 } 12918 } 12919 12920 /* 12921 * This method handles package deletion in general 12922 */ 12923 private boolean deletePackageLI(String packageName, UserHandle user, 12924 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 12925 int flags, PackageRemovedInfo outInfo, 12926 boolean writeSettings) { 12927 if (packageName == null) { 12928 Slog.w(TAG, "Attempt to delete null packageName."); 12929 return false; 12930 } 12931 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 12932 PackageSetting ps; 12933 boolean dataOnly = false; 12934 int removeUser = -1; 12935 int appId = -1; 12936 synchronized (mPackages) { 12937 ps = mSettings.mPackages.get(packageName); 12938 if (ps == null) { 12939 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12940 return false; 12941 } 12942 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 12943 && user.getIdentifier() != UserHandle.USER_ALL) { 12944 // The caller is asking that the package only be deleted for a single 12945 // user. To do this, we just mark its uninstalled state and delete 12946 // its data. If this is a system app, we only allow this to happen if 12947 // they have set the special DELETE_SYSTEM_APP which requests different 12948 // semantics than normal for uninstalling system apps. 12949 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 12950 ps.setUserState(user.getIdentifier(), 12951 COMPONENT_ENABLED_STATE_DEFAULT, 12952 false, //installed 12953 true, //stopped 12954 true, //notLaunched 12955 false, //hidden 12956 null, null, null, 12957 false, // blockUninstall 12958 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 12959 if (!isSystemApp(ps)) { 12960 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 12961 // Other user still have this package installed, so all 12962 // we need to do is clear this user's data and save that 12963 // it is uninstalled. 12964 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 12965 removeUser = user.getIdentifier(); 12966 appId = ps.appId; 12967 scheduleWritePackageRestrictionsLocked(removeUser); 12968 } else { 12969 // We need to set it back to 'installed' so the uninstall 12970 // broadcasts will be sent correctly. 12971 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 12972 ps.setInstalled(true, user.getIdentifier()); 12973 } 12974 } else { 12975 // This is a system app, so we assume that the 12976 // other users still have this package installed, so all 12977 // we need to do is clear this user's data and save that 12978 // it is uninstalled. 12979 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 12980 removeUser = user.getIdentifier(); 12981 appId = ps.appId; 12982 scheduleWritePackageRestrictionsLocked(removeUser); 12983 } 12984 } 12985 } 12986 12987 if (removeUser >= 0) { 12988 // From above, we determined that we are deleting this only 12989 // for a single user. Continue the work here. 12990 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 12991 if (outInfo != null) { 12992 outInfo.removedPackage = packageName; 12993 outInfo.removedAppId = appId; 12994 outInfo.removedUsers = new int[] {removeUser}; 12995 } 12996 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 12997 removeKeystoreDataIfNeeded(removeUser, appId); 12998 schedulePackageCleaning(packageName, removeUser, false); 12999 synchronized (mPackages) { 13000 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 13001 scheduleWritePackageRestrictionsLocked(removeUser); 13002 } 13003 resetUserChangesToRuntimePermissionsAndFlagsLocked(ps, removeUser); 13004 } 13005 return true; 13006 } 13007 13008 if (dataOnly) { 13009 // Delete application data first 13010 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 13011 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 13012 return true; 13013 } 13014 13015 boolean ret = false; 13016 if (isSystemApp(ps)) { 13017 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 13018 // When an updated system application is deleted we delete the existing resources as well and 13019 // fall back to existing code in system partition 13020 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 13021 flags, outInfo, writeSettings); 13022 } else { 13023 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 13024 // Kill application pre-emptively especially for apps on sd. 13025 killApplication(packageName, ps.appId, "uninstall pkg"); 13026 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 13027 allUserHandles, perUserInstalled, 13028 outInfo, writeSettings); 13029 } 13030 13031 return ret; 13032 } 13033 13034 private final class ClearStorageConnection implements ServiceConnection { 13035 IMediaContainerService mContainerService; 13036 13037 @Override 13038 public void onServiceConnected(ComponentName name, IBinder service) { 13039 synchronized (this) { 13040 mContainerService = IMediaContainerService.Stub.asInterface(service); 13041 notifyAll(); 13042 } 13043 } 13044 13045 @Override 13046 public void onServiceDisconnected(ComponentName name) { 13047 } 13048 } 13049 13050 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 13051 final boolean mounted; 13052 if (Environment.isExternalStorageEmulated()) { 13053 mounted = true; 13054 } else { 13055 final String status = Environment.getExternalStorageState(); 13056 13057 mounted = status.equals(Environment.MEDIA_MOUNTED) 13058 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 13059 } 13060 13061 if (!mounted) { 13062 return; 13063 } 13064 13065 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 13066 int[] users; 13067 if (userId == UserHandle.USER_ALL) { 13068 users = sUserManager.getUserIds(); 13069 } else { 13070 users = new int[] { userId }; 13071 } 13072 final ClearStorageConnection conn = new ClearStorageConnection(); 13073 if (mContext.bindServiceAsUser( 13074 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 13075 try { 13076 for (int curUser : users) { 13077 long timeout = SystemClock.uptimeMillis() + 5000; 13078 synchronized (conn) { 13079 long now = SystemClock.uptimeMillis(); 13080 while (conn.mContainerService == null && now < timeout) { 13081 try { 13082 conn.wait(timeout - now); 13083 } catch (InterruptedException e) { 13084 } 13085 } 13086 } 13087 if (conn.mContainerService == null) { 13088 return; 13089 } 13090 13091 final UserEnvironment userEnv = new UserEnvironment(curUser); 13092 clearDirectory(conn.mContainerService, 13093 userEnv.buildExternalStorageAppCacheDirs(packageName)); 13094 if (allData) { 13095 clearDirectory(conn.mContainerService, 13096 userEnv.buildExternalStorageAppDataDirs(packageName)); 13097 clearDirectory(conn.mContainerService, 13098 userEnv.buildExternalStorageAppMediaDirs(packageName)); 13099 } 13100 } 13101 } finally { 13102 mContext.unbindService(conn); 13103 } 13104 } 13105 } 13106 13107 @Override 13108 public void clearApplicationUserData(final String packageName, 13109 final IPackageDataObserver observer, final int userId) { 13110 mContext.enforceCallingOrSelfPermission( 13111 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 13112 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 13113 // Queue up an async operation since the package deletion may take a little while. 13114 mHandler.post(new Runnable() { 13115 public void run() { 13116 mHandler.removeCallbacks(this); 13117 final boolean succeeded; 13118 synchronized (mInstallLock) { 13119 succeeded = clearApplicationUserDataLI(packageName, userId); 13120 } 13121 clearExternalStorageDataSync(packageName, userId, true); 13122 if (succeeded) { 13123 // invoke DeviceStorageMonitor's update method to clear any notifications 13124 DeviceStorageMonitorInternal 13125 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13126 if (dsm != null) { 13127 dsm.checkMemory(); 13128 } 13129 } 13130 if(observer != null) { 13131 try { 13132 observer.onRemoveCompleted(packageName, succeeded); 13133 } catch (RemoteException e) { 13134 Log.i(TAG, "Observer no longer exists."); 13135 } 13136 } //end if observer 13137 } //end run 13138 }); 13139 } 13140 13141 private boolean clearApplicationUserDataLI(String packageName, int userId) { 13142 if (packageName == null) { 13143 Slog.w(TAG, "Attempt to delete null packageName."); 13144 return false; 13145 } 13146 13147 // Try finding details about the requested package 13148 PackageParser.Package pkg; 13149 synchronized (mPackages) { 13150 pkg = mPackages.get(packageName); 13151 if (pkg == null) { 13152 final PackageSetting ps = mSettings.mPackages.get(packageName); 13153 if (ps != null) { 13154 pkg = ps.pkg; 13155 } 13156 } 13157 13158 if (pkg == null) { 13159 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13160 return false; 13161 } 13162 13163 PackageSetting ps = (PackageSetting) pkg.mExtras; 13164 resetUserChangesToRuntimePermissionsAndFlagsLocked(ps, userId); 13165 } 13166 13167 // Always delete data directories for package, even if we found no other 13168 // record of app. This helps users recover from UID mismatches without 13169 // resorting to a full data wipe. 13170 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 13171 if (retCode < 0) { 13172 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 13173 return false; 13174 } 13175 13176 final int appId = pkg.applicationInfo.uid; 13177 removeKeystoreDataIfNeeded(userId, appId); 13178 13179 // Create a native library symlink only if we have native libraries 13180 // and if the native libraries are 32 bit libraries. We do not provide 13181 // this symlink for 64 bit libraries. 13182 if (pkg.applicationInfo.primaryCpuAbi != null && 13183 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 13184 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 13185 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 13186 nativeLibPath, userId) < 0) { 13187 Slog.w(TAG, "Failed linking native library dir"); 13188 return false; 13189 } 13190 } 13191 13192 return true; 13193 } 13194 13195 /** 13196 * Reverts user permission state changes (permissions and flags). 13197 * 13198 * @param ps The package for which to reset. 13199 * @param userId The device user for which to do a reset. 13200 */ 13201 private void resetUserChangesToRuntimePermissionsAndFlagsLocked( 13202 final PackageSetting ps, final int userId) { 13203 if (ps.pkg == null) { 13204 return; 13205 } 13206 13207 final int userSettableFlags = FLAG_PERMISSION_USER_SET 13208 | FLAG_PERMISSION_USER_FIXED 13209 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 13210 13211 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 13212 | FLAG_PERMISSION_POLICY_FIXED; 13213 13214 boolean writeInstallPermissions = false; 13215 boolean writeRuntimePermissions = false; 13216 13217 final int permissionCount = ps.pkg.requestedPermissions.size(); 13218 for (int i = 0; i < permissionCount; i++) { 13219 String permission = ps.pkg.requestedPermissions.get(i); 13220 13221 BasePermission bp = mSettings.mPermissions.get(permission); 13222 if (bp == null) { 13223 continue; 13224 } 13225 13226 // If shared user we just reset the state to which only this app contributed. 13227 if (ps.sharedUser != null) { 13228 boolean used = false; 13229 final int packageCount = ps.sharedUser.packages.size(); 13230 for (int j = 0; j < packageCount; j++) { 13231 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 13232 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 13233 && pkg.pkg.requestedPermissions.contains(permission)) { 13234 used = true; 13235 break; 13236 } 13237 } 13238 if (used) { 13239 continue; 13240 } 13241 } 13242 13243 PermissionsState permissionsState = ps.getPermissionsState(); 13244 13245 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 13246 13247 // Always clear the user settable flags. 13248 final boolean hasInstallState = permissionsState.getInstallPermissionState( 13249 bp.name) != null; 13250 if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) { 13251 if (hasInstallState) { 13252 writeInstallPermissions = true; 13253 } else { 13254 writeRuntimePermissions = true; 13255 } 13256 } 13257 13258 // Below is only runtime permission handling. 13259 if (!bp.isRuntime()) { 13260 continue; 13261 } 13262 13263 // Never clobber system or policy. 13264 if ((oldFlags & policyOrSystemFlags) != 0) { 13265 continue; 13266 } 13267 13268 // If this permission was granted by default, make sure it is. 13269 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 13270 if (permissionsState.grantRuntimePermission(bp, userId) 13271 != PERMISSION_OPERATION_FAILURE) { 13272 writeRuntimePermissions = true; 13273 } 13274 } else { 13275 // Otherwise, reset the permission. 13276 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 13277 switch (revokeResult) { 13278 case PERMISSION_OPERATION_SUCCESS: { 13279 writeRuntimePermissions = true; 13280 } break; 13281 13282 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 13283 writeRuntimePermissions = true; 13284 // If gids changed for this user, kill all affected packages. 13285 mHandler.post(new Runnable() { 13286 @Override 13287 public void run() { 13288 // This has to happen with no lock held. 13289 killSettingPackagesForUser(ps, userId, 13290 KILL_APP_REASON_GIDS_CHANGED); 13291 } 13292 }); 13293 } break; 13294 } 13295 } 13296 } 13297 13298 // Synchronously write as we are taking permissions away. 13299 if (writeRuntimePermissions) { 13300 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 13301 } 13302 13303 // Synchronously write as we are taking permissions away. 13304 if (writeInstallPermissions) { 13305 mSettings.writeLPr(); 13306 } 13307 } 13308 13309 /** 13310 * Remove entries from the keystore daemon. Will only remove it if the 13311 * {@code appId} is valid. 13312 */ 13313 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 13314 if (appId < 0) { 13315 return; 13316 } 13317 13318 final KeyStore keyStore = KeyStore.getInstance(); 13319 if (keyStore != null) { 13320 if (userId == UserHandle.USER_ALL) { 13321 for (final int individual : sUserManager.getUserIds()) { 13322 keyStore.clearUid(UserHandle.getUid(individual, appId)); 13323 } 13324 } else { 13325 keyStore.clearUid(UserHandle.getUid(userId, appId)); 13326 } 13327 } else { 13328 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 13329 } 13330 } 13331 13332 @Override 13333 public void deleteApplicationCacheFiles(final String packageName, 13334 final IPackageDataObserver observer) { 13335 mContext.enforceCallingOrSelfPermission( 13336 android.Manifest.permission.DELETE_CACHE_FILES, null); 13337 // Queue up an async operation since the package deletion may take a little while. 13338 final int userId = UserHandle.getCallingUserId(); 13339 mHandler.post(new Runnable() { 13340 public void run() { 13341 mHandler.removeCallbacks(this); 13342 final boolean succeded; 13343 synchronized (mInstallLock) { 13344 succeded = deleteApplicationCacheFilesLI(packageName, userId); 13345 } 13346 clearExternalStorageDataSync(packageName, userId, false); 13347 if (observer != null) { 13348 try { 13349 observer.onRemoveCompleted(packageName, succeded); 13350 } catch (RemoteException e) { 13351 Log.i(TAG, "Observer no longer exists."); 13352 } 13353 } //end if observer 13354 } //end run 13355 }); 13356 } 13357 13358 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 13359 if (packageName == null) { 13360 Slog.w(TAG, "Attempt to delete null packageName."); 13361 return false; 13362 } 13363 PackageParser.Package p; 13364 synchronized (mPackages) { 13365 p = mPackages.get(packageName); 13366 } 13367 if (p == null) { 13368 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13369 return false; 13370 } 13371 final ApplicationInfo applicationInfo = p.applicationInfo; 13372 if (applicationInfo == null) { 13373 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13374 return false; 13375 } 13376 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 13377 if (retCode < 0) { 13378 Slog.w(TAG, "Couldn't remove cache files for package: " 13379 + packageName + " u" + userId); 13380 return false; 13381 } 13382 return true; 13383 } 13384 13385 @Override 13386 public void getPackageSizeInfo(final String packageName, int userHandle, 13387 final IPackageStatsObserver observer) { 13388 mContext.enforceCallingOrSelfPermission( 13389 android.Manifest.permission.GET_PACKAGE_SIZE, null); 13390 if (packageName == null) { 13391 throw new IllegalArgumentException("Attempt to get size of null packageName"); 13392 } 13393 13394 PackageStats stats = new PackageStats(packageName, userHandle); 13395 13396 /* 13397 * Queue up an async operation since the package measurement may take a 13398 * little while. 13399 */ 13400 Message msg = mHandler.obtainMessage(INIT_COPY); 13401 msg.obj = new MeasureParams(stats, observer); 13402 mHandler.sendMessage(msg); 13403 } 13404 13405 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 13406 PackageStats pStats) { 13407 if (packageName == null) { 13408 Slog.w(TAG, "Attempt to get size of null packageName."); 13409 return false; 13410 } 13411 PackageParser.Package p; 13412 boolean dataOnly = false; 13413 String libDirRoot = null; 13414 String asecPath = null; 13415 PackageSetting ps = null; 13416 synchronized (mPackages) { 13417 p = mPackages.get(packageName); 13418 ps = mSettings.mPackages.get(packageName); 13419 if(p == null) { 13420 dataOnly = true; 13421 if((ps == null) || (ps.pkg == null)) { 13422 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13423 return false; 13424 } 13425 p = ps.pkg; 13426 } 13427 if (ps != null) { 13428 libDirRoot = ps.legacyNativeLibraryPathString; 13429 } 13430 if (p != null && (isExternal(p) || p.isForwardLocked())) { 13431 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 13432 if (secureContainerId != null) { 13433 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 13434 } 13435 } 13436 } 13437 String publicSrcDir = null; 13438 if(!dataOnly) { 13439 final ApplicationInfo applicationInfo = p.applicationInfo; 13440 if (applicationInfo == null) { 13441 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13442 return false; 13443 } 13444 if (p.isForwardLocked()) { 13445 publicSrcDir = applicationInfo.getBaseResourcePath(); 13446 } 13447 } 13448 // TODO: extend to measure size of split APKs 13449 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 13450 // not just the first level. 13451 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 13452 // just the primary. 13453 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 13454 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath, 13455 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 13456 if (res < 0) { 13457 return false; 13458 } 13459 13460 // Fix-up for forward-locked applications in ASEC containers. 13461 if (!isExternal(p)) { 13462 pStats.codeSize += pStats.externalCodeSize; 13463 pStats.externalCodeSize = 0L; 13464 } 13465 13466 return true; 13467 } 13468 13469 13470 @Override 13471 public void addPackageToPreferred(String packageName) { 13472 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 13473 } 13474 13475 @Override 13476 public void removePackageFromPreferred(String packageName) { 13477 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 13478 } 13479 13480 @Override 13481 public List<PackageInfo> getPreferredPackages(int flags) { 13482 return new ArrayList<PackageInfo>(); 13483 } 13484 13485 private int getUidTargetSdkVersionLockedLPr(int uid) { 13486 Object obj = mSettings.getUserIdLPr(uid); 13487 if (obj instanceof SharedUserSetting) { 13488 final SharedUserSetting sus = (SharedUserSetting) obj; 13489 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 13490 final Iterator<PackageSetting> it = sus.packages.iterator(); 13491 while (it.hasNext()) { 13492 final PackageSetting ps = it.next(); 13493 if (ps.pkg != null) { 13494 int v = ps.pkg.applicationInfo.targetSdkVersion; 13495 if (v < vers) vers = v; 13496 } 13497 } 13498 return vers; 13499 } else if (obj instanceof PackageSetting) { 13500 final PackageSetting ps = (PackageSetting) obj; 13501 if (ps.pkg != null) { 13502 return ps.pkg.applicationInfo.targetSdkVersion; 13503 } 13504 } 13505 return Build.VERSION_CODES.CUR_DEVELOPMENT; 13506 } 13507 13508 @Override 13509 public void addPreferredActivity(IntentFilter filter, int match, 13510 ComponentName[] set, ComponentName activity, int userId) { 13511 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13512 "Adding preferred"); 13513 } 13514 13515 private void addPreferredActivityInternal(IntentFilter filter, int match, 13516 ComponentName[] set, ComponentName activity, boolean always, int userId, 13517 String opname) { 13518 // writer 13519 int callingUid = Binder.getCallingUid(); 13520 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 13521 if (filter.countActions() == 0) { 13522 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13523 return; 13524 } 13525 synchronized (mPackages) { 13526 if (mContext.checkCallingOrSelfPermission( 13527 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13528 != PackageManager.PERMISSION_GRANTED) { 13529 if (getUidTargetSdkVersionLockedLPr(callingUid) 13530 < Build.VERSION_CODES.FROYO) { 13531 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 13532 + callingUid); 13533 return; 13534 } 13535 mContext.enforceCallingOrSelfPermission( 13536 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13537 } 13538 13539 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 13540 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 13541 + userId + ":"); 13542 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13543 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 13544 scheduleWritePackageRestrictionsLocked(userId); 13545 } 13546 } 13547 13548 @Override 13549 public void replacePreferredActivity(IntentFilter filter, int match, 13550 ComponentName[] set, ComponentName activity, int userId) { 13551 if (filter.countActions() != 1) { 13552 throw new IllegalArgumentException( 13553 "replacePreferredActivity expects filter to have only 1 action."); 13554 } 13555 if (filter.countDataAuthorities() != 0 13556 || filter.countDataPaths() != 0 13557 || filter.countDataSchemes() > 1 13558 || filter.countDataTypes() != 0) { 13559 throw new IllegalArgumentException( 13560 "replacePreferredActivity expects filter to have no data authorities, " + 13561 "paths, or types; and at most one scheme."); 13562 } 13563 13564 final int callingUid = Binder.getCallingUid(); 13565 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 13566 synchronized (mPackages) { 13567 if (mContext.checkCallingOrSelfPermission( 13568 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13569 != PackageManager.PERMISSION_GRANTED) { 13570 if (getUidTargetSdkVersionLockedLPr(callingUid) 13571 < Build.VERSION_CODES.FROYO) { 13572 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 13573 + Binder.getCallingUid()); 13574 return; 13575 } 13576 mContext.enforceCallingOrSelfPermission( 13577 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13578 } 13579 13580 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13581 if (pir != null) { 13582 // Get all of the existing entries that exactly match this filter. 13583 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 13584 if (existing != null && existing.size() == 1) { 13585 PreferredActivity cur = existing.get(0); 13586 if (DEBUG_PREFERRED) { 13587 Slog.i(TAG, "Checking replace of preferred:"); 13588 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13589 if (!cur.mPref.mAlways) { 13590 Slog.i(TAG, " -- CUR; not mAlways!"); 13591 } else { 13592 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 13593 Slog.i(TAG, " -- CUR: mSet=" 13594 + Arrays.toString(cur.mPref.mSetComponents)); 13595 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 13596 Slog.i(TAG, " -- NEW: mMatch=" 13597 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 13598 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 13599 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 13600 } 13601 } 13602 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 13603 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 13604 && cur.mPref.sameSet(set)) { 13605 // Setting the preferred activity to what it happens to be already 13606 if (DEBUG_PREFERRED) { 13607 Slog.i(TAG, "Replacing with same preferred activity " 13608 + cur.mPref.mShortComponent + " for user " 13609 + userId + ":"); 13610 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13611 } 13612 return; 13613 } 13614 } 13615 13616 if (existing != null) { 13617 if (DEBUG_PREFERRED) { 13618 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 13619 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13620 } 13621 for (int i = 0; i < existing.size(); i++) { 13622 PreferredActivity pa = existing.get(i); 13623 if (DEBUG_PREFERRED) { 13624 Slog.i(TAG, "Removing existing preferred activity " 13625 + pa.mPref.mComponent + ":"); 13626 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 13627 } 13628 pir.removeFilter(pa); 13629 } 13630 } 13631 } 13632 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13633 "Replacing preferred"); 13634 } 13635 } 13636 13637 @Override 13638 public void clearPackagePreferredActivities(String packageName) { 13639 final int uid = Binder.getCallingUid(); 13640 // writer 13641 synchronized (mPackages) { 13642 PackageParser.Package pkg = mPackages.get(packageName); 13643 if (pkg == null || pkg.applicationInfo.uid != uid) { 13644 if (mContext.checkCallingOrSelfPermission( 13645 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13646 != PackageManager.PERMISSION_GRANTED) { 13647 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 13648 < Build.VERSION_CODES.FROYO) { 13649 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 13650 + Binder.getCallingUid()); 13651 return; 13652 } 13653 mContext.enforceCallingOrSelfPermission( 13654 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13655 } 13656 } 13657 13658 int user = UserHandle.getCallingUserId(); 13659 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 13660 scheduleWritePackageRestrictionsLocked(user); 13661 } 13662 } 13663 } 13664 13665 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13666 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 13667 ArrayList<PreferredActivity> removed = null; 13668 boolean changed = false; 13669 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13670 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 13671 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13672 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 13673 continue; 13674 } 13675 Iterator<PreferredActivity> it = pir.filterIterator(); 13676 while (it.hasNext()) { 13677 PreferredActivity pa = it.next(); 13678 // Mark entry for removal only if it matches the package name 13679 // and the entry is of type "always". 13680 if (packageName == null || 13681 (pa.mPref.mComponent.getPackageName().equals(packageName) 13682 && pa.mPref.mAlways)) { 13683 if (removed == null) { 13684 removed = new ArrayList<PreferredActivity>(); 13685 } 13686 removed.add(pa); 13687 } 13688 } 13689 if (removed != null) { 13690 for (int j=0; j<removed.size(); j++) { 13691 PreferredActivity pa = removed.get(j); 13692 pir.removeFilter(pa); 13693 } 13694 changed = true; 13695 } 13696 } 13697 return changed; 13698 } 13699 13700 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13701 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 13702 if (userId == UserHandle.USER_ALL) { 13703 if (mSettings.removeIntentFilterVerificationLPw(packageName, 13704 sUserManager.getUserIds())) { 13705 for (int oneUserId : sUserManager.getUserIds()) { 13706 scheduleWritePackageRestrictionsLocked(oneUserId); 13707 } 13708 } 13709 } else { 13710 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 13711 scheduleWritePackageRestrictionsLocked(userId); 13712 } 13713 } 13714 } 13715 13716 13717 void clearDefaultBrowserIfNeeded(String packageName) { 13718 for (int oneUserId : sUserManager.getUserIds()) { 13719 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 13720 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 13721 if (packageName.equals(defaultBrowserPackageName)) { 13722 setDefaultBrowserPackageName(null, oneUserId); 13723 } 13724 } 13725 } 13726 13727 @Override 13728 public void resetPreferredActivities(int userId) { 13729 mContext.enforceCallingOrSelfPermission( 13730 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13731 // writer 13732 synchronized (mPackages) { 13733 clearPackagePreferredActivitiesLPw(null, userId); 13734 mSettings.applyDefaultPreferredAppsLPw(this, userId); 13735 applyFactoryDefaultBrowserLPw(userId); 13736 primeDomainVerificationsLPw(userId); 13737 13738 scheduleWritePackageRestrictionsLocked(userId); 13739 } 13740 } 13741 13742 @Override 13743 public int getPreferredActivities(List<IntentFilter> outFilters, 13744 List<ComponentName> outActivities, String packageName) { 13745 13746 int num = 0; 13747 final int userId = UserHandle.getCallingUserId(); 13748 // reader 13749 synchronized (mPackages) { 13750 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13751 if (pir != null) { 13752 final Iterator<PreferredActivity> it = pir.filterIterator(); 13753 while (it.hasNext()) { 13754 final PreferredActivity pa = it.next(); 13755 if (packageName == null 13756 || (pa.mPref.mComponent.getPackageName().equals(packageName) 13757 && pa.mPref.mAlways)) { 13758 if (outFilters != null) { 13759 outFilters.add(new IntentFilter(pa)); 13760 } 13761 if (outActivities != null) { 13762 outActivities.add(pa.mPref.mComponent); 13763 } 13764 } 13765 } 13766 } 13767 } 13768 13769 return num; 13770 } 13771 13772 @Override 13773 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 13774 int userId) { 13775 int callingUid = Binder.getCallingUid(); 13776 if (callingUid != Process.SYSTEM_UID) { 13777 throw new SecurityException( 13778 "addPersistentPreferredActivity can only be run by the system"); 13779 } 13780 if (filter.countActions() == 0) { 13781 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13782 return; 13783 } 13784 synchronized (mPackages) { 13785 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 13786 " :"); 13787 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13788 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 13789 new PersistentPreferredActivity(filter, activity)); 13790 scheduleWritePackageRestrictionsLocked(userId); 13791 } 13792 } 13793 13794 @Override 13795 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 13796 int callingUid = Binder.getCallingUid(); 13797 if (callingUid != Process.SYSTEM_UID) { 13798 throw new SecurityException( 13799 "clearPackagePersistentPreferredActivities can only be run by the system"); 13800 } 13801 ArrayList<PersistentPreferredActivity> removed = null; 13802 boolean changed = false; 13803 synchronized (mPackages) { 13804 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 13805 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 13806 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 13807 .valueAt(i); 13808 if (userId != thisUserId) { 13809 continue; 13810 } 13811 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 13812 while (it.hasNext()) { 13813 PersistentPreferredActivity ppa = it.next(); 13814 // Mark entry for removal only if it matches the package name. 13815 if (ppa.mComponent.getPackageName().equals(packageName)) { 13816 if (removed == null) { 13817 removed = new ArrayList<PersistentPreferredActivity>(); 13818 } 13819 removed.add(ppa); 13820 } 13821 } 13822 if (removed != null) { 13823 for (int j=0; j<removed.size(); j++) { 13824 PersistentPreferredActivity ppa = removed.get(j); 13825 ppir.removeFilter(ppa); 13826 } 13827 changed = true; 13828 } 13829 } 13830 13831 if (changed) { 13832 scheduleWritePackageRestrictionsLocked(userId); 13833 } 13834 } 13835 } 13836 13837 /** 13838 * Common machinery for picking apart a restored XML blob and passing 13839 * it to a caller-supplied functor to be applied to the running system. 13840 */ 13841 private void restoreFromXml(XmlPullParser parser, int userId, 13842 String expectedStartTag, BlobXmlRestorer functor) 13843 throws IOException, XmlPullParserException { 13844 int type; 13845 while ((type = parser.next()) != XmlPullParser.START_TAG 13846 && type != XmlPullParser.END_DOCUMENT) { 13847 } 13848 if (type != XmlPullParser.START_TAG) { 13849 // oops didn't find a start tag?! 13850 if (DEBUG_BACKUP) { 13851 Slog.e(TAG, "Didn't find start tag during restore"); 13852 } 13853 return; 13854 } 13855 13856 // this is supposed to be TAG_PREFERRED_BACKUP 13857 if (!expectedStartTag.equals(parser.getName())) { 13858 if (DEBUG_BACKUP) { 13859 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 13860 } 13861 return; 13862 } 13863 13864 // skip interfering stuff, then we're aligned with the backing implementation 13865 while ((type = parser.next()) == XmlPullParser.TEXT) { } 13866 functor.apply(parser, userId); 13867 } 13868 13869 private interface BlobXmlRestorer { 13870 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 13871 } 13872 13873 /** 13874 * Non-Binder method, support for the backup/restore mechanism: write the 13875 * full set of preferred activities in its canonical XML format. Returns the 13876 * XML output as a byte array, or null if there is none. 13877 */ 13878 @Override 13879 public byte[] getPreferredActivityBackup(int userId) { 13880 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13881 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 13882 } 13883 13884 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13885 try { 13886 final XmlSerializer serializer = new FastXmlSerializer(); 13887 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13888 serializer.startDocument(null, true); 13889 serializer.startTag(null, TAG_PREFERRED_BACKUP); 13890 13891 synchronized (mPackages) { 13892 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 13893 } 13894 13895 serializer.endTag(null, TAG_PREFERRED_BACKUP); 13896 serializer.endDocument(); 13897 serializer.flush(); 13898 } catch (Exception e) { 13899 if (DEBUG_BACKUP) { 13900 Slog.e(TAG, "Unable to write preferred activities for backup", e); 13901 } 13902 return null; 13903 } 13904 13905 return dataStream.toByteArray(); 13906 } 13907 13908 @Override 13909 public void restorePreferredActivities(byte[] backup, int userId) { 13910 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13911 throw new SecurityException("Only the system may call restorePreferredActivities()"); 13912 } 13913 13914 try { 13915 final XmlPullParser parser = Xml.newPullParser(); 13916 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13917 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 13918 new BlobXmlRestorer() { 13919 @Override 13920 public void apply(XmlPullParser parser, int userId) 13921 throws XmlPullParserException, IOException { 13922 synchronized (mPackages) { 13923 mSettings.readPreferredActivitiesLPw(parser, userId); 13924 } 13925 } 13926 } ); 13927 } catch (Exception e) { 13928 if (DEBUG_BACKUP) { 13929 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 13930 } 13931 } 13932 } 13933 13934 /** 13935 * Non-Binder method, support for the backup/restore mechanism: write the 13936 * default browser (etc) settings in its canonical XML format. Returns the default 13937 * browser XML representation as a byte array, or null if there is none. 13938 */ 13939 @Override 13940 public byte[] getDefaultAppsBackup(int userId) { 13941 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13942 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 13943 } 13944 13945 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13946 try { 13947 final XmlSerializer serializer = new FastXmlSerializer(); 13948 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13949 serializer.startDocument(null, true); 13950 serializer.startTag(null, TAG_DEFAULT_APPS); 13951 13952 synchronized (mPackages) { 13953 mSettings.writeDefaultAppsLPr(serializer, userId); 13954 } 13955 13956 serializer.endTag(null, TAG_DEFAULT_APPS); 13957 serializer.endDocument(); 13958 serializer.flush(); 13959 } catch (Exception e) { 13960 if (DEBUG_BACKUP) { 13961 Slog.e(TAG, "Unable to write default apps for backup", e); 13962 } 13963 return null; 13964 } 13965 13966 return dataStream.toByteArray(); 13967 } 13968 13969 @Override 13970 public void restoreDefaultApps(byte[] backup, int userId) { 13971 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13972 throw new SecurityException("Only the system may call restoreDefaultApps()"); 13973 } 13974 13975 try { 13976 final XmlPullParser parser = Xml.newPullParser(); 13977 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13978 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 13979 new BlobXmlRestorer() { 13980 @Override 13981 public void apply(XmlPullParser parser, int userId) 13982 throws XmlPullParserException, IOException { 13983 synchronized (mPackages) { 13984 mSettings.readDefaultAppsLPw(parser, userId); 13985 } 13986 } 13987 } ); 13988 } catch (Exception e) { 13989 if (DEBUG_BACKUP) { 13990 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 13991 } 13992 } 13993 } 13994 13995 @Override 13996 public byte[] getIntentFilterVerificationBackup(int userId) { 13997 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13998 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 13999 } 14000 14001 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14002 try { 14003 final XmlSerializer serializer = new FastXmlSerializer(); 14004 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14005 serializer.startDocument(null, true); 14006 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 14007 14008 synchronized (mPackages) { 14009 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 14010 } 14011 14012 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 14013 serializer.endDocument(); 14014 serializer.flush(); 14015 } catch (Exception e) { 14016 if (DEBUG_BACKUP) { 14017 Slog.e(TAG, "Unable to write default apps for backup", e); 14018 } 14019 return null; 14020 } 14021 14022 return dataStream.toByteArray(); 14023 } 14024 14025 @Override 14026 public void restoreIntentFilterVerification(byte[] backup, int userId) { 14027 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14028 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14029 } 14030 14031 try { 14032 final XmlPullParser parser = Xml.newPullParser(); 14033 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14034 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 14035 new BlobXmlRestorer() { 14036 @Override 14037 public void apply(XmlPullParser parser, int userId) 14038 throws XmlPullParserException, IOException { 14039 synchronized (mPackages) { 14040 mSettings.readAllDomainVerificationsLPr(parser, userId); 14041 mSettings.writeLPr(); 14042 } 14043 } 14044 } ); 14045 } catch (Exception e) { 14046 if (DEBUG_BACKUP) { 14047 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14048 } 14049 } 14050 } 14051 14052 @Override 14053 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 14054 int sourceUserId, int targetUserId, int flags) { 14055 mContext.enforceCallingOrSelfPermission( 14056 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14057 int callingUid = Binder.getCallingUid(); 14058 enforceOwnerRights(ownerPackage, callingUid); 14059 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14060 if (intentFilter.countActions() == 0) { 14061 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 14062 return; 14063 } 14064 synchronized (mPackages) { 14065 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 14066 ownerPackage, targetUserId, flags); 14067 CrossProfileIntentResolver resolver = 14068 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14069 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 14070 // We have all those whose filter is equal. Now checking if the rest is equal as well. 14071 if (existing != null) { 14072 int size = existing.size(); 14073 for (int i = 0; i < size; i++) { 14074 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 14075 return; 14076 } 14077 } 14078 } 14079 resolver.addFilter(newFilter); 14080 scheduleWritePackageRestrictionsLocked(sourceUserId); 14081 } 14082 } 14083 14084 @Override 14085 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 14086 mContext.enforceCallingOrSelfPermission( 14087 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14088 int callingUid = Binder.getCallingUid(); 14089 enforceOwnerRights(ownerPackage, callingUid); 14090 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14091 synchronized (mPackages) { 14092 CrossProfileIntentResolver resolver = 14093 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14094 ArraySet<CrossProfileIntentFilter> set = 14095 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 14096 for (CrossProfileIntentFilter filter : set) { 14097 if (filter.getOwnerPackage().equals(ownerPackage)) { 14098 resolver.removeFilter(filter); 14099 } 14100 } 14101 scheduleWritePackageRestrictionsLocked(sourceUserId); 14102 } 14103 } 14104 14105 // Enforcing that callingUid is owning pkg on userId 14106 private void enforceOwnerRights(String pkg, int callingUid) { 14107 // The system owns everything. 14108 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 14109 return; 14110 } 14111 int callingUserId = UserHandle.getUserId(callingUid); 14112 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 14113 if (pi == null) { 14114 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 14115 + callingUserId); 14116 } 14117 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 14118 throw new SecurityException("Calling uid " + callingUid 14119 + " does not own package " + pkg); 14120 } 14121 } 14122 14123 @Override 14124 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 14125 Intent intent = new Intent(Intent.ACTION_MAIN); 14126 intent.addCategory(Intent.CATEGORY_HOME); 14127 14128 final int callingUserId = UserHandle.getCallingUserId(); 14129 List<ResolveInfo> list = queryIntentActivities(intent, null, 14130 PackageManager.GET_META_DATA, callingUserId); 14131 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 14132 true, false, false, callingUserId); 14133 14134 allHomeCandidates.clear(); 14135 if (list != null) { 14136 for (ResolveInfo ri : list) { 14137 allHomeCandidates.add(ri); 14138 } 14139 } 14140 return (preferred == null || preferred.activityInfo == null) 14141 ? null 14142 : new ComponentName(preferred.activityInfo.packageName, 14143 preferred.activityInfo.name); 14144 } 14145 14146 @Override 14147 public void setApplicationEnabledSetting(String appPackageName, 14148 int newState, int flags, int userId, String callingPackage) { 14149 if (!sUserManager.exists(userId)) return; 14150 if (callingPackage == null) { 14151 callingPackage = Integer.toString(Binder.getCallingUid()); 14152 } 14153 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 14154 } 14155 14156 @Override 14157 public void setComponentEnabledSetting(ComponentName componentName, 14158 int newState, int flags, int userId) { 14159 if (!sUserManager.exists(userId)) return; 14160 setEnabledSetting(componentName.getPackageName(), 14161 componentName.getClassName(), newState, flags, userId, null); 14162 } 14163 14164 private void setEnabledSetting(final String packageName, String className, int newState, 14165 final int flags, int userId, String callingPackage) { 14166 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 14167 || newState == COMPONENT_ENABLED_STATE_ENABLED 14168 || newState == COMPONENT_ENABLED_STATE_DISABLED 14169 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 14170 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 14171 throw new IllegalArgumentException("Invalid new component state: " 14172 + newState); 14173 } 14174 PackageSetting pkgSetting; 14175 final int uid = Binder.getCallingUid(); 14176 final int permission = mContext.checkCallingOrSelfPermission( 14177 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14178 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 14179 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14180 boolean sendNow = false; 14181 boolean isApp = (className == null); 14182 String componentName = isApp ? packageName : className; 14183 int packageUid = -1; 14184 ArrayList<String> components; 14185 14186 // writer 14187 synchronized (mPackages) { 14188 pkgSetting = mSettings.mPackages.get(packageName); 14189 if (pkgSetting == null) { 14190 if (className == null) { 14191 throw new IllegalArgumentException( 14192 "Unknown package: " + packageName); 14193 } 14194 throw new IllegalArgumentException( 14195 "Unknown component: " + packageName 14196 + "/" + className); 14197 } 14198 // Allow root and verify that userId is not being specified by a different user 14199 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 14200 throw new SecurityException( 14201 "Permission Denial: attempt to change component state from pid=" 14202 + Binder.getCallingPid() 14203 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 14204 } 14205 if (className == null) { 14206 // We're dealing with an application/package level state change 14207 if (pkgSetting.getEnabled(userId) == newState) { 14208 // Nothing to do 14209 return; 14210 } 14211 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 14212 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 14213 // Don't care about who enables an app. 14214 callingPackage = null; 14215 } 14216 pkgSetting.setEnabled(newState, userId, callingPackage); 14217 // pkgSetting.pkg.mSetEnabled = newState; 14218 } else { 14219 // We're dealing with a component level state change 14220 // First, verify that this is a valid class name. 14221 PackageParser.Package pkg = pkgSetting.pkg; 14222 if (pkg == null || !pkg.hasComponentClassName(className)) { 14223 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 14224 throw new IllegalArgumentException("Component class " + className 14225 + " does not exist in " + packageName); 14226 } else { 14227 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 14228 + className + " does not exist in " + packageName); 14229 } 14230 } 14231 switch (newState) { 14232 case COMPONENT_ENABLED_STATE_ENABLED: 14233 if (!pkgSetting.enableComponentLPw(className, userId)) { 14234 return; 14235 } 14236 break; 14237 case COMPONENT_ENABLED_STATE_DISABLED: 14238 if (!pkgSetting.disableComponentLPw(className, userId)) { 14239 return; 14240 } 14241 break; 14242 case COMPONENT_ENABLED_STATE_DEFAULT: 14243 if (!pkgSetting.restoreComponentLPw(className, userId)) { 14244 return; 14245 } 14246 break; 14247 default: 14248 Slog.e(TAG, "Invalid new component state: " + newState); 14249 return; 14250 } 14251 } 14252 scheduleWritePackageRestrictionsLocked(userId); 14253 components = mPendingBroadcasts.get(userId, packageName); 14254 final boolean newPackage = components == null; 14255 if (newPackage) { 14256 components = new ArrayList<String>(); 14257 } 14258 if (!components.contains(componentName)) { 14259 components.add(componentName); 14260 } 14261 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 14262 sendNow = true; 14263 // Purge entry from pending broadcast list if another one exists already 14264 // since we are sending one right away. 14265 mPendingBroadcasts.remove(userId, packageName); 14266 } else { 14267 if (newPackage) { 14268 mPendingBroadcasts.put(userId, packageName, components); 14269 } 14270 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 14271 // Schedule a message 14272 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 14273 } 14274 } 14275 } 14276 14277 long callingId = Binder.clearCallingIdentity(); 14278 try { 14279 if (sendNow) { 14280 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 14281 sendPackageChangedBroadcast(packageName, 14282 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 14283 } 14284 } finally { 14285 Binder.restoreCallingIdentity(callingId); 14286 } 14287 } 14288 14289 private void sendPackageChangedBroadcast(String packageName, 14290 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 14291 if (DEBUG_INSTALL) 14292 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 14293 + componentNames); 14294 Bundle extras = new Bundle(4); 14295 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 14296 String nameList[] = new String[componentNames.size()]; 14297 componentNames.toArray(nameList); 14298 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 14299 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 14300 extras.putInt(Intent.EXTRA_UID, packageUid); 14301 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 14302 new int[] {UserHandle.getUserId(packageUid)}); 14303 } 14304 14305 @Override 14306 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 14307 if (!sUserManager.exists(userId)) return; 14308 final int uid = Binder.getCallingUid(); 14309 final int permission = mContext.checkCallingOrSelfPermission( 14310 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14311 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14312 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 14313 // writer 14314 synchronized (mPackages) { 14315 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 14316 allowedByPermission, uid, userId)) { 14317 scheduleWritePackageRestrictionsLocked(userId); 14318 } 14319 } 14320 } 14321 14322 @Override 14323 public String getInstallerPackageName(String packageName) { 14324 // reader 14325 synchronized (mPackages) { 14326 return mSettings.getInstallerPackageNameLPr(packageName); 14327 } 14328 } 14329 14330 @Override 14331 public int getApplicationEnabledSetting(String packageName, int userId) { 14332 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14333 int uid = Binder.getCallingUid(); 14334 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 14335 // reader 14336 synchronized (mPackages) { 14337 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 14338 } 14339 } 14340 14341 @Override 14342 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 14343 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14344 int uid = Binder.getCallingUid(); 14345 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 14346 // reader 14347 synchronized (mPackages) { 14348 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 14349 } 14350 } 14351 14352 @Override 14353 public void enterSafeMode() { 14354 enforceSystemOrRoot("Only the system can request entering safe mode"); 14355 14356 if (!mSystemReady) { 14357 mSafeMode = true; 14358 } 14359 } 14360 14361 @Override 14362 public void systemReady() { 14363 mSystemReady = true; 14364 14365 // Read the compatibilty setting when the system is ready. 14366 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 14367 mContext.getContentResolver(), 14368 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 14369 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 14370 if (DEBUG_SETTINGS) { 14371 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 14372 } 14373 14374 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 14375 14376 synchronized (mPackages) { 14377 // Verify that all of the preferred activity components actually 14378 // exist. It is possible for applications to be updated and at 14379 // that point remove a previously declared activity component that 14380 // had been set as a preferred activity. We try to clean this up 14381 // the next time we encounter that preferred activity, but it is 14382 // possible for the user flow to never be able to return to that 14383 // situation so here we do a sanity check to make sure we haven't 14384 // left any junk around. 14385 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 14386 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14387 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14388 removed.clear(); 14389 for (PreferredActivity pa : pir.filterSet()) { 14390 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 14391 removed.add(pa); 14392 } 14393 } 14394 if (removed.size() > 0) { 14395 for (int r=0; r<removed.size(); r++) { 14396 PreferredActivity pa = removed.get(r); 14397 Slog.w(TAG, "Removing dangling preferred activity: " 14398 + pa.mPref.mComponent); 14399 pir.removeFilter(pa); 14400 } 14401 mSettings.writePackageRestrictionsLPr( 14402 mSettings.mPreferredActivities.keyAt(i)); 14403 } 14404 } 14405 14406 for (int userId : UserManagerService.getInstance().getUserIds()) { 14407 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 14408 grantPermissionsUserIds = ArrayUtils.appendInt( 14409 grantPermissionsUserIds, userId); 14410 } 14411 } 14412 } 14413 sUserManager.systemReady(); 14414 14415 // If we upgraded grant all default permissions before kicking off. 14416 for (int userId : grantPermissionsUserIds) { 14417 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 14418 } 14419 14420 // Kick off any messages waiting for system ready 14421 if (mPostSystemReadyMessages != null) { 14422 for (Message msg : mPostSystemReadyMessages) { 14423 msg.sendToTarget(); 14424 } 14425 mPostSystemReadyMessages = null; 14426 } 14427 14428 // Watch for external volumes that come and go over time 14429 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14430 storage.registerListener(mStorageListener); 14431 14432 mInstallerService.systemReady(); 14433 mPackageDexOptimizer.systemReady(); 14434 } 14435 14436 @Override 14437 public boolean isSafeMode() { 14438 return mSafeMode; 14439 } 14440 14441 @Override 14442 public boolean hasSystemUidErrors() { 14443 return mHasSystemUidErrors; 14444 } 14445 14446 static String arrayToString(int[] array) { 14447 StringBuffer buf = new StringBuffer(128); 14448 buf.append('['); 14449 if (array != null) { 14450 for (int i=0; i<array.length; i++) { 14451 if (i > 0) buf.append(", "); 14452 buf.append(array[i]); 14453 } 14454 } 14455 buf.append(']'); 14456 return buf.toString(); 14457 } 14458 14459 static class DumpState { 14460 public static final int DUMP_LIBS = 1 << 0; 14461 public static final int DUMP_FEATURES = 1 << 1; 14462 public static final int DUMP_RESOLVERS = 1 << 2; 14463 public static final int DUMP_PERMISSIONS = 1 << 3; 14464 public static final int DUMP_PACKAGES = 1 << 4; 14465 public static final int DUMP_SHARED_USERS = 1 << 5; 14466 public static final int DUMP_MESSAGES = 1 << 6; 14467 public static final int DUMP_PROVIDERS = 1 << 7; 14468 public static final int DUMP_VERIFIERS = 1 << 8; 14469 public static final int DUMP_PREFERRED = 1 << 9; 14470 public static final int DUMP_PREFERRED_XML = 1 << 10; 14471 public static final int DUMP_KEYSETS = 1 << 11; 14472 public static final int DUMP_VERSION = 1 << 12; 14473 public static final int DUMP_INSTALLS = 1 << 13; 14474 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 14475 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 14476 14477 public static final int OPTION_SHOW_FILTERS = 1 << 0; 14478 14479 private int mTypes; 14480 14481 private int mOptions; 14482 14483 private boolean mTitlePrinted; 14484 14485 private SharedUserSetting mSharedUser; 14486 14487 public boolean isDumping(int type) { 14488 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 14489 return true; 14490 } 14491 14492 return (mTypes & type) != 0; 14493 } 14494 14495 public void setDump(int type) { 14496 mTypes |= type; 14497 } 14498 14499 public boolean isOptionEnabled(int option) { 14500 return (mOptions & option) != 0; 14501 } 14502 14503 public void setOptionEnabled(int option) { 14504 mOptions |= option; 14505 } 14506 14507 public boolean onTitlePrinted() { 14508 final boolean printed = mTitlePrinted; 14509 mTitlePrinted = true; 14510 return printed; 14511 } 14512 14513 public boolean getTitlePrinted() { 14514 return mTitlePrinted; 14515 } 14516 14517 public void setTitlePrinted(boolean enabled) { 14518 mTitlePrinted = enabled; 14519 } 14520 14521 public SharedUserSetting getSharedUser() { 14522 return mSharedUser; 14523 } 14524 14525 public void setSharedUser(SharedUserSetting user) { 14526 mSharedUser = user; 14527 } 14528 } 14529 14530 @Override 14531 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 14532 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 14533 != PackageManager.PERMISSION_GRANTED) { 14534 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 14535 + Binder.getCallingPid() 14536 + ", uid=" + Binder.getCallingUid() 14537 + " without permission " 14538 + android.Manifest.permission.DUMP); 14539 return; 14540 } 14541 14542 DumpState dumpState = new DumpState(); 14543 boolean fullPreferred = false; 14544 boolean checkin = false; 14545 14546 String packageName = null; 14547 ArraySet<String> permissionNames = null; 14548 14549 int opti = 0; 14550 while (opti < args.length) { 14551 String opt = args[opti]; 14552 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 14553 break; 14554 } 14555 opti++; 14556 14557 if ("-a".equals(opt)) { 14558 // Right now we only know how to print all. 14559 } else if ("-h".equals(opt)) { 14560 pw.println("Package manager dump options:"); 14561 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 14562 pw.println(" --checkin: dump for a checkin"); 14563 pw.println(" -f: print details of intent filters"); 14564 pw.println(" -h: print this help"); 14565 pw.println(" cmd may be one of:"); 14566 pw.println(" l[ibraries]: list known shared libraries"); 14567 pw.println(" f[ibraries]: list device features"); 14568 pw.println(" k[eysets]: print known keysets"); 14569 pw.println(" r[esolvers]: dump intent resolvers"); 14570 pw.println(" perm[issions]: dump permissions"); 14571 pw.println(" permission [name ...]: dump declaration and use of given permission"); 14572 pw.println(" pref[erred]: print preferred package settings"); 14573 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 14574 pw.println(" prov[iders]: dump content providers"); 14575 pw.println(" p[ackages]: dump installed packages"); 14576 pw.println(" s[hared-users]: dump shared user IDs"); 14577 pw.println(" m[essages]: print collected runtime messages"); 14578 pw.println(" v[erifiers]: print package verifier info"); 14579 pw.println(" version: print database version info"); 14580 pw.println(" write: write current settings now"); 14581 pw.println(" <package.name>: info about given package"); 14582 pw.println(" installs: details about install sessions"); 14583 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 14584 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 14585 return; 14586 } else if ("--checkin".equals(opt)) { 14587 checkin = true; 14588 } else if ("-f".equals(opt)) { 14589 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14590 } else { 14591 pw.println("Unknown argument: " + opt + "; use -h for help"); 14592 } 14593 } 14594 14595 // Is the caller requesting to dump a particular piece of data? 14596 if (opti < args.length) { 14597 String cmd = args[opti]; 14598 opti++; 14599 // Is this a package name? 14600 if ("android".equals(cmd) || cmd.contains(".")) { 14601 packageName = cmd; 14602 // When dumping a single package, we always dump all of its 14603 // filter information since the amount of data will be reasonable. 14604 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14605 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 14606 dumpState.setDump(DumpState.DUMP_LIBS); 14607 } else if ("f".equals(cmd) || "features".equals(cmd)) { 14608 dumpState.setDump(DumpState.DUMP_FEATURES); 14609 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 14610 dumpState.setDump(DumpState.DUMP_RESOLVERS); 14611 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 14612 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 14613 } else if ("permission".equals(cmd)) { 14614 if (opti >= args.length) { 14615 pw.println("Error: permission requires permission name"); 14616 return; 14617 } 14618 permissionNames = new ArraySet<>(); 14619 while (opti < args.length) { 14620 permissionNames.add(args[opti]); 14621 opti++; 14622 } 14623 dumpState.setDump(DumpState.DUMP_PERMISSIONS 14624 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 14625 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 14626 dumpState.setDump(DumpState.DUMP_PREFERRED); 14627 } else if ("preferred-xml".equals(cmd)) { 14628 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 14629 if (opti < args.length && "--full".equals(args[opti])) { 14630 fullPreferred = true; 14631 opti++; 14632 } 14633 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 14634 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 14635 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 14636 dumpState.setDump(DumpState.DUMP_PACKAGES); 14637 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 14638 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 14639 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 14640 dumpState.setDump(DumpState.DUMP_PROVIDERS); 14641 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 14642 dumpState.setDump(DumpState.DUMP_MESSAGES); 14643 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 14644 dumpState.setDump(DumpState.DUMP_VERIFIERS); 14645 } else if ("i".equals(cmd) || "ifv".equals(cmd) 14646 || "intent-filter-verifiers".equals(cmd)) { 14647 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 14648 } else if ("version".equals(cmd)) { 14649 dumpState.setDump(DumpState.DUMP_VERSION); 14650 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 14651 dumpState.setDump(DumpState.DUMP_KEYSETS); 14652 } else if ("installs".equals(cmd)) { 14653 dumpState.setDump(DumpState.DUMP_INSTALLS); 14654 } else if ("write".equals(cmd)) { 14655 synchronized (mPackages) { 14656 mSettings.writeLPr(); 14657 pw.println("Settings written."); 14658 return; 14659 } 14660 } 14661 } 14662 14663 if (checkin) { 14664 pw.println("vers,1"); 14665 } 14666 14667 // reader 14668 synchronized (mPackages) { 14669 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 14670 if (!checkin) { 14671 if (dumpState.onTitlePrinted()) 14672 pw.println(); 14673 pw.println("Database versions:"); 14674 pw.print(" SDK Version:"); 14675 pw.print(" internal="); 14676 pw.print(mSettings.mInternalSdkPlatform); 14677 pw.print(" external="); 14678 pw.println(mSettings.mExternalSdkPlatform); 14679 pw.print(" DB Version:"); 14680 pw.print(" internal="); 14681 pw.print(mSettings.mInternalDatabaseVersion); 14682 pw.print(" external="); 14683 pw.println(mSettings.mExternalDatabaseVersion); 14684 } 14685 } 14686 14687 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 14688 if (!checkin) { 14689 if (dumpState.onTitlePrinted()) 14690 pw.println(); 14691 pw.println("Verifiers:"); 14692 pw.print(" Required: "); 14693 pw.print(mRequiredVerifierPackage); 14694 pw.print(" (uid="); 14695 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 14696 pw.println(")"); 14697 } else if (mRequiredVerifierPackage != null) { 14698 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 14699 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 14700 } 14701 } 14702 14703 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 14704 packageName == null) { 14705 if (mIntentFilterVerifierComponent != null) { 14706 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 14707 if (!checkin) { 14708 if (dumpState.onTitlePrinted()) 14709 pw.println(); 14710 pw.println("Intent Filter Verifier:"); 14711 pw.print(" Using: "); 14712 pw.print(verifierPackageName); 14713 pw.print(" (uid="); 14714 pw.print(getPackageUid(verifierPackageName, 0)); 14715 pw.println(")"); 14716 } else if (verifierPackageName != null) { 14717 pw.print("ifv,"); pw.print(verifierPackageName); 14718 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 14719 } 14720 } else { 14721 pw.println(); 14722 pw.println("No Intent Filter Verifier available!"); 14723 } 14724 } 14725 14726 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 14727 boolean printedHeader = false; 14728 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 14729 while (it.hasNext()) { 14730 String name = it.next(); 14731 SharedLibraryEntry ent = mSharedLibraries.get(name); 14732 if (!checkin) { 14733 if (!printedHeader) { 14734 if (dumpState.onTitlePrinted()) 14735 pw.println(); 14736 pw.println("Libraries:"); 14737 printedHeader = true; 14738 } 14739 pw.print(" "); 14740 } else { 14741 pw.print("lib,"); 14742 } 14743 pw.print(name); 14744 if (!checkin) { 14745 pw.print(" -> "); 14746 } 14747 if (ent.path != null) { 14748 if (!checkin) { 14749 pw.print("(jar) "); 14750 pw.print(ent.path); 14751 } else { 14752 pw.print(",jar,"); 14753 pw.print(ent.path); 14754 } 14755 } else { 14756 if (!checkin) { 14757 pw.print("(apk) "); 14758 pw.print(ent.apk); 14759 } else { 14760 pw.print(",apk,"); 14761 pw.print(ent.apk); 14762 } 14763 } 14764 pw.println(); 14765 } 14766 } 14767 14768 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 14769 if (dumpState.onTitlePrinted()) 14770 pw.println(); 14771 if (!checkin) { 14772 pw.println("Features:"); 14773 } 14774 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 14775 while (it.hasNext()) { 14776 String name = it.next(); 14777 if (!checkin) { 14778 pw.print(" "); 14779 } else { 14780 pw.print("feat,"); 14781 } 14782 pw.println(name); 14783 } 14784 } 14785 14786 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 14787 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 14788 : "Activity Resolver Table:", " ", packageName, 14789 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14790 dumpState.setTitlePrinted(true); 14791 } 14792 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 14793 : "Receiver Resolver Table:", " ", packageName, 14794 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14795 dumpState.setTitlePrinted(true); 14796 } 14797 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 14798 : "Service Resolver Table:", " ", packageName, 14799 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14800 dumpState.setTitlePrinted(true); 14801 } 14802 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 14803 : "Provider Resolver Table:", " ", packageName, 14804 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14805 dumpState.setTitlePrinted(true); 14806 } 14807 } 14808 14809 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 14810 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14811 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14812 int user = mSettings.mPreferredActivities.keyAt(i); 14813 if (pir.dump(pw, 14814 dumpState.getTitlePrinted() 14815 ? "\nPreferred Activities User " + user + ":" 14816 : "Preferred Activities User " + user + ":", " ", 14817 packageName, true, false)) { 14818 dumpState.setTitlePrinted(true); 14819 } 14820 } 14821 } 14822 14823 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 14824 pw.flush(); 14825 FileOutputStream fout = new FileOutputStream(fd); 14826 BufferedOutputStream str = new BufferedOutputStream(fout); 14827 XmlSerializer serializer = new FastXmlSerializer(); 14828 try { 14829 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 14830 serializer.startDocument(null, true); 14831 serializer.setFeature( 14832 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 14833 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 14834 serializer.endDocument(); 14835 serializer.flush(); 14836 } catch (IllegalArgumentException e) { 14837 pw.println("Failed writing: " + e); 14838 } catch (IllegalStateException e) { 14839 pw.println("Failed writing: " + e); 14840 } catch (IOException e) { 14841 pw.println("Failed writing: " + e); 14842 } 14843 } 14844 14845 if (!checkin 14846 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 14847 && packageName == null) { 14848 pw.println(); 14849 int count = mSettings.mPackages.size(); 14850 if (count == 0) { 14851 pw.println("No applications!"); 14852 pw.println(); 14853 } else { 14854 final String prefix = " "; 14855 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 14856 if (allPackageSettings.size() == 0) { 14857 pw.println("No domain preferred apps!"); 14858 pw.println(); 14859 } else { 14860 pw.println("App verification status:"); 14861 pw.println(); 14862 count = 0; 14863 for (PackageSetting ps : allPackageSettings) { 14864 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 14865 if (ivi == null || ivi.getPackageName() == null) continue; 14866 pw.println(prefix + "Package: " + ivi.getPackageName()); 14867 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 14868 pw.println(prefix + "Status: " + ivi.getStatusString()); 14869 pw.println(); 14870 count++; 14871 } 14872 if (count == 0) { 14873 pw.println(prefix + "No app verification established."); 14874 pw.println(); 14875 } 14876 for (int userId : sUserManager.getUserIds()) { 14877 pw.println("App linkages for user " + userId + ":"); 14878 pw.println(); 14879 count = 0; 14880 for (PackageSetting ps : allPackageSettings) { 14881 final int status = ps.getDomainVerificationStatusForUser(userId); 14882 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 14883 continue; 14884 } 14885 pw.println(prefix + "Package: " + ps.name); 14886 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 14887 String statusStr = IntentFilterVerificationInfo. 14888 getStatusStringFromValue(status); 14889 pw.println(prefix + "Status: " + statusStr); 14890 pw.println(); 14891 count++; 14892 } 14893 if (count == 0) { 14894 pw.println(prefix + "No configured app linkages."); 14895 pw.println(); 14896 } 14897 } 14898 } 14899 } 14900 } 14901 14902 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 14903 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 14904 if (packageName == null && permissionNames == null) { 14905 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 14906 if (iperm == 0) { 14907 if (dumpState.onTitlePrinted()) 14908 pw.println(); 14909 pw.println("AppOp Permissions:"); 14910 } 14911 pw.print(" AppOp Permission "); 14912 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 14913 pw.println(":"); 14914 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 14915 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 14916 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 14917 } 14918 } 14919 } 14920 } 14921 14922 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 14923 boolean printedSomething = false; 14924 for (PackageParser.Provider p : mProviders.mProviders.values()) { 14925 if (packageName != null && !packageName.equals(p.info.packageName)) { 14926 continue; 14927 } 14928 if (!printedSomething) { 14929 if (dumpState.onTitlePrinted()) 14930 pw.println(); 14931 pw.println("Registered ContentProviders:"); 14932 printedSomething = true; 14933 } 14934 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 14935 pw.print(" "); pw.println(p.toString()); 14936 } 14937 printedSomething = false; 14938 for (Map.Entry<String, PackageParser.Provider> entry : 14939 mProvidersByAuthority.entrySet()) { 14940 PackageParser.Provider p = entry.getValue(); 14941 if (packageName != null && !packageName.equals(p.info.packageName)) { 14942 continue; 14943 } 14944 if (!printedSomething) { 14945 if (dumpState.onTitlePrinted()) 14946 pw.println(); 14947 pw.println("ContentProvider Authorities:"); 14948 printedSomething = true; 14949 } 14950 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 14951 pw.print(" "); pw.println(p.toString()); 14952 if (p.info != null && p.info.applicationInfo != null) { 14953 final String appInfo = p.info.applicationInfo.toString(); 14954 pw.print(" applicationInfo="); pw.println(appInfo); 14955 } 14956 } 14957 } 14958 14959 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 14960 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 14961 } 14962 14963 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 14964 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 14965 } 14966 14967 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 14968 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 14969 } 14970 14971 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 14972 // XXX should handle packageName != null by dumping only install data that 14973 // the given package is involved with. 14974 if (dumpState.onTitlePrinted()) pw.println(); 14975 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 14976 } 14977 14978 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 14979 if (dumpState.onTitlePrinted()) pw.println(); 14980 mSettings.dumpReadMessagesLPr(pw, dumpState); 14981 14982 pw.println(); 14983 pw.println("Package warning messages:"); 14984 BufferedReader in = null; 14985 String line = null; 14986 try { 14987 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 14988 while ((line = in.readLine()) != null) { 14989 if (line.contains("ignored: updated version")) continue; 14990 pw.println(line); 14991 } 14992 } catch (IOException ignored) { 14993 } finally { 14994 IoUtils.closeQuietly(in); 14995 } 14996 } 14997 14998 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 14999 BufferedReader in = null; 15000 String line = null; 15001 try { 15002 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15003 while ((line = in.readLine()) != null) { 15004 if (line.contains("ignored: updated version")) continue; 15005 pw.print("msg,"); 15006 pw.println(line); 15007 } 15008 } catch (IOException ignored) { 15009 } finally { 15010 IoUtils.closeQuietly(in); 15011 } 15012 } 15013 } 15014 } 15015 15016 private String dumpDomainString(String packageName) { 15017 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName); 15018 List<IntentFilter> filters = getAllIntentFilters(packageName); 15019 15020 ArraySet<String> result = new ArraySet<>(); 15021 if (iviList.size() > 0) { 15022 for (IntentFilterVerificationInfo ivi : iviList) { 15023 for (String host : ivi.getDomains()) { 15024 result.add(host); 15025 } 15026 } 15027 } 15028 if (filters != null && filters.size() > 0) { 15029 for (IntentFilter filter : filters) { 15030 if (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 15031 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)) { 15032 result.addAll(filter.getHostsList()); 15033 } 15034 } 15035 } 15036 15037 StringBuilder sb = new StringBuilder(result.size() * 16); 15038 for (String domain : result) { 15039 if (sb.length() > 0) sb.append(" "); 15040 sb.append(domain); 15041 } 15042 return sb.toString(); 15043 } 15044 15045 // ------- apps on sdcard specific code ------- 15046 static final boolean DEBUG_SD_INSTALL = false; 15047 15048 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 15049 15050 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 15051 15052 private boolean mMediaMounted = false; 15053 15054 static String getEncryptKey() { 15055 try { 15056 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 15057 SD_ENCRYPTION_KEYSTORE_NAME); 15058 if (sdEncKey == null) { 15059 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 15060 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 15061 if (sdEncKey == null) { 15062 Slog.e(TAG, "Failed to create encryption keys"); 15063 return null; 15064 } 15065 } 15066 return sdEncKey; 15067 } catch (NoSuchAlgorithmException nsae) { 15068 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 15069 return null; 15070 } catch (IOException ioe) { 15071 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 15072 return null; 15073 } 15074 } 15075 15076 /* 15077 * Update media status on PackageManager. 15078 */ 15079 @Override 15080 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 15081 int callingUid = Binder.getCallingUid(); 15082 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 15083 throw new SecurityException("Media status can only be updated by the system"); 15084 } 15085 // reader; this apparently protects mMediaMounted, but should probably 15086 // be a different lock in that case. 15087 synchronized (mPackages) { 15088 Log.i(TAG, "Updating external media status from " 15089 + (mMediaMounted ? "mounted" : "unmounted") + " to " 15090 + (mediaStatus ? "mounted" : "unmounted")); 15091 if (DEBUG_SD_INSTALL) 15092 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 15093 + ", mMediaMounted=" + mMediaMounted); 15094 if (mediaStatus == mMediaMounted) { 15095 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 15096 : 0, -1); 15097 mHandler.sendMessage(msg); 15098 return; 15099 } 15100 mMediaMounted = mediaStatus; 15101 } 15102 // Queue up an async operation since the package installation may take a 15103 // little while. 15104 mHandler.post(new Runnable() { 15105 public void run() { 15106 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 15107 } 15108 }); 15109 } 15110 15111 /** 15112 * Called by MountService when the initial ASECs to scan are available. 15113 * Should block until all the ASEC containers are finished being scanned. 15114 */ 15115 public void scanAvailableAsecs() { 15116 updateExternalMediaStatusInner(true, false, false); 15117 if (mShouldRestoreconData) { 15118 SELinuxMMAC.setRestoreconDone(); 15119 mShouldRestoreconData = false; 15120 } 15121 } 15122 15123 /* 15124 * Collect information of applications on external media, map them against 15125 * existing containers and update information based on current mount status. 15126 * Please note that we always have to report status if reportStatus has been 15127 * set to true especially when unloading packages. 15128 */ 15129 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 15130 boolean externalStorage) { 15131 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 15132 int[] uidArr = EmptyArray.INT; 15133 15134 final String[] list = PackageHelper.getSecureContainerList(); 15135 if (ArrayUtils.isEmpty(list)) { 15136 Log.i(TAG, "No secure containers found"); 15137 } else { 15138 // Process list of secure containers and categorize them 15139 // as active or stale based on their package internal state. 15140 15141 // reader 15142 synchronized (mPackages) { 15143 for (String cid : list) { 15144 // Leave stages untouched for now; installer service owns them 15145 if (PackageInstallerService.isStageName(cid)) continue; 15146 15147 if (DEBUG_SD_INSTALL) 15148 Log.i(TAG, "Processing container " + cid); 15149 String pkgName = getAsecPackageName(cid); 15150 if (pkgName == null) { 15151 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 15152 continue; 15153 } 15154 if (DEBUG_SD_INSTALL) 15155 Log.i(TAG, "Looking for pkg : " + pkgName); 15156 15157 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15158 if (ps == null) { 15159 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 15160 continue; 15161 } 15162 15163 /* 15164 * Skip packages that are not external if we're unmounting 15165 * external storage. 15166 */ 15167 if (externalStorage && !isMounted && !isExternal(ps)) { 15168 continue; 15169 } 15170 15171 final AsecInstallArgs args = new AsecInstallArgs(cid, 15172 getAppDexInstructionSets(ps), ps.isForwardLocked()); 15173 // The package status is changed only if the code path 15174 // matches between settings and the container id. 15175 if (ps.codePathString != null 15176 && ps.codePathString.startsWith(args.getCodePath())) { 15177 if (DEBUG_SD_INSTALL) { 15178 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 15179 + " at code path: " + ps.codePathString); 15180 } 15181 15182 // We do have a valid package installed on sdcard 15183 processCids.put(args, ps.codePathString); 15184 final int uid = ps.appId; 15185 if (uid != -1) { 15186 uidArr = ArrayUtils.appendInt(uidArr, uid); 15187 } 15188 } else { 15189 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 15190 + ps.codePathString); 15191 } 15192 } 15193 } 15194 15195 Arrays.sort(uidArr); 15196 } 15197 15198 // Process packages with valid entries. 15199 if (isMounted) { 15200 if (DEBUG_SD_INSTALL) 15201 Log.i(TAG, "Loading packages"); 15202 loadMediaPackages(processCids, uidArr); 15203 startCleaningPackages(); 15204 mInstallerService.onSecureContainersAvailable(); 15205 } else { 15206 if (DEBUG_SD_INSTALL) 15207 Log.i(TAG, "Unloading packages"); 15208 unloadMediaPackages(processCids, uidArr, reportStatus); 15209 } 15210 } 15211 15212 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15213 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 15214 final int size = infos.size(); 15215 final String[] packageNames = new String[size]; 15216 final int[] packageUids = new int[size]; 15217 for (int i = 0; i < size; i++) { 15218 final ApplicationInfo info = infos.get(i); 15219 packageNames[i] = info.packageName; 15220 packageUids[i] = info.uid; 15221 } 15222 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 15223 finishedReceiver); 15224 } 15225 15226 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15227 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15228 sendResourcesChangedBroadcast(mediaStatus, replacing, 15229 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 15230 } 15231 15232 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15233 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15234 int size = pkgList.length; 15235 if (size > 0) { 15236 // Send broadcasts here 15237 Bundle extras = new Bundle(); 15238 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 15239 if (uidArr != null) { 15240 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 15241 } 15242 if (replacing) { 15243 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 15244 } 15245 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 15246 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 15247 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 15248 } 15249 } 15250 15251 /* 15252 * Look at potentially valid container ids from processCids If package 15253 * information doesn't match the one on record or package scanning fails, 15254 * the cid is added to list of removeCids. We currently don't delete stale 15255 * containers. 15256 */ 15257 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 15258 ArrayList<String> pkgList = new ArrayList<String>(); 15259 Set<AsecInstallArgs> keys = processCids.keySet(); 15260 15261 for (AsecInstallArgs args : keys) { 15262 String codePath = processCids.get(args); 15263 if (DEBUG_SD_INSTALL) 15264 Log.i(TAG, "Loading container : " + args.cid); 15265 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15266 try { 15267 // Make sure there are no container errors first. 15268 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 15269 Slog.e(TAG, "Failed to mount cid : " + args.cid 15270 + " when installing from sdcard"); 15271 continue; 15272 } 15273 // Check code path here. 15274 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 15275 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 15276 + " does not match one in settings " + codePath); 15277 continue; 15278 } 15279 // Parse package 15280 int parseFlags = mDefParseFlags; 15281 if (args.isExternalAsec()) { 15282 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 15283 } 15284 if (args.isFwdLocked()) { 15285 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 15286 } 15287 15288 synchronized (mInstallLock) { 15289 PackageParser.Package pkg = null; 15290 try { 15291 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 15292 } catch (PackageManagerException e) { 15293 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 15294 } 15295 // Scan the package 15296 if (pkg != null) { 15297 /* 15298 * TODO why is the lock being held? doPostInstall is 15299 * called in other places without the lock. This needs 15300 * to be straightened out. 15301 */ 15302 // writer 15303 synchronized (mPackages) { 15304 retCode = PackageManager.INSTALL_SUCCEEDED; 15305 pkgList.add(pkg.packageName); 15306 // Post process args 15307 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 15308 pkg.applicationInfo.uid); 15309 } 15310 } else { 15311 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 15312 } 15313 } 15314 15315 } finally { 15316 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 15317 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 15318 } 15319 } 15320 } 15321 // writer 15322 synchronized (mPackages) { 15323 // If the platform SDK has changed since the last time we booted, 15324 // we need to re-grant app permission to catch any new ones that 15325 // appear. This is really a hack, and means that apps can in some 15326 // cases get permissions that the user didn't initially explicitly 15327 // allow... it would be nice to have some better way to handle 15328 // this situation. 15329 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 15330 if (regrantPermissions) 15331 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 15332 + mSdkVersion + "; regranting permissions for external storage"); 15333 mSettings.mExternalSdkPlatform = mSdkVersion; 15334 15335 // Make sure group IDs have been assigned, and any permission 15336 // changes in other apps are accounted for 15337 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 15338 | (regrantPermissions 15339 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 15340 : 0)); 15341 15342 mSettings.updateExternalDatabaseVersion(); 15343 15344 // can downgrade to reader 15345 // Persist settings 15346 mSettings.writeLPr(); 15347 } 15348 // Send a broadcast to let everyone know we are done processing 15349 if (pkgList.size() > 0) { 15350 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 15351 } 15352 } 15353 15354 /* 15355 * Utility method to unload a list of specified containers 15356 */ 15357 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 15358 // Just unmount all valid containers. 15359 for (AsecInstallArgs arg : cidArgs) { 15360 synchronized (mInstallLock) { 15361 arg.doPostDeleteLI(false); 15362 } 15363 } 15364 } 15365 15366 /* 15367 * Unload packages mounted on external media. This involves deleting package 15368 * data from internal structures, sending broadcasts about diabled packages, 15369 * gc'ing to free up references, unmounting all secure containers 15370 * corresponding to packages on external media, and posting a 15371 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 15372 * that we always have to post this message if status has been requested no 15373 * matter what. 15374 */ 15375 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 15376 final boolean reportStatus) { 15377 if (DEBUG_SD_INSTALL) 15378 Log.i(TAG, "unloading media packages"); 15379 ArrayList<String> pkgList = new ArrayList<String>(); 15380 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 15381 final Set<AsecInstallArgs> keys = processCids.keySet(); 15382 for (AsecInstallArgs args : keys) { 15383 String pkgName = args.getPackageName(); 15384 if (DEBUG_SD_INSTALL) 15385 Log.i(TAG, "Trying to unload pkg : " + pkgName); 15386 // Delete package internally 15387 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15388 synchronized (mInstallLock) { 15389 boolean res = deletePackageLI(pkgName, null, false, null, null, 15390 PackageManager.DELETE_KEEP_DATA, outInfo, false); 15391 if (res) { 15392 pkgList.add(pkgName); 15393 } else { 15394 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 15395 failedList.add(args); 15396 } 15397 } 15398 } 15399 15400 // reader 15401 synchronized (mPackages) { 15402 // We didn't update the settings after removing each package; 15403 // write them now for all packages. 15404 mSettings.writeLPr(); 15405 } 15406 15407 // We have to absolutely send UPDATED_MEDIA_STATUS only 15408 // after confirming that all the receivers processed the ordered 15409 // broadcast when packages get disabled, force a gc to clean things up. 15410 // and unload all the containers. 15411 if (pkgList.size() > 0) { 15412 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 15413 new IIntentReceiver.Stub() { 15414 public void performReceive(Intent intent, int resultCode, String data, 15415 Bundle extras, boolean ordered, boolean sticky, 15416 int sendingUser) throws RemoteException { 15417 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 15418 reportStatus ? 1 : 0, 1, keys); 15419 mHandler.sendMessage(msg); 15420 } 15421 }); 15422 } else { 15423 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 15424 keys); 15425 mHandler.sendMessage(msg); 15426 } 15427 } 15428 15429 private void loadPrivatePackages(VolumeInfo vol) { 15430 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 15431 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 15432 synchronized (mInstallLock) { 15433 synchronized (mPackages) { 15434 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15435 for (PackageSetting ps : packages) { 15436 final PackageParser.Package pkg; 15437 try { 15438 pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null); 15439 loaded.add(pkg.applicationInfo); 15440 } catch (PackageManagerException e) { 15441 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 15442 } 15443 } 15444 15445 // TODO: regrant any permissions that changed based since original install 15446 15447 mSettings.writeLPr(); 15448 } 15449 } 15450 15451 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 15452 sendResourcesChangedBroadcast(true, false, loaded, null); 15453 } 15454 15455 private void unloadPrivatePackages(VolumeInfo vol) { 15456 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 15457 synchronized (mInstallLock) { 15458 synchronized (mPackages) { 15459 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15460 for (PackageSetting ps : packages) { 15461 if (ps.pkg == null) continue; 15462 15463 final ApplicationInfo info = ps.pkg.applicationInfo; 15464 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15465 if (deletePackageLI(ps.name, null, false, null, null, 15466 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 15467 unloaded.add(info); 15468 } else { 15469 Slog.w(TAG, "Failed to unload " + ps.codePath); 15470 } 15471 } 15472 15473 mSettings.writeLPr(); 15474 } 15475 } 15476 15477 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 15478 sendResourcesChangedBroadcast(false, false, unloaded, null); 15479 } 15480 15481 /** 15482 * Examine all users present on given mounted volume, and destroy data 15483 * belonging to users that are no longer valid, or whose user ID has been 15484 * recycled. 15485 */ 15486 private void reconcileUsers(String volumeUuid) { 15487 final File[] files = Environment.getDataUserDirectory(volumeUuid).listFiles(); 15488 if (ArrayUtils.isEmpty(files)) { 15489 Slog.d(TAG, "No users found on " + volumeUuid); 15490 return; 15491 } 15492 15493 for (File file : files) { 15494 if (!file.isDirectory()) continue; 15495 15496 final int userId; 15497 final UserInfo info; 15498 try { 15499 userId = Integer.parseInt(file.getName()); 15500 info = sUserManager.getUserInfo(userId); 15501 } catch (NumberFormatException e) { 15502 Slog.w(TAG, "Invalid user directory " + file); 15503 continue; 15504 } 15505 15506 boolean destroyUser = false; 15507 if (info == null) { 15508 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15509 + " because no matching user was found"); 15510 destroyUser = true; 15511 } else { 15512 try { 15513 UserManagerService.enforceSerialNumber(file, info.serialNumber); 15514 } catch (IOException e) { 15515 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15516 + " because we failed to enforce serial number: " + e); 15517 destroyUser = true; 15518 } 15519 } 15520 15521 if (destroyUser) { 15522 synchronized (mInstallLock) { 15523 mInstaller.removeUserDataDirs(volumeUuid, userId); 15524 } 15525 } 15526 } 15527 15528 final UserManager um = mContext.getSystemService(UserManager.class); 15529 for (UserInfo user : um.getUsers()) { 15530 final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id); 15531 if (userDir.exists()) continue; 15532 15533 try { 15534 UserManagerService.prepareUserDirectory(userDir); 15535 UserManagerService.enforceSerialNumber(userDir, user.serialNumber); 15536 } catch (IOException e) { 15537 Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e); 15538 } 15539 } 15540 } 15541 15542 /** 15543 * Examine all apps present on given mounted volume, and destroy apps that 15544 * aren't expected, either due to uninstallation or reinstallation on 15545 * another volume. 15546 */ 15547 private void reconcileApps(String volumeUuid) { 15548 final File[] files = Environment.getDataAppDirectory(volumeUuid).listFiles(); 15549 if (ArrayUtils.isEmpty(files)) { 15550 Slog.d(TAG, "No apps found on " + volumeUuid); 15551 return; 15552 } 15553 15554 for (File file : files) { 15555 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 15556 && !PackageInstallerService.isStageName(file.getName()); 15557 if (!isPackage) { 15558 // Ignore entries which are not packages 15559 continue; 15560 } 15561 15562 boolean destroyApp = false; 15563 String packageName = null; 15564 try { 15565 final PackageLite pkg = PackageParser.parsePackageLite(file, 15566 PackageParser.PARSE_MUST_BE_APK); 15567 packageName = pkg.packageName; 15568 15569 synchronized (mPackages) { 15570 final PackageSetting ps = mSettings.mPackages.get(packageName); 15571 if (ps == null) { 15572 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + " 15573 + volumeUuid + " because we found no install record"); 15574 destroyApp = true; 15575 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 15576 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on " 15577 + volumeUuid + " because we expected it on " + ps.volumeUuid); 15578 destroyApp = true; 15579 } 15580 } 15581 15582 } catch (PackageParserException e) { 15583 logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e); 15584 destroyApp = true; 15585 } 15586 15587 if (destroyApp) { 15588 synchronized (mInstallLock) { 15589 if (packageName != null) { 15590 removeDataDirsLI(volumeUuid, packageName); 15591 } 15592 if (file.isDirectory()) { 15593 mInstaller.rmPackageDir(file.getAbsolutePath()); 15594 } else { 15595 file.delete(); 15596 } 15597 } 15598 } 15599 } 15600 } 15601 15602 private void unfreezePackage(String packageName) { 15603 synchronized (mPackages) { 15604 final PackageSetting ps = mSettings.mPackages.get(packageName); 15605 if (ps != null) { 15606 ps.frozen = false; 15607 } 15608 } 15609 } 15610 15611 @Override 15612 public int movePackage(final String packageName, final String volumeUuid) { 15613 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15614 15615 final int moveId = mNextMoveId.getAndIncrement(); 15616 try { 15617 movePackageInternal(packageName, volumeUuid, moveId); 15618 } catch (PackageManagerException e) { 15619 Slog.w(TAG, "Failed to move " + packageName, e); 15620 mMoveCallbacks.notifyStatusChanged(moveId, 15621 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15622 } 15623 return moveId; 15624 } 15625 15626 private void movePackageInternal(final String packageName, final String volumeUuid, 15627 final int moveId) throws PackageManagerException { 15628 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 15629 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15630 final PackageManager pm = mContext.getPackageManager(); 15631 15632 final boolean currentAsec; 15633 final String currentVolumeUuid; 15634 final File codeFile; 15635 final String installerPackageName; 15636 final String packageAbiOverride; 15637 final int appId; 15638 final String seinfo; 15639 final String label; 15640 15641 // reader 15642 synchronized (mPackages) { 15643 final PackageParser.Package pkg = mPackages.get(packageName); 15644 final PackageSetting ps = mSettings.mPackages.get(packageName); 15645 if (pkg == null || ps == null) { 15646 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 15647 } 15648 15649 if (pkg.applicationInfo.isSystemApp()) { 15650 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 15651 "Cannot move system application"); 15652 } 15653 15654 if (Objects.equals(ps.volumeUuid, volumeUuid)) { 15655 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15656 "Package already moved to " + volumeUuid); 15657 } 15658 15659 final File probe = new File(pkg.codePath); 15660 final File probeOat = new File(probe, "oat"); 15661 if (!probe.isDirectory() || !probeOat.isDirectory()) { 15662 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15663 "Move only supported for modern cluster style installs"); 15664 } 15665 15666 if (ps.frozen) { 15667 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 15668 "Failed to move already frozen package"); 15669 } 15670 ps.frozen = true; 15671 15672 currentAsec = pkg.applicationInfo.isForwardLocked() 15673 || pkg.applicationInfo.isExternalAsec(); 15674 currentVolumeUuid = ps.volumeUuid; 15675 codeFile = new File(pkg.codePath); 15676 installerPackageName = ps.installerPackageName; 15677 packageAbiOverride = ps.cpuAbiOverrideString; 15678 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 15679 seinfo = pkg.applicationInfo.seinfo; 15680 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 15681 } 15682 15683 // Now that we're guarded by frozen state, kill app during move 15684 killApplication(packageName, appId, "move pkg"); 15685 15686 final Bundle extras = new Bundle(); 15687 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 15688 extras.putString(Intent.EXTRA_TITLE, label); 15689 mMoveCallbacks.notifyCreated(moveId, extras); 15690 15691 int installFlags; 15692 final boolean moveCompleteApp; 15693 final File measurePath; 15694 15695 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 15696 installFlags = INSTALL_INTERNAL; 15697 moveCompleteApp = !currentAsec; 15698 measurePath = Environment.getDataAppDirectory(volumeUuid); 15699 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 15700 installFlags = INSTALL_EXTERNAL; 15701 moveCompleteApp = false; 15702 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 15703 } else { 15704 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 15705 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 15706 || !volume.isMountedWritable()) { 15707 unfreezePackage(packageName); 15708 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15709 "Move location not mounted private volume"); 15710 } 15711 15712 Preconditions.checkState(!currentAsec); 15713 15714 installFlags = INSTALL_INTERNAL; 15715 moveCompleteApp = true; 15716 measurePath = Environment.getDataAppDirectory(volumeUuid); 15717 } 15718 15719 final PackageStats stats = new PackageStats(null, -1); 15720 synchronized (mInstaller) { 15721 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 15722 unfreezePackage(packageName); 15723 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15724 "Failed to measure package size"); 15725 } 15726 } 15727 15728 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 15729 + stats.dataSize); 15730 15731 final long startFreeBytes = measurePath.getFreeSpace(); 15732 final long sizeBytes; 15733 if (moveCompleteApp) { 15734 sizeBytes = stats.codeSize + stats.dataSize; 15735 } else { 15736 sizeBytes = stats.codeSize; 15737 } 15738 15739 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 15740 unfreezePackage(packageName); 15741 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15742 "Not enough free space to move"); 15743 } 15744 15745 mMoveCallbacks.notifyStatusChanged(moveId, 10); 15746 15747 final CountDownLatch installedLatch = new CountDownLatch(1); 15748 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 15749 @Override 15750 public void onUserActionRequired(Intent intent) throws RemoteException { 15751 throw new IllegalStateException(); 15752 } 15753 15754 @Override 15755 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 15756 Bundle extras) throws RemoteException { 15757 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 15758 + PackageManager.installStatusToString(returnCode, msg)); 15759 15760 installedLatch.countDown(); 15761 15762 // Regardless of success or failure of the move operation, 15763 // always unfreeze the package 15764 unfreezePackage(packageName); 15765 15766 final int status = PackageManager.installStatusToPublicStatus(returnCode); 15767 switch (status) { 15768 case PackageInstaller.STATUS_SUCCESS: 15769 mMoveCallbacks.notifyStatusChanged(moveId, 15770 PackageManager.MOVE_SUCCEEDED); 15771 break; 15772 case PackageInstaller.STATUS_FAILURE_STORAGE: 15773 mMoveCallbacks.notifyStatusChanged(moveId, 15774 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 15775 break; 15776 default: 15777 mMoveCallbacks.notifyStatusChanged(moveId, 15778 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15779 break; 15780 } 15781 } 15782 }; 15783 15784 final MoveInfo move; 15785 if (moveCompleteApp) { 15786 // Kick off a thread to report progress estimates 15787 new Thread() { 15788 @Override 15789 public void run() { 15790 while (true) { 15791 try { 15792 if (installedLatch.await(1, TimeUnit.SECONDS)) { 15793 break; 15794 } 15795 } catch (InterruptedException ignored) { 15796 } 15797 15798 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 15799 final int progress = 10 + (int) MathUtils.constrain( 15800 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 15801 mMoveCallbacks.notifyStatusChanged(moveId, progress); 15802 } 15803 } 15804 }.start(); 15805 15806 final String dataAppName = codeFile.getName(); 15807 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 15808 dataAppName, appId, seinfo); 15809 } else { 15810 move = null; 15811 } 15812 15813 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 15814 15815 final Message msg = mHandler.obtainMessage(INIT_COPY); 15816 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 15817 msg.obj = new InstallParams(origin, move, installObserver, installFlags, 15818 installerPackageName, volumeUuid, null, user, packageAbiOverride); 15819 mHandler.sendMessage(msg); 15820 } 15821 15822 @Override 15823 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 15824 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15825 15826 final int realMoveId = mNextMoveId.getAndIncrement(); 15827 final Bundle extras = new Bundle(); 15828 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 15829 mMoveCallbacks.notifyCreated(realMoveId, extras); 15830 15831 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 15832 @Override 15833 public void onCreated(int moveId, Bundle extras) { 15834 // Ignored 15835 } 15836 15837 @Override 15838 public void onStatusChanged(int moveId, int status, long estMillis) { 15839 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 15840 } 15841 }; 15842 15843 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15844 storage.setPrimaryStorageUuid(volumeUuid, callback); 15845 return realMoveId; 15846 } 15847 15848 @Override 15849 public int getMoveStatus(int moveId) { 15850 mContext.enforceCallingOrSelfPermission( 15851 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15852 return mMoveCallbacks.mLastStatus.get(moveId); 15853 } 15854 15855 @Override 15856 public void registerMoveCallback(IPackageMoveObserver callback) { 15857 mContext.enforceCallingOrSelfPermission( 15858 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15859 mMoveCallbacks.register(callback); 15860 } 15861 15862 @Override 15863 public void unregisterMoveCallback(IPackageMoveObserver callback) { 15864 mContext.enforceCallingOrSelfPermission( 15865 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15866 mMoveCallbacks.unregister(callback); 15867 } 15868 15869 @Override 15870 public boolean setInstallLocation(int loc) { 15871 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 15872 null); 15873 if (getInstallLocation() == loc) { 15874 return true; 15875 } 15876 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 15877 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 15878 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 15879 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 15880 return true; 15881 } 15882 return false; 15883 } 15884 15885 @Override 15886 public int getInstallLocation() { 15887 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 15888 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 15889 PackageHelper.APP_INSTALL_AUTO); 15890 } 15891 15892 /** Called by UserManagerService */ 15893 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 15894 mDirtyUsers.remove(userHandle); 15895 mSettings.removeUserLPw(userHandle); 15896 mPendingBroadcasts.remove(userHandle); 15897 if (mInstaller != null) { 15898 // Technically, we shouldn't be doing this with the package lock 15899 // held. However, this is very rare, and there is already so much 15900 // other disk I/O going on, that we'll let it slide for now. 15901 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15902 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 15903 final String volumeUuid = vol.getFsUuid(); 15904 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 15905 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 15906 } 15907 } 15908 mUserNeedsBadging.delete(userHandle); 15909 removeUnusedPackagesLILPw(userManager, userHandle); 15910 } 15911 15912 /** 15913 * We're removing userHandle and would like to remove any downloaded packages 15914 * that are no longer in use by any other user. 15915 * @param userHandle the user being removed 15916 */ 15917 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 15918 final boolean DEBUG_CLEAN_APKS = false; 15919 int [] users = userManager.getUserIdsLPr(); 15920 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 15921 while (psit.hasNext()) { 15922 PackageSetting ps = psit.next(); 15923 if (ps.pkg == null) { 15924 continue; 15925 } 15926 final String packageName = ps.pkg.packageName; 15927 // Skip over if system app 15928 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 15929 continue; 15930 } 15931 if (DEBUG_CLEAN_APKS) { 15932 Slog.i(TAG, "Checking package " + packageName); 15933 } 15934 boolean keep = false; 15935 for (int i = 0; i < users.length; i++) { 15936 if (users[i] != userHandle && ps.getInstalled(users[i])) { 15937 keep = true; 15938 if (DEBUG_CLEAN_APKS) { 15939 Slog.i(TAG, " Keeping package " + packageName + " for user " 15940 + users[i]); 15941 } 15942 break; 15943 } 15944 } 15945 if (!keep) { 15946 if (DEBUG_CLEAN_APKS) { 15947 Slog.i(TAG, " Removing package " + packageName); 15948 } 15949 mHandler.post(new Runnable() { 15950 public void run() { 15951 deletePackageX(packageName, userHandle, 0); 15952 } //end run 15953 }); 15954 } 15955 } 15956 } 15957 15958 /** Called by UserManagerService */ 15959 void createNewUserLILPw(int userHandle) { 15960 if (mInstaller != null) { 15961 mInstaller.createUserConfig(userHandle); 15962 mSettings.createNewUserLILPw(this, mInstaller, userHandle); 15963 applyFactoryDefaultBrowserLPw(userHandle); 15964 primeDomainVerificationsLPw(userHandle); 15965 } 15966 } 15967 15968 void newUserCreatedLILPw(final int userHandle) { 15969 // We cannot grant the default permissions with a lock held as 15970 // we query providers from other components for default handlers 15971 // such as enabled IMEs, etc. 15972 mHandler.post(new Runnable() { 15973 @Override 15974 public void run() { 15975 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 15976 } 15977 }); 15978 } 15979 15980 @Override 15981 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 15982 mContext.enforceCallingOrSelfPermission( 15983 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 15984 "Only package verification agents can read the verifier device identity"); 15985 15986 synchronized (mPackages) { 15987 return mSettings.getVerifierDeviceIdentityLPw(); 15988 } 15989 } 15990 15991 @Override 15992 public void setPermissionEnforced(String permission, boolean enforced) { 15993 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 15994 if (READ_EXTERNAL_STORAGE.equals(permission)) { 15995 synchronized (mPackages) { 15996 if (mSettings.mReadExternalStorageEnforced == null 15997 || mSettings.mReadExternalStorageEnforced != enforced) { 15998 mSettings.mReadExternalStorageEnforced = enforced; 15999 mSettings.writeLPr(); 16000 } 16001 } 16002 // kill any non-foreground processes so we restart them and 16003 // grant/revoke the GID. 16004 final IActivityManager am = ActivityManagerNative.getDefault(); 16005 if (am != null) { 16006 final long token = Binder.clearCallingIdentity(); 16007 try { 16008 am.killProcessesBelowForeground("setPermissionEnforcement"); 16009 } catch (RemoteException e) { 16010 } finally { 16011 Binder.restoreCallingIdentity(token); 16012 } 16013 } 16014 } else { 16015 throw new IllegalArgumentException("No selective enforcement for " + permission); 16016 } 16017 } 16018 16019 @Override 16020 @Deprecated 16021 public boolean isPermissionEnforced(String permission) { 16022 return true; 16023 } 16024 16025 @Override 16026 public boolean isStorageLow() { 16027 final long token = Binder.clearCallingIdentity(); 16028 try { 16029 final DeviceStorageMonitorInternal 16030 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 16031 if (dsm != null) { 16032 return dsm.isMemoryLow(); 16033 } else { 16034 return false; 16035 } 16036 } finally { 16037 Binder.restoreCallingIdentity(token); 16038 } 16039 } 16040 16041 @Override 16042 public IPackageInstaller getPackageInstaller() { 16043 return mInstallerService; 16044 } 16045 16046 private boolean userNeedsBadging(int userId) { 16047 int index = mUserNeedsBadging.indexOfKey(userId); 16048 if (index < 0) { 16049 final UserInfo userInfo; 16050 final long token = Binder.clearCallingIdentity(); 16051 try { 16052 userInfo = sUserManager.getUserInfo(userId); 16053 } finally { 16054 Binder.restoreCallingIdentity(token); 16055 } 16056 final boolean b; 16057 if (userInfo != null && userInfo.isManagedProfile()) { 16058 b = true; 16059 } else { 16060 b = false; 16061 } 16062 mUserNeedsBadging.put(userId, b); 16063 return b; 16064 } 16065 return mUserNeedsBadging.valueAt(index); 16066 } 16067 16068 @Override 16069 public KeySet getKeySetByAlias(String packageName, String alias) { 16070 if (packageName == null || alias == null) { 16071 return null; 16072 } 16073 synchronized(mPackages) { 16074 final PackageParser.Package pkg = mPackages.get(packageName); 16075 if (pkg == null) { 16076 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16077 throw new IllegalArgumentException("Unknown package: " + packageName); 16078 } 16079 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16080 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 16081 } 16082 } 16083 16084 @Override 16085 public KeySet getSigningKeySet(String packageName) { 16086 if (packageName == null) { 16087 return null; 16088 } 16089 synchronized(mPackages) { 16090 final PackageParser.Package pkg = mPackages.get(packageName); 16091 if (pkg == null) { 16092 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16093 throw new IllegalArgumentException("Unknown package: " + packageName); 16094 } 16095 if (pkg.applicationInfo.uid != Binder.getCallingUid() 16096 && Process.SYSTEM_UID != Binder.getCallingUid()) { 16097 throw new SecurityException("May not access signing KeySet of other apps."); 16098 } 16099 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16100 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 16101 } 16102 } 16103 16104 @Override 16105 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 16106 if (packageName == null || ks == null) { 16107 return false; 16108 } 16109 synchronized(mPackages) { 16110 final PackageParser.Package pkg = mPackages.get(packageName); 16111 if (pkg == null) { 16112 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16113 throw new IllegalArgumentException("Unknown package: " + packageName); 16114 } 16115 IBinder ksh = ks.getToken(); 16116 if (ksh instanceof KeySetHandle) { 16117 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16118 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 16119 } 16120 return false; 16121 } 16122 } 16123 16124 @Override 16125 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 16126 if (packageName == null || ks == null) { 16127 return false; 16128 } 16129 synchronized(mPackages) { 16130 final PackageParser.Package pkg = mPackages.get(packageName); 16131 if (pkg == null) { 16132 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16133 throw new IllegalArgumentException("Unknown package: " + packageName); 16134 } 16135 IBinder ksh = ks.getToken(); 16136 if (ksh instanceof KeySetHandle) { 16137 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16138 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 16139 } 16140 return false; 16141 } 16142 } 16143 16144 public void getUsageStatsIfNoPackageUsageInfo() { 16145 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 16146 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 16147 if (usm == null) { 16148 throw new IllegalStateException("UsageStatsManager must be initialized"); 16149 } 16150 long now = System.currentTimeMillis(); 16151 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 16152 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 16153 String packageName = entry.getKey(); 16154 PackageParser.Package pkg = mPackages.get(packageName); 16155 if (pkg == null) { 16156 continue; 16157 } 16158 UsageStats usage = entry.getValue(); 16159 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 16160 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 16161 } 16162 } 16163 } 16164 16165 /** 16166 * Check and throw if the given before/after packages would be considered a 16167 * downgrade. 16168 */ 16169 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 16170 throws PackageManagerException { 16171 if (after.versionCode < before.mVersionCode) { 16172 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16173 "Update version code " + after.versionCode + " is older than current " 16174 + before.mVersionCode); 16175 } else if (after.versionCode == before.mVersionCode) { 16176 if (after.baseRevisionCode < before.baseRevisionCode) { 16177 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16178 "Update base revision code " + after.baseRevisionCode 16179 + " is older than current " + before.baseRevisionCode); 16180 } 16181 16182 if (!ArrayUtils.isEmpty(after.splitNames)) { 16183 for (int i = 0; i < after.splitNames.length; i++) { 16184 final String splitName = after.splitNames[i]; 16185 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 16186 if (j != -1) { 16187 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 16188 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16189 "Update split " + splitName + " revision code " 16190 + after.splitRevisionCodes[i] + " is older than current " 16191 + before.splitRevisionCodes[j]); 16192 } 16193 } 16194 } 16195 } 16196 } 16197 } 16198 16199 private static class MoveCallbacks extends Handler { 16200 private static final int MSG_CREATED = 1; 16201 private static final int MSG_STATUS_CHANGED = 2; 16202 16203 private final RemoteCallbackList<IPackageMoveObserver> 16204 mCallbacks = new RemoteCallbackList<>(); 16205 16206 private final SparseIntArray mLastStatus = new SparseIntArray(); 16207 16208 public MoveCallbacks(Looper looper) { 16209 super(looper); 16210 } 16211 16212 public void register(IPackageMoveObserver callback) { 16213 mCallbacks.register(callback); 16214 } 16215 16216 public void unregister(IPackageMoveObserver callback) { 16217 mCallbacks.unregister(callback); 16218 } 16219 16220 @Override 16221 public void handleMessage(Message msg) { 16222 final SomeArgs args = (SomeArgs) msg.obj; 16223 final int n = mCallbacks.beginBroadcast(); 16224 for (int i = 0; i < n; i++) { 16225 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 16226 try { 16227 invokeCallback(callback, msg.what, args); 16228 } catch (RemoteException ignored) { 16229 } 16230 } 16231 mCallbacks.finishBroadcast(); 16232 args.recycle(); 16233 } 16234 16235 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 16236 throws RemoteException { 16237 switch (what) { 16238 case MSG_CREATED: { 16239 callback.onCreated(args.argi1, (Bundle) args.arg2); 16240 break; 16241 } 16242 case MSG_STATUS_CHANGED: { 16243 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 16244 break; 16245 } 16246 } 16247 } 16248 16249 private void notifyCreated(int moveId, Bundle extras) { 16250 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 16251 16252 final SomeArgs args = SomeArgs.obtain(); 16253 args.argi1 = moveId; 16254 args.arg2 = extras; 16255 obtainMessage(MSG_CREATED, args).sendToTarget(); 16256 } 16257 16258 private void notifyStatusChanged(int moveId, int status) { 16259 notifyStatusChanged(moveId, status, -1); 16260 } 16261 16262 private void notifyStatusChanged(int moveId, int status, long estMillis) { 16263 Slog.v(TAG, "Move " + moveId + " status " + status); 16264 16265 final SomeArgs args = SomeArgs.obtain(); 16266 args.argi1 = moveId; 16267 args.argi2 = status; 16268 args.arg3 = estMillis; 16269 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 16270 16271 synchronized (mLastStatus) { 16272 mLastStatus.put(moveId, status); 16273 } 16274 } 16275 } 16276 16277 private final class OnPermissionChangeListeners extends Handler { 16278 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 16279 16280 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 16281 new RemoteCallbackList<>(); 16282 16283 public OnPermissionChangeListeners(Looper looper) { 16284 super(looper); 16285 } 16286 16287 @Override 16288 public void handleMessage(Message msg) { 16289 switch (msg.what) { 16290 case MSG_ON_PERMISSIONS_CHANGED: { 16291 final int uid = msg.arg1; 16292 handleOnPermissionsChanged(uid); 16293 } break; 16294 } 16295 } 16296 16297 public void addListenerLocked(IOnPermissionsChangeListener listener) { 16298 mPermissionListeners.register(listener); 16299 16300 } 16301 16302 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 16303 mPermissionListeners.unregister(listener); 16304 } 16305 16306 public void onPermissionsChanged(int uid) { 16307 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 16308 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 16309 } 16310 } 16311 16312 private void handleOnPermissionsChanged(int uid) { 16313 final int count = mPermissionListeners.beginBroadcast(); 16314 try { 16315 for (int i = 0; i < count; i++) { 16316 IOnPermissionsChangeListener callback = mPermissionListeners 16317 .getBroadcastItem(i); 16318 try { 16319 callback.onPermissionsChanged(uid); 16320 } catch (RemoteException e) { 16321 Log.e(TAG, "Permission listener is dead", e); 16322 } 16323 } 16324 } finally { 16325 mPermissionListeners.finishBroadcast(); 16326 } 16327 } 16328 } 16329 16330 private class PackageManagerInternalImpl extends PackageManagerInternal { 16331 @Override 16332 public void setLocationPackagesProvider(PackagesProvider provider) { 16333 synchronized (mPackages) { 16334 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 16335 } 16336 } 16337 16338 @Override 16339 public void setImePackagesProvider(PackagesProvider provider) { 16340 synchronized (mPackages) { 16341 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 16342 } 16343 } 16344 16345 @Override 16346 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 16347 synchronized (mPackages) { 16348 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 16349 } 16350 } 16351 16352 @Override 16353 public void setSmsAppPackagesProvider(PackagesProvider provider) { 16354 synchronized (mPackages) { 16355 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 16356 } 16357 } 16358 16359 @Override 16360 public void setDialerAppPackagesProvider(PackagesProvider provider) { 16361 synchronized (mPackages) { 16362 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 16363 } 16364 } 16365 16366 @Override 16367 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 16368 synchronized (mPackages) { 16369 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderrLPw(provider); 16370 } 16371 } 16372 16373 @Override 16374 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 16375 synchronized (mPackages) { 16376 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 16377 packageName, userId); 16378 } 16379 } 16380 16381 @Override 16382 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 16383 synchronized (mPackages) { 16384 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 16385 packageName, userId); 16386 } 16387 } 16388 } 16389 16390 @Override 16391 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 16392 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 16393 synchronized (mPackages) { 16394 final long identity = Binder.clearCallingIdentity(); 16395 try { 16396 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 16397 packageNames, userId); 16398 } finally { 16399 Binder.restoreCallingIdentity(identity); 16400 } 16401 } 16402 } 16403 16404 private static void enforceSystemOrPhoneCaller(String tag) { 16405 int callingUid = Binder.getCallingUid(); 16406 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 16407 throw new SecurityException( 16408 "Cannot call " + tag + " from UID " + callingUid); 16409 } 16410 } 16411} 16412