PackageManagerService.java revision f463ac6647bce5e88c6329b730b5965029b9f372
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 // Only need to do this if user is initialized. Otherwise it's a new user 3462 // and there are no processes running as the user yet and there's no need 3463 // to make an expensive call to remount processes for the changed permissions. 3464 if ((READ_EXTERNAL_STORAGE.equals(name) 3465 || WRITE_EXTERNAL_STORAGE.equals(name)) 3466 && sUserManager.isInitialized(userId)) { 3467 final long token = Binder.clearCallingIdentity(); 3468 try { 3469 final StorageManager storage = mContext.getSystemService(StorageManager.class); 3470 storage.remountUid(uid); 3471 } finally { 3472 Binder.restoreCallingIdentity(token); 3473 } 3474 } 3475 } 3476 3477 @Override 3478 public void revokeRuntimePermission(String packageName, String name, int userId) { 3479 if (!sUserManager.exists(userId)) { 3480 Log.e(TAG, "No such user:" + userId); 3481 return; 3482 } 3483 3484 mContext.enforceCallingOrSelfPermission( 3485 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3486 "revokeRuntimePermission"); 3487 3488 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3489 "revokeRuntimePermission"); 3490 3491 final SettingBase sb; 3492 3493 synchronized (mPackages) { 3494 final PackageParser.Package pkg = mPackages.get(packageName); 3495 if (pkg == null) { 3496 throw new IllegalArgumentException("Unknown package: " + packageName); 3497 } 3498 3499 final BasePermission bp = mSettings.mPermissions.get(name); 3500 if (bp == null) { 3501 throw new IllegalArgumentException("Unknown permission: " + name); 3502 } 3503 3504 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3505 3506 sb = (SettingBase) pkg.mExtras; 3507 if (sb == null) { 3508 throw new IllegalArgumentException("Unknown package: " + packageName); 3509 } 3510 3511 final PermissionsState permissionsState = sb.getPermissionsState(); 3512 3513 final int flags = permissionsState.getPermissionFlags(name, userId); 3514 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3515 throw new SecurityException("Cannot revoke system fixed permission: " 3516 + name + " for package: " + packageName); 3517 } 3518 3519 if (permissionsState.revokeRuntimePermission(bp, userId) == 3520 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3521 return; 3522 } 3523 3524 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3525 3526 // Critical, after this call app should never have the permission. 3527 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3528 } 3529 3530 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3531 } 3532 3533 @Override 3534 public void resetRuntimePermissions() { 3535 mContext.enforceCallingOrSelfPermission( 3536 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3537 "revokeRuntimePermission"); 3538 3539 int callingUid = Binder.getCallingUid(); 3540 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3541 mContext.enforceCallingOrSelfPermission( 3542 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3543 "resetRuntimePermissions"); 3544 } 3545 3546 final int[] userIds; 3547 3548 synchronized (mPackages) { 3549 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 3550 final int userCount = UserManagerService.getInstance().getUserIds().length; 3551 userIds = Arrays.copyOf(UserManagerService.getInstance().getUserIds(), userCount); 3552 } 3553 3554 for (int userId : userIds) { 3555 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 3556 } 3557 } 3558 3559 @Override 3560 public int getPermissionFlags(String name, String packageName, int userId) { 3561 if (!sUserManager.exists(userId)) { 3562 return 0; 3563 } 3564 3565 mContext.enforceCallingOrSelfPermission( 3566 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3567 "getPermissionFlags"); 3568 3569 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3570 "getPermissionFlags"); 3571 3572 synchronized (mPackages) { 3573 final PackageParser.Package pkg = mPackages.get(packageName); 3574 if (pkg == null) { 3575 throw new IllegalArgumentException("Unknown package: " + packageName); 3576 } 3577 3578 final BasePermission bp = mSettings.mPermissions.get(name); 3579 if (bp == null) { 3580 throw new IllegalArgumentException("Unknown permission: " + name); 3581 } 3582 3583 SettingBase sb = (SettingBase) pkg.mExtras; 3584 if (sb == null) { 3585 throw new IllegalArgumentException("Unknown package: " + packageName); 3586 } 3587 3588 PermissionsState permissionsState = sb.getPermissionsState(); 3589 return permissionsState.getPermissionFlags(name, userId); 3590 } 3591 } 3592 3593 @Override 3594 public void updatePermissionFlags(String name, String packageName, int flagMask, 3595 int flagValues, int userId) { 3596 if (!sUserManager.exists(userId)) { 3597 return; 3598 } 3599 3600 mContext.enforceCallingOrSelfPermission( 3601 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3602 "updatePermissionFlags"); 3603 3604 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3605 "updatePermissionFlags"); 3606 3607 // Only the system can change system fixed flags. 3608 if (getCallingUid() != Process.SYSTEM_UID) { 3609 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3610 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3611 } 3612 3613 synchronized (mPackages) { 3614 final PackageParser.Package pkg = mPackages.get(packageName); 3615 if (pkg == null) { 3616 throw new IllegalArgumentException("Unknown package: " + packageName); 3617 } 3618 3619 final BasePermission bp = mSettings.mPermissions.get(name); 3620 if (bp == null) { 3621 throw new IllegalArgumentException("Unknown permission: " + name); 3622 } 3623 3624 SettingBase sb = (SettingBase) pkg.mExtras; 3625 if (sb == null) { 3626 throw new IllegalArgumentException("Unknown package: " + packageName); 3627 } 3628 3629 PermissionsState permissionsState = sb.getPermissionsState(); 3630 3631 // Only the package manager can change flags for system component permissions. 3632 final int flags = permissionsState.getPermissionFlags(bp.name, userId); 3633 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3634 return; 3635 } 3636 3637 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 3638 3639 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3640 // Install and runtime permissions are stored in different places, 3641 // so figure out what permission changed and persist the change. 3642 if (permissionsState.getInstallPermissionState(name) != null) { 3643 scheduleWriteSettingsLocked(); 3644 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 3645 || hadState) { 3646 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3647 } 3648 } 3649 } 3650 } 3651 3652 /** 3653 * Update the permission flags for all packages and runtime permissions of a user in order 3654 * to allow device or profile owner to remove POLICY_FIXED. 3655 */ 3656 @Override 3657 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 3658 if (!sUserManager.exists(userId)) { 3659 return; 3660 } 3661 3662 mContext.enforceCallingOrSelfPermission( 3663 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3664 "updatePermissionFlagsForAllApps"); 3665 3666 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3667 "updatePermissionFlagsForAllApps"); 3668 3669 // Only the system can change system fixed flags. 3670 if (getCallingUid() != Process.SYSTEM_UID) { 3671 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3672 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3673 } 3674 3675 synchronized (mPackages) { 3676 boolean changed = false; 3677 final int packageCount = mPackages.size(); 3678 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 3679 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 3680 SettingBase sb = (SettingBase) pkg.mExtras; 3681 if (sb == null) { 3682 continue; 3683 } 3684 PermissionsState permissionsState = sb.getPermissionsState(); 3685 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 3686 userId, flagMask, flagValues); 3687 } 3688 if (changed) { 3689 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3690 } 3691 } 3692 } 3693 3694 @Override 3695 public boolean shouldShowRequestPermissionRationale(String permissionName, 3696 String packageName, int userId) { 3697 if (UserHandle.getCallingUserId() != userId) { 3698 mContext.enforceCallingPermission( 3699 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3700 "canShowRequestPermissionRationale for user " + userId); 3701 } 3702 3703 final int uid = getPackageUid(packageName, userId); 3704 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 3705 return false; 3706 } 3707 3708 if (checkPermission(permissionName, packageName, userId) 3709 == PackageManager.PERMISSION_GRANTED) { 3710 return false; 3711 } 3712 3713 final int flags; 3714 3715 final long identity = Binder.clearCallingIdentity(); 3716 try { 3717 flags = getPermissionFlags(permissionName, 3718 packageName, userId); 3719 } finally { 3720 Binder.restoreCallingIdentity(identity); 3721 } 3722 3723 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 3724 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 3725 | PackageManager.FLAG_PERMISSION_USER_FIXED; 3726 3727 if ((flags & fixedFlags) != 0) { 3728 return false; 3729 } 3730 3731 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 3732 } 3733 3734 void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) { 3735 BasePermission bp = mSettings.mPermissions.get(permission); 3736 if (bp == null) { 3737 throw new SecurityException("Missing " + permission + " permission"); 3738 } 3739 3740 SettingBase sb = (SettingBase) pkg.mExtras; 3741 PermissionsState permissionsState = sb.getPermissionsState(); 3742 3743 if (permissionsState.grantInstallPermission(bp) != 3744 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3745 scheduleWriteSettingsLocked(); 3746 } 3747 } 3748 3749 @Override 3750 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3751 mContext.enforceCallingOrSelfPermission( 3752 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 3753 "addOnPermissionsChangeListener"); 3754 3755 synchronized (mPackages) { 3756 mOnPermissionChangeListeners.addListenerLocked(listener); 3757 } 3758 } 3759 3760 @Override 3761 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3762 synchronized (mPackages) { 3763 mOnPermissionChangeListeners.removeListenerLocked(listener); 3764 } 3765 } 3766 3767 @Override 3768 public boolean isProtectedBroadcast(String actionName) { 3769 synchronized (mPackages) { 3770 return mProtectedBroadcasts.contains(actionName); 3771 } 3772 } 3773 3774 @Override 3775 public int checkSignatures(String pkg1, String pkg2) { 3776 synchronized (mPackages) { 3777 final PackageParser.Package p1 = mPackages.get(pkg1); 3778 final PackageParser.Package p2 = mPackages.get(pkg2); 3779 if (p1 == null || p1.mExtras == null 3780 || p2 == null || p2.mExtras == null) { 3781 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3782 } 3783 return compareSignatures(p1.mSignatures, p2.mSignatures); 3784 } 3785 } 3786 3787 @Override 3788 public int checkUidSignatures(int uid1, int uid2) { 3789 // Map to base uids. 3790 uid1 = UserHandle.getAppId(uid1); 3791 uid2 = UserHandle.getAppId(uid2); 3792 // reader 3793 synchronized (mPackages) { 3794 Signature[] s1; 3795 Signature[] s2; 3796 Object obj = mSettings.getUserIdLPr(uid1); 3797 if (obj != null) { 3798 if (obj instanceof SharedUserSetting) { 3799 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3800 } else if (obj instanceof PackageSetting) { 3801 s1 = ((PackageSetting)obj).signatures.mSignatures; 3802 } else { 3803 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3804 } 3805 } else { 3806 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3807 } 3808 obj = mSettings.getUserIdLPr(uid2); 3809 if (obj != null) { 3810 if (obj instanceof SharedUserSetting) { 3811 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3812 } else if (obj instanceof PackageSetting) { 3813 s2 = ((PackageSetting)obj).signatures.mSignatures; 3814 } else { 3815 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3816 } 3817 } else { 3818 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3819 } 3820 return compareSignatures(s1, s2); 3821 } 3822 } 3823 3824 private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) { 3825 final long identity = Binder.clearCallingIdentity(); 3826 try { 3827 if (sb instanceof SharedUserSetting) { 3828 SharedUserSetting sus = (SharedUserSetting) sb; 3829 final int packageCount = sus.packages.size(); 3830 for (int i = 0; i < packageCount; i++) { 3831 PackageSetting susPs = sus.packages.valueAt(i); 3832 if (userId == UserHandle.USER_ALL) { 3833 killApplication(susPs.pkg.packageName, susPs.appId, reason); 3834 } else { 3835 final int uid = UserHandle.getUid(userId, susPs.appId); 3836 killUid(uid, reason); 3837 } 3838 } 3839 } else if (sb instanceof PackageSetting) { 3840 PackageSetting ps = (PackageSetting) sb; 3841 if (userId == UserHandle.USER_ALL) { 3842 killApplication(ps.pkg.packageName, ps.appId, reason); 3843 } else { 3844 final int uid = UserHandle.getUid(userId, ps.appId); 3845 killUid(uid, reason); 3846 } 3847 } 3848 } finally { 3849 Binder.restoreCallingIdentity(identity); 3850 } 3851 } 3852 3853 private static void killUid(int uid, String reason) { 3854 IActivityManager am = ActivityManagerNative.getDefault(); 3855 if (am != null) { 3856 try { 3857 am.killUid(uid, reason); 3858 } catch (RemoteException e) { 3859 /* ignore - same process */ 3860 } 3861 } 3862 } 3863 3864 /** 3865 * Compares two sets of signatures. Returns: 3866 * <br /> 3867 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3868 * <br /> 3869 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3870 * <br /> 3871 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3872 * <br /> 3873 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3874 * <br /> 3875 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3876 */ 3877 static int compareSignatures(Signature[] s1, Signature[] s2) { 3878 if (s1 == null) { 3879 return s2 == null 3880 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3881 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3882 } 3883 3884 if (s2 == null) { 3885 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3886 } 3887 3888 if (s1.length != s2.length) { 3889 return PackageManager.SIGNATURE_NO_MATCH; 3890 } 3891 3892 // Since both signature sets are of size 1, we can compare without HashSets. 3893 if (s1.length == 1) { 3894 return s1[0].equals(s2[0]) ? 3895 PackageManager.SIGNATURE_MATCH : 3896 PackageManager.SIGNATURE_NO_MATCH; 3897 } 3898 3899 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3900 for (Signature sig : s1) { 3901 set1.add(sig); 3902 } 3903 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3904 for (Signature sig : s2) { 3905 set2.add(sig); 3906 } 3907 // Make sure s2 contains all signatures in s1. 3908 if (set1.equals(set2)) { 3909 return PackageManager.SIGNATURE_MATCH; 3910 } 3911 return PackageManager.SIGNATURE_NO_MATCH; 3912 } 3913 3914 /** 3915 * If the database version for this type of package (internal storage or 3916 * external storage) is less than the version where package signatures 3917 * were updated, return true. 3918 */ 3919 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3920 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 3921 DatabaseVersion.SIGNATURE_END_ENTITY)) 3922 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 3923 DatabaseVersion.SIGNATURE_END_ENTITY)); 3924 } 3925 3926 /** 3927 * Used for backward compatibility to make sure any packages with 3928 * certificate chains get upgraded to the new style. {@code existingSigs} 3929 * will be in the old format (since they were stored on disk from before the 3930 * system upgrade) and {@code scannedSigs} will be in the newer format. 3931 */ 3932 private int compareSignaturesCompat(PackageSignatures existingSigs, 3933 PackageParser.Package scannedPkg) { 3934 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 3935 return PackageManager.SIGNATURE_NO_MATCH; 3936 } 3937 3938 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 3939 for (Signature sig : existingSigs.mSignatures) { 3940 existingSet.add(sig); 3941 } 3942 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 3943 for (Signature sig : scannedPkg.mSignatures) { 3944 try { 3945 Signature[] chainSignatures = sig.getChainSignatures(); 3946 for (Signature chainSig : chainSignatures) { 3947 scannedCompatSet.add(chainSig); 3948 } 3949 } catch (CertificateEncodingException e) { 3950 scannedCompatSet.add(sig); 3951 } 3952 } 3953 /* 3954 * Make sure the expanded scanned set contains all signatures in the 3955 * existing one. 3956 */ 3957 if (scannedCompatSet.equals(existingSet)) { 3958 // Migrate the old signatures to the new scheme. 3959 existingSigs.assignSignatures(scannedPkg.mSignatures); 3960 // The new KeySets will be re-added later in the scanning process. 3961 synchronized (mPackages) { 3962 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 3963 } 3964 return PackageManager.SIGNATURE_MATCH; 3965 } 3966 return PackageManager.SIGNATURE_NO_MATCH; 3967 } 3968 3969 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3970 if (isExternal(scannedPkg)) { 3971 return mSettings.isExternalDatabaseVersionOlderThan( 3972 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3973 } else { 3974 return mSettings.isInternalDatabaseVersionOlderThan( 3975 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3976 } 3977 } 3978 3979 private int compareSignaturesRecover(PackageSignatures existingSigs, 3980 PackageParser.Package scannedPkg) { 3981 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 3982 return PackageManager.SIGNATURE_NO_MATCH; 3983 } 3984 3985 String msg = null; 3986 try { 3987 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 3988 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 3989 + scannedPkg.packageName); 3990 return PackageManager.SIGNATURE_MATCH; 3991 } 3992 } catch (CertificateException e) { 3993 msg = e.getMessage(); 3994 } 3995 3996 logCriticalInfo(Log.INFO, 3997 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 3998 return PackageManager.SIGNATURE_NO_MATCH; 3999 } 4000 4001 @Override 4002 public String[] getPackagesForUid(int uid) { 4003 uid = UserHandle.getAppId(uid); 4004 // reader 4005 synchronized (mPackages) { 4006 Object obj = mSettings.getUserIdLPr(uid); 4007 if (obj instanceof SharedUserSetting) { 4008 final SharedUserSetting sus = (SharedUserSetting) obj; 4009 final int N = sus.packages.size(); 4010 final String[] res = new String[N]; 4011 final Iterator<PackageSetting> it = sus.packages.iterator(); 4012 int i = 0; 4013 while (it.hasNext()) { 4014 res[i++] = it.next().name; 4015 } 4016 return res; 4017 } else if (obj instanceof PackageSetting) { 4018 final PackageSetting ps = (PackageSetting) obj; 4019 return new String[] { ps.name }; 4020 } 4021 } 4022 return null; 4023 } 4024 4025 @Override 4026 public String getNameForUid(int uid) { 4027 // reader 4028 synchronized (mPackages) { 4029 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4030 if (obj instanceof SharedUserSetting) { 4031 final SharedUserSetting sus = (SharedUserSetting) obj; 4032 return sus.name + ":" + sus.userId; 4033 } else if (obj instanceof PackageSetting) { 4034 final PackageSetting ps = (PackageSetting) obj; 4035 return ps.name; 4036 } 4037 } 4038 return null; 4039 } 4040 4041 @Override 4042 public int getUidForSharedUser(String sharedUserName) { 4043 if(sharedUserName == null) { 4044 return -1; 4045 } 4046 // reader 4047 synchronized (mPackages) { 4048 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4049 if (suid == null) { 4050 return -1; 4051 } 4052 return suid.userId; 4053 } 4054 } 4055 4056 @Override 4057 public int getFlagsForUid(int uid) { 4058 synchronized (mPackages) { 4059 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4060 if (obj instanceof SharedUserSetting) { 4061 final SharedUserSetting sus = (SharedUserSetting) obj; 4062 return sus.pkgFlags; 4063 } else if (obj instanceof PackageSetting) { 4064 final PackageSetting ps = (PackageSetting) obj; 4065 return ps.pkgFlags; 4066 } 4067 } 4068 return 0; 4069 } 4070 4071 @Override 4072 public int getPrivateFlagsForUid(int uid) { 4073 synchronized (mPackages) { 4074 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4075 if (obj instanceof SharedUserSetting) { 4076 final SharedUserSetting sus = (SharedUserSetting) obj; 4077 return sus.pkgPrivateFlags; 4078 } else if (obj instanceof PackageSetting) { 4079 final PackageSetting ps = (PackageSetting) obj; 4080 return ps.pkgPrivateFlags; 4081 } 4082 } 4083 return 0; 4084 } 4085 4086 @Override 4087 public boolean isUidPrivileged(int uid) { 4088 uid = UserHandle.getAppId(uid); 4089 // reader 4090 synchronized (mPackages) { 4091 Object obj = mSettings.getUserIdLPr(uid); 4092 if (obj instanceof SharedUserSetting) { 4093 final SharedUserSetting sus = (SharedUserSetting) obj; 4094 final Iterator<PackageSetting> it = sus.packages.iterator(); 4095 while (it.hasNext()) { 4096 if (it.next().isPrivileged()) { 4097 return true; 4098 } 4099 } 4100 } else if (obj instanceof PackageSetting) { 4101 final PackageSetting ps = (PackageSetting) obj; 4102 return ps.isPrivileged(); 4103 } 4104 } 4105 return false; 4106 } 4107 4108 @Override 4109 public String[] getAppOpPermissionPackages(String permissionName) { 4110 synchronized (mPackages) { 4111 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4112 if (pkgs == null) { 4113 return null; 4114 } 4115 return pkgs.toArray(new String[pkgs.size()]); 4116 } 4117 } 4118 4119 @Override 4120 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4121 int flags, int userId) { 4122 if (!sUserManager.exists(userId)) return null; 4123 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 4124 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4125 return chooseBestActivity(intent, resolvedType, flags, query, userId); 4126 } 4127 4128 @Override 4129 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4130 IntentFilter filter, int match, ComponentName activity) { 4131 final int userId = UserHandle.getCallingUserId(); 4132 if (DEBUG_PREFERRED) { 4133 Log.v(TAG, "setLastChosenActivity intent=" + intent 4134 + " resolvedType=" + resolvedType 4135 + " flags=" + flags 4136 + " filter=" + filter 4137 + " match=" + match 4138 + " activity=" + activity); 4139 filter.dump(new PrintStreamPrinter(System.out), " "); 4140 } 4141 intent.setComponent(null); 4142 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4143 // Find any earlier preferred or last chosen entries and nuke them 4144 findPreferredActivity(intent, resolvedType, 4145 flags, query, 0, false, true, false, userId); 4146 // Add the new activity as the last chosen for this filter 4147 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4148 "Setting last chosen"); 4149 } 4150 4151 @Override 4152 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4153 final int userId = UserHandle.getCallingUserId(); 4154 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4155 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4156 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4157 false, false, false, userId); 4158 } 4159 4160 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4161 int flags, List<ResolveInfo> query, int userId) { 4162 if (query != null) { 4163 final int N = query.size(); 4164 if (N == 1) { 4165 return query.get(0); 4166 } else if (N > 1) { 4167 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4168 // If there is more than one activity with the same priority, 4169 // then let the user decide between them. 4170 ResolveInfo r0 = query.get(0); 4171 ResolveInfo r1 = query.get(1); 4172 if (DEBUG_INTENT_MATCHING || debug) { 4173 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4174 + r1.activityInfo.name + "=" + r1.priority); 4175 } 4176 // If the first activity has a higher priority, or a different 4177 // default, then it is always desireable to pick it. 4178 if (r0.priority != r1.priority 4179 || r0.preferredOrder != r1.preferredOrder 4180 || r0.isDefault != r1.isDefault) { 4181 return query.get(0); 4182 } 4183 // If we have saved a preference for a preferred activity for 4184 // this Intent, use that. 4185 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4186 flags, query, r0.priority, true, false, debug, userId); 4187 if (ri != null) { 4188 return ri; 4189 } 4190 if (userId != 0) { 4191 ri = new ResolveInfo(mResolveInfo); 4192 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4193 ri.activityInfo.applicationInfo = new ApplicationInfo( 4194 ri.activityInfo.applicationInfo); 4195 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4196 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4197 return ri; 4198 } 4199 return mResolveInfo; 4200 } 4201 } 4202 return null; 4203 } 4204 4205 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4206 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4207 final int N = query.size(); 4208 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4209 .get(userId); 4210 // Get the list of persistent preferred activities that handle the intent 4211 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4212 List<PersistentPreferredActivity> pprefs = ppir != null 4213 ? ppir.queryIntent(intent, resolvedType, 4214 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4215 : null; 4216 if (pprefs != null && pprefs.size() > 0) { 4217 final int M = pprefs.size(); 4218 for (int i=0; i<M; i++) { 4219 final PersistentPreferredActivity ppa = pprefs.get(i); 4220 if (DEBUG_PREFERRED || debug) { 4221 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4222 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4223 + "\n component=" + ppa.mComponent); 4224 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4225 } 4226 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4227 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4228 if (DEBUG_PREFERRED || debug) { 4229 Slog.v(TAG, "Found persistent preferred activity:"); 4230 if (ai != null) { 4231 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4232 } else { 4233 Slog.v(TAG, " null"); 4234 } 4235 } 4236 if (ai == null) { 4237 // This previously registered persistent preferred activity 4238 // component is no longer known. Ignore it and do NOT remove it. 4239 continue; 4240 } 4241 for (int j=0; j<N; j++) { 4242 final ResolveInfo ri = query.get(j); 4243 if (!ri.activityInfo.applicationInfo.packageName 4244 .equals(ai.applicationInfo.packageName)) { 4245 continue; 4246 } 4247 if (!ri.activityInfo.name.equals(ai.name)) { 4248 continue; 4249 } 4250 // Found a persistent preference that can handle the intent. 4251 if (DEBUG_PREFERRED || debug) { 4252 Slog.v(TAG, "Returning persistent preferred activity: " + 4253 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4254 } 4255 return ri; 4256 } 4257 } 4258 } 4259 return null; 4260 } 4261 4262 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4263 List<ResolveInfo> query, int priority, boolean always, 4264 boolean removeMatches, boolean debug, int userId) { 4265 if (!sUserManager.exists(userId)) return null; 4266 // writer 4267 synchronized (mPackages) { 4268 if (intent.getSelector() != null) { 4269 intent = intent.getSelector(); 4270 } 4271 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4272 4273 // Try to find a matching persistent preferred activity. 4274 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4275 debug, userId); 4276 4277 // If a persistent preferred activity matched, use it. 4278 if (pri != null) { 4279 return pri; 4280 } 4281 4282 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4283 // Get the list of preferred activities that handle the intent 4284 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4285 List<PreferredActivity> prefs = pir != null 4286 ? pir.queryIntent(intent, resolvedType, 4287 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4288 : null; 4289 if (prefs != null && prefs.size() > 0) { 4290 boolean changed = false; 4291 try { 4292 // First figure out how good the original match set is. 4293 // We will only allow preferred activities that came 4294 // from the same match quality. 4295 int match = 0; 4296 4297 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4298 4299 final int N = query.size(); 4300 for (int j=0; j<N; j++) { 4301 final ResolveInfo ri = query.get(j); 4302 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4303 + ": 0x" + Integer.toHexString(match)); 4304 if (ri.match > match) { 4305 match = ri.match; 4306 } 4307 } 4308 4309 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4310 + Integer.toHexString(match)); 4311 4312 match &= IntentFilter.MATCH_CATEGORY_MASK; 4313 final int M = prefs.size(); 4314 for (int i=0; i<M; i++) { 4315 final PreferredActivity pa = prefs.get(i); 4316 if (DEBUG_PREFERRED || debug) { 4317 Slog.v(TAG, "Checking PreferredActivity ds=" 4318 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4319 + "\n component=" + pa.mPref.mComponent); 4320 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4321 } 4322 if (pa.mPref.mMatch != match) { 4323 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4324 + Integer.toHexString(pa.mPref.mMatch)); 4325 continue; 4326 } 4327 // If it's not an "always" type preferred activity and that's what we're 4328 // looking for, skip it. 4329 if (always && !pa.mPref.mAlways) { 4330 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4331 continue; 4332 } 4333 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4334 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4335 if (DEBUG_PREFERRED || debug) { 4336 Slog.v(TAG, "Found preferred activity:"); 4337 if (ai != null) { 4338 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4339 } else { 4340 Slog.v(TAG, " null"); 4341 } 4342 } 4343 if (ai == null) { 4344 // This previously registered preferred activity 4345 // component is no longer known. Most likely an update 4346 // to the app was installed and in the new version this 4347 // component no longer exists. Clean it up by removing 4348 // it from the preferred activities list, and skip it. 4349 Slog.w(TAG, "Removing dangling preferred activity: " 4350 + pa.mPref.mComponent); 4351 pir.removeFilter(pa); 4352 changed = true; 4353 continue; 4354 } 4355 for (int j=0; j<N; j++) { 4356 final ResolveInfo ri = query.get(j); 4357 if (!ri.activityInfo.applicationInfo.packageName 4358 .equals(ai.applicationInfo.packageName)) { 4359 continue; 4360 } 4361 if (!ri.activityInfo.name.equals(ai.name)) { 4362 continue; 4363 } 4364 4365 if (removeMatches) { 4366 pir.removeFilter(pa); 4367 changed = true; 4368 if (DEBUG_PREFERRED) { 4369 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4370 } 4371 break; 4372 } 4373 4374 // Okay we found a previously set preferred or last chosen app. 4375 // If the result set is different from when this 4376 // was created, we need to clear it and re-ask the 4377 // user their preference, if we're looking for an "always" type entry. 4378 if (always && !pa.mPref.sameSet(query)) { 4379 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4380 + intent + " type " + resolvedType); 4381 if (DEBUG_PREFERRED) { 4382 Slog.v(TAG, "Removing preferred activity since set changed " 4383 + pa.mPref.mComponent); 4384 } 4385 pir.removeFilter(pa); 4386 // Re-add the filter as a "last chosen" entry (!always) 4387 PreferredActivity lastChosen = new PreferredActivity( 4388 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4389 pir.addFilter(lastChosen); 4390 changed = true; 4391 return null; 4392 } 4393 4394 // Yay! Either the set matched or we're looking for the last chosen 4395 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4396 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4397 return ri; 4398 } 4399 } 4400 } finally { 4401 if (changed) { 4402 if (DEBUG_PREFERRED) { 4403 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4404 } 4405 scheduleWritePackageRestrictionsLocked(userId); 4406 } 4407 } 4408 } 4409 } 4410 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4411 return null; 4412 } 4413 4414 /* 4415 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4416 */ 4417 @Override 4418 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4419 int targetUserId) { 4420 mContext.enforceCallingOrSelfPermission( 4421 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4422 List<CrossProfileIntentFilter> matches = 4423 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4424 if (matches != null) { 4425 int size = matches.size(); 4426 for (int i = 0; i < size; i++) { 4427 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4428 } 4429 } 4430 if (hasWebURI(intent)) { 4431 // cross-profile app linking works only towards the parent. 4432 final UserInfo parent = getProfileParent(sourceUserId); 4433 synchronized(mPackages) { 4434 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 4435 intent, resolvedType, 0, sourceUserId, parent.id); 4436 return xpDomainInfo != null 4437 && xpDomainInfo.bestDomainVerificationStatus != 4438 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 4439 } 4440 } 4441 return false; 4442 } 4443 4444 private UserInfo getProfileParent(int userId) { 4445 final long identity = Binder.clearCallingIdentity(); 4446 try { 4447 return sUserManager.getProfileParent(userId); 4448 } finally { 4449 Binder.restoreCallingIdentity(identity); 4450 } 4451 } 4452 4453 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4454 String resolvedType, int userId) { 4455 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4456 if (resolver != null) { 4457 return resolver.queryIntent(intent, resolvedType, false, userId); 4458 } 4459 return null; 4460 } 4461 4462 @Override 4463 public List<ResolveInfo> queryIntentActivities(Intent intent, 4464 String resolvedType, int flags, int userId) { 4465 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4466 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4467 ComponentName comp = intent.getComponent(); 4468 if (comp == null) { 4469 if (intent.getSelector() != null) { 4470 intent = intent.getSelector(); 4471 comp = intent.getComponent(); 4472 } 4473 } 4474 4475 if (comp != null) { 4476 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4477 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4478 if (ai != null) { 4479 final ResolveInfo ri = new ResolveInfo(); 4480 ri.activityInfo = ai; 4481 list.add(ri); 4482 } 4483 return list; 4484 } 4485 4486 // reader 4487 synchronized (mPackages) { 4488 final String pkgName = intent.getPackage(); 4489 if (pkgName == null) { 4490 List<CrossProfileIntentFilter> matchingFilters = 4491 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4492 // Check for results that need to skip the current profile. 4493 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4494 resolvedType, flags, userId); 4495 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4496 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4497 result.add(xpResolveInfo); 4498 return filterIfNotPrimaryUser(result, userId); 4499 } 4500 4501 // Check for results in the current profile. 4502 List<ResolveInfo> result = mActivities.queryIntent( 4503 intent, resolvedType, flags, userId); 4504 4505 // Check for cross profile results. 4506 xpResolveInfo = queryCrossProfileIntents( 4507 matchingFilters, intent, resolvedType, flags, userId); 4508 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4509 result.add(xpResolveInfo); 4510 Collections.sort(result, mResolvePrioritySorter); 4511 } 4512 result = filterIfNotPrimaryUser(result, userId); 4513 if (hasWebURI(intent)) { 4514 CrossProfileDomainInfo xpDomainInfo = null; 4515 final UserInfo parent = getProfileParent(userId); 4516 if (parent != null) { 4517 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 4518 flags, userId, parent.id); 4519 } 4520 if (xpDomainInfo != null) { 4521 if (xpResolveInfo != null) { 4522 // If we didn't remove it, the cross-profile ResolveInfo would be twice 4523 // in the result. 4524 result.remove(xpResolveInfo); 4525 } 4526 if (result.size() == 0) { 4527 result.add(xpDomainInfo.resolveInfo); 4528 return result; 4529 } 4530 } else if (result.size() <= 1) { 4531 return result; 4532 } 4533 result = filterCandidatesWithDomainPreferredActivitiesLPr(flags, result, 4534 xpDomainInfo, userId); 4535 Collections.sort(result, mResolvePrioritySorter); 4536 } 4537 return result; 4538 } 4539 final PackageParser.Package pkg = mPackages.get(pkgName); 4540 if (pkg != null) { 4541 return filterIfNotPrimaryUser( 4542 mActivities.queryIntentForPackage( 4543 intent, resolvedType, flags, pkg.activities, userId), 4544 userId); 4545 } 4546 return new ArrayList<ResolveInfo>(); 4547 } 4548 } 4549 4550 private static class CrossProfileDomainInfo { 4551 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 4552 ResolveInfo resolveInfo; 4553 /* Best domain verification status of the activities found in the other profile */ 4554 int bestDomainVerificationStatus; 4555 } 4556 4557 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 4558 String resolvedType, int flags, int sourceUserId, int parentUserId) { 4559 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 4560 sourceUserId)) { 4561 return null; 4562 } 4563 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4564 resolvedType, flags, parentUserId); 4565 4566 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 4567 return null; 4568 } 4569 CrossProfileDomainInfo result = null; 4570 int size = resultTargetUser.size(); 4571 for (int i = 0; i < size; i++) { 4572 ResolveInfo riTargetUser = resultTargetUser.get(i); 4573 // Intent filter verification is only for filters that specify a host. So don't return 4574 // those that handle all web uris. 4575 if (riTargetUser.handleAllWebDataURI) { 4576 continue; 4577 } 4578 String packageName = riTargetUser.activityInfo.packageName; 4579 PackageSetting ps = mSettings.mPackages.get(packageName); 4580 if (ps == null) { 4581 continue; 4582 } 4583 int status = getDomainVerificationStatusLPr(ps, parentUserId); 4584 if (result == null) { 4585 result = new CrossProfileDomainInfo(); 4586 result.resolveInfo = 4587 createForwardingResolveInfo(null, sourceUserId, parentUserId); 4588 result.bestDomainVerificationStatus = status; 4589 } else { 4590 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 4591 result.bestDomainVerificationStatus); 4592 } 4593 } 4594 return result; 4595 } 4596 4597 /** 4598 * Verification statuses are ordered from the worse to the best, except for 4599 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 4600 */ 4601 private int bestDomainVerificationStatus(int status1, int status2) { 4602 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4603 return status2; 4604 } 4605 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4606 return status1; 4607 } 4608 return (int) MathUtils.max(status1, status2); 4609 } 4610 4611 private boolean isUserEnabled(int userId) { 4612 long callingId = Binder.clearCallingIdentity(); 4613 try { 4614 UserInfo userInfo = sUserManager.getUserInfo(userId); 4615 return userInfo != null && userInfo.isEnabled(); 4616 } finally { 4617 Binder.restoreCallingIdentity(callingId); 4618 } 4619 } 4620 4621 /** 4622 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 4623 * 4624 * @return filtered list 4625 */ 4626 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 4627 if (userId == UserHandle.USER_OWNER) { 4628 return resolveInfos; 4629 } 4630 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 4631 ResolveInfo info = resolveInfos.get(i); 4632 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 4633 resolveInfos.remove(i); 4634 } 4635 } 4636 return resolveInfos; 4637 } 4638 4639 private static boolean hasWebURI(Intent intent) { 4640 if (intent.getData() == null) { 4641 return false; 4642 } 4643 final String scheme = intent.getScheme(); 4644 if (TextUtils.isEmpty(scheme)) { 4645 return false; 4646 } 4647 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4648 } 4649 4650 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr( 4651 int flags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 4652 int userId) { 4653 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4654 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 4655 candidates.size()); 4656 } 4657 4658 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4659 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 4660 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4661 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4662 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4663 4664 synchronized (mPackages) { 4665 final int count = candidates.size(); 4666 // First, try to use linked apps. Partition the candidates into four lists: 4667 // one for the final results, one for the "do not use ever", one for "undefined status" 4668 // and finally one for "browser app type". 4669 for (int n=0; n<count; n++) { 4670 ResolveInfo info = candidates.get(n); 4671 String packageName = info.activityInfo.packageName; 4672 PackageSetting ps = mSettings.mPackages.get(packageName); 4673 if (ps != null) { 4674 // Add to the special match all list (Browser use case) 4675 if (info.handleAllWebDataURI) { 4676 matchAllList.add(info); 4677 continue; 4678 } 4679 // Try to get the status from User settings first 4680 int status = getDomainVerificationStatusLPr(ps, userId); 4681 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4682 if (DEBUG_DOMAIN_VERIFICATION) { 4683 Slog.i(TAG, " + always: " + info.activityInfo.packageName); 4684 } 4685 alwaysList.add(info); 4686 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4687 if (DEBUG_DOMAIN_VERIFICATION) { 4688 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 4689 } 4690 neverList.add(info); 4691 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 4692 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 4693 if (DEBUG_DOMAIN_VERIFICATION) { 4694 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 4695 } 4696 undefinedList.add(info); 4697 } 4698 } 4699 } 4700 // First try to add the "always" resolution for the current user if there is any 4701 if (alwaysList.size() > 0) { 4702 result.addAll(alwaysList); 4703 // if there is an "always" for the parent user, add it. 4704 } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus 4705 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4706 result.add(xpDomainInfo.resolveInfo); 4707 } else { 4708 // Add all undefined Apps as we want them to appear in the Disambiguation dialog. 4709 result.addAll(undefinedList); 4710 if (xpDomainInfo != null && ( 4711 xpDomainInfo.bestDomainVerificationStatus 4712 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 4713 || xpDomainInfo.bestDomainVerificationStatus 4714 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) { 4715 result.add(xpDomainInfo.resolveInfo); 4716 } 4717 // Also add Browsers (all of them or only the default one) 4718 if ((flags & MATCH_ALL) != 0) { 4719 result.addAll(matchAllList); 4720 } else { 4721 // Try to add the Default Browser if we can 4722 final String defaultBrowserPackageName = getDefaultBrowserPackageName( 4723 UserHandle.myUserId()); 4724 if (!TextUtils.isEmpty(defaultBrowserPackageName)) { 4725 boolean defaultBrowserFound = false; 4726 final int browserCount = matchAllList.size(); 4727 for (int n=0; n<browserCount; n++) { 4728 ResolveInfo browser = matchAllList.get(n); 4729 if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4730 result.add(browser); 4731 defaultBrowserFound = true; 4732 break; 4733 } 4734 } 4735 if (!defaultBrowserFound) { 4736 result.addAll(matchAllList); 4737 } 4738 } else { 4739 result.addAll(matchAllList); 4740 } 4741 } 4742 4743 // If there is nothing selected, add all candidates and remove the ones that the user 4744 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 4745 if (result.size() == 0) { 4746 result.addAll(candidates); 4747 result.removeAll(neverList); 4748 } 4749 } 4750 } 4751 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4752 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 4753 result.size()); 4754 for (ResolveInfo info : result) { 4755 Slog.v(TAG, " + " + info.activityInfo); 4756 } 4757 } 4758 return result; 4759 } 4760 4761 private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4762 int status = ps.getDomainVerificationStatusForUser(userId); 4763 // if none available, get the master status 4764 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4765 if (ps.getIntentFilterVerificationInfo() != null) { 4766 status = ps.getIntentFilterVerificationInfo().getStatus(); 4767 } 4768 } 4769 return status; 4770 } 4771 4772 private ResolveInfo querySkipCurrentProfileIntents( 4773 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4774 int flags, int sourceUserId) { 4775 if (matchingFilters != null) { 4776 int size = matchingFilters.size(); 4777 for (int i = 0; i < size; i ++) { 4778 CrossProfileIntentFilter filter = matchingFilters.get(i); 4779 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4780 // Checking if there are activities in the target user that can handle the 4781 // intent. 4782 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4783 flags, sourceUserId); 4784 if (resolveInfo != null) { 4785 return resolveInfo; 4786 } 4787 } 4788 } 4789 } 4790 return null; 4791 } 4792 4793 // Return matching ResolveInfo if any for skip current profile intent filters. 4794 private ResolveInfo queryCrossProfileIntents( 4795 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4796 int flags, int sourceUserId) { 4797 if (matchingFilters != null) { 4798 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4799 // match the same intent. For performance reasons, it is better not to 4800 // run queryIntent twice for the same userId 4801 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4802 int size = matchingFilters.size(); 4803 for (int i = 0; i < size; i++) { 4804 CrossProfileIntentFilter filter = matchingFilters.get(i); 4805 int targetUserId = filter.getTargetUserId(); 4806 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4807 && !alreadyTriedUserIds.get(targetUserId)) { 4808 // Checking if there are activities in the target user that can handle the 4809 // intent. 4810 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4811 flags, sourceUserId); 4812 if (resolveInfo != null) return resolveInfo; 4813 alreadyTriedUserIds.put(targetUserId, true); 4814 } 4815 } 4816 } 4817 return null; 4818 } 4819 4820 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 4821 String resolvedType, int flags, int sourceUserId) { 4822 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4823 resolvedType, flags, filter.getTargetUserId()); 4824 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4825 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4826 } 4827 return null; 4828 } 4829 4830 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4831 int sourceUserId, int targetUserId) { 4832 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4833 String className; 4834 if (targetUserId == UserHandle.USER_OWNER) { 4835 className = FORWARD_INTENT_TO_USER_OWNER; 4836 } else { 4837 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4838 } 4839 ComponentName forwardingActivityComponentName = new ComponentName( 4840 mAndroidApplication.packageName, className); 4841 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4842 sourceUserId); 4843 if (targetUserId == UserHandle.USER_OWNER) { 4844 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 4845 forwardingResolveInfo.noResourceId = true; 4846 } 4847 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4848 forwardingResolveInfo.priority = 0; 4849 forwardingResolveInfo.preferredOrder = 0; 4850 forwardingResolveInfo.match = 0; 4851 forwardingResolveInfo.isDefault = true; 4852 forwardingResolveInfo.filter = filter; 4853 forwardingResolveInfo.targetUserId = targetUserId; 4854 return forwardingResolveInfo; 4855 } 4856 4857 @Override 4858 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4859 Intent[] specifics, String[] specificTypes, Intent intent, 4860 String resolvedType, int flags, int userId) { 4861 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4862 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4863 false, "query intent activity options"); 4864 final String resultsAction = intent.getAction(); 4865 4866 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4867 | PackageManager.GET_RESOLVED_FILTER, userId); 4868 4869 if (DEBUG_INTENT_MATCHING) { 4870 Log.v(TAG, "Query " + intent + ": " + results); 4871 } 4872 4873 int specificsPos = 0; 4874 int N; 4875 4876 // todo: note that the algorithm used here is O(N^2). This 4877 // isn't a problem in our current environment, but if we start running 4878 // into situations where we have more than 5 or 10 matches then this 4879 // should probably be changed to something smarter... 4880 4881 // First we go through and resolve each of the specific items 4882 // that were supplied, taking care of removing any corresponding 4883 // duplicate items in the generic resolve list. 4884 if (specifics != null) { 4885 for (int i=0; i<specifics.length; i++) { 4886 final Intent sintent = specifics[i]; 4887 if (sintent == null) { 4888 continue; 4889 } 4890 4891 if (DEBUG_INTENT_MATCHING) { 4892 Log.v(TAG, "Specific #" + i + ": " + sintent); 4893 } 4894 4895 String action = sintent.getAction(); 4896 if (resultsAction != null && resultsAction.equals(action)) { 4897 // If this action was explicitly requested, then don't 4898 // remove things that have it. 4899 action = null; 4900 } 4901 4902 ResolveInfo ri = null; 4903 ActivityInfo ai = null; 4904 4905 ComponentName comp = sintent.getComponent(); 4906 if (comp == null) { 4907 ri = resolveIntent( 4908 sintent, 4909 specificTypes != null ? specificTypes[i] : null, 4910 flags, userId); 4911 if (ri == null) { 4912 continue; 4913 } 4914 if (ri == mResolveInfo) { 4915 // ACK! Must do something better with this. 4916 } 4917 ai = ri.activityInfo; 4918 comp = new ComponentName(ai.applicationInfo.packageName, 4919 ai.name); 4920 } else { 4921 ai = getActivityInfo(comp, flags, userId); 4922 if (ai == null) { 4923 continue; 4924 } 4925 } 4926 4927 // Look for any generic query activities that are duplicates 4928 // of this specific one, and remove them from the results. 4929 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 4930 N = results.size(); 4931 int j; 4932 for (j=specificsPos; j<N; j++) { 4933 ResolveInfo sri = results.get(j); 4934 if ((sri.activityInfo.name.equals(comp.getClassName()) 4935 && sri.activityInfo.applicationInfo.packageName.equals( 4936 comp.getPackageName())) 4937 || (action != null && sri.filter.matchAction(action))) { 4938 results.remove(j); 4939 if (DEBUG_INTENT_MATCHING) Log.v( 4940 TAG, "Removing duplicate item from " + j 4941 + " due to specific " + specificsPos); 4942 if (ri == null) { 4943 ri = sri; 4944 } 4945 j--; 4946 N--; 4947 } 4948 } 4949 4950 // Add this specific item to its proper place. 4951 if (ri == null) { 4952 ri = new ResolveInfo(); 4953 ri.activityInfo = ai; 4954 } 4955 results.add(specificsPos, ri); 4956 ri.specificIndex = i; 4957 specificsPos++; 4958 } 4959 } 4960 4961 // Now we go through the remaining generic results and remove any 4962 // duplicate actions that are found here. 4963 N = results.size(); 4964 for (int i=specificsPos; i<N-1; i++) { 4965 final ResolveInfo rii = results.get(i); 4966 if (rii.filter == null) { 4967 continue; 4968 } 4969 4970 // Iterate over all of the actions of this result's intent 4971 // filter... typically this should be just one. 4972 final Iterator<String> it = rii.filter.actionsIterator(); 4973 if (it == null) { 4974 continue; 4975 } 4976 while (it.hasNext()) { 4977 final String action = it.next(); 4978 if (resultsAction != null && resultsAction.equals(action)) { 4979 // If this action was explicitly requested, then don't 4980 // remove things that have it. 4981 continue; 4982 } 4983 for (int j=i+1; j<N; j++) { 4984 final ResolveInfo rij = results.get(j); 4985 if (rij.filter != null && rij.filter.hasAction(action)) { 4986 results.remove(j); 4987 if (DEBUG_INTENT_MATCHING) Log.v( 4988 TAG, "Removing duplicate item from " + j 4989 + " due to action " + action + " at " + i); 4990 j--; 4991 N--; 4992 } 4993 } 4994 } 4995 4996 // If the caller didn't request filter information, drop it now 4997 // so we don't have to marshall/unmarshall it. 4998 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4999 rii.filter = null; 5000 } 5001 } 5002 5003 // Filter out the caller activity if so requested. 5004 if (caller != null) { 5005 N = results.size(); 5006 for (int i=0; i<N; i++) { 5007 ActivityInfo ainfo = results.get(i).activityInfo; 5008 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5009 && caller.getClassName().equals(ainfo.name)) { 5010 results.remove(i); 5011 break; 5012 } 5013 } 5014 } 5015 5016 // If the caller didn't request filter information, 5017 // drop them now so we don't have to 5018 // marshall/unmarshall it. 5019 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5020 N = results.size(); 5021 for (int i=0; i<N; i++) { 5022 results.get(i).filter = null; 5023 } 5024 } 5025 5026 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5027 return results; 5028 } 5029 5030 @Override 5031 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 5032 int userId) { 5033 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5034 ComponentName comp = intent.getComponent(); 5035 if (comp == null) { 5036 if (intent.getSelector() != null) { 5037 intent = intent.getSelector(); 5038 comp = intent.getComponent(); 5039 } 5040 } 5041 if (comp != null) { 5042 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5043 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5044 if (ai != null) { 5045 ResolveInfo ri = new ResolveInfo(); 5046 ri.activityInfo = ai; 5047 list.add(ri); 5048 } 5049 return list; 5050 } 5051 5052 // reader 5053 synchronized (mPackages) { 5054 String pkgName = intent.getPackage(); 5055 if (pkgName == null) { 5056 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5057 } 5058 final PackageParser.Package pkg = mPackages.get(pkgName); 5059 if (pkg != null) { 5060 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5061 userId); 5062 } 5063 return null; 5064 } 5065 } 5066 5067 @Override 5068 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5069 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 5070 if (!sUserManager.exists(userId)) return null; 5071 if (query != null) { 5072 if (query.size() >= 1) { 5073 // If there is more than one service with the same priority, 5074 // just arbitrarily pick the first one. 5075 return query.get(0); 5076 } 5077 } 5078 return null; 5079 } 5080 5081 @Override 5082 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 5083 int userId) { 5084 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5085 ComponentName comp = intent.getComponent(); 5086 if (comp == null) { 5087 if (intent.getSelector() != null) { 5088 intent = intent.getSelector(); 5089 comp = intent.getComponent(); 5090 } 5091 } 5092 if (comp != null) { 5093 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5094 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5095 if (si != null) { 5096 final ResolveInfo ri = new ResolveInfo(); 5097 ri.serviceInfo = si; 5098 list.add(ri); 5099 } 5100 return list; 5101 } 5102 5103 // reader 5104 synchronized (mPackages) { 5105 String pkgName = intent.getPackage(); 5106 if (pkgName == null) { 5107 return mServices.queryIntent(intent, resolvedType, flags, userId); 5108 } 5109 final PackageParser.Package pkg = mPackages.get(pkgName); 5110 if (pkg != null) { 5111 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5112 userId); 5113 } 5114 return null; 5115 } 5116 } 5117 5118 @Override 5119 public List<ResolveInfo> queryIntentContentProviders( 5120 Intent intent, String resolvedType, int flags, int userId) { 5121 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5122 ComponentName comp = intent.getComponent(); 5123 if (comp == null) { 5124 if (intent.getSelector() != null) { 5125 intent = intent.getSelector(); 5126 comp = intent.getComponent(); 5127 } 5128 } 5129 if (comp != null) { 5130 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5131 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5132 if (pi != null) { 5133 final ResolveInfo ri = new ResolveInfo(); 5134 ri.providerInfo = pi; 5135 list.add(ri); 5136 } 5137 return list; 5138 } 5139 5140 // reader 5141 synchronized (mPackages) { 5142 String pkgName = intent.getPackage(); 5143 if (pkgName == null) { 5144 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5145 } 5146 final PackageParser.Package pkg = mPackages.get(pkgName); 5147 if (pkg != null) { 5148 return mProviders.queryIntentForPackage( 5149 intent, resolvedType, flags, pkg.providers, userId); 5150 } 5151 return null; 5152 } 5153 } 5154 5155 @Override 5156 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5157 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5158 5159 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 5160 5161 // writer 5162 synchronized (mPackages) { 5163 ArrayList<PackageInfo> list; 5164 if (listUninstalled) { 5165 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5166 for (PackageSetting ps : mSettings.mPackages.values()) { 5167 PackageInfo pi; 5168 if (ps.pkg != null) { 5169 pi = generatePackageInfo(ps.pkg, flags, userId); 5170 } else { 5171 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5172 } 5173 if (pi != null) { 5174 list.add(pi); 5175 } 5176 } 5177 } else { 5178 list = new ArrayList<PackageInfo>(mPackages.size()); 5179 for (PackageParser.Package p : mPackages.values()) { 5180 PackageInfo pi = generatePackageInfo(p, flags, userId); 5181 if (pi != null) { 5182 list.add(pi); 5183 } 5184 } 5185 } 5186 5187 return new ParceledListSlice<PackageInfo>(list); 5188 } 5189 } 5190 5191 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5192 String[] permissions, boolean[] tmp, int flags, int userId) { 5193 int numMatch = 0; 5194 final PermissionsState permissionsState = ps.getPermissionsState(); 5195 for (int i=0; i<permissions.length; i++) { 5196 final String permission = permissions[i]; 5197 if (permissionsState.hasPermission(permission, userId)) { 5198 tmp[i] = true; 5199 numMatch++; 5200 } else { 5201 tmp[i] = false; 5202 } 5203 } 5204 if (numMatch == 0) { 5205 return; 5206 } 5207 PackageInfo pi; 5208 if (ps.pkg != null) { 5209 pi = generatePackageInfo(ps.pkg, flags, userId); 5210 } else { 5211 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5212 } 5213 // The above might return null in cases of uninstalled apps or install-state 5214 // skew across users/profiles. 5215 if (pi != null) { 5216 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5217 if (numMatch == permissions.length) { 5218 pi.requestedPermissions = permissions; 5219 } else { 5220 pi.requestedPermissions = new String[numMatch]; 5221 numMatch = 0; 5222 for (int i=0; i<permissions.length; i++) { 5223 if (tmp[i]) { 5224 pi.requestedPermissions[numMatch] = permissions[i]; 5225 numMatch++; 5226 } 5227 } 5228 } 5229 } 5230 list.add(pi); 5231 } 5232 } 5233 5234 @Override 5235 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5236 String[] permissions, int flags, int userId) { 5237 if (!sUserManager.exists(userId)) return null; 5238 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5239 5240 // writer 5241 synchronized (mPackages) { 5242 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5243 boolean[] tmpBools = new boolean[permissions.length]; 5244 if (listUninstalled) { 5245 for (PackageSetting ps : mSettings.mPackages.values()) { 5246 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5247 } 5248 } else { 5249 for (PackageParser.Package pkg : mPackages.values()) { 5250 PackageSetting ps = (PackageSetting)pkg.mExtras; 5251 if (ps != null) { 5252 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5253 userId); 5254 } 5255 } 5256 } 5257 5258 return new ParceledListSlice<PackageInfo>(list); 5259 } 5260 } 5261 5262 @Override 5263 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5264 if (!sUserManager.exists(userId)) return null; 5265 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5266 5267 // writer 5268 synchronized (mPackages) { 5269 ArrayList<ApplicationInfo> list; 5270 if (listUninstalled) { 5271 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5272 for (PackageSetting ps : mSettings.mPackages.values()) { 5273 ApplicationInfo ai; 5274 if (ps.pkg != null) { 5275 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5276 ps.readUserState(userId), userId); 5277 } else { 5278 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5279 } 5280 if (ai != null) { 5281 list.add(ai); 5282 } 5283 } 5284 } else { 5285 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5286 for (PackageParser.Package p : mPackages.values()) { 5287 if (p.mExtras != null) { 5288 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5289 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5290 if (ai != null) { 5291 list.add(ai); 5292 } 5293 } 5294 } 5295 } 5296 5297 return new ParceledListSlice<ApplicationInfo>(list); 5298 } 5299 } 5300 5301 public List<ApplicationInfo> getPersistentApplications(int flags) { 5302 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 5303 5304 // reader 5305 synchronized (mPackages) { 5306 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 5307 final int userId = UserHandle.getCallingUserId(); 5308 while (i.hasNext()) { 5309 final PackageParser.Package p = i.next(); 5310 if (p.applicationInfo != null 5311 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 5312 && (!mSafeMode || isSystemApp(p))) { 5313 PackageSetting ps = mSettings.mPackages.get(p.packageName); 5314 if (ps != null) { 5315 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5316 ps.readUserState(userId), userId); 5317 if (ai != null) { 5318 finalList.add(ai); 5319 } 5320 } 5321 } 5322 } 5323 } 5324 5325 return finalList; 5326 } 5327 5328 @Override 5329 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 5330 if (!sUserManager.exists(userId)) return null; 5331 // reader 5332 synchronized (mPackages) { 5333 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 5334 PackageSetting ps = provider != null 5335 ? mSettings.mPackages.get(provider.owner.packageName) 5336 : null; 5337 return ps != null 5338 && mSettings.isEnabledLPr(provider.info, flags, userId) 5339 && (!mSafeMode || (provider.info.applicationInfo.flags 5340 &ApplicationInfo.FLAG_SYSTEM) != 0) 5341 ? PackageParser.generateProviderInfo(provider, flags, 5342 ps.readUserState(userId), userId) 5343 : null; 5344 } 5345 } 5346 5347 /** 5348 * @deprecated 5349 */ 5350 @Deprecated 5351 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 5352 // reader 5353 synchronized (mPackages) { 5354 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 5355 .entrySet().iterator(); 5356 final int userId = UserHandle.getCallingUserId(); 5357 while (i.hasNext()) { 5358 Map.Entry<String, PackageParser.Provider> entry = i.next(); 5359 PackageParser.Provider p = entry.getValue(); 5360 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5361 5362 if (ps != null && p.syncable 5363 && (!mSafeMode || (p.info.applicationInfo.flags 5364 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 5365 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 5366 ps.readUserState(userId), userId); 5367 if (info != null) { 5368 outNames.add(entry.getKey()); 5369 outInfo.add(info); 5370 } 5371 } 5372 } 5373 } 5374 } 5375 5376 @Override 5377 public List<ProviderInfo> queryContentProviders(String processName, 5378 int uid, int flags) { 5379 ArrayList<ProviderInfo> finalList = null; 5380 // reader 5381 synchronized (mPackages) { 5382 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 5383 final int userId = processName != null ? 5384 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 5385 while (i.hasNext()) { 5386 final PackageParser.Provider p = i.next(); 5387 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5388 if (ps != null && p.info.authority != null 5389 && (processName == null 5390 || (p.info.processName.equals(processName) 5391 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 5392 && mSettings.isEnabledLPr(p.info, flags, userId) 5393 && (!mSafeMode 5394 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 5395 if (finalList == null) { 5396 finalList = new ArrayList<ProviderInfo>(3); 5397 } 5398 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 5399 ps.readUserState(userId), userId); 5400 if (info != null) { 5401 finalList.add(info); 5402 } 5403 } 5404 } 5405 } 5406 5407 if (finalList != null) { 5408 Collections.sort(finalList, mProviderInitOrderSorter); 5409 } 5410 5411 return finalList; 5412 } 5413 5414 @Override 5415 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 5416 int flags) { 5417 // reader 5418 synchronized (mPackages) { 5419 final PackageParser.Instrumentation i = mInstrumentation.get(name); 5420 return PackageParser.generateInstrumentationInfo(i, flags); 5421 } 5422 } 5423 5424 @Override 5425 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 5426 int flags) { 5427 ArrayList<InstrumentationInfo> finalList = 5428 new ArrayList<InstrumentationInfo>(); 5429 5430 // reader 5431 synchronized (mPackages) { 5432 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 5433 while (i.hasNext()) { 5434 final PackageParser.Instrumentation p = i.next(); 5435 if (targetPackage == null 5436 || targetPackage.equals(p.info.targetPackage)) { 5437 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 5438 flags); 5439 if (ii != null) { 5440 finalList.add(ii); 5441 } 5442 } 5443 } 5444 } 5445 5446 return finalList; 5447 } 5448 5449 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 5450 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 5451 if (overlays == null) { 5452 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 5453 return; 5454 } 5455 for (PackageParser.Package opkg : overlays.values()) { 5456 // Not much to do if idmap fails: we already logged the error 5457 // and we certainly don't want to abort installation of pkg simply 5458 // because an overlay didn't fit properly. For these reasons, 5459 // ignore the return value of createIdmapForPackagePairLI. 5460 createIdmapForPackagePairLI(pkg, opkg); 5461 } 5462 } 5463 5464 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 5465 PackageParser.Package opkg) { 5466 if (!opkg.mTrustedOverlay) { 5467 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 5468 opkg.baseCodePath + ": overlay not trusted"); 5469 return false; 5470 } 5471 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 5472 if (overlaySet == null) { 5473 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 5474 opkg.baseCodePath + " but target package has no known overlays"); 5475 return false; 5476 } 5477 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 5478 // TODO: generate idmap for split APKs 5479 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 5480 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 5481 + opkg.baseCodePath); 5482 return false; 5483 } 5484 PackageParser.Package[] overlayArray = 5485 overlaySet.values().toArray(new PackageParser.Package[0]); 5486 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 5487 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 5488 return p1.mOverlayPriority - p2.mOverlayPriority; 5489 } 5490 }; 5491 Arrays.sort(overlayArray, cmp); 5492 5493 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 5494 int i = 0; 5495 for (PackageParser.Package p : overlayArray) { 5496 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 5497 } 5498 return true; 5499 } 5500 5501 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5502 final File[] files = dir.listFiles(); 5503 if (ArrayUtils.isEmpty(files)) { 5504 Log.d(TAG, "No files in app dir " + dir); 5505 return; 5506 } 5507 5508 if (DEBUG_PACKAGE_SCANNING) { 5509 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 5510 + " flags=0x" + Integer.toHexString(parseFlags)); 5511 } 5512 5513 for (File file : files) { 5514 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 5515 && !PackageInstallerService.isStageName(file.getName()); 5516 if (!isPackage) { 5517 // Ignore entries which are not packages 5518 continue; 5519 } 5520 try { 5521 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 5522 scanFlags, currentTime, null); 5523 } catch (PackageManagerException e) { 5524 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 5525 5526 // Delete invalid userdata apps 5527 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 5528 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 5529 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 5530 if (file.isDirectory()) { 5531 mInstaller.rmPackageDir(file.getAbsolutePath()); 5532 } else { 5533 file.delete(); 5534 } 5535 } 5536 } 5537 } 5538 } 5539 5540 private static File getSettingsProblemFile() { 5541 File dataDir = Environment.getDataDirectory(); 5542 File systemDir = new File(dataDir, "system"); 5543 File fname = new File(systemDir, "uiderrors.txt"); 5544 return fname; 5545 } 5546 5547 static void reportSettingsProblem(int priority, String msg) { 5548 logCriticalInfo(priority, msg); 5549 } 5550 5551 static void logCriticalInfo(int priority, String msg) { 5552 Slog.println(priority, TAG, msg); 5553 EventLogTags.writePmCriticalInfo(msg); 5554 try { 5555 File fname = getSettingsProblemFile(); 5556 FileOutputStream out = new FileOutputStream(fname, true); 5557 PrintWriter pw = new FastPrintWriter(out); 5558 SimpleDateFormat formatter = new SimpleDateFormat(); 5559 String dateString = formatter.format(new Date(System.currentTimeMillis())); 5560 pw.println(dateString + ": " + msg); 5561 pw.close(); 5562 FileUtils.setPermissions( 5563 fname.toString(), 5564 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 5565 -1, -1); 5566 } catch (java.io.IOException e) { 5567 } 5568 } 5569 5570 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 5571 PackageParser.Package pkg, File srcFile, int parseFlags) 5572 throws PackageManagerException { 5573 if (ps != null 5574 && ps.codePath.equals(srcFile) 5575 && ps.timeStamp == srcFile.lastModified() 5576 && !isCompatSignatureUpdateNeeded(pkg) 5577 && !isRecoverSignatureUpdateNeeded(pkg)) { 5578 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 5579 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5580 ArraySet<PublicKey> signingKs; 5581 synchronized (mPackages) { 5582 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 5583 } 5584 if (ps.signatures.mSignatures != null 5585 && ps.signatures.mSignatures.length != 0 5586 && signingKs != null) { 5587 // Optimization: reuse the existing cached certificates 5588 // if the package appears to be unchanged. 5589 pkg.mSignatures = ps.signatures.mSignatures; 5590 pkg.mSigningKeys = signingKs; 5591 return; 5592 } 5593 5594 Slog.w(TAG, "PackageSetting for " + ps.name 5595 + " is missing signatures. Collecting certs again to recover them."); 5596 } else { 5597 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 5598 } 5599 5600 try { 5601 pp.collectCertificates(pkg, parseFlags); 5602 pp.collectManifestDigest(pkg); 5603 } catch (PackageParserException e) { 5604 throw PackageManagerException.from(e); 5605 } 5606 } 5607 5608 /* 5609 * Scan a package and return the newly parsed package. 5610 * Returns null in case of errors and the error code is stored in mLastScanError 5611 */ 5612 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 5613 long currentTime, UserHandle user) throws PackageManagerException { 5614 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 5615 parseFlags |= mDefParseFlags; 5616 PackageParser pp = new PackageParser(); 5617 pp.setSeparateProcesses(mSeparateProcesses); 5618 pp.setOnlyCoreApps(mOnlyCore); 5619 pp.setDisplayMetrics(mMetrics); 5620 5621 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 5622 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 5623 } 5624 5625 final PackageParser.Package pkg; 5626 try { 5627 pkg = pp.parsePackage(scanFile, parseFlags); 5628 } catch (PackageParserException e) { 5629 throw PackageManagerException.from(e); 5630 } 5631 5632 PackageSetting ps = null; 5633 PackageSetting updatedPkg; 5634 // reader 5635 synchronized (mPackages) { 5636 // Look to see if we already know about this package. 5637 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 5638 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 5639 // This package has been renamed to its original name. Let's 5640 // use that. 5641 ps = mSettings.peekPackageLPr(oldName); 5642 } 5643 // If there was no original package, see one for the real package name. 5644 if (ps == null) { 5645 ps = mSettings.peekPackageLPr(pkg.packageName); 5646 } 5647 // Check to see if this package could be hiding/updating a system 5648 // package. Must look for it either under the original or real 5649 // package name depending on our state. 5650 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 5651 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 5652 } 5653 boolean updatedPkgBetter = false; 5654 // First check if this is a system package that may involve an update 5655 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5656 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5657 // it needs to drop FLAG_PRIVILEGED. 5658 if (locationIsPrivileged(scanFile)) { 5659 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5660 } else { 5661 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5662 } 5663 5664 if (ps != null && !ps.codePath.equals(scanFile)) { 5665 // The path has changed from what was last scanned... check the 5666 // version of the new path against what we have stored to determine 5667 // what to do. 5668 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5669 if (pkg.mVersionCode <= ps.versionCode) { 5670 // The system package has been updated and the code path does not match 5671 // Ignore entry. Skip it. 5672 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5673 + " ignored: updated version " + ps.versionCode 5674 + " better than this " + pkg.mVersionCode); 5675 if (!updatedPkg.codePath.equals(scanFile)) { 5676 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5677 + ps.name + " changing from " + updatedPkg.codePathString 5678 + " to " + scanFile); 5679 updatedPkg.codePath = scanFile; 5680 updatedPkg.codePathString = scanFile.toString(); 5681 updatedPkg.resourcePath = scanFile; 5682 updatedPkg.resourcePathString = scanFile.toString(); 5683 } 5684 updatedPkg.pkg = pkg; 5685 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5686 "Package " + ps.name + " at " + scanFile 5687 + " ignored: updated version " + ps.versionCode 5688 + " better than this " + pkg.mVersionCode); 5689 } else { 5690 // The current app on the system partition is better than 5691 // what we have updated to on the data partition; switch 5692 // back to the system partition version. 5693 // At this point, its safely assumed that package installation for 5694 // apps in system partition will go through. If not there won't be a working 5695 // version of the app 5696 // writer 5697 synchronized (mPackages) { 5698 // Just remove the loaded entries from package lists. 5699 mPackages.remove(ps.name); 5700 } 5701 5702 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5703 + " reverting from " + ps.codePathString 5704 + ": new version " + pkg.mVersionCode 5705 + " better than installed " + ps.versionCode); 5706 5707 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5708 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5709 synchronized (mInstallLock) { 5710 args.cleanUpResourcesLI(); 5711 } 5712 synchronized (mPackages) { 5713 mSettings.enableSystemPackageLPw(ps.name); 5714 } 5715 updatedPkgBetter = true; 5716 } 5717 } 5718 } 5719 5720 if (updatedPkg != null) { 5721 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5722 // initially 5723 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5724 5725 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5726 // flag set initially 5727 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5728 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5729 } 5730 } 5731 5732 // Verify certificates against what was last scanned 5733 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5734 5735 /* 5736 * A new system app appeared, but we already had a non-system one of the 5737 * same name installed earlier. 5738 */ 5739 boolean shouldHideSystemApp = false; 5740 if (updatedPkg == null && ps != null 5741 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5742 /* 5743 * Check to make sure the signatures match first. If they don't, 5744 * wipe the installed application and its data. 5745 */ 5746 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5747 != PackageManager.SIGNATURE_MATCH) { 5748 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5749 + " signatures don't match existing userdata copy; removing"); 5750 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5751 ps = null; 5752 } else { 5753 /* 5754 * If the newly-added system app is an older version than the 5755 * already installed version, hide it. It will be scanned later 5756 * and re-added like an update. 5757 */ 5758 if (pkg.mVersionCode <= ps.versionCode) { 5759 shouldHideSystemApp = true; 5760 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5761 + " but new version " + pkg.mVersionCode + " better than installed " 5762 + ps.versionCode + "; hiding system"); 5763 } else { 5764 /* 5765 * The newly found system app is a newer version that the 5766 * one previously installed. Simply remove the 5767 * already-installed application and replace it with our own 5768 * while keeping the application data. 5769 */ 5770 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5771 + " reverting from " + ps.codePathString + ": new version " 5772 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5773 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5774 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5775 synchronized (mInstallLock) { 5776 args.cleanUpResourcesLI(); 5777 } 5778 } 5779 } 5780 } 5781 5782 // The apk is forward locked (not public) if its code and resources 5783 // are kept in different files. (except for app in either system or 5784 // vendor path). 5785 // TODO grab this value from PackageSettings 5786 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5787 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5788 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5789 } 5790 } 5791 5792 // TODO: extend to support forward-locked splits 5793 String resourcePath = null; 5794 String baseResourcePath = null; 5795 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5796 if (ps != null && ps.resourcePathString != null) { 5797 resourcePath = ps.resourcePathString; 5798 baseResourcePath = ps.resourcePathString; 5799 } else { 5800 // Should not happen at all. Just log an error. 5801 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5802 } 5803 } else { 5804 resourcePath = pkg.codePath; 5805 baseResourcePath = pkg.baseCodePath; 5806 } 5807 5808 // Set application objects path explicitly. 5809 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5810 pkg.applicationInfo.setCodePath(pkg.codePath); 5811 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5812 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5813 pkg.applicationInfo.setResourcePath(resourcePath); 5814 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5815 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5816 5817 // Note that we invoke the following method only if we are about to unpack an application 5818 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5819 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5820 5821 /* 5822 * If the system app should be overridden by a previously installed 5823 * data, hide the system app now and let the /data/app scan pick it up 5824 * again. 5825 */ 5826 if (shouldHideSystemApp) { 5827 synchronized (mPackages) { 5828 /* 5829 * We have to grant systems permissions before we hide, because 5830 * grantPermissions will assume the package update is trying to 5831 * expand its permissions. 5832 */ 5833 grantPermissionsLPw(pkg, true, pkg.packageName); 5834 mSettings.disableSystemPackageLPw(pkg.packageName); 5835 } 5836 } 5837 5838 return scannedPkg; 5839 } 5840 5841 private static String fixProcessName(String defProcessName, 5842 String processName, int uid) { 5843 if (processName == null) { 5844 return defProcessName; 5845 } 5846 return processName; 5847 } 5848 5849 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 5850 throws PackageManagerException { 5851 if (pkgSetting.signatures.mSignatures != null) { 5852 // Already existing package. Make sure signatures match 5853 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 5854 == PackageManager.SIGNATURE_MATCH; 5855 if (!match) { 5856 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 5857 == PackageManager.SIGNATURE_MATCH; 5858 } 5859 if (!match) { 5860 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 5861 == PackageManager.SIGNATURE_MATCH; 5862 } 5863 if (!match) { 5864 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5865 + pkg.packageName + " signatures do not match the " 5866 + "previously installed version; ignoring!"); 5867 } 5868 } 5869 5870 // Check for shared user signatures 5871 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 5872 // Already existing package. Make sure signatures match 5873 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5874 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 5875 if (!match) { 5876 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 5877 == PackageManager.SIGNATURE_MATCH; 5878 } 5879 if (!match) { 5880 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 5881 == PackageManager.SIGNATURE_MATCH; 5882 } 5883 if (!match) { 5884 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 5885 "Package " + pkg.packageName 5886 + " has no signatures that match those in shared user " 5887 + pkgSetting.sharedUser.name + "; ignoring!"); 5888 } 5889 } 5890 } 5891 5892 /** 5893 * Enforces that only the system UID or root's UID can call a method exposed 5894 * via Binder. 5895 * 5896 * @param message used as message if SecurityException is thrown 5897 * @throws SecurityException if the caller is not system or root 5898 */ 5899 private static final void enforceSystemOrRoot(String message) { 5900 final int uid = Binder.getCallingUid(); 5901 if (uid != Process.SYSTEM_UID && uid != 0) { 5902 throw new SecurityException(message); 5903 } 5904 } 5905 5906 @Override 5907 public void performBootDexOpt() { 5908 enforceSystemOrRoot("Only the system can request dexopt be performed"); 5909 5910 // Before everything else, see whether we need to fstrim. 5911 try { 5912 IMountService ms = PackageHelper.getMountService(); 5913 if (ms != null) { 5914 final boolean isUpgrade = isUpgrade(); 5915 boolean doTrim = isUpgrade; 5916 if (doTrim) { 5917 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 5918 } else { 5919 final long interval = android.provider.Settings.Global.getLong( 5920 mContext.getContentResolver(), 5921 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 5922 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 5923 if (interval > 0) { 5924 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 5925 if (timeSinceLast > interval) { 5926 doTrim = true; 5927 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 5928 + "; running immediately"); 5929 } 5930 } 5931 } 5932 if (doTrim) { 5933 if (!isFirstBoot()) { 5934 try { 5935 ActivityManagerNative.getDefault().showBootMessage( 5936 mContext.getResources().getString( 5937 R.string.android_upgrading_fstrim), true); 5938 } catch (RemoteException e) { 5939 } 5940 } 5941 ms.runMaintenance(); 5942 } 5943 } else { 5944 Slog.e(TAG, "Mount service unavailable!"); 5945 } 5946 } catch (RemoteException e) { 5947 // Can't happen; MountService is local 5948 } 5949 5950 final ArraySet<PackageParser.Package> pkgs; 5951 synchronized (mPackages) { 5952 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 5953 } 5954 5955 if (pkgs != null) { 5956 // Sort apps by importance for dexopt ordering. Important apps are given more priority 5957 // in case the device runs out of space. 5958 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 5959 // Give priority to core apps. 5960 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5961 PackageParser.Package pkg = it.next(); 5962 if (pkg.coreApp) { 5963 if (DEBUG_DEXOPT) { 5964 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 5965 } 5966 sortedPkgs.add(pkg); 5967 it.remove(); 5968 } 5969 } 5970 // Give priority to system apps that listen for pre boot complete. 5971 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 5972 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 5973 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5974 PackageParser.Package pkg = it.next(); 5975 if (pkgNames.contains(pkg.packageName)) { 5976 if (DEBUG_DEXOPT) { 5977 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 5978 } 5979 sortedPkgs.add(pkg); 5980 it.remove(); 5981 } 5982 } 5983 // Give priority to system apps. 5984 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5985 PackageParser.Package pkg = it.next(); 5986 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 5987 if (DEBUG_DEXOPT) { 5988 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 5989 } 5990 sortedPkgs.add(pkg); 5991 it.remove(); 5992 } 5993 } 5994 // Give priority to updated system apps. 5995 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5996 PackageParser.Package pkg = it.next(); 5997 if (pkg.isUpdatedSystemApp()) { 5998 if (DEBUG_DEXOPT) { 5999 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 6000 } 6001 sortedPkgs.add(pkg); 6002 it.remove(); 6003 } 6004 } 6005 // Give priority to apps that listen for boot complete. 6006 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 6007 pkgNames = getPackageNamesForIntent(intent); 6008 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6009 PackageParser.Package pkg = it.next(); 6010 if (pkgNames.contains(pkg.packageName)) { 6011 if (DEBUG_DEXOPT) { 6012 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 6013 } 6014 sortedPkgs.add(pkg); 6015 it.remove(); 6016 } 6017 } 6018 // Filter out packages that aren't recently used. 6019 filterRecentlyUsedApps(pkgs); 6020 // Add all remaining apps. 6021 for (PackageParser.Package pkg : pkgs) { 6022 if (DEBUG_DEXOPT) { 6023 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 6024 } 6025 sortedPkgs.add(pkg); 6026 } 6027 6028 // If we want to be lazy, filter everything that wasn't recently used. 6029 if (mLazyDexOpt) { 6030 filterRecentlyUsedApps(sortedPkgs); 6031 } 6032 6033 int i = 0; 6034 int total = sortedPkgs.size(); 6035 File dataDir = Environment.getDataDirectory(); 6036 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 6037 if (lowThreshold == 0) { 6038 throw new IllegalStateException("Invalid low memory threshold"); 6039 } 6040 for (PackageParser.Package pkg : sortedPkgs) { 6041 long usableSpace = dataDir.getUsableSpace(); 6042 if (usableSpace < lowThreshold) { 6043 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 6044 break; 6045 } 6046 performBootDexOpt(pkg, ++i, total); 6047 } 6048 } 6049 } 6050 6051 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 6052 // Filter out packages that aren't recently used. 6053 // 6054 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 6055 // should do a full dexopt. 6056 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 6057 int total = pkgs.size(); 6058 int skipped = 0; 6059 long now = System.currentTimeMillis(); 6060 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 6061 PackageParser.Package pkg = i.next(); 6062 long then = pkg.mLastPackageUsageTimeInMills; 6063 if (then + mDexOptLRUThresholdInMills < now) { 6064 if (DEBUG_DEXOPT) { 6065 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 6066 ((then == 0) ? "never" : new Date(then))); 6067 } 6068 i.remove(); 6069 skipped++; 6070 } 6071 } 6072 if (DEBUG_DEXOPT) { 6073 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 6074 } 6075 } 6076 } 6077 6078 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 6079 List<ResolveInfo> ris = null; 6080 try { 6081 ris = AppGlobals.getPackageManager().queryIntentReceivers( 6082 intent, null, 0, UserHandle.USER_OWNER); 6083 } catch (RemoteException e) { 6084 } 6085 ArraySet<String> pkgNames = new ArraySet<String>(); 6086 if (ris != null) { 6087 for (ResolveInfo ri : ris) { 6088 pkgNames.add(ri.activityInfo.packageName); 6089 } 6090 } 6091 return pkgNames; 6092 } 6093 6094 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 6095 if (DEBUG_DEXOPT) { 6096 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 6097 } 6098 if (!isFirstBoot()) { 6099 try { 6100 ActivityManagerNative.getDefault().showBootMessage( 6101 mContext.getResources().getString(R.string.android_upgrading_apk, 6102 curr, total), true); 6103 } catch (RemoteException e) { 6104 } 6105 } 6106 PackageParser.Package p = pkg; 6107 synchronized (mInstallLock) { 6108 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 6109 false /* force dex */, false /* defer */, true /* include dependencies */); 6110 } 6111 } 6112 6113 @Override 6114 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6115 return performDexOpt(packageName, instructionSet, false); 6116 } 6117 6118 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 6119 boolean dexopt = mLazyDexOpt || backgroundDexopt; 6120 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 6121 if (!dexopt && !updateUsage) { 6122 // We aren't going to dexopt or update usage, so bail early. 6123 return false; 6124 } 6125 PackageParser.Package p; 6126 final String targetInstructionSet; 6127 synchronized (mPackages) { 6128 p = mPackages.get(packageName); 6129 if (p == null) { 6130 return false; 6131 } 6132 if (updateUsage) { 6133 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6134 } 6135 mPackageUsage.write(false); 6136 if (!dexopt) { 6137 // We aren't going to dexopt, so bail early. 6138 return false; 6139 } 6140 6141 targetInstructionSet = instructionSet != null ? instructionSet : 6142 getPrimaryInstructionSet(p.applicationInfo); 6143 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 6144 return false; 6145 } 6146 } 6147 6148 synchronized (mInstallLock) { 6149 final String[] instructionSets = new String[] { targetInstructionSet }; 6150 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 6151 false /* forceDex */, false /* defer */, true /* inclDependencies */); 6152 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6153 } 6154 } 6155 6156 public ArraySet<String> getPackagesThatNeedDexOpt() { 6157 ArraySet<String> pkgs = null; 6158 synchronized (mPackages) { 6159 for (PackageParser.Package p : mPackages.values()) { 6160 if (DEBUG_DEXOPT) { 6161 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 6162 } 6163 if (!p.mDexOptPerformed.isEmpty()) { 6164 continue; 6165 } 6166 if (pkgs == null) { 6167 pkgs = new ArraySet<String>(); 6168 } 6169 pkgs.add(p.packageName); 6170 } 6171 } 6172 return pkgs; 6173 } 6174 6175 public void shutdown() { 6176 mPackageUsage.write(true); 6177 } 6178 6179 @Override 6180 public void forceDexOpt(String packageName) { 6181 enforceSystemOrRoot("forceDexOpt"); 6182 6183 PackageParser.Package pkg; 6184 synchronized (mPackages) { 6185 pkg = mPackages.get(packageName); 6186 if (pkg == null) { 6187 throw new IllegalArgumentException("Missing package: " + packageName); 6188 } 6189 } 6190 6191 synchronized (mInstallLock) { 6192 final String[] instructionSets = new String[] { 6193 getPrimaryInstructionSet(pkg.applicationInfo) }; 6194 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 6195 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 6196 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 6197 throw new IllegalStateException("Failed to dexopt: " + res); 6198 } 6199 } 6200 } 6201 6202 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 6203 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 6204 Slog.w(TAG, "Unable to update from " + oldPkg.name 6205 + " to " + newPkg.packageName 6206 + ": old package not in system partition"); 6207 return false; 6208 } else if (mPackages.get(oldPkg.name) != null) { 6209 Slog.w(TAG, "Unable to update from " + oldPkg.name 6210 + " to " + newPkg.packageName 6211 + ": old package still exists"); 6212 return false; 6213 } 6214 return true; 6215 } 6216 6217 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 6218 int[] users = sUserManager.getUserIds(); 6219 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 6220 if (res < 0) { 6221 return res; 6222 } 6223 for (int user : users) { 6224 if (user != 0) { 6225 res = mInstaller.createUserData(volumeUuid, packageName, 6226 UserHandle.getUid(user, uid), user, seinfo); 6227 if (res < 0) { 6228 return res; 6229 } 6230 } 6231 } 6232 return res; 6233 } 6234 6235 private int removeDataDirsLI(String volumeUuid, String packageName) { 6236 int[] users = sUserManager.getUserIds(); 6237 int res = 0; 6238 for (int user : users) { 6239 int resInner = mInstaller.remove(volumeUuid, packageName, user); 6240 if (resInner < 0) { 6241 res = resInner; 6242 } 6243 } 6244 6245 return res; 6246 } 6247 6248 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 6249 int[] users = sUserManager.getUserIds(); 6250 int res = 0; 6251 for (int user : users) { 6252 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 6253 if (resInner < 0) { 6254 res = resInner; 6255 } 6256 } 6257 return res; 6258 } 6259 6260 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 6261 PackageParser.Package changingLib) { 6262 if (file.path != null) { 6263 usesLibraryFiles.add(file.path); 6264 return; 6265 } 6266 PackageParser.Package p = mPackages.get(file.apk); 6267 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 6268 // If we are doing this while in the middle of updating a library apk, 6269 // then we need to make sure to use that new apk for determining the 6270 // dependencies here. (We haven't yet finished committing the new apk 6271 // to the package manager state.) 6272 if (p == null || p.packageName.equals(changingLib.packageName)) { 6273 p = changingLib; 6274 } 6275 } 6276 if (p != null) { 6277 usesLibraryFiles.addAll(p.getAllCodePaths()); 6278 } 6279 } 6280 6281 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 6282 PackageParser.Package changingLib) throws PackageManagerException { 6283 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 6284 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 6285 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 6286 for (int i=0; i<N; i++) { 6287 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 6288 if (file == null) { 6289 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 6290 "Package " + pkg.packageName + " requires unavailable shared library " 6291 + pkg.usesLibraries.get(i) + "; failing!"); 6292 } 6293 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6294 } 6295 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 6296 for (int i=0; i<N; i++) { 6297 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 6298 if (file == null) { 6299 Slog.w(TAG, "Package " + pkg.packageName 6300 + " desires unavailable shared library " 6301 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 6302 } else { 6303 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6304 } 6305 } 6306 N = usesLibraryFiles.size(); 6307 if (N > 0) { 6308 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 6309 } else { 6310 pkg.usesLibraryFiles = null; 6311 } 6312 } 6313 } 6314 6315 private static boolean hasString(List<String> list, List<String> which) { 6316 if (list == null) { 6317 return false; 6318 } 6319 for (int i=list.size()-1; i>=0; i--) { 6320 for (int j=which.size()-1; j>=0; j--) { 6321 if (which.get(j).equals(list.get(i))) { 6322 return true; 6323 } 6324 } 6325 } 6326 return false; 6327 } 6328 6329 private void updateAllSharedLibrariesLPw() { 6330 for (PackageParser.Package pkg : mPackages.values()) { 6331 try { 6332 updateSharedLibrariesLPw(pkg, null); 6333 } catch (PackageManagerException e) { 6334 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6335 } 6336 } 6337 } 6338 6339 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 6340 PackageParser.Package changingPkg) { 6341 ArrayList<PackageParser.Package> res = null; 6342 for (PackageParser.Package pkg : mPackages.values()) { 6343 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 6344 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 6345 if (res == null) { 6346 res = new ArrayList<PackageParser.Package>(); 6347 } 6348 res.add(pkg); 6349 try { 6350 updateSharedLibrariesLPw(pkg, changingPkg); 6351 } catch (PackageManagerException e) { 6352 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6353 } 6354 } 6355 } 6356 return res; 6357 } 6358 6359 /** 6360 * Derive the value of the {@code cpuAbiOverride} based on the provided 6361 * value and an optional stored value from the package settings. 6362 */ 6363 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 6364 String cpuAbiOverride = null; 6365 6366 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 6367 cpuAbiOverride = null; 6368 } else if (abiOverride != null) { 6369 cpuAbiOverride = abiOverride; 6370 } else if (settings != null) { 6371 cpuAbiOverride = settings.cpuAbiOverrideString; 6372 } 6373 6374 return cpuAbiOverride; 6375 } 6376 6377 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 6378 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6379 boolean success = false; 6380 try { 6381 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 6382 currentTime, user); 6383 success = true; 6384 return res; 6385 } finally { 6386 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 6387 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 6388 } 6389 } 6390 } 6391 6392 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 6393 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6394 final File scanFile = new File(pkg.codePath); 6395 if (pkg.applicationInfo.getCodePath() == null || 6396 pkg.applicationInfo.getResourcePath() == null) { 6397 // Bail out. The resource and code paths haven't been set. 6398 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 6399 "Code and resource paths haven't been set correctly"); 6400 } 6401 6402 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 6403 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 6404 } else { 6405 // Only allow system apps to be flagged as core apps. 6406 pkg.coreApp = false; 6407 } 6408 6409 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 6410 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6411 } 6412 6413 if (mCustomResolverComponentName != null && 6414 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 6415 setUpCustomResolverActivity(pkg); 6416 } 6417 6418 if (pkg.packageName.equals("android")) { 6419 synchronized (mPackages) { 6420 if (mAndroidApplication != null) { 6421 Slog.w(TAG, "*************************************************"); 6422 Slog.w(TAG, "Core android package being redefined. Skipping."); 6423 Slog.w(TAG, " file=" + scanFile); 6424 Slog.w(TAG, "*************************************************"); 6425 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6426 "Core android package being redefined. Skipping."); 6427 } 6428 6429 // Set up information for our fall-back user intent resolution activity. 6430 mPlatformPackage = pkg; 6431 pkg.mVersionCode = mSdkVersion; 6432 mAndroidApplication = pkg.applicationInfo; 6433 6434 if (!mResolverReplaced) { 6435 mResolveActivity.applicationInfo = mAndroidApplication; 6436 mResolveActivity.name = ResolverActivity.class.getName(); 6437 mResolveActivity.packageName = mAndroidApplication.packageName; 6438 mResolveActivity.processName = "system:ui"; 6439 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6440 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 6441 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 6442 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 6443 mResolveActivity.exported = true; 6444 mResolveActivity.enabled = true; 6445 mResolveInfo.activityInfo = mResolveActivity; 6446 mResolveInfo.priority = 0; 6447 mResolveInfo.preferredOrder = 0; 6448 mResolveInfo.match = 0; 6449 mResolveComponentName = new ComponentName( 6450 mAndroidApplication.packageName, mResolveActivity.name); 6451 } 6452 } 6453 } 6454 6455 if (DEBUG_PACKAGE_SCANNING) { 6456 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6457 Log.d(TAG, "Scanning package " + pkg.packageName); 6458 } 6459 6460 if (mPackages.containsKey(pkg.packageName) 6461 || mSharedLibraries.containsKey(pkg.packageName)) { 6462 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6463 "Application package " + pkg.packageName 6464 + " already installed. Skipping duplicate."); 6465 } 6466 6467 // If we're only installing presumed-existing packages, require that the 6468 // scanned APK is both already known and at the path previously established 6469 // for it. Previously unknown packages we pick up normally, but if we have an 6470 // a priori expectation about this package's install presence, enforce it. 6471 // With a singular exception for new system packages. When an OTA contains 6472 // a new system package, we allow the codepath to change from a system location 6473 // to the user-installed location. If we don't allow this change, any newer, 6474 // user-installed version of the application will be ignored. 6475 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 6476 if (mExpectingBetter.containsKey(pkg.packageName)) { 6477 logCriticalInfo(Log.WARN, 6478 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 6479 } else { 6480 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 6481 if (known != null) { 6482 if (DEBUG_PACKAGE_SCANNING) { 6483 Log.d(TAG, "Examining " + pkg.codePath 6484 + " and requiring known paths " + known.codePathString 6485 + " & " + known.resourcePathString); 6486 } 6487 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6488 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6489 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6490 "Application package " + pkg.packageName 6491 + " found at " + pkg.applicationInfo.getCodePath() 6492 + " but expected at " + known.codePathString + "; ignoring."); 6493 } 6494 } 6495 } 6496 } 6497 6498 // Initialize package source and resource directories 6499 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6500 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6501 6502 SharedUserSetting suid = null; 6503 PackageSetting pkgSetting = null; 6504 6505 if (!isSystemApp(pkg)) { 6506 // Only system apps can use these features. 6507 pkg.mOriginalPackages = null; 6508 pkg.mRealPackage = null; 6509 pkg.mAdoptPermissions = null; 6510 } 6511 6512 // writer 6513 synchronized (mPackages) { 6514 if (pkg.mSharedUserId != null) { 6515 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 6516 if (suid == null) { 6517 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6518 "Creating application package " + pkg.packageName 6519 + " for shared user failed"); 6520 } 6521 if (DEBUG_PACKAGE_SCANNING) { 6522 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6523 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 6524 + "): packages=" + suid.packages); 6525 } 6526 } 6527 6528 // Check if we are renaming from an original package name. 6529 PackageSetting origPackage = null; 6530 String realName = null; 6531 if (pkg.mOriginalPackages != null) { 6532 // This package may need to be renamed to a previously 6533 // installed name. Let's check on that... 6534 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 6535 if (pkg.mOriginalPackages.contains(renamed)) { 6536 // This package had originally been installed as the 6537 // original name, and we have already taken care of 6538 // transitioning to the new one. Just update the new 6539 // one to continue using the old name. 6540 realName = pkg.mRealPackage; 6541 if (!pkg.packageName.equals(renamed)) { 6542 // Callers into this function may have already taken 6543 // care of renaming the package; only do it here if 6544 // it is not already done. 6545 pkg.setPackageName(renamed); 6546 } 6547 6548 } else { 6549 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 6550 if ((origPackage = mSettings.peekPackageLPr( 6551 pkg.mOriginalPackages.get(i))) != null) { 6552 // We do have the package already installed under its 6553 // original name... should we use it? 6554 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 6555 // New package is not compatible with original. 6556 origPackage = null; 6557 continue; 6558 } else if (origPackage.sharedUser != null) { 6559 // Make sure uid is compatible between packages. 6560 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 6561 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 6562 + " to " + pkg.packageName + ": old uid " 6563 + origPackage.sharedUser.name 6564 + " differs from " + pkg.mSharedUserId); 6565 origPackage = null; 6566 continue; 6567 } 6568 } else { 6569 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6570 + pkg.packageName + " to old name " + origPackage.name); 6571 } 6572 break; 6573 } 6574 } 6575 } 6576 } 6577 6578 if (mTransferedPackages.contains(pkg.packageName)) { 6579 Slog.w(TAG, "Package " + pkg.packageName 6580 + " was transferred to another, but its .apk remains"); 6581 } 6582 6583 // Just create the setting, don't add it yet. For already existing packages 6584 // the PkgSetting exists already and doesn't have to be created. 6585 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6586 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6587 pkg.applicationInfo.primaryCpuAbi, 6588 pkg.applicationInfo.secondaryCpuAbi, 6589 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6590 user, false); 6591 if (pkgSetting == null) { 6592 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6593 "Creating application package " + pkg.packageName + " failed"); 6594 } 6595 6596 if (pkgSetting.origPackage != null) { 6597 // If we are first transitioning from an original package, 6598 // fix up the new package's name now. We need to do this after 6599 // looking up the package under its new name, so getPackageLP 6600 // can take care of fiddling things correctly. 6601 pkg.setPackageName(origPackage.name); 6602 6603 // File a report about this. 6604 String msg = "New package " + pkgSetting.realName 6605 + " renamed to replace old package " + pkgSetting.name; 6606 reportSettingsProblem(Log.WARN, msg); 6607 6608 // Make a note of it. 6609 mTransferedPackages.add(origPackage.name); 6610 6611 // No longer need to retain this. 6612 pkgSetting.origPackage = null; 6613 } 6614 6615 if (realName != null) { 6616 // Make a note of it. 6617 mTransferedPackages.add(pkg.packageName); 6618 } 6619 6620 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6621 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6622 } 6623 6624 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6625 // Check all shared libraries and map to their actual file path. 6626 // We only do this here for apps not on a system dir, because those 6627 // are the only ones that can fail an install due to this. We 6628 // will take care of the system apps by updating all of their 6629 // library paths after the scan is done. 6630 updateSharedLibrariesLPw(pkg, null); 6631 } 6632 6633 if (mFoundPolicyFile) { 6634 SELinuxMMAC.assignSeinfoValue(pkg); 6635 } 6636 6637 pkg.applicationInfo.uid = pkgSetting.appId; 6638 pkg.mExtras = pkgSetting; 6639 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 6640 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 6641 // We just determined the app is signed correctly, so bring 6642 // over the latest parsed certs. 6643 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6644 } else { 6645 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6646 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6647 "Package " + pkg.packageName + " upgrade keys do not match the " 6648 + "previously installed version"); 6649 } else { 6650 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6651 String msg = "System package " + pkg.packageName 6652 + " signature changed; retaining data."; 6653 reportSettingsProblem(Log.WARN, msg); 6654 } 6655 } 6656 } else { 6657 try { 6658 verifySignaturesLP(pkgSetting, pkg); 6659 // We just determined the app is signed correctly, so bring 6660 // over the latest parsed certs. 6661 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6662 } catch (PackageManagerException e) { 6663 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6664 throw e; 6665 } 6666 // The signature has changed, but this package is in the system 6667 // image... let's recover! 6668 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6669 // However... if this package is part of a shared user, but it 6670 // doesn't match the signature of the shared user, let's fail. 6671 // What this means is that you can't change the signatures 6672 // associated with an overall shared user, which doesn't seem all 6673 // that unreasonable. 6674 if (pkgSetting.sharedUser != null) { 6675 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6676 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 6677 throw new PackageManagerException( 6678 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6679 "Signature mismatch for shared user : " 6680 + pkgSetting.sharedUser); 6681 } 6682 } 6683 // File a report about this. 6684 String msg = "System package " + pkg.packageName 6685 + " signature changed; retaining data."; 6686 reportSettingsProblem(Log.WARN, msg); 6687 } 6688 } 6689 // Verify that this new package doesn't have any content providers 6690 // that conflict with existing packages. Only do this if the 6691 // package isn't already installed, since we don't want to break 6692 // things that are installed. 6693 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6694 final int N = pkg.providers.size(); 6695 int i; 6696 for (i=0; i<N; i++) { 6697 PackageParser.Provider p = pkg.providers.get(i); 6698 if (p.info.authority != null) { 6699 String names[] = p.info.authority.split(";"); 6700 for (int j = 0; j < names.length; j++) { 6701 if (mProvidersByAuthority.containsKey(names[j])) { 6702 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6703 final String otherPackageName = 6704 ((other != null && other.getComponentName() != null) ? 6705 other.getComponentName().getPackageName() : "?"); 6706 throw new PackageManagerException( 6707 INSTALL_FAILED_CONFLICTING_PROVIDER, 6708 "Can't install because provider name " + names[j] 6709 + " (in package " + pkg.applicationInfo.packageName 6710 + ") is already used by " + otherPackageName); 6711 } 6712 } 6713 } 6714 } 6715 } 6716 6717 if (pkg.mAdoptPermissions != null) { 6718 // This package wants to adopt ownership of permissions from 6719 // another package. 6720 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6721 final String origName = pkg.mAdoptPermissions.get(i); 6722 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6723 if (orig != null) { 6724 if (verifyPackageUpdateLPr(orig, pkg)) { 6725 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6726 + pkg.packageName); 6727 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6728 } 6729 } 6730 } 6731 } 6732 } 6733 6734 final String pkgName = pkg.packageName; 6735 6736 final long scanFileTime = scanFile.lastModified(); 6737 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6738 pkg.applicationInfo.processName = fixProcessName( 6739 pkg.applicationInfo.packageName, 6740 pkg.applicationInfo.processName, 6741 pkg.applicationInfo.uid); 6742 6743 File dataPath; 6744 if (mPlatformPackage == pkg) { 6745 // The system package is special. 6746 dataPath = new File(Environment.getDataDirectory(), "system"); 6747 6748 pkg.applicationInfo.dataDir = dataPath.getPath(); 6749 6750 } else { 6751 // This is a normal package, need to make its data directory. 6752 dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid, 6753 UserHandle.USER_OWNER, pkg.packageName); 6754 6755 boolean uidError = false; 6756 if (dataPath.exists()) { 6757 int currentUid = 0; 6758 try { 6759 StructStat stat = Os.stat(dataPath.getPath()); 6760 currentUid = stat.st_uid; 6761 } catch (ErrnoException e) { 6762 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6763 } 6764 6765 // If we have mismatched owners for the data path, we have a problem. 6766 if (currentUid != pkg.applicationInfo.uid) { 6767 boolean recovered = false; 6768 if (currentUid == 0) { 6769 // The directory somehow became owned by root. Wow. 6770 // This is probably because the system was stopped while 6771 // installd was in the middle of messing with its libs 6772 // directory. Ask installd to fix that. 6773 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6774 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6775 if (ret >= 0) { 6776 recovered = true; 6777 String msg = "Package " + pkg.packageName 6778 + " unexpectedly changed to uid 0; recovered to " + 6779 + pkg.applicationInfo.uid; 6780 reportSettingsProblem(Log.WARN, msg); 6781 } 6782 } 6783 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6784 || (scanFlags&SCAN_BOOTING) != 0)) { 6785 // If this is a system app, we can at least delete its 6786 // current data so the application will still work. 6787 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6788 if (ret >= 0) { 6789 // TODO: Kill the processes first 6790 // Old data gone! 6791 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6792 ? "System package " : "Third party package "; 6793 String msg = prefix + pkg.packageName 6794 + " has changed from uid: " 6795 + currentUid + " to " 6796 + pkg.applicationInfo.uid + "; old data erased"; 6797 reportSettingsProblem(Log.WARN, msg); 6798 recovered = true; 6799 6800 // And now re-install the app. 6801 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6802 pkg.applicationInfo.seinfo); 6803 if (ret == -1) { 6804 // Ack should not happen! 6805 msg = prefix + pkg.packageName 6806 + " could not have data directory re-created after delete."; 6807 reportSettingsProblem(Log.WARN, msg); 6808 throw new PackageManagerException( 6809 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6810 } 6811 } 6812 if (!recovered) { 6813 mHasSystemUidErrors = true; 6814 } 6815 } else if (!recovered) { 6816 // If we allow this install to proceed, we will be broken. 6817 // Abort, abort! 6818 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6819 "scanPackageLI"); 6820 } 6821 if (!recovered) { 6822 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6823 + pkg.applicationInfo.uid + "/fs_" 6824 + currentUid; 6825 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6826 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6827 String msg = "Package " + pkg.packageName 6828 + " has mismatched uid: " 6829 + currentUid + " on disk, " 6830 + pkg.applicationInfo.uid + " in settings"; 6831 // writer 6832 synchronized (mPackages) { 6833 mSettings.mReadMessages.append(msg); 6834 mSettings.mReadMessages.append('\n'); 6835 uidError = true; 6836 if (!pkgSetting.uidError) { 6837 reportSettingsProblem(Log.ERROR, msg); 6838 } 6839 } 6840 } 6841 } 6842 pkg.applicationInfo.dataDir = dataPath.getPath(); 6843 if (mShouldRestoreconData) { 6844 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6845 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 6846 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 6847 } 6848 } else { 6849 if (DEBUG_PACKAGE_SCANNING) { 6850 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6851 Log.v(TAG, "Want this data dir: " + dataPath); 6852 } 6853 //invoke installer to do the actual installation 6854 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6855 pkg.applicationInfo.seinfo); 6856 if (ret < 0) { 6857 // Error from installer 6858 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6859 "Unable to create data dirs [errorCode=" + ret + "]"); 6860 } 6861 6862 if (dataPath.exists()) { 6863 pkg.applicationInfo.dataDir = dataPath.getPath(); 6864 } else { 6865 Slog.w(TAG, "Unable to create data directory: " + dataPath); 6866 pkg.applicationInfo.dataDir = null; 6867 } 6868 } 6869 6870 pkgSetting.uidError = uidError; 6871 } 6872 6873 final String path = scanFile.getPath(); 6874 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6875 6876 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 6877 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 6878 6879 // Some system apps still use directory structure for native libraries 6880 // in which case we might end up not detecting abi solely based on apk 6881 // structure. Try to detect abi based on directory structure. 6882 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 6883 pkg.applicationInfo.primaryCpuAbi == null) { 6884 setBundledAppAbisAndRoots(pkg, pkgSetting); 6885 setNativeLibraryPaths(pkg); 6886 } 6887 6888 } else { 6889 if ((scanFlags & SCAN_MOVE) != 0) { 6890 // We haven't run dex-opt for this move (since we've moved the compiled output too) 6891 // but we already have this packages package info in the PackageSetting. We just 6892 // use that and derive the native library path based on the new codepath. 6893 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 6894 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 6895 } 6896 6897 // Set native library paths again. For moves, the path will be updated based on the 6898 // ABIs we've determined above. For non-moves, the path will be updated based on the 6899 // ABIs we determined during compilation, but the path will depend on the final 6900 // package path (after the rename away from the stage path). 6901 setNativeLibraryPaths(pkg); 6902 } 6903 6904 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 6905 final int[] userIds = sUserManager.getUserIds(); 6906 synchronized (mInstallLock) { 6907 // Make sure all user data directories are ready to roll; we're okay 6908 // if they already exist 6909 if (!TextUtils.isEmpty(pkg.volumeUuid)) { 6910 for (int userId : userIds) { 6911 if (userId != 0) { 6912 mInstaller.createUserData(pkg.volumeUuid, pkg.packageName, 6913 UserHandle.getUid(userId, pkg.applicationInfo.uid), userId, 6914 pkg.applicationInfo.seinfo); 6915 } 6916 } 6917 } 6918 6919 // Create a native library symlink only if we have native libraries 6920 // and if the native libraries are 32 bit libraries. We do not provide 6921 // this symlink for 64 bit libraries. 6922 if (pkg.applicationInfo.primaryCpuAbi != null && 6923 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 6924 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 6925 for (int userId : userIds) { 6926 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 6927 nativeLibPath, userId) < 0) { 6928 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6929 "Failed linking native library dir (user=" + userId + ")"); 6930 } 6931 } 6932 } 6933 } 6934 6935 // This is a special case for the "system" package, where the ABI is 6936 // dictated by the zygote configuration (and init.rc). We should keep track 6937 // of this ABI so that we can deal with "normal" applications that run under 6938 // the same UID correctly. 6939 if (mPlatformPackage == pkg) { 6940 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 6941 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 6942 } 6943 6944 // If there's a mismatch between the abi-override in the package setting 6945 // and the abiOverride specified for the install. Warn about this because we 6946 // would've already compiled the app without taking the package setting into 6947 // account. 6948 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 6949 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 6950 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 6951 " for package: " + pkg.packageName); 6952 } 6953 } 6954 6955 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6956 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6957 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 6958 6959 // Copy the derived override back to the parsed package, so that we can 6960 // update the package settings accordingly. 6961 pkg.cpuAbiOverride = cpuAbiOverride; 6962 6963 if (DEBUG_ABI_SELECTION) { 6964 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 6965 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 6966 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 6967 } 6968 6969 // Push the derived path down into PackageSettings so we know what to 6970 // clean up at uninstall time. 6971 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 6972 6973 if (DEBUG_ABI_SELECTION) { 6974 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 6975 " primary=" + pkg.applicationInfo.primaryCpuAbi + 6976 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 6977 } 6978 6979 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 6980 // We don't do this here during boot because we can do it all 6981 // at once after scanning all existing packages. 6982 // 6983 // We also do this *before* we perform dexopt on this package, so that 6984 // we can avoid redundant dexopts, and also to make sure we've got the 6985 // code and package path correct. 6986 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 6987 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 6988 } 6989 6990 if ((scanFlags & SCAN_NO_DEX) == 0) { 6991 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 6992 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 6993 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6994 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 6995 } 6996 } 6997 if (mFactoryTest && pkg.requestedPermissions.contains( 6998 android.Manifest.permission.FACTORY_TEST)) { 6999 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 7000 } 7001 7002 ArrayList<PackageParser.Package> clientLibPkgs = null; 7003 7004 // writer 7005 synchronized (mPackages) { 7006 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7007 // Only system apps can add new shared libraries. 7008 if (pkg.libraryNames != null) { 7009 for (int i=0; i<pkg.libraryNames.size(); i++) { 7010 String name = pkg.libraryNames.get(i); 7011 boolean allowed = false; 7012 if (pkg.isUpdatedSystemApp()) { 7013 // New library entries can only be added through the 7014 // system image. This is important to get rid of a lot 7015 // of nasty edge cases: for example if we allowed a non- 7016 // system update of the app to add a library, then uninstalling 7017 // the update would make the library go away, and assumptions 7018 // we made such as through app install filtering would now 7019 // have allowed apps on the device which aren't compatible 7020 // with it. Better to just have the restriction here, be 7021 // conservative, and create many fewer cases that can negatively 7022 // impact the user experience. 7023 final PackageSetting sysPs = mSettings 7024 .getDisabledSystemPkgLPr(pkg.packageName); 7025 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 7026 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 7027 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 7028 allowed = true; 7029 allowed = true; 7030 break; 7031 } 7032 } 7033 } 7034 } else { 7035 allowed = true; 7036 } 7037 if (allowed) { 7038 if (!mSharedLibraries.containsKey(name)) { 7039 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 7040 } else if (!name.equals(pkg.packageName)) { 7041 Slog.w(TAG, "Package " + pkg.packageName + " library " 7042 + name + " already exists; skipping"); 7043 } 7044 } else { 7045 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 7046 + name + " that is not declared on system image; skipping"); 7047 } 7048 } 7049 if ((scanFlags&SCAN_BOOTING) == 0) { 7050 // If we are not booting, we need to update any applications 7051 // that are clients of our shared library. If we are booting, 7052 // this will all be done once the scan is complete. 7053 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 7054 } 7055 } 7056 } 7057 } 7058 7059 // We also need to dexopt any apps that are dependent on this library. Note that 7060 // if these fail, we should abort the install since installing the library will 7061 // result in some apps being broken. 7062 if (clientLibPkgs != null) { 7063 if ((scanFlags & SCAN_NO_DEX) == 0) { 7064 for (int i = 0; i < clientLibPkgs.size(); i++) { 7065 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7066 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 7067 null /* instruction sets */, forceDex, 7068 (scanFlags & SCAN_DEFER_DEX) != 0, false); 7069 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7070 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 7071 "scanPackageLI failed to dexopt clientLibPkgs"); 7072 } 7073 } 7074 } 7075 } 7076 7077 // Also need to kill any apps that are dependent on the library. 7078 if (clientLibPkgs != null) { 7079 for (int i=0; i<clientLibPkgs.size(); i++) { 7080 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7081 killApplication(clientPkg.applicationInfo.packageName, 7082 clientPkg.applicationInfo.uid, "update lib"); 7083 } 7084 } 7085 7086 // Make sure we're not adding any bogus keyset info 7087 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7088 ksms.assertScannedPackageValid(pkg); 7089 7090 // writer 7091 synchronized (mPackages) { 7092 // We don't expect installation to fail beyond this point 7093 7094 // Add the new setting to mSettings 7095 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 7096 // Add the new setting to mPackages 7097 mPackages.put(pkg.applicationInfo.packageName, pkg); 7098 // Make sure we don't accidentally delete its data. 7099 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 7100 while (iter.hasNext()) { 7101 PackageCleanItem item = iter.next(); 7102 if (pkgName.equals(item.packageName)) { 7103 iter.remove(); 7104 } 7105 } 7106 7107 // Take care of first install / last update times. 7108 if (currentTime != 0) { 7109 if (pkgSetting.firstInstallTime == 0) { 7110 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7111 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7112 pkgSetting.lastUpdateTime = currentTime; 7113 } 7114 } else if (pkgSetting.firstInstallTime == 0) { 7115 // We need *something*. Take time time stamp of the file. 7116 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7117 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7118 if (scanFileTime != pkgSetting.timeStamp) { 7119 // A package on the system image has changed; consider this 7120 // to be an update. 7121 pkgSetting.lastUpdateTime = scanFileTime; 7122 } 7123 } 7124 7125 // Add the package's KeySets to the global KeySetManagerService 7126 ksms.addScannedPackageLPw(pkg); 7127 7128 int N = pkg.providers.size(); 7129 StringBuilder r = null; 7130 int i; 7131 for (i=0; i<N; i++) { 7132 PackageParser.Provider p = pkg.providers.get(i); 7133 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7134 p.info.processName, pkg.applicationInfo.uid); 7135 mProviders.addProvider(p); 7136 p.syncable = p.info.isSyncable; 7137 if (p.info.authority != null) { 7138 String names[] = p.info.authority.split(";"); 7139 p.info.authority = null; 7140 for (int j = 0; j < names.length; j++) { 7141 if (j == 1 && p.syncable) { 7142 // We only want the first authority for a provider to possibly be 7143 // syncable, so if we already added this provider using a different 7144 // authority clear the syncable flag. We copy the provider before 7145 // changing it because the mProviders object contains a reference 7146 // to a provider that we don't want to change. 7147 // Only do this for the second authority since the resulting provider 7148 // object can be the same for all future authorities for this provider. 7149 p = new PackageParser.Provider(p); 7150 p.syncable = false; 7151 } 7152 if (!mProvidersByAuthority.containsKey(names[j])) { 7153 mProvidersByAuthority.put(names[j], p); 7154 if (p.info.authority == null) { 7155 p.info.authority = names[j]; 7156 } else { 7157 p.info.authority = p.info.authority + ";" + names[j]; 7158 } 7159 if (DEBUG_PACKAGE_SCANNING) { 7160 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7161 Log.d(TAG, "Registered content provider: " + names[j] 7162 + ", className = " + p.info.name + ", isSyncable = " 7163 + p.info.isSyncable); 7164 } 7165 } else { 7166 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7167 Slog.w(TAG, "Skipping provider name " + names[j] + 7168 " (in package " + pkg.applicationInfo.packageName + 7169 "): name already used by " 7170 + ((other != null && other.getComponentName() != null) 7171 ? other.getComponentName().getPackageName() : "?")); 7172 } 7173 } 7174 } 7175 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7176 if (r == null) { 7177 r = new StringBuilder(256); 7178 } else { 7179 r.append(' '); 7180 } 7181 r.append(p.info.name); 7182 } 7183 } 7184 if (r != null) { 7185 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7186 } 7187 7188 N = pkg.services.size(); 7189 r = null; 7190 for (i=0; i<N; i++) { 7191 PackageParser.Service s = pkg.services.get(i); 7192 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 7193 s.info.processName, pkg.applicationInfo.uid); 7194 mServices.addService(s); 7195 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7196 if (r == null) { 7197 r = new StringBuilder(256); 7198 } else { 7199 r.append(' '); 7200 } 7201 r.append(s.info.name); 7202 } 7203 } 7204 if (r != null) { 7205 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 7206 } 7207 7208 N = pkg.receivers.size(); 7209 r = null; 7210 for (i=0; i<N; i++) { 7211 PackageParser.Activity a = pkg.receivers.get(i); 7212 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7213 a.info.processName, pkg.applicationInfo.uid); 7214 mReceivers.addActivity(a, "receiver"); 7215 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7216 if (r == null) { 7217 r = new StringBuilder(256); 7218 } else { 7219 r.append(' '); 7220 } 7221 r.append(a.info.name); 7222 } 7223 } 7224 if (r != null) { 7225 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 7226 } 7227 7228 N = pkg.activities.size(); 7229 r = null; 7230 for (i=0; i<N; i++) { 7231 PackageParser.Activity a = pkg.activities.get(i); 7232 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7233 a.info.processName, pkg.applicationInfo.uid); 7234 mActivities.addActivity(a, "activity"); 7235 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7236 if (r == null) { 7237 r = new StringBuilder(256); 7238 } else { 7239 r.append(' '); 7240 } 7241 r.append(a.info.name); 7242 } 7243 } 7244 if (r != null) { 7245 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 7246 } 7247 7248 N = pkg.permissionGroups.size(); 7249 r = null; 7250 for (i=0; i<N; i++) { 7251 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 7252 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 7253 if (cur == null) { 7254 mPermissionGroups.put(pg.info.name, pg); 7255 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7256 if (r == null) { 7257 r = new StringBuilder(256); 7258 } else { 7259 r.append(' '); 7260 } 7261 r.append(pg.info.name); 7262 } 7263 } else { 7264 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 7265 + pg.info.packageName + " ignored: original from " 7266 + cur.info.packageName); 7267 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7268 if (r == null) { 7269 r = new StringBuilder(256); 7270 } else { 7271 r.append(' '); 7272 } 7273 r.append("DUP:"); 7274 r.append(pg.info.name); 7275 } 7276 } 7277 } 7278 if (r != null) { 7279 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 7280 } 7281 7282 N = pkg.permissions.size(); 7283 r = null; 7284 for (i=0; i<N; i++) { 7285 PackageParser.Permission p = pkg.permissions.get(i); 7286 7287 // Now that permission groups have a special meaning, we ignore permission 7288 // groups for legacy apps to prevent unexpected behavior. In particular, 7289 // permissions for one app being granted to someone just becuase they happen 7290 // to be in a group defined by another app (before this had no implications). 7291 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 7292 p.group = mPermissionGroups.get(p.info.group); 7293 // Warn for a permission in an unknown group. 7294 if (p.info.group != null && p.group == null) { 7295 Slog.w(TAG, "Permission " + p.info.name + " from package " 7296 + p.info.packageName + " in an unknown group " + p.info.group); 7297 } 7298 } 7299 7300 ArrayMap<String, BasePermission> permissionMap = 7301 p.tree ? mSettings.mPermissionTrees 7302 : mSettings.mPermissions; 7303 BasePermission bp = permissionMap.get(p.info.name); 7304 7305 // Allow system apps to redefine non-system permissions 7306 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 7307 final boolean currentOwnerIsSystem = (bp.perm != null 7308 && isSystemApp(bp.perm.owner)); 7309 if (isSystemApp(p.owner)) { 7310 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 7311 // It's a built-in permission and no owner, take ownership now 7312 bp.packageSetting = pkgSetting; 7313 bp.perm = p; 7314 bp.uid = pkg.applicationInfo.uid; 7315 bp.sourcePackage = p.info.packageName; 7316 } else if (!currentOwnerIsSystem) { 7317 String msg = "New decl " + p.owner + " of permission " 7318 + p.info.name + " is system; overriding " + bp.sourcePackage; 7319 reportSettingsProblem(Log.WARN, msg); 7320 bp = null; 7321 } 7322 } 7323 } 7324 7325 if (bp == null) { 7326 bp = new BasePermission(p.info.name, p.info.packageName, 7327 BasePermission.TYPE_NORMAL); 7328 permissionMap.put(p.info.name, bp); 7329 } 7330 7331 if (bp.perm == null) { 7332 if (bp.sourcePackage == null 7333 || bp.sourcePackage.equals(p.info.packageName)) { 7334 BasePermission tree = findPermissionTreeLP(p.info.name); 7335 if (tree == null 7336 || tree.sourcePackage.equals(p.info.packageName)) { 7337 bp.packageSetting = pkgSetting; 7338 bp.perm = p; 7339 bp.uid = pkg.applicationInfo.uid; 7340 bp.sourcePackage = p.info.packageName; 7341 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7342 if (r == null) { 7343 r = new StringBuilder(256); 7344 } else { 7345 r.append(' '); 7346 } 7347 r.append(p.info.name); 7348 } 7349 } else { 7350 Slog.w(TAG, "Permission " + p.info.name + " from package " 7351 + p.info.packageName + " ignored: base tree " 7352 + tree.name + " is from package " 7353 + tree.sourcePackage); 7354 } 7355 } else { 7356 Slog.w(TAG, "Permission " + p.info.name + " from package " 7357 + p.info.packageName + " ignored: original from " 7358 + bp.sourcePackage); 7359 } 7360 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7361 if (r == null) { 7362 r = new StringBuilder(256); 7363 } else { 7364 r.append(' '); 7365 } 7366 r.append("DUP:"); 7367 r.append(p.info.name); 7368 } 7369 if (bp.perm == p) { 7370 bp.protectionLevel = p.info.protectionLevel; 7371 } 7372 } 7373 7374 if (r != null) { 7375 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 7376 } 7377 7378 N = pkg.instrumentation.size(); 7379 r = null; 7380 for (i=0; i<N; i++) { 7381 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7382 a.info.packageName = pkg.applicationInfo.packageName; 7383 a.info.sourceDir = pkg.applicationInfo.sourceDir; 7384 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 7385 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 7386 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 7387 a.info.dataDir = pkg.applicationInfo.dataDir; 7388 7389 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 7390 // need other information about the application, like the ABI and what not ? 7391 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 7392 mInstrumentation.put(a.getComponentName(), a); 7393 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7394 if (r == null) { 7395 r = new StringBuilder(256); 7396 } else { 7397 r.append(' '); 7398 } 7399 r.append(a.info.name); 7400 } 7401 } 7402 if (r != null) { 7403 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 7404 } 7405 7406 if (pkg.protectedBroadcasts != null) { 7407 N = pkg.protectedBroadcasts.size(); 7408 for (i=0; i<N; i++) { 7409 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 7410 } 7411 } 7412 7413 pkgSetting.setTimeStamp(scanFileTime); 7414 7415 // Create idmap files for pairs of (packages, overlay packages). 7416 // Note: "android", ie framework-res.apk, is handled by native layers. 7417 if (pkg.mOverlayTarget != null) { 7418 // This is an overlay package. 7419 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 7420 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 7421 mOverlays.put(pkg.mOverlayTarget, 7422 new ArrayMap<String, PackageParser.Package>()); 7423 } 7424 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 7425 map.put(pkg.packageName, pkg); 7426 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 7427 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 7428 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7429 "scanPackageLI failed to createIdmap"); 7430 } 7431 } 7432 } else if (mOverlays.containsKey(pkg.packageName) && 7433 !pkg.packageName.equals("android")) { 7434 // This is a regular package, with one or more known overlay packages. 7435 createIdmapsForPackageLI(pkg); 7436 } 7437 } 7438 7439 return pkg; 7440 } 7441 7442 /** 7443 * Derive the ABI of a non-system package located at {@code scanFile}. This information 7444 * is derived purely on the basis of the contents of {@code scanFile} and 7445 * {@code cpuAbiOverride}. 7446 * 7447 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 7448 */ 7449 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 7450 String cpuAbiOverride, boolean extractLibs) 7451 throws PackageManagerException { 7452 // TODO: We can probably be smarter about this stuff. For installed apps, 7453 // we can calculate this information at install time once and for all. For 7454 // system apps, we can probably assume that this information doesn't change 7455 // after the first boot scan. As things stand, we do lots of unnecessary work. 7456 7457 // Give ourselves some initial paths; we'll come back for another 7458 // pass once we've determined ABI below. 7459 setNativeLibraryPaths(pkg); 7460 7461 // We would never need to extract libs for forward-locked and external packages, 7462 // since the container service will do it for us. We shouldn't attempt to 7463 // extract libs from system app when it was not updated. 7464 if (pkg.isForwardLocked() || isExternal(pkg) || 7465 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) { 7466 extractLibs = false; 7467 } 7468 7469 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7470 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7471 7472 NativeLibraryHelper.Handle handle = null; 7473 try { 7474 handle = NativeLibraryHelper.Handle.create(scanFile); 7475 // TODO(multiArch): This can be null for apps that didn't go through the 7476 // usual installation process. We can calculate it again, like we 7477 // do during install time. 7478 // 7479 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7480 // unnecessary. 7481 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7482 7483 // Null out the abis so that they can be recalculated. 7484 pkg.applicationInfo.primaryCpuAbi = null; 7485 pkg.applicationInfo.secondaryCpuAbi = null; 7486 if (isMultiArch(pkg.applicationInfo)) { 7487 // Warn if we've set an abiOverride for multi-lib packages.. 7488 // By definition, we need to copy both 32 and 64 bit libraries for 7489 // such packages. 7490 if (pkg.cpuAbiOverride != null 7491 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7492 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7493 } 7494 7495 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7496 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7497 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7498 if (extractLibs) { 7499 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7500 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7501 useIsaSpecificSubdirs); 7502 } else { 7503 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7504 } 7505 } 7506 7507 maybeThrowExceptionForMultiArchCopy( 7508 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7509 7510 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7511 if (extractLibs) { 7512 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7513 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7514 useIsaSpecificSubdirs); 7515 } else { 7516 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7517 } 7518 } 7519 7520 maybeThrowExceptionForMultiArchCopy( 7521 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7522 7523 if (abi64 >= 0) { 7524 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7525 } 7526 7527 if (abi32 >= 0) { 7528 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7529 if (abi64 >= 0) { 7530 pkg.applicationInfo.secondaryCpuAbi = abi; 7531 } else { 7532 pkg.applicationInfo.primaryCpuAbi = abi; 7533 } 7534 } 7535 } else { 7536 String[] abiList = (cpuAbiOverride != null) ? 7537 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7538 7539 // Enable gross and lame hacks for apps that are built with old 7540 // SDK tools. We must scan their APKs for renderscript bitcode and 7541 // not launch them if it's present. Don't bother checking on devices 7542 // that don't have 64 bit support. 7543 boolean needsRenderScriptOverride = false; 7544 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7545 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7546 abiList = Build.SUPPORTED_32_BIT_ABIS; 7547 needsRenderScriptOverride = true; 7548 } 7549 7550 final int copyRet; 7551 if (extractLibs) { 7552 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7553 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7554 } else { 7555 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7556 } 7557 7558 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7559 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7560 "Error unpackaging native libs for app, errorCode=" + copyRet); 7561 } 7562 7563 if (copyRet >= 0) { 7564 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7565 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7566 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7567 } else if (needsRenderScriptOverride) { 7568 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7569 } 7570 } 7571 } catch (IOException ioe) { 7572 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7573 } finally { 7574 IoUtils.closeQuietly(handle); 7575 } 7576 7577 // Now that we've calculated the ABIs and determined if it's an internal app, 7578 // we will go ahead and populate the nativeLibraryPath. 7579 setNativeLibraryPaths(pkg); 7580 } 7581 7582 /** 7583 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7584 * i.e, so that all packages can be run inside a single process if required. 7585 * 7586 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7587 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7588 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7589 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7590 * updating a package that belongs to a shared user. 7591 * 7592 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7593 * adds unnecessary complexity. 7594 */ 7595 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7596 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 7597 String requiredInstructionSet = null; 7598 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7599 requiredInstructionSet = VMRuntime.getInstructionSet( 7600 scannedPackage.applicationInfo.primaryCpuAbi); 7601 } 7602 7603 PackageSetting requirer = null; 7604 for (PackageSetting ps : packagesForUser) { 7605 // If packagesForUser contains scannedPackage, we skip it. This will happen 7606 // when scannedPackage is an update of an existing package. Without this check, 7607 // we will never be able to change the ABI of any package belonging to a shared 7608 // user, even if it's compatible with other packages. 7609 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7610 if (ps.primaryCpuAbiString == null) { 7611 continue; 7612 } 7613 7614 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7615 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7616 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7617 // this but there's not much we can do. 7618 String errorMessage = "Instruction set mismatch, " 7619 + ((requirer == null) ? "[caller]" : requirer) 7620 + " requires " + requiredInstructionSet + " whereas " + ps 7621 + " requires " + instructionSet; 7622 Slog.w(TAG, errorMessage); 7623 } 7624 7625 if (requiredInstructionSet == null) { 7626 requiredInstructionSet = instructionSet; 7627 requirer = ps; 7628 } 7629 } 7630 } 7631 7632 if (requiredInstructionSet != null) { 7633 String adjustedAbi; 7634 if (requirer != null) { 7635 // requirer != null implies that either scannedPackage was null or that scannedPackage 7636 // did not require an ABI, in which case we have to adjust scannedPackage to match 7637 // the ABI of the set (which is the same as requirer's ABI) 7638 adjustedAbi = requirer.primaryCpuAbiString; 7639 if (scannedPackage != null) { 7640 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7641 } 7642 } else { 7643 // requirer == null implies that we're updating all ABIs in the set to 7644 // match scannedPackage. 7645 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7646 } 7647 7648 for (PackageSetting ps : packagesForUser) { 7649 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7650 if (ps.primaryCpuAbiString != null) { 7651 continue; 7652 } 7653 7654 ps.primaryCpuAbiString = adjustedAbi; 7655 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7656 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7657 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7658 7659 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 7660 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 7661 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7662 ps.primaryCpuAbiString = null; 7663 ps.pkg.applicationInfo.primaryCpuAbi = null; 7664 return; 7665 } else { 7666 mInstaller.rmdex(ps.codePathString, 7667 getDexCodeInstructionSet(getPreferredInstructionSet())); 7668 } 7669 } 7670 } 7671 } 7672 } 7673 } 7674 7675 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7676 synchronized (mPackages) { 7677 mResolverReplaced = true; 7678 // Set up information for custom user intent resolution activity. 7679 mResolveActivity.applicationInfo = pkg.applicationInfo; 7680 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7681 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7682 mResolveActivity.processName = pkg.applicationInfo.packageName; 7683 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7684 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7685 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7686 mResolveActivity.theme = 0; 7687 mResolveActivity.exported = true; 7688 mResolveActivity.enabled = true; 7689 mResolveInfo.activityInfo = mResolveActivity; 7690 mResolveInfo.priority = 0; 7691 mResolveInfo.preferredOrder = 0; 7692 mResolveInfo.match = 0; 7693 mResolveComponentName = mCustomResolverComponentName; 7694 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7695 mResolveComponentName); 7696 } 7697 } 7698 7699 private static String calculateBundledApkRoot(final String codePathString) { 7700 final File codePath = new File(codePathString); 7701 final File codeRoot; 7702 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 7703 codeRoot = Environment.getRootDirectory(); 7704 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7705 codeRoot = Environment.getOemDirectory(); 7706 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7707 codeRoot = Environment.getVendorDirectory(); 7708 } else { 7709 // Unrecognized code path; take its top real segment as the apk root: 7710 // e.g. /something/app/blah.apk => /something 7711 try { 7712 File f = codePath.getCanonicalFile(); 7713 File parent = f.getParentFile(); // non-null because codePath is a file 7714 File tmp; 7715 while ((tmp = parent.getParentFile()) != null) { 7716 f = parent; 7717 parent = tmp; 7718 } 7719 codeRoot = f; 7720 Slog.w(TAG, "Unrecognized code path " 7721 + codePath + " - using " + codeRoot); 7722 } catch (IOException e) { 7723 // Can't canonicalize the code path -- shenanigans? 7724 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7725 return Environment.getRootDirectory().getPath(); 7726 } 7727 } 7728 return codeRoot.getPath(); 7729 } 7730 7731 /** 7732 * Derive and set the location of native libraries for the given package, 7733 * which varies depending on where and how the package was installed. 7734 */ 7735 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7736 final ApplicationInfo info = pkg.applicationInfo; 7737 final String codePath = pkg.codePath; 7738 final File codeFile = new File(codePath); 7739 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7740 final boolean asecApp = info.isForwardLocked() || isExternal(info); 7741 7742 info.nativeLibraryRootDir = null; 7743 info.nativeLibraryRootRequiresIsa = false; 7744 info.nativeLibraryDir = null; 7745 info.secondaryNativeLibraryDir = null; 7746 7747 if (isApkFile(codeFile)) { 7748 // Monolithic install 7749 if (bundledApp) { 7750 // If "/system/lib64/apkname" exists, assume that is the per-package 7751 // native library directory to use; otherwise use "/system/lib/apkname". 7752 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7753 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7754 getPrimaryInstructionSet(info)); 7755 7756 // This is a bundled system app so choose the path based on the ABI. 7757 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7758 // is just the default path. 7759 final String apkName = deriveCodePathName(codePath); 7760 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7761 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7762 apkName).getAbsolutePath(); 7763 7764 if (info.secondaryCpuAbi != null) { 7765 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7766 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7767 secondaryLibDir, apkName).getAbsolutePath(); 7768 } 7769 } else if (asecApp) { 7770 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 7771 .getAbsolutePath(); 7772 } else { 7773 final String apkName = deriveCodePathName(codePath); 7774 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 7775 .getAbsolutePath(); 7776 } 7777 7778 info.nativeLibraryRootRequiresIsa = false; 7779 info.nativeLibraryDir = info.nativeLibraryRootDir; 7780 } else { 7781 // Cluster install 7782 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 7783 info.nativeLibraryRootRequiresIsa = true; 7784 7785 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 7786 getPrimaryInstructionSet(info)).getAbsolutePath(); 7787 7788 if (info.secondaryCpuAbi != null) { 7789 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 7790 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 7791 } 7792 } 7793 } 7794 7795 /** 7796 * Calculate the abis and roots for a bundled app. These can uniquely 7797 * be determined from the contents of the system partition, i.e whether 7798 * it contains 64 or 32 bit shared libraries etc. We do not validate any 7799 * of this information, and instead assume that the system was built 7800 * sensibly. 7801 */ 7802 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 7803 PackageSetting pkgSetting) { 7804 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 7805 7806 // If "/system/lib64/apkname" exists, assume that is the per-package 7807 // native library directory to use; otherwise use "/system/lib/apkname". 7808 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 7809 setBundledAppAbi(pkg, apkRoot, apkName); 7810 // pkgSetting might be null during rescan following uninstall of updates 7811 // to a bundled app, so accommodate that possibility. The settings in 7812 // that case will be established later from the parsed package. 7813 // 7814 // If the settings aren't null, sync them up with what we've just derived. 7815 // note that apkRoot isn't stored in the package settings. 7816 if (pkgSetting != null) { 7817 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7818 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7819 } 7820 } 7821 7822 /** 7823 * Deduces the ABI of a bundled app and sets the relevant fields on the 7824 * parsed pkg object. 7825 * 7826 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 7827 * under which system libraries are installed. 7828 * @param apkName the name of the installed package. 7829 */ 7830 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 7831 final File codeFile = new File(pkg.codePath); 7832 7833 final boolean has64BitLibs; 7834 final boolean has32BitLibs; 7835 if (isApkFile(codeFile)) { 7836 // Monolithic install 7837 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 7838 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7839 } else { 7840 // Cluster install 7841 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7842 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7843 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7844 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7845 has64BitLibs = (new File(rootDir, isa)).exists(); 7846 } else { 7847 has64BitLibs = false; 7848 } 7849 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7850 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 7851 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 7852 has32BitLibs = (new File(rootDir, isa)).exists(); 7853 } else { 7854 has32BitLibs = false; 7855 } 7856 } 7857 7858 if (has64BitLibs && !has32BitLibs) { 7859 // The package has 64 bit libs, but not 32 bit libs. Its primary 7860 // ABI should be 64 bit. We can safely assume here that the bundled 7861 // native libraries correspond to the most preferred ABI in the list. 7862 7863 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7864 pkg.applicationInfo.secondaryCpuAbi = null; 7865 } else if (has32BitLibs && !has64BitLibs) { 7866 // The package has 32 bit libs but not 64 bit libs. Its primary 7867 // ABI should be 32 bit. 7868 7869 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7870 pkg.applicationInfo.secondaryCpuAbi = null; 7871 } else if (has32BitLibs && has64BitLibs) { 7872 // The application has both 64 and 32 bit bundled libraries. We check 7873 // here that the app declares multiArch support, and warn if it doesn't. 7874 // 7875 // We will be lenient here and record both ABIs. The primary will be the 7876 // ABI that's higher on the list, i.e, a device that's configured to prefer 7877 // 64 bit apps will see a 64 bit primary ABI, 7878 7879 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 7880 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 7881 } 7882 7883 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 7884 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7885 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7886 } else { 7887 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7888 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7889 } 7890 } else { 7891 pkg.applicationInfo.primaryCpuAbi = null; 7892 pkg.applicationInfo.secondaryCpuAbi = null; 7893 } 7894 } 7895 7896 private void killApplication(String pkgName, int appId, String reason) { 7897 // Request the ActivityManager to kill the process(only for existing packages) 7898 // so that we do not end up in a confused state while the user is still using the older 7899 // version of the application while the new one gets installed. 7900 IActivityManager am = ActivityManagerNative.getDefault(); 7901 if (am != null) { 7902 try { 7903 am.killApplicationWithAppId(pkgName, appId, reason); 7904 } catch (RemoteException e) { 7905 } 7906 } 7907 } 7908 7909 void removePackageLI(PackageSetting ps, boolean chatty) { 7910 if (DEBUG_INSTALL) { 7911 if (chatty) 7912 Log.d(TAG, "Removing package " + ps.name); 7913 } 7914 7915 // writer 7916 synchronized (mPackages) { 7917 mPackages.remove(ps.name); 7918 final PackageParser.Package pkg = ps.pkg; 7919 if (pkg != null) { 7920 cleanPackageDataStructuresLILPw(pkg, chatty); 7921 } 7922 } 7923 } 7924 7925 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 7926 if (DEBUG_INSTALL) { 7927 if (chatty) 7928 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 7929 } 7930 7931 // writer 7932 synchronized (mPackages) { 7933 mPackages.remove(pkg.applicationInfo.packageName); 7934 cleanPackageDataStructuresLILPw(pkg, chatty); 7935 } 7936 } 7937 7938 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 7939 int N = pkg.providers.size(); 7940 StringBuilder r = null; 7941 int i; 7942 for (i=0; i<N; i++) { 7943 PackageParser.Provider p = pkg.providers.get(i); 7944 mProviders.removeProvider(p); 7945 if (p.info.authority == null) { 7946 7947 /* There was another ContentProvider with this authority when 7948 * this app was installed so this authority is null, 7949 * Ignore it as we don't have to unregister the provider. 7950 */ 7951 continue; 7952 } 7953 String names[] = p.info.authority.split(";"); 7954 for (int j = 0; j < names.length; j++) { 7955 if (mProvidersByAuthority.get(names[j]) == p) { 7956 mProvidersByAuthority.remove(names[j]); 7957 if (DEBUG_REMOVE) { 7958 if (chatty) 7959 Log.d(TAG, "Unregistered content provider: " + names[j] 7960 + ", className = " + p.info.name + ", isSyncable = " 7961 + p.info.isSyncable); 7962 } 7963 } 7964 } 7965 if (DEBUG_REMOVE && chatty) { 7966 if (r == null) { 7967 r = new StringBuilder(256); 7968 } else { 7969 r.append(' '); 7970 } 7971 r.append(p.info.name); 7972 } 7973 } 7974 if (r != null) { 7975 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 7976 } 7977 7978 N = pkg.services.size(); 7979 r = null; 7980 for (i=0; i<N; i++) { 7981 PackageParser.Service s = pkg.services.get(i); 7982 mServices.removeService(s); 7983 if (chatty) { 7984 if (r == null) { 7985 r = new StringBuilder(256); 7986 } else { 7987 r.append(' '); 7988 } 7989 r.append(s.info.name); 7990 } 7991 } 7992 if (r != null) { 7993 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 7994 } 7995 7996 N = pkg.receivers.size(); 7997 r = null; 7998 for (i=0; i<N; i++) { 7999 PackageParser.Activity a = pkg.receivers.get(i); 8000 mReceivers.removeActivity(a, "receiver"); 8001 if (DEBUG_REMOVE && chatty) { 8002 if (r == null) { 8003 r = new StringBuilder(256); 8004 } else { 8005 r.append(' '); 8006 } 8007 r.append(a.info.name); 8008 } 8009 } 8010 if (r != null) { 8011 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 8012 } 8013 8014 N = pkg.activities.size(); 8015 r = null; 8016 for (i=0; i<N; i++) { 8017 PackageParser.Activity a = pkg.activities.get(i); 8018 mActivities.removeActivity(a, "activity"); 8019 if (DEBUG_REMOVE && chatty) { 8020 if (r == null) { 8021 r = new StringBuilder(256); 8022 } else { 8023 r.append(' '); 8024 } 8025 r.append(a.info.name); 8026 } 8027 } 8028 if (r != null) { 8029 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 8030 } 8031 8032 N = pkg.permissions.size(); 8033 r = null; 8034 for (i=0; i<N; i++) { 8035 PackageParser.Permission p = pkg.permissions.get(i); 8036 BasePermission bp = mSettings.mPermissions.get(p.info.name); 8037 if (bp == null) { 8038 bp = mSettings.mPermissionTrees.get(p.info.name); 8039 } 8040 if (bp != null && bp.perm == p) { 8041 bp.perm = null; 8042 if (DEBUG_REMOVE && chatty) { 8043 if (r == null) { 8044 r = new StringBuilder(256); 8045 } else { 8046 r.append(' '); 8047 } 8048 r.append(p.info.name); 8049 } 8050 } 8051 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8052 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 8053 if (appOpPerms != null) { 8054 appOpPerms.remove(pkg.packageName); 8055 } 8056 } 8057 } 8058 if (r != null) { 8059 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8060 } 8061 8062 N = pkg.requestedPermissions.size(); 8063 r = null; 8064 for (i=0; i<N; i++) { 8065 String perm = pkg.requestedPermissions.get(i); 8066 BasePermission bp = mSettings.mPermissions.get(perm); 8067 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8068 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 8069 if (appOpPerms != null) { 8070 appOpPerms.remove(pkg.packageName); 8071 if (appOpPerms.isEmpty()) { 8072 mAppOpPermissionPackages.remove(perm); 8073 } 8074 } 8075 } 8076 } 8077 if (r != null) { 8078 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8079 } 8080 8081 N = pkg.instrumentation.size(); 8082 r = null; 8083 for (i=0; i<N; i++) { 8084 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8085 mInstrumentation.remove(a.getComponentName()); 8086 if (DEBUG_REMOVE && chatty) { 8087 if (r == null) { 8088 r = new StringBuilder(256); 8089 } else { 8090 r.append(' '); 8091 } 8092 r.append(a.info.name); 8093 } 8094 } 8095 if (r != null) { 8096 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 8097 } 8098 8099 r = null; 8100 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8101 // Only system apps can hold shared libraries. 8102 if (pkg.libraryNames != null) { 8103 for (i=0; i<pkg.libraryNames.size(); i++) { 8104 String name = pkg.libraryNames.get(i); 8105 SharedLibraryEntry cur = mSharedLibraries.get(name); 8106 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 8107 mSharedLibraries.remove(name); 8108 if (DEBUG_REMOVE && chatty) { 8109 if (r == null) { 8110 r = new StringBuilder(256); 8111 } else { 8112 r.append(' '); 8113 } 8114 r.append(name); 8115 } 8116 } 8117 } 8118 } 8119 } 8120 if (r != null) { 8121 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 8122 } 8123 } 8124 8125 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 8126 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 8127 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 8128 return true; 8129 } 8130 } 8131 return false; 8132 } 8133 8134 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 8135 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 8136 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 8137 8138 private void updatePermissionsLPw(String changingPkg, 8139 PackageParser.Package pkgInfo, int flags) { 8140 // Make sure there are no dangling permission trees. 8141 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 8142 while (it.hasNext()) { 8143 final BasePermission bp = it.next(); 8144 if (bp.packageSetting == null) { 8145 // We may not yet have parsed the package, so just see if 8146 // we still know about its settings. 8147 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8148 } 8149 if (bp.packageSetting == null) { 8150 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 8151 + " from package " + bp.sourcePackage); 8152 it.remove(); 8153 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8154 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8155 Slog.i(TAG, "Removing old permission tree: " + bp.name 8156 + " from package " + bp.sourcePackage); 8157 flags |= UPDATE_PERMISSIONS_ALL; 8158 it.remove(); 8159 } 8160 } 8161 } 8162 8163 // Make sure all dynamic permissions have been assigned to a package, 8164 // and make sure there are no dangling permissions. 8165 it = mSettings.mPermissions.values().iterator(); 8166 while (it.hasNext()) { 8167 final BasePermission bp = it.next(); 8168 if (bp.type == BasePermission.TYPE_DYNAMIC) { 8169 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 8170 + bp.name + " pkg=" + bp.sourcePackage 8171 + " info=" + bp.pendingInfo); 8172 if (bp.packageSetting == null && bp.pendingInfo != null) { 8173 final BasePermission tree = findPermissionTreeLP(bp.name); 8174 if (tree != null && tree.perm != null) { 8175 bp.packageSetting = tree.packageSetting; 8176 bp.perm = new PackageParser.Permission(tree.perm.owner, 8177 new PermissionInfo(bp.pendingInfo)); 8178 bp.perm.info.packageName = tree.perm.info.packageName; 8179 bp.perm.info.name = bp.name; 8180 bp.uid = tree.uid; 8181 } 8182 } 8183 } 8184 if (bp.packageSetting == null) { 8185 // We may not yet have parsed the package, so just see if 8186 // we still know about its settings. 8187 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8188 } 8189 if (bp.packageSetting == null) { 8190 Slog.w(TAG, "Removing dangling permission: " + bp.name 8191 + " from package " + bp.sourcePackage); 8192 it.remove(); 8193 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8194 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8195 Slog.i(TAG, "Removing old permission: " + bp.name 8196 + " from package " + bp.sourcePackage); 8197 flags |= UPDATE_PERMISSIONS_ALL; 8198 it.remove(); 8199 } 8200 } 8201 } 8202 8203 // Now update the permissions for all packages, in particular 8204 // replace the granted permissions of the system packages. 8205 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 8206 for (PackageParser.Package pkg : mPackages.values()) { 8207 if (pkg != pkgInfo) { 8208 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 8209 changingPkg); 8210 } 8211 } 8212 } 8213 8214 if (pkgInfo != null) { 8215 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 8216 } 8217 } 8218 8219 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 8220 String packageOfInterest) { 8221 // IMPORTANT: There are two types of permissions: install and runtime. 8222 // Install time permissions are granted when the app is installed to 8223 // all device users and users added in the future. Runtime permissions 8224 // are granted at runtime explicitly to specific users. Normal and signature 8225 // protected permissions are install time permissions. Dangerous permissions 8226 // are install permissions if the app's target SDK is Lollipop MR1 or older, 8227 // otherwise they are runtime permissions. This function does not manage 8228 // runtime permissions except for the case an app targeting Lollipop MR1 8229 // being upgraded to target a newer SDK, in which case dangerous permissions 8230 // are transformed from install time to runtime ones. 8231 8232 final PackageSetting ps = (PackageSetting) pkg.mExtras; 8233 if (ps == null) { 8234 return; 8235 } 8236 8237 PermissionsState permissionsState = ps.getPermissionsState(); 8238 PermissionsState origPermissions = permissionsState; 8239 8240 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 8241 8242 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 8243 8244 boolean changedInstallPermission = false; 8245 8246 if (replace) { 8247 ps.installPermissionsFixed = false; 8248 if (!ps.isSharedUser()) { 8249 origPermissions = new PermissionsState(permissionsState); 8250 permissionsState.reset(); 8251 } 8252 } 8253 8254 permissionsState.setGlobalGids(mGlobalGids); 8255 8256 final int N = pkg.requestedPermissions.size(); 8257 for (int i=0; i<N; i++) { 8258 final String name = pkg.requestedPermissions.get(i); 8259 final BasePermission bp = mSettings.mPermissions.get(name); 8260 8261 if (DEBUG_INSTALL) { 8262 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 8263 } 8264 8265 if (bp == null || bp.packageSetting == null) { 8266 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8267 Slog.w(TAG, "Unknown permission " + name 8268 + " in package " + pkg.packageName); 8269 } 8270 continue; 8271 } 8272 8273 final String perm = bp.name; 8274 boolean allowedSig = false; 8275 int grant = GRANT_DENIED; 8276 8277 // Keep track of app op permissions. 8278 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8279 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 8280 if (pkgs == null) { 8281 pkgs = new ArraySet<>(); 8282 mAppOpPermissionPackages.put(bp.name, pkgs); 8283 } 8284 pkgs.add(pkg.packageName); 8285 } 8286 8287 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 8288 switch (level) { 8289 case PermissionInfo.PROTECTION_NORMAL: { 8290 // For all apps normal permissions are install time ones. 8291 grant = GRANT_INSTALL; 8292 } break; 8293 8294 case PermissionInfo.PROTECTION_DANGEROUS: { 8295 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 8296 // For legacy apps dangerous permissions are install time ones. 8297 grant = GRANT_INSTALL_LEGACY; 8298 } else if (origPermissions.hasInstallPermission(bp.name)) { 8299 // For legacy apps that became modern, install becomes runtime. 8300 grant = GRANT_UPGRADE; 8301 } else { 8302 // For modern apps keep runtime permissions unchanged. 8303 grant = GRANT_RUNTIME; 8304 } 8305 } break; 8306 8307 case PermissionInfo.PROTECTION_SIGNATURE: { 8308 // For all apps signature permissions are install time ones. 8309 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 8310 if (allowedSig) { 8311 grant = GRANT_INSTALL; 8312 } 8313 } break; 8314 } 8315 8316 if (DEBUG_INSTALL) { 8317 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 8318 } 8319 8320 if (grant != GRANT_DENIED) { 8321 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 8322 // If this is an existing, non-system package, then 8323 // we can't add any new permissions to it. 8324 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 8325 // Except... if this is a permission that was added 8326 // to the platform (note: need to only do this when 8327 // updating the platform). 8328 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 8329 grant = GRANT_DENIED; 8330 } 8331 } 8332 } 8333 8334 switch (grant) { 8335 case GRANT_INSTALL: { 8336 // Revoke this as runtime permission to handle the case of 8337 // a runtime permission being downgraded to an install one. 8338 for (int userId : UserManagerService.getInstance().getUserIds()) { 8339 if (origPermissions.getRuntimePermissionState( 8340 bp.name, userId) != null) { 8341 // Revoke the runtime permission and clear the flags. 8342 origPermissions.revokeRuntimePermission(bp, userId); 8343 origPermissions.updatePermissionFlags(bp, userId, 8344 PackageManager.MASK_PERMISSION_FLAGS, 0); 8345 // If we revoked a permission permission, we have to write. 8346 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8347 changedRuntimePermissionUserIds, userId); 8348 } 8349 } 8350 // Grant an install permission. 8351 if (permissionsState.grantInstallPermission(bp) != 8352 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8353 changedInstallPermission = true; 8354 } 8355 } break; 8356 8357 case GRANT_INSTALL_LEGACY: { 8358 // Grant an install permission. 8359 if (permissionsState.grantInstallPermission(bp) != 8360 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8361 changedInstallPermission = true; 8362 } 8363 } break; 8364 8365 case GRANT_RUNTIME: { 8366 // Grant previously granted runtime permissions. 8367 for (int userId : UserManagerService.getInstance().getUserIds()) { 8368 PermissionState permissionState = origPermissions 8369 .getRuntimePermissionState(bp.name, userId); 8370 final int flags = permissionState != null 8371 ? permissionState.getFlags() : 0; 8372 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8373 if (permissionsState.grantRuntimePermission(bp, userId) == 8374 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8375 // If we cannot put the permission as it was, we have to write. 8376 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8377 changedRuntimePermissionUserIds, userId); 8378 } 8379 } 8380 // Propagate the permission flags. 8381 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 8382 } 8383 } break; 8384 8385 case GRANT_UPGRADE: { 8386 // Grant runtime permissions for a previously held install permission. 8387 PermissionState permissionState = origPermissions 8388 .getInstallPermissionState(bp.name); 8389 final int flags = permissionState != null ? permissionState.getFlags() : 0; 8390 8391 if (origPermissions.revokeInstallPermission(bp) 8392 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 8393 // We will be transferring the permission flags, so clear them. 8394 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 8395 PackageManager.MASK_PERMISSION_FLAGS, 0); 8396 changedInstallPermission = true; 8397 } 8398 8399 // If the permission is not to be promoted to runtime we ignore it and 8400 // also its other flags as they are not applicable to install permissions. 8401 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 8402 for (int userId : currentUserIds) { 8403 if (permissionsState.grantRuntimePermission(bp, userId) != 8404 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8405 // Transfer the permission flags. 8406 permissionsState.updatePermissionFlags(bp, userId, 8407 flags, flags); 8408 // If we granted the permission, we have to write. 8409 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8410 changedRuntimePermissionUserIds, userId); 8411 } 8412 } 8413 } 8414 } break; 8415 8416 default: { 8417 if (packageOfInterest == null 8418 || packageOfInterest.equals(pkg.packageName)) { 8419 Slog.w(TAG, "Not granting permission " + perm 8420 + " to package " + pkg.packageName 8421 + " because it was previously installed without"); 8422 } 8423 } break; 8424 } 8425 } else { 8426 if (permissionsState.revokeInstallPermission(bp) != 8427 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8428 // Also drop the permission flags. 8429 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 8430 PackageManager.MASK_PERMISSION_FLAGS, 0); 8431 changedInstallPermission = true; 8432 Slog.i(TAG, "Un-granting permission " + perm 8433 + " from package " + pkg.packageName 8434 + " (protectionLevel=" + bp.protectionLevel 8435 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8436 + ")"); 8437 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 8438 // Don't print warning for app op permissions, since it is fine for them 8439 // not to be granted, there is a UI for the user to decide. 8440 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8441 Slog.w(TAG, "Not granting permission " + perm 8442 + " to package " + pkg.packageName 8443 + " (protectionLevel=" + bp.protectionLevel 8444 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8445 + ")"); 8446 } 8447 } 8448 } 8449 } 8450 8451 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 8452 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 8453 // This is the first that we have heard about this package, so the 8454 // permissions we have now selected are fixed until explicitly 8455 // changed. 8456 ps.installPermissionsFixed = true; 8457 } 8458 8459 // Persist the runtime permissions state for users with changes. 8460 for (int userId : changedRuntimePermissionUserIds) { 8461 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 8462 } 8463 } 8464 8465 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8466 boolean allowed = false; 8467 final int NP = PackageParser.NEW_PERMISSIONS.length; 8468 for (int ip=0; ip<NP; ip++) { 8469 final PackageParser.NewPermissionInfo npi 8470 = PackageParser.NEW_PERMISSIONS[ip]; 8471 if (npi.name.equals(perm) 8472 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8473 allowed = true; 8474 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8475 + pkg.packageName); 8476 break; 8477 } 8478 } 8479 return allowed; 8480 } 8481 8482 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 8483 BasePermission bp, PermissionsState origPermissions) { 8484 boolean allowed; 8485 allowed = (compareSignatures( 8486 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 8487 == PackageManager.SIGNATURE_MATCH) 8488 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 8489 == PackageManager.SIGNATURE_MATCH); 8490 if (!allowed && (bp.protectionLevel 8491 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 8492 if (isSystemApp(pkg)) { 8493 // For updated system applications, a system permission 8494 // is granted only if it had been defined by the original application. 8495 if (pkg.isUpdatedSystemApp()) { 8496 final PackageSetting sysPs = mSettings 8497 .getDisabledSystemPkgLPr(pkg.packageName); 8498 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 8499 // If the original was granted this permission, we take 8500 // that grant decision as read and propagate it to the 8501 // update. 8502 if (sysPs.isPrivileged()) { 8503 allowed = true; 8504 } 8505 } else { 8506 // The system apk may have been updated with an older 8507 // version of the one on the data partition, but which 8508 // granted a new system permission that it didn't have 8509 // before. In this case we do want to allow the app to 8510 // now get the new permission if the ancestral apk is 8511 // privileged to get it. 8512 if (sysPs.pkg != null && sysPs.isPrivileged()) { 8513 for (int j=0; 8514 j<sysPs.pkg.requestedPermissions.size(); j++) { 8515 if (perm.equals( 8516 sysPs.pkg.requestedPermissions.get(j))) { 8517 allowed = true; 8518 break; 8519 } 8520 } 8521 } 8522 } 8523 } else { 8524 allowed = isPrivilegedApp(pkg); 8525 } 8526 } 8527 } 8528 if (!allowed) { 8529 if (!allowed && (bp.protectionLevel 8530 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 8531 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.MNC) { 8532 // If this was a previously normal/dangerous permission that got moved 8533 // to a system permission as part of the runtime permission redesign, then 8534 // we still want to blindly grant it to old apps. 8535 allowed = true; 8536 } 8537 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 8538 && pkg.packageName.equals(mRequiredInstallerPackage)) { 8539 // If this permission is to be granted to the system installer and 8540 // this app is an installer, then it gets the permission. 8541 allowed = true; 8542 } 8543 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 8544 && pkg.packageName.equals(mRequiredVerifierPackage)) { 8545 // If this permission is to be granted to the system verifier and 8546 // this app is a verifier, then it gets the permission. 8547 allowed = true; 8548 } 8549 if (!allowed && (bp.protectionLevel 8550 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 8551 && isSystemApp(pkg)) { 8552 // Any pre-installed system app is allowed to get this permission. 8553 allowed = true; 8554 } 8555 if (!allowed && (bp.protectionLevel 8556 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 8557 // For development permissions, a development permission 8558 // is granted only if it was already granted. 8559 allowed = origPermissions.hasInstallPermission(perm); 8560 } 8561 } 8562 return allowed; 8563 } 8564 8565 final class ActivityIntentResolver 8566 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 8567 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8568 boolean defaultOnly, int userId) { 8569 if (!sUserManager.exists(userId)) return null; 8570 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8571 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8572 } 8573 8574 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8575 int userId) { 8576 if (!sUserManager.exists(userId)) return null; 8577 mFlags = flags; 8578 return super.queryIntent(intent, resolvedType, 8579 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8580 } 8581 8582 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8583 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 8584 if (!sUserManager.exists(userId)) return null; 8585 if (packageActivities == null) { 8586 return null; 8587 } 8588 mFlags = flags; 8589 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8590 final int N = packageActivities.size(); 8591 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 8592 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 8593 8594 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 8595 for (int i = 0; i < N; ++i) { 8596 intentFilters = packageActivities.get(i).intents; 8597 if (intentFilters != null && intentFilters.size() > 0) { 8598 PackageParser.ActivityIntentInfo[] array = 8599 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 8600 intentFilters.toArray(array); 8601 listCut.add(array); 8602 } 8603 } 8604 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8605 } 8606 8607 public final void addActivity(PackageParser.Activity a, String type) { 8608 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 8609 mActivities.put(a.getComponentName(), a); 8610 if (DEBUG_SHOW_INFO) 8611 Log.v( 8612 TAG, " " + type + " " + 8613 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 8614 if (DEBUG_SHOW_INFO) 8615 Log.v(TAG, " Class=" + a.info.name); 8616 final int NI = a.intents.size(); 8617 for (int j=0; j<NI; j++) { 8618 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8619 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 8620 intent.setPriority(0); 8621 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 8622 + a.className + " with priority > 0, forcing to 0"); 8623 } 8624 if (DEBUG_SHOW_INFO) { 8625 Log.v(TAG, " IntentFilter:"); 8626 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8627 } 8628 if (!intent.debugCheck()) { 8629 Log.w(TAG, "==> For Activity " + a.info.name); 8630 } 8631 addFilter(intent); 8632 } 8633 } 8634 8635 public final void removeActivity(PackageParser.Activity a, String type) { 8636 mActivities.remove(a.getComponentName()); 8637 if (DEBUG_SHOW_INFO) { 8638 Log.v(TAG, " " + type + " " 8639 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 8640 : a.info.name) + ":"); 8641 Log.v(TAG, " Class=" + a.info.name); 8642 } 8643 final int NI = a.intents.size(); 8644 for (int j=0; j<NI; j++) { 8645 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8646 if (DEBUG_SHOW_INFO) { 8647 Log.v(TAG, " IntentFilter:"); 8648 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8649 } 8650 removeFilter(intent); 8651 } 8652 } 8653 8654 @Override 8655 protected boolean allowFilterResult( 8656 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 8657 ActivityInfo filterAi = filter.activity.info; 8658 for (int i=dest.size()-1; i>=0; i--) { 8659 ActivityInfo destAi = dest.get(i).activityInfo; 8660 if (destAi.name == filterAi.name 8661 && destAi.packageName == filterAi.packageName) { 8662 return false; 8663 } 8664 } 8665 return true; 8666 } 8667 8668 @Override 8669 protected ActivityIntentInfo[] newArray(int size) { 8670 return new ActivityIntentInfo[size]; 8671 } 8672 8673 @Override 8674 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 8675 if (!sUserManager.exists(userId)) return true; 8676 PackageParser.Package p = filter.activity.owner; 8677 if (p != null) { 8678 PackageSetting ps = (PackageSetting)p.mExtras; 8679 if (ps != null) { 8680 // System apps are never considered stopped for purposes of 8681 // filtering, because there may be no way for the user to 8682 // actually re-launch them. 8683 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 8684 && ps.getStopped(userId); 8685 } 8686 } 8687 return false; 8688 } 8689 8690 @Override 8691 protected boolean isPackageForFilter(String packageName, 8692 PackageParser.ActivityIntentInfo info) { 8693 return packageName.equals(info.activity.owner.packageName); 8694 } 8695 8696 @Override 8697 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 8698 int match, int userId) { 8699 if (!sUserManager.exists(userId)) return null; 8700 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 8701 return null; 8702 } 8703 final PackageParser.Activity activity = info.activity; 8704 if (mSafeMode && (activity.info.applicationInfo.flags 8705 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8706 return null; 8707 } 8708 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 8709 if (ps == null) { 8710 return null; 8711 } 8712 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 8713 ps.readUserState(userId), userId); 8714 if (ai == null) { 8715 return null; 8716 } 8717 final ResolveInfo res = new ResolveInfo(); 8718 res.activityInfo = ai; 8719 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8720 res.filter = info; 8721 } 8722 if (info != null) { 8723 res.handleAllWebDataURI = info.handleAllWebDataURI(); 8724 } 8725 res.priority = info.getPriority(); 8726 res.preferredOrder = activity.owner.mPreferredOrder; 8727 //System.out.println("Result: " + res.activityInfo.className + 8728 // " = " + res.priority); 8729 res.match = match; 8730 res.isDefault = info.hasDefault; 8731 res.labelRes = info.labelRes; 8732 res.nonLocalizedLabel = info.nonLocalizedLabel; 8733 if (userNeedsBadging(userId)) { 8734 res.noResourceId = true; 8735 } else { 8736 res.icon = info.icon; 8737 } 8738 res.iconResourceId = info.icon; 8739 res.system = res.activityInfo.applicationInfo.isSystemApp(); 8740 return res; 8741 } 8742 8743 @Override 8744 protected void sortResults(List<ResolveInfo> results) { 8745 Collections.sort(results, mResolvePrioritySorter); 8746 } 8747 8748 @Override 8749 protected void dumpFilter(PrintWriter out, String prefix, 8750 PackageParser.ActivityIntentInfo filter) { 8751 out.print(prefix); out.print( 8752 Integer.toHexString(System.identityHashCode(filter.activity))); 8753 out.print(' '); 8754 filter.activity.printComponentShortName(out); 8755 out.print(" filter "); 8756 out.println(Integer.toHexString(System.identityHashCode(filter))); 8757 } 8758 8759 @Override 8760 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 8761 return filter.activity; 8762 } 8763 8764 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8765 PackageParser.Activity activity = (PackageParser.Activity)label; 8766 out.print(prefix); out.print( 8767 Integer.toHexString(System.identityHashCode(activity))); 8768 out.print(' '); 8769 activity.printComponentShortName(out); 8770 if (count > 1) { 8771 out.print(" ("); out.print(count); out.print(" filters)"); 8772 } 8773 out.println(); 8774 } 8775 8776// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8777// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8778// final List<ResolveInfo> retList = Lists.newArrayList(); 8779// while (i.hasNext()) { 8780// final ResolveInfo resolveInfo = i.next(); 8781// if (isEnabledLP(resolveInfo.activityInfo)) { 8782// retList.add(resolveInfo); 8783// } 8784// } 8785// return retList; 8786// } 8787 8788 // Keys are String (activity class name), values are Activity. 8789 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 8790 = new ArrayMap<ComponentName, PackageParser.Activity>(); 8791 private int mFlags; 8792 } 8793 8794 private final class ServiceIntentResolver 8795 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 8796 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8797 boolean defaultOnly, int userId) { 8798 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8799 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8800 } 8801 8802 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8803 int userId) { 8804 if (!sUserManager.exists(userId)) return null; 8805 mFlags = flags; 8806 return super.queryIntent(intent, resolvedType, 8807 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8808 } 8809 8810 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8811 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 8812 if (!sUserManager.exists(userId)) return null; 8813 if (packageServices == null) { 8814 return null; 8815 } 8816 mFlags = flags; 8817 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8818 final int N = packageServices.size(); 8819 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 8820 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 8821 8822 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 8823 for (int i = 0; i < N; ++i) { 8824 intentFilters = packageServices.get(i).intents; 8825 if (intentFilters != null && intentFilters.size() > 0) { 8826 PackageParser.ServiceIntentInfo[] array = 8827 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 8828 intentFilters.toArray(array); 8829 listCut.add(array); 8830 } 8831 } 8832 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8833 } 8834 8835 public final void addService(PackageParser.Service s) { 8836 mServices.put(s.getComponentName(), s); 8837 if (DEBUG_SHOW_INFO) { 8838 Log.v(TAG, " " 8839 + (s.info.nonLocalizedLabel != null 8840 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8841 Log.v(TAG, " Class=" + s.info.name); 8842 } 8843 final int NI = s.intents.size(); 8844 int j; 8845 for (j=0; j<NI; j++) { 8846 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8847 if (DEBUG_SHOW_INFO) { 8848 Log.v(TAG, " IntentFilter:"); 8849 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8850 } 8851 if (!intent.debugCheck()) { 8852 Log.w(TAG, "==> For Service " + s.info.name); 8853 } 8854 addFilter(intent); 8855 } 8856 } 8857 8858 public final void removeService(PackageParser.Service s) { 8859 mServices.remove(s.getComponentName()); 8860 if (DEBUG_SHOW_INFO) { 8861 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 8862 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8863 Log.v(TAG, " Class=" + s.info.name); 8864 } 8865 final int NI = s.intents.size(); 8866 int j; 8867 for (j=0; j<NI; j++) { 8868 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8869 if (DEBUG_SHOW_INFO) { 8870 Log.v(TAG, " IntentFilter:"); 8871 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8872 } 8873 removeFilter(intent); 8874 } 8875 } 8876 8877 @Override 8878 protected boolean allowFilterResult( 8879 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 8880 ServiceInfo filterSi = filter.service.info; 8881 for (int i=dest.size()-1; i>=0; i--) { 8882 ServiceInfo destAi = dest.get(i).serviceInfo; 8883 if (destAi.name == filterSi.name 8884 && destAi.packageName == filterSi.packageName) { 8885 return false; 8886 } 8887 } 8888 return true; 8889 } 8890 8891 @Override 8892 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 8893 return new PackageParser.ServiceIntentInfo[size]; 8894 } 8895 8896 @Override 8897 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 8898 if (!sUserManager.exists(userId)) return true; 8899 PackageParser.Package p = filter.service.owner; 8900 if (p != null) { 8901 PackageSetting ps = (PackageSetting)p.mExtras; 8902 if (ps != null) { 8903 // System apps are never considered stopped for purposes of 8904 // filtering, because there may be no way for the user to 8905 // actually re-launch them. 8906 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8907 && ps.getStopped(userId); 8908 } 8909 } 8910 return false; 8911 } 8912 8913 @Override 8914 protected boolean isPackageForFilter(String packageName, 8915 PackageParser.ServiceIntentInfo info) { 8916 return packageName.equals(info.service.owner.packageName); 8917 } 8918 8919 @Override 8920 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 8921 int match, int userId) { 8922 if (!sUserManager.exists(userId)) return null; 8923 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 8924 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 8925 return null; 8926 } 8927 final PackageParser.Service service = info.service; 8928 if (mSafeMode && (service.info.applicationInfo.flags 8929 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8930 return null; 8931 } 8932 PackageSetting ps = (PackageSetting) service.owner.mExtras; 8933 if (ps == null) { 8934 return null; 8935 } 8936 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 8937 ps.readUserState(userId), userId); 8938 if (si == null) { 8939 return null; 8940 } 8941 final ResolveInfo res = new ResolveInfo(); 8942 res.serviceInfo = si; 8943 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8944 res.filter = filter; 8945 } 8946 res.priority = info.getPriority(); 8947 res.preferredOrder = service.owner.mPreferredOrder; 8948 res.match = match; 8949 res.isDefault = info.hasDefault; 8950 res.labelRes = info.labelRes; 8951 res.nonLocalizedLabel = info.nonLocalizedLabel; 8952 res.icon = info.icon; 8953 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 8954 return res; 8955 } 8956 8957 @Override 8958 protected void sortResults(List<ResolveInfo> results) { 8959 Collections.sort(results, mResolvePrioritySorter); 8960 } 8961 8962 @Override 8963 protected void dumpFilter(PrintWriter out, String prefix, 8964 PackageParser.ServiceIntentInfo filter) { 8965 out.print(prefix); out.print( 8966 Integer.toHexString(System.identityHashCode(filter.service))); 8967 out.print(' '); 8968 filter.service.printComponentShortName(out); 8969 out.print(" filter "); 8970 out.println(Integer.toHexString(System.identityHashCode(filter))); 8971 } 8972 8973 @Override 8974 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 8975 return filter.service; 8976 } 8977 8978 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8979 PackageParser.Service service = (PackageParser.Service)label; 8980 out.print(prefix); out.print( 8981 Integer.toHexString(System.identityHashCode(service))); 8982 out.print(' '); 8983 service.printComponentShortName(out); 8984 if (count > 1) { 8985 out.print(" ("); out.print(count); out.print(" filters)"); 8986 } 8987 out.println(); 8988 } 8989 8990// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8991// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8992// final List<ResolveInfo> retList = Lists.newArrayList(); 8993// while (i.hasNext()) { 8994// final ResolveInfo resolveInfo = (ResolveInfo) i; 8995// if (isEnabledLP(resolveInfo.serviceInfo)) { 8996// retList.add(resolveInfo); 8997// } 8998// } 8999// return retList; 9000// } 9001 9002 // Keys are String (activity class name), values are Activity. 9003 private final ArrayMap<ComponentName, PackageParser.Service> mServices 9004 = new ArrayMap<ComponentName, PackageParser.Service>(); 9005 private int mFlags; 9006 }; 9007 9008 private final class ProviderIntentResolver 9009 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 9010 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9011 boolean defaultOnly, int userId) { 9012 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9013 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9014 } 9015 9016 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9017 int userId) { 9018 if (!sUserManager.exists(userId)) 9019 return null; 9020 mFlags = flags; 9021 return super.queryIntent(intent, resolvedType, 9022 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9023 } 9024 9025 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9026 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 9027 if (!sUserManager.exists(userId)) 9028 return null; 9029 if (packageProviders == null) { 9030 return null; 9031 } 9032 mFlags = flags; 9033 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 9034 final int N = packageProviders.size(); 9035 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 9036 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 9037 9038 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 9039 for (int i = 0; i < N; ++i) { 9040 intentFilters = packageProviders.get(i).intents; 9041 if (intentFilters != null && intentFilters.size() > 0) { 9042 PackageParser.ProviderIntentInfo[] array = 9043 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 9044 intentFilters.toArray(array); 9045 listCut.add(array); 9046 } 9047 } 9048 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9049 } 9050 9051 public final void addProvider(PackageParser.Provider p) { 9052 if (mProviders.containsKey(p.getComponentName())) { 9053 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 9054 return; 9055 } 9056 9057 mProviders.put(p.getComponentName(), p); 9058 if (DEBUG_SHOW_INFO) { 9059 Log.v(TAG, " " 9060 + (p.info.nonLocalizedLabel != null 9061 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9062 Log.v(TAG, " Class=" + p.info.name); 9063 } 9064 final int NI = p.intents.size(); 9065 int j; 9066 for (j = 0; j < NI; j++) { 9067 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9068 if (DEBUG_SHOW_INFO) { 9069 Log.v(TAG, " IntentFilter:"); 9070 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9071 } 9072 if (!intent.debugCheck()) { 9073 Log.w(TAG, "==> For Provider " + p.info.name); 9074 } 9075 addFilter(intent); 9076 } 9077 } 9078 9079 public final void removeProvider(PackageParser.Provider p) { 9080 mProviders.remove(p.getComponentName()); 9081 if (DEBUG_SHOW_INFO) { 9082 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 9083 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9084 Log.v(TAG, " Class=" + p.info.name); 9085 } 9086 final int NI = p.intents.size(); 9087 int j; 9088 for (j = 0; j < NI; j++) { 9089 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9090 if (DEBUG_SHOW_INFO) { 9091 Log.v(TAG, " IntentFilter:"); 9092 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9093 } 9094 removeFilter(intent); 9095 } 9096 } 9097 9098 @Override 9099 protected boolean allowFilterResult( 9100 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 9101 ProviderInfo filterPi = filter.provider.info; 9102 for (int i = dest.size() - 1; i >= 0; i--) { 9103 ProviderInfo destPi = dest.get(i).providerInfo; 9104 if (destPi.name == filterPi.name 9105 && destPi.packageName == filterPi.packageName) { 9106 return false; 9107 } 9108 } 9109 return true; 9110 } 9111 9112 @Override 9113 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 9114 return new PackageParser.ProviderIntentInfo[size]; 9115 } 9116 9117 @Override 9118 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 9119 if (!sUserManager.exists(userId)) 9120 return true; 9121 PackageParser.Package p = filter.provider.owner; 9122 if (p != null) { 9123 PackageSetting ps = (PackageSetting) p.mExtras; 9124 if (ps != null) { 9125 // System apps are never considered stopped for purposes of 9126 // filtering, because there may be no way for the user to 9127 // actually re-launch them. 9128 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9129 && ps.getStopped(userId); 9130 } 9131 } 9132 return false; 9133 } 9134 9135 @Override 9136 protected boolean isPackageForFilter(String packageName, 9137 PackageParser.ProviderIntentInfo info) { 9138 return packageName.equals(info.provider.owner.packageName); 9139 } 9140 9141 @Override 9142 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 9143 int match, int userId) { 9144 if (!sUserManager.exists(userId)) 9145 return null; 9146 final PackageParser.ProviderIntentInfo info = filter; 9147 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 9148 return null; 9149 } 9150 final PackageParser.Provider provider = info.provider; 9151 if (mSafeMode && (provider.info.applicationInfo.flags 9152 & ApplicationInfo.FLAG_SYSTEM) == 0) { 9153 return null; 9154 } 9155 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 9156 if (ps == null) { 9157 return null; 9158 } 9159 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 9160 ps.readUserState(userId), userId); 9161 if (pi == null) { 9162 return null; 9163 } 9164 final ResolveInfo res = new ResolveInfo(); 9165 res.providerInfo = pi; 9166 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 9167 res.filter = filter; 9168 } 9169 res.priority = info.getPriority(); 9170 res.preferredOrder = provider.owner.mPreferredOrder; 9171 res.match = match; 9172 res.isDefault = info.hasDefault; 9173 res.labelRes = info.labelRes; 9174 res.nonLocalizedLabel = info.nonLocalizedLabel; 9175 res.icon = info.icon; 9176 res.system = res.providerInfo.applicationInfo.isSystemApp(); 9177 return res; 9178 } 9179 9180 @Override 9181 protected void sortResults(List<ResolveInfo> results) { 9182 Collections.sort(results, mResolvePrioritySorter); 9183 } 9184 9185 @Override 9186 protected void dumpFilter(PrintWriter out, String prefix, 9187 PackageParser.ProviderIntentInfo filter) { 9188 out.print(prefix); 9189 out.print( 9190 Integer.toHexString(System.identityHashCode(filter.provider))); 9191 out.print(' '); 9192 filter.provider.printComponentShortName(out); 9193 out.print(" filter "); 9194 out.println(Integer.toHexString(System.identityHashCode(filter))); 9195 } 9196 9197 @Override 9198 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 9199 return filter.provider; 9200 } 9201 9202 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9203 PackageParser.Provider provider = (PackageParser.Provider)label; 9204 out.print(prefix); out.print( 9205 Integer.toHexString(System.identityHashCode(provider))); 9206 out.print(' '); 9207 provider.printComponentShortName(out); 9208 if (count > 1) { 9209 out.print(" ("); out.print(count); out.print(" filters)"); 9210 } 9211 out.println(); 9212 } 9213 9214 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 9215 = new ArrayMap<ComponentName, PackageParser.Provider>(); 9216 private int mFlags; 9217 }; 9218 9219 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 9220 new Comparator<ResolveInfo>() { 9221 public int compare(ResolveInfo r1, ResolveInfo r2) { 9222 int v1 = r1.priority; 9223 int v2 = r2.priority; 9224 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 9225 if (v1 != v2) { 9226 return (v1 > v2) ? -1 : 1; 9227 } 9228 v1 = r1.preferredOrder; 9229 v2 = r2.preferredOrder; 9230 if (v1 != v2) { 9231 return (v1 > v2) ? -1 : 1; 9232 } 9233 if (r1.isDefault != r2.isDefault) { 9234 return r1.isDefault ? -1 : 1; 9235 } 9236 v1 = r1.match; 9237 v2 = r2.match; 9238 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 9239 if (v1 != v2) { 9240 return (v1 > v2) ? -1 : 1; 9241 } 9242 if (r1.system != r2.system) { 9243 return r1.system ? -1 : 1; 9244 } 9245 return 0; 9246 } 9247 }; 9248 9249 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 9250 new Comparator<ProviderInfo>() { 9251 public int compare(ProviderInfo p1, ProviderInfo p2) { 9252 final int v1 = p1.initOrder; 9253 final int v2 = p2.initOrder; 9254 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 9255 } 9256 }; 9257 9258 final void sendPackageBroadcast(final String action, final String pkg, 9259 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 9260 final int[] userIds) { 9261 mHandler.post(new Runnable() { 9262 @Override 9263 public void run() { 9264 try { 9265 final IActivityManager am = ActivityManagerNative.getDefault(); 9266 if (am == null) return; 9267 final int[] resolvedUserIds; 9268 if (userIds == null) { 9269 resolvedUserIds = am.getRunningUserIds(); 9270 } else { 9271 resolvedUserIds = userIds; 9272 } 9273 for (int id : resolvedUserIds) { 9274 final Intent intent = new Intent(action, 9275 pkg != null ? Uri.fromParts("package", pkg, null) : null); 9276 if (extras != null) { 9277 intent.putExtras(extras); 9278 } 9279 if (targetPkg != null) { 9280 intent.setPackage(targetPkg); 9281 } 9282 // Modify the UID when posting to other users 9283 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 9284 if (uid > 0 && UserHandle.getUserId(uid) != id) { 9285 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 9286 intent.putExtra(Intent.EXTRA_UID, uid); 9287 } 9288 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 9289 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 9290 if (DEBUG_BROADCASTS) { 9291 RuntimeException here = new RuntimeException("here"); 9292 here.fillInStackTrace(); 9293 Slog.d(TAG, "Sending to user " + id + ": " 9294 + intent.toShortString(false, true, false, false) 9295 + " " + intent.getExtras(), here); 9296 } 9297 am.broadcastIntent(null, intent, null, finishedReceiver, 9298 0, null, null, null, android.app.AppOpsManager.OP_NONE, 9299 null, finishedReceiver != null, false, id); 9300 } 9301 } catch (RemoteException ex) { 9302 } 9303 } 9304 }); 9305 } 9306 9307 /** 9308 * Check if the external storage media is available. This is true if there 9309 * is a mounted external storage medium or if the external storage is 9310 * emulated. 9311 */ 9312 private boolean isExternalMediaAvailable() { 9313 return mMediaMounted || Environment.isExternalStorageEmulated(); 9314 } 9315 9316 @Override 9317 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 9318 // writer 9319 synchronized (mPackages) { 9320 if (!isExternalMediaAvailable()) { 9321 // If the external storage is no longer mounted at this point, 9322 // the caller may not have been able to delete all of this 9323 // packages files and can not delete any more. Bail. 9324 return null; 9325 } 9326 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 9327 if (lastPackage != null) { 9328 pkgs.remove(lastPackage); 9329 } 9330 if (pkgs.size() > 0) { 9331 return pkgs.get(0); 9332 } 9333 } 9334 return null; 9335 } 9336 9337 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 9338 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 9339 userId, andCode ? 1 : 0, packageName); 9340 if (mSystemReady) { 9341 msg.sendToTarget(); 9342 } else { 9343 if (mPostSystemReadyMessages == null) { 9344 mPostSystemReadyMessages = new ArrayList<>(); 9345 } 9346 mPostSystemReadyMessages.add(msg); 9347 } 9348 } 9349 9350 void startCleaningPackages() { 9351 // reader 9352 synchronized (mPackages) { 9353 if (!isExternalMediaAvailable()) { 9354 return; 9355 } 9356 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 9357 return; 9358 } 9359 } 9360 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 9361 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 9362 IActivityManager am = ActivityManagerNative.getDefault(); 9363 if (am != null) { 9364 try { 9365 am.startService(null, intent, null, mContext.getOpPackageName(), 9366 UserHandle.USER_OWNER); 9367 } catch (RemoteException e) { 9368 } 9369 } 9370 } 9371 9372 @Override 9373 public void installPackage(String originPath, IPackageInstallObserver2 observer, 9374 int installFlags, String installerPackageName, VerificationParams verificationParams, 9375 String packageAbiOverride) { 9376 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 9377 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 9378 } 9379 9380 @Override 9381 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 9382 int installFlags, String installerPackageName, VerificationParams verificationParams, 9383 String packageAbiOverride, int userId) { 9384 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 9385 9386 final int callingUid = Binder.getCallingUid(); 9387 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 9388 9389 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9390 try { 9391 if (observer != null) { 9392 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 9393 } 9394 } catch (RemoteException re) { 9395 } 9396 return; 9397 } 9398 9399 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 9400 installFlags |= PackageManager.INSTALL_FROM_ADB; 9401 9402 } else { 9403 // Caller holds INSTALL_PACKAGES permission, so we're less strict 9404 // about installerPackageName. 9405 9406 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 9407 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 9408 } 9409 9410 UserHandle user; 9411 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 9412 user = UserHandle.ALL; 9413 } else { 9414 user = new UserHandle(userId); 9415 } 9416 9417 // Only system components can circumvent runtime permissions when installing. 9418 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 9419 && mContext.checkCallingOrSelfPermission(Manifest.permission 9420 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 9421 throw new SecurityException("You need the " 9422 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 9423 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 9424 } 9425 9426 verificationParams.setInstallerUid(callingUid); 9427 9428 final File originFile = new File(originPath); 9429 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 9430 9431 final Message msg = mHandler.obtainMessage(INIT_COPY); 9432 msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName, 9433 null, verificationParams, user, packageAbiOverride); 9434 mHandler.sendMessage(msg); 9435 } 9436 9437 void installStage(String packageName, File stagedDir, String stagedCid, 9438 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 9439 String installerPackageName, int installerUid, UserHandle user) { 9440 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 9441 params.referrerUri, installerUid, null); 9442 verifParams.setInstallerUid(installerUid); 9443 9444 final OriginInfo origin; 9445 if (stagedDir != null) { 9446 origin = OriginInfo.fromStagedFile(stagedDir); 9447 } else { 9448 origin = OriginInfo.fromStagedContainer(stagedCid); 9449 } 9450 9451 final Message msg = mHandler.obtainMessage(INIT_COPY); 9452 msg.obj = new InstallParams(origin, null, observer, params.installFlags, 9453 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride); 9454 mHandler.sendMessage(msg); 9455 } 9456 9457 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 9458 Bundle extras = new Bundle(1); 9459 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 9460 9461 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 9462 packageName, extras, null, null, new int[] {userId}); 9463 try { 9464 IActivityManager am = ActivityManagerNative.getDefault(); 9465 final boolean isSystem = 9466 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 9467 if (isSystem && am.isUserRunning(userId, false)) { 9468 // The just-installed/enabled app is bundled on the system, so presumed 9469 // to be able to run automatically without needing an explicit launch. 9470 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 9471 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 9472 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 9473 .setPackage(packageName); 9474 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 9475 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 9476 } 9477 } catch (RemoteException e) { 9478 // shouldn't happen 9479 Slog.w(TAG, "Unable to bootstrap installed package", e); 9480 } 9481 } 9482 9483 @Override 9484 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 9485 int userId) { 9486 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9487 PackageSetting pkgSetting; 9488 final int uid = Binder.getCallingUid(); 9489 enforceCrossUserPermission(uid, userId, true, true, 9490 "setApplicationHiddenSetting for user " + userId); 9491 9492 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 9493 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 9494 return false; 9495 } 9496 9497 long callingId = Binder.clearCallingIdentity(); 9498 try { 9499 boolean sendAdded = false; 9500 boolean sendRemoved = false; 9501 // writer 9502 synchronized (mPackages) { 9503 pkgSetting = mSettings.mPackages.get(packageName); 9504 if (pkgSetting == null) { 9505 return false; 9506 } 9507 if (pkgSetting.getHidden(userId) != hidden) { 9508 pkgSetting.setHidden(hidden, userId); 9509 mSettings.writePackageRestrictionsLPr(userId); 9510 if (hidden) { 9511 sendRemoved = true; 9512 } else { 9513 sendAdded = true; 9514 } 9515 } 9516 } 9517 if (sendAdded) { 9518 sendPackageAddedForUser(packageName, pkgSetting, userId); 9519 return true; 9520 } 9521 if (sendRemoved) { 9522 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 9523 "hiding pkg"); 9524 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 9525 } 9526 } finally { 9527 Binder.restoreCallingIdentity(callingId); 9528 } 9529 return false; 9530 } 9531 9532 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 9533 int userId) { 9534 final PackageRemovedInfo info = new PackageRemovedInfo(); 9535 info.removedPackage = packageName; 9536 info.removedUsers = new int[] {userId}; 9537 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 9538 info.sendBroadcast(false, false, false); 9539 } 9540 9541 /** 9542 * Returns true if application is not found or there was an error. Otherwise it returns 9543 * the hidden state of the package for the given user. 9544 */ 9545 @Override 9546 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 9547 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9548 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 9549 false, "getApplicationHidden for user " + userId); 9550 PackageSetting pkgSetting; 9551 long callingId = Binder.clearCallingIdentity(); 9552 try { 9553 // writer 9554 synchronized (mPackages) { 9555 pkgSetting = mSettings.mPackages.get(packageName); 9556 if (pkgSetting == null) { 9557 return true; 9558 } 9559 return pkgSetting.getHidden(userId); 9560 } 9561 } finally { 9562 Binder.restoreCallingIdentity(callingId); 9563 } 9564 } 9565 9566 /** 9567 * @hide 9568 */ 9569 @Override 9570 public int installExistingPackageAsUser(String packageName, int userId) { 9571 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 9572 null); 9573 PackageSetting pkgSetting; 9574 final int uid = Binder.getCallingUid(); 9575 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 9576 + userId); 9577 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9578 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 9579 } 9580 9581 long callingId = Binder.clearCallingIdentity(); 9582 try { 9583 boolean sendAdded = false; 9584 9585 // writer 9586 synchronized (mPackages) { 9587 pkgSetting = mSettings.mPackages.get(packageName); 9588 if (pkgSetting == null) { 9589 return PackageManager.INSTALL_FAILED_INVALID_URI; 9590 } 9591 if (!pkgSetting.getInstalled(userId)) { 9592 pkgSetting.setInstalled(true, userId); 9593 pkgSetting.setHidden(false, userId); 9594 mSettings.writePackageRestrictionsLPr(userId); 9595 sendAdded = true; 9596 } 9597 } 9598 9599 if (sendAdded) { 9600 sendPackageAddedForUser(packageName, pkgSetting, userId); 9601 } 9602 } finally { 9603 Binder.restoreCallingIdentity(callingId); 9604 } 9605 9606 return PackageManager.INSTALL_SUCCEEDED; 9607 } 9608 9609 boolean isUserRestricted(int userId, String restrictionKey) { 9610 Bundle restrictions = sUserManager.getUserRestrictions(userId); 9611 if (restrictions.getBoolean(restrictionKey, false)) { 9612 Log.w(TAG, "User is restricted: " + restrictionKey); 9613 return true; 9614 } 9615 return false; 9616 } 9617 9618 @Override 9619 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 9620 mContext.enforceCallingOrSelfPermission( 9621 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9622 "Only package verification agents can verify applications"); 9623 9624 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9625 final PackageVerificationResponse response = new PackageVerificationResponse( 9626 verificationCode, Binder.getCallingUid()); 9627 msg.arg1 = id; 9628 msg.obj = response; 9629 mHandler.sendMessage(msg); 9630 } 9631 9632 @Override 9633 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 9634 long millisecondsToDelay) { 9635 mContext.enforceCallingOrSelfPermission( 9636 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9637 "Only package verification agents can extend verification timeouts"); 9638 9639 final PackageVerificationState state = mPendingVerification.get(id); 9640 final PackageVerificationResponse response = new PackageVerificationResponse( 9641 verificationCodeAtTimeout, Binder.getCallingUid()); 9642 9643 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 9644 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 9645 } 9646 if (millisecondsToDelay < 0) { 9647 millisecondsToDelay = 0; 9648 } 9649 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 9650 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 9651 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 9652 } 9653 9654 if ((state != null) && !state.timeoutExtended()) { 9655 state.extendTimeout(); 9656 9657 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9658 msg.arg1 = id; 9659 msg.obj = response; 9660 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 9661 } 9662 } 9663 9664 private void broadcastPackageVerified(int verificationId, Uri packageUri, 9665 int verificationCode, UserHandle user) { 9666 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 9667 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 9668 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9669 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9670 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 9671 9672 mContext.sendBroadcastAsUser(intent, user, 9673 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 9674 } 9675 9676 private ComponentName matchComponentForVerifier(String packageName, 9677 List<ResolveInfo> receivers) { 9678 ActivityInfo targetReceiver = null; 9679 9680 final int NR = receivers.size(); 9681 for (int i = 0; i < NR; i++) { 9682 final ResolveInfo info = receivers.get(i); 9683 if (info.activityInfo == null) { 9684 continue; 9685 } 9686 9687 if (packageName.equals(info.activityInfo.packageName)) { 9688 targetReceiver = info.activityInfo; 9689 break; 9690 } 9691 } 9692 9693 if (targetReceiver == null) { 9694 return null; 9695 } 9696 9697 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 9698 } 9699 9700 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 9701 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 9702 if (pkgInfo.verifiers.length == 0) { 9703 return null; 9704 } 9705 9706 final int N = pkgInfo.verifiers.length; 9707 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 9708 for (int i = 0; i < N; i++) { 9709 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 9710 9711 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 9712 receivers); 9713 if (comp == null) { 9714 continue; 9715 } 9716 9717 final int verifierUid = getUidForVerifier(verifierInfo); 9718 if (verifierUid == -1) { 9719 continue; 9720 } 9721 9722 if (DEBUG_VERIFY) { 9723 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 9724 + " with the correct signature"); 9725 } 9726 sufficientVerifiers.add(comp); 9727 verificationState.addSufficientVerifier(verifierUid); 9728 } 9729 9730 return sufficientVerifiers; 9731 } 9732 9733 private int getUidForVerifier(VerifierInfo verifierInfo) { 9734 synchronized (mPackages) { 9735 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 9736 if (pkg == null) { 9737 return -1; 9738 } else if (pkg.mSignatures.length != 1) { 9739 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9740 + " has more than one signature; ignoring"); 9741 return -1; 9742 } 9743 9744 /* 9745 * If the public key of the package's signature does not match 9746 * our expected public key, then this is a different package and 9747 * we should skip. 9748 */ 9749 9750 final byte[] expectedPublicKey; 9751 try { 9752 final Signature verifierSig = pkg.mSignatures[0]; 9753 final PublicKey publicKey = verifierSig.getPublicKey(); 9754 expectedPublicKey = publicKey.getEncoded(); 9755 } catch (CertificateException e) { 9756 return -1; 9757 } 9758 9759 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 9760 9761 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 9762 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9763 + " does not have the expected public key; ignoring"); 9764 return -1; 9765 } 9766 9767 return pkg.applicationInfo.uid; 9768 } 9769 } 9770 9771 @Override 9772 public void finishPackageInstall(int token) { 9773 enforceSystemOrRoot("Only the system is allowed to finish installs"); 9774 9775 if (DEBUG_INSTALL) { 9776 Slog.v(TAG, "BM finishing package install for " + token); 9777 } 9778 9779 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9780 mHandler.sendMessage(msg); 9781 } 9782 9783 /** 9784 * Get the verification agent timeout. 9785 * 9786 * @return verification timeout in milliseconds 9787 */ 9788 private long getVerificationTimeout() { 9789 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 9790 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 9791 DEFAULT_VERIFICATION_TIMEOUT); 9792 } 9793 9794 /** 9795 * Get the default verification agent response code. 9796 * 9797 * @return default verification response code 9798 */ 9799 private int getDefaultVerificationResponse() { 9800 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9801 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 9802 DEFAULT_VERIFICATION_RESPONSE); 9803 } 9804 9805 /** 9806 * Check whether or not package verification has been enabled. 9807 * 9808 * @return true if verification should be performed 9809 */ 9810 private boolean isVerificationEnabled(int userId, int installFlags) { 9811 if (!DEFAULT_VERIFY_ENABLE) { 9812 return false; 9813 } 9814 9815 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 9816 9817 // Check if installing from ADB 9818 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 9819 // Do not run verification in a test harness environment 9820 if (ActivityManager.isRunningInTestHarness()) { 9821 return false; 9822 } 9823 if (ensureVerifyAppsEnabled) { 9824 return true; 9825 } 9826 // Check if the developer does not want package verification for ADB installs 9827 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9828 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 9829 return false; 9830 } 9831 } 9832 9833 if (ensureVerifyAppsEnabled) { 9834 return true; 9835 } 9836 9837 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9838 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 9839 } 9840 9841 @Override 9842 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 9843 throws RemoteException { 9844 mContext.enforceCallingOrSelfPermission( 9845 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 9846 "Only intentfilter verification agents can verify applications"); 9847 9848 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 9849 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 9850 Binder.getCallingUid(), verificationCode, failedDomains); 9851 msg.arg1 = id; 9852 msg.obj = response; 9853 mHandler.sendMessage(msg); 9854 } 9855 9856 @Override 9857 public int getIntentVerificationStatus(String packageName, int userId) { 9858 synchronized (mPackages) { 9859 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 9860 } 9861 } 9862 9863 @Override 9864 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 9865 mContext.enforceCallingOrSelfPermission( 9866 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 9867 9868 boolean result = false; 9869 synchronized (mPackages) { 9870 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 9871 } 9872 if (result) { 9873 scheduleWritePackageRestrictionsLocked(userId); 9874 } 9875 return result; 9876 } 9877 9878 @Override 9879 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 9880 synchronized (mPackages) { 9881 return mSettings.getIntentFilterVerificationsLPr(packageName); 9882 } 9883 } 9884 9885 @Override 9886 public List<IntentFilter> getAllIntentFilters(String packageName) { 9887 if (TextUtils.isEmpty(packageName)) { 9888 return Collections.<IntentFilter>emptyList(); 9889 } 9890 synchronized (mPackages) { 9891 PackageParser.Package pkg = mPackages.get(packageName); 9892 if (pkg == null || pkg.activities == null) { 9893 return Collections.<IntentFilter>emptyList(); 9894 } 9895 final int count = pkg.activities.size(); 9896 ArrayList<IntentFilter> result = new ArrayList<>(); 9897 for (int n=0; n<count; n++) { 9898 PackageParser.Activity activity = pkg.activities.get(n); 9899 if (activity.intents != null || activity.intents.size() > 0) { 9900 result.addAll(activity.intents); 9901 } 9902 } 9903 return result; 9904 } 9905 } 9906 9907 @Override 9908 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 9909 mContext.enforceCallingOrSelfPermission( 9910 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 9911 9912 synchronized (mPackages) { 9913 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 9914 if (packageName != null) { 9915 result |= updateIntentVerificationStatus(packageName, 9916 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 9917 UserHandle.myUserId()); 9918 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 9919 packageName, userId); 9920 } 9921 return result; 9922 } 9923 } 9924 9925 @Override 9926 public String getDefaultBrowserPackageName(int userId) { 9927 synchronized (mPackages) { 9928 return mSettings.getDefaultBrowserPackageNameLPw(userId); 9929 } 9930 } 9931 9932 /** 9933 * Get the "allow unknown sources" setting. 9934 * 9935 * @return the current "allow unknown sources" setting 9936 */ 9937 private int getUnknownSourcesSettings() { 9938 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9939 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 9940 -1); 9941 } 9942 9943 @Override 9944 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 9945 final int uid = Binder.getCallingUid(); 9946 // writer 9947 synchronized (mPackages) { 9948 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 9949 if (targetPackageSetting == null) { 9950 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 9951 } 9952 9953 PackageSetting installerPackageSetting; 9954 if (installerPackageName != null) { 9955 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 9956 if (installerPackageSetting == null) { 9957 throw new IllegalArgumentException("Unknown installer package: " 9958 + installerPackageName); 9959 } 9960 } else { 9961 installerPackageSetting = null; 9962 } 9963 9964 Signature[] callerSignature; 9965 Object obj = mSettings.getUserIdLPr(uid); 9966 if (obj != null) { 9967 if (obj instanceof SharedUserSetting) { 9968 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 9969 } else if (obj instanceof PackageSetting) { 9970 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 9971 } else { 9972 throw new SecurityException("Bad object " + obj + " for uid " + uid); 9973 } 9974 } else { 9975 throw new SecurityException("Unknown calling uid " + uid); 9976 } 9977 9978 // Verify: can't set installerPackageName to a package that is 9979 // not signed with the same cert as the caller. 9980 if (installerPackageSetting != null) { 9981 if (compareSignatures(callerSignature, 9982 installerPackageSetting.signatures.mSignatures) 9983 != PackageManager.SIGNATURE_MATCH) { 9984 throw new SecurityException( 9985 "Caller does not have same cert as new installer package " 9986 + installerPackageName); 9987 } 9988 } 9989 9990 // Verify: if target already has an installer package, it must 9991 // be signed with the same cert as the caller. 9992 if (targetPackageSetting.installerPackageName != null) { 9993 PackageSetting setting = mSettings.mPackages.get( 9994 targetPackageSetting.installerPackageName); 9995 // If the currently set package isn't valid, then it's always 9996 // okay to change it. 9997 if (setting != null) { 9998 if (compareSignatures(callerSignature, 9999 setting.signatures.mSignatures) 10000 != PackageManager.SIGNATURE_MATCH) { 10001 throw new SecurityException( 10002 "Caller does not have same cert as old installer package " 10003 + targetPackageSetting.installerPackageName); 10004 } 10005 } 10006 } 10007 10008 // Okay! 10009 targetPackageSetting.installerPackageName = installerPackageName; 10010 scheduleWriteSettingsLocked(); 10011 } 10012 } 10013 10014 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 10015 // Queue up an async operation since the package installation may take a little while. 10016 mHandler.post(new Runnable() { 10017 public void run() { 10018 mHandler.removeCallbacks(this); 10019 // Result object to be returned 10020 PackageInstalledInfo res = new PackageInstalledInfo(); 10021 res.returnCode = currentStatus; 10022 res.uid = -1; 10023 res.pkg = null; 10024 res.removedInfo = new PackageRemovedInfo(); 10025 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10026 args.doPreInstall(res.returnCode); 10027 synchronized (mInstallLock) { 10028 installPackageLI(args, res); 10029 } 10030 args.doPostInstall(res.returnCode, res.uid); 10031 } 10032 10033 // A restore should be performed at this point if (a) the install 10034 // succeeded, (b) the operation is not an update, and (c) the new 10035 // package has not opted out of backup participation. 10036 final boolean update = res.removedInfo.removedPackage != null; 10037 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 10038 boolean doRestore = !update 10039 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 10040 10041 // Set up the post-install work request bookkeeping. This will be used 10042 // and cleaned up by the post-install event handling regardless of whether 10043 // there's a restore pass performed. Token values are >= 1. 10044 int token; 10045 if (mNextInstallToken < 0) mNextInstallToken = 1; 10046 token = mNextInstallToken++; 10047 10048 PostInstallData data = new PostInstallData(args, res); 10049 mRunningInstalls.put(token, data); 10050 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 10051 10052 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 10053 // Pass responsibility to the Backup Manager. It will perform a 10054 // restore if appropriate, then pass responsibility back to the 10055 // Package Manager to run the post-install observer callbacks 10056 // and broadcasts. 10057 IBackupManager bm = IBackupManager.Stub.asInterface( 10058 ServiceManager.getService(Context.BACKUP_SERVICE)); 10059 if (bm != null) { 10060 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 10061 + " to BM for possible restore"); 10062 try { 10063 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 10064 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 10065 } else { 10066 doRestore = false; 10067 } 10068 } catch (RemoteException e) { 10069 // can't happen; the backup manager is local 10070 } catch (Exception e) { 10071 Slog.e(TAG, "Exception trying to enqueue restore", e); 10072 doRestore = false; 10073 } 10074 } else { 10075 Slog.e(TAG, "Backup Manager not found!"); 10076 doRestore = false; 10077 } 10078 } 10079 10080 if (!doRestore) { 10081 // No restore possible, or the Backup Manager was mysteriously not 10082 // available -- just fire the post-install work request directly. 10083 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 10084 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10085 mHandler.sendMessage(msg); 10086 } 10087 } 10088 }); 10089 } 10090 10091 private abstract class HandlerParams { 10092 private static final int MAX_RETRIES = 4; 10093 10094 /** 10095 * Number of times startCopy() has been attempted and had a non-fatal 10096 * error. 10097 */ 10098 private int mRetries = 0; 10099 10100 /** User handle for the user requesting the information or installation. */ 10101 private final UserHandle mUser; 10102 10103 HandlerParams(UserHandle user) { 10104 mUser = user; 10105 } 10106 10107 UserHandle getUser() { 10108 return mUser; 10109 } 10110 10111 final boolean startCopy() { 10112 boolean res; 10113 try { 10114 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 10115 10116 if (++mRetries > MAX_RETRIES) { 10117 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 10118 mHandler.sendEmptyMessage(MCS_GIVE_UP); 10119 handleServiceError(); 10120 return false; 10121 } else { 10122 handleStartCopy(); 10123 res = true; 10124 } 10125 } catch (RemoteException e) { 10126 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 10127 mHandler.sendEmptyMessage(MCS_RECONNECT); 10128 res = false; 10129 } 10130 handleReturnCode(); 10131 return res; 10132 } 10133 10134 final void serviceError() { 10135 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 10136 handleServiceError(); 10137 handleReturnCode(); 10138 } 10139 10140 abstract void handleStartCopy() throws RemoteException; 10141 abstract void handleServiceError(); 10142 abstract void handleReturnCode(); 10143 } 10144 10145 class MeasureParams extends HandlerParams { 10146 private final PackageStats mStats; 10147 private boolean mSuccess; 10148 10149 private final IPackageStatsObserver mObserver; 10150 10151 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 10152 super(new UserHandle(stats.userHandle)); 10153 mObserver = observer; 10154 mStats = stats; 10155 } 10156 10157 @Override 10158 public String toString() { 10159 return "MeasureParams{" 10160 + Integer.toHexString(System.identityHashCode(this)) 10161 + " " + mStats.packageName + "}"; 10162 } 10163 10164 @Override 10165 void handleStartCopy() throws RemoteException { 10166 synchronized (mInstallLock) { 10167 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 10168 } 10169 10170 if (mSuccess) { 10171 final boolean mounted; 10172 if (Environment.isExternalStorageEmulated()) { 10173 mounted = true; 10174 } else { 10175 final String status = Environment.getExternalStorageState(); 10176 mounted = (Environment.MEDIA_MOUNTED.equals(status) 10177 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 10178 } 10179 10180 if (mounted) { 10181 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 10182 10183 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 10184 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 10185 10186 mStats.externalDataSize = calculateDirectorySize(mContainerService, 10187 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 10188 10189 // Always subtract cache size, since it's a subdirectory 10190 mStats.externalDataSize -= mStats.externalCacheSize; 10191 10192 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 10193 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 10194 10195 mStats.externalObbSize = calculateDirectorySize(mContainerService, 10196 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 10197 } 10198 } 10199 } 10200 10201 @Override 10202 void handleReturnCode() { 10203 if (mObserver != null) { 10204 try { 10205 mObserver.onGetStatsCompleted(mStats, mSuccess); 10206 } catch (RemoteException e) { 10207 Slog.i(TAG, "Observer no longer exists."); 10208 } 10209 } 10210 } 10211 10212 @Override 10213 void handleServiceError() { 10214 Slog.e(TAG, "Could not measure application " + mStats.packageName 10215 + " external storage"); 10216 } 10217 } 10218 10219 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 10220 throws RemoteException { 10221 long result = 0; 10222 for (File path : paths) { 10223 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 10224 } 10225 return result; 10226 } 10227 10228 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 10229 for (File path : paths) { 10230 try { 10231 mcs.clearDirectory(path.getAbsolutePath()); 10232 } catch (RemoteException e) { 10233 } 10234 } 10235 } 10236 10237 static class OriginInfo { 10238 /** 10239 * Location where install is coming from, before it has been 10240 * copied/renamed into place. This could be a single monolithic APK 10241 * file, or a cluster directory. This location may be untrusted. 10242 */ 10243 final File file; 10244 final String cid; 10245 10246 /** 10247 * Flag indicating that {@link #file} or {@link #cid} has already been 10248 * staged, meaning downstream users don't need to defensively copy the 10249 * contents. 10250 */ 10251 final boolean staged; 10252 10253 /** 10254 * Flag indicating that {@link #file} or {@link #cid} is an already 10255 * installed app that is being moved. 10256 */ 10257 final boolean existing; 10258 10259 final String resolvedPath; 10260 final File resolvedFile; 10261 10262 static OriginInfo fromNothing() { 10263 return new OriginInfo(null, null, false, false); 10264 } 10265 10266 static OriginInfo fromUntrustedFile(File file) { 10267 return new OriginInfo(file, null, false, false); 10268 } 10269 10270 static OriginInfo fromExistingFile(File file) { 10271 return new OriginInfo(file, null, false, true); 10272 } 10273 10274 static OriginInfo fromStagedFile(File file) { 10275 return new OriginInfo(file, null, true, false); 10276 } 10277 10278 static OriginInfo fromStagedContainer(String cid) { 10279 return new OriginInfo(null, cid, true, false); 10280 } 10281 10282 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 10283 this.file = file; 10284 this.cid = cid; 10285 this.staged = staged; 10286 this.existing = existing; 10287 10288 if (cid != null) { 10289 resolvedPath = PackageHelper.getSdDir(cid); 10290 resolvedFile = new File(resolvedPath); 10291 } else if (file != null) { 10292 resolvedPath = file.getAbsolutePath(); 10293 resolvedFile = file; 10294 } else { 10295 resolvedPath = null; 10296 resolvedFile = null; 10297 } 10298 } 10299 } 10300 10301 class MoveInfo { 10302 final int moveId; 10303 final String fromUuid; 10304 final String toUuid; 10305 final String packageName; 10306 final String dataAppName; 10307 final int appId; 10308 final String seinfo; 10309 10310 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 10311 String dataAppName, int appId, String seinfo) { 10312 this.moveId = moveId; 10313 this.fromUuid = fromUuid; 10314 this.toUuid = toUuid; 10315 this.packageName = packageName; 10316 this.dataAppName = dataAppName; 10317 this.appId = appId; 10318 this.seinfo = seinfo; 10319 } 10320 } 10321 10322 class InstallParams extends HandlerParams { 10323 final OriginInfo origin; 10324 final MoveInfo move; 10325 final IPackageInstallObserver2 observer; 10326 int installFlags; 10327 final String installerPackageName; 10328 final String volumeUuid; 10329 final VerificationParams verificationParams; 10330 private InstallArgs mArgs; 10331 private int mRet; 10332 final String packageAbiOverride; 10333 10334 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10335 int installFlags, String installerPackageName, String volumeUuid, 10336 VerificationParams verificationParams, UserHandle user, String packageAbiOverride) { 10337 super(user); 10338 this.origin = origin; 10339 this.move = move; 10340 this.observer = observer; 10341 this.installFlags = installFlags; 10342 this.installerPackageName = installerPackageName; 10343 this.volumeUuid = volumeUuid; 10344 this.verificationParams = verificationParams; 10345 this.packageAbiOverride = packageAbiOverride; 10346 } 10347 10348 @Override 10349 public String toString() { 10350 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 10351 + " file=" + origin.file + " cid=" + origin.cid + "}"; 10352 } 10353 10354 public ManifestDigest getManifestDigest() { 10355 if (verificationParams == null) { 10356 return null; 10357 } 10358 return verificationParams.getManifestDigest(); 10359 } 10360 10361 private int installLocationPolicy(PackageInfoLite pkgLite) { 10362 String packageName = pkgLite.packageName; 10363 int installLocation = pkgLite.installLocation; 10364 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10365 // reader 10366 synchronized (mPackages) { 10367 PackageParser.Package pkg = mPackages.get(packageName); 10368 if (pkg != null) { 10369 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10370 // Check for downgrading. 10371 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 10372 try { 10373 checkDowngrade(pkg, pkgLite); 10374 } catch (PackageManagerException e) { 10375 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 10376 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 10377 } 10378 } 10379 // Check for updated system application. 10380 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10381 if (onSd) { 10382 Slog.w(TAG, "Cannot install update to system app on sdcard"); 10383 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 10384 } 10385 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10386 } else { 10387 if (onSd) { 10388 // Install flag overrides everything. 10389 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10390 } 10391 // If current upgrade specifies particular preference 10392 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 10393 // Application explicitly specified internal. 10394 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10395 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 10396 // App explictly prefers external. Let policy decide 10397 } else { 10398 // Prefer previous location 10399 if (isExternal(pkg)) { 10400 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10401 } 10402 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10403 } 10404 } 10405 } else { 10406 // Invalid install. Return error code 10407 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 10408 } 10409 } 10410 } 10411 // All the special cases have been taken care of. 10412 // Return result based on recommended install location. 10413 if (onSd) { 10414 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10415 } 10416 return pkgLite.recommendedInstallLocation; 10417 } 10418 10419 /* 10420 * Invoke remote method to get package information and install 10421 * location values. Override install location based on default 10422 * policy if needed and then create install arguments based 10423 * on the install location. 10424 */ 10425 public void handleStartCopy() throws RemoteException { 10426 int ret = PackageManager.INSTALL_SUCCEEDED; 10427 10428 // If we're already staged, we've firmly committed to an install location 10429 if (origin.staged) { 10430 if (origin.file != null) { 10431 installFlags |= PackageManager.INSTALL_INTERNAL; 10432 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10433 } else if (origin.cid != null) { 10434 installFlags |= PackageManager.INSTALL_EXTERNAL; 10435 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10436 } else { 10437 throw new IllegalStateException("Invalid stage location"); 10438 } 10439 } 10440 10441 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10442 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 10443 10444 PackageInfoLite pkgLite = null; 10445 10446 if (onInt && onSd) { 10447 // Check if both bits are set. 10448 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 10449 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10450 } else { 10451 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 10452 packageAbiOverride); 10453 10454 /* 10455 * If we have too little free space, try to free cache 10456 * before giving up. 10457 */ 10458 if (!origin.staged && pkgLite.recommendedInstallLocation 10459 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10460 // TODO: focus freeing disk space on the target device 10461 final StorageManager storage = StorageManager.from(mContext); 10462 final long lowThreshold = storage.getStorageLowBytes( 10463 Environment.getDataDirectory()); 10464 10465 final long sizeBytes = mContainerService.calculateInstalledSize( 10466 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 10467 10468 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 10469 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 10470 installFlags, packageAbiOverride); 10471 } 10472 10473 /* 10474 * The cache free must have deleted the file we 10475 * downloaded to install. 10476 * 10477 * TODO: fix the "freeCache" call to not delete 10478 * the file we care about. 10479 */ 10480 if (pkgLite.recommendedInstallLocation 10481 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10482 pkgLite.recommendedInstallLocation 10483 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 10484 } 10485 } 10486 } 10487 10488 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10489 int loc = pkgLite.recommendedInstallLocation; 10490 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 10491 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10492 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 10493 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 10494 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10495 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10496 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 10497 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 10498 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10499 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 10500 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 10501 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 10502 } else { 10503 // Override with defaults if needed. 10504 loc = installLocationPolicy(pkgLite); 10505 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 10506 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 10507 } else if (!onSd && !onInt) { 10508 // Override install location with flags 10509 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 10510 // Set the flag to install on external media. 10511 installFlags |= PackageManager.INSTALL_EXTERNAL; 10512 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10513 } else { 10514 // Make sure the flag for installing on external 10515 // media is unset 10516 installFlags |= PackageManager.INSTALL_INTERNAL; 10517 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10518 } 10519 } 10520 } 10521 } 10522 10523 final InstallArgs args = createInstallArgs(this); 10524 mArgs = args; 10525 10526 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10527 /* 10528 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 10529 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 10530 */ 10531 int userIdentifier = getUser().getIdentifier(); 10532 if (userIdentifier == UserHandle.USER_ALL 10533 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 10534 userIdentifier = UserHandle.USER_OWNER; 10535 } 10536 10537 /* 10538 * Determine if we have any installed package verifiers. If we 10539 * do, then we'll defer to them to verify the packages. 10540 */ 10541 final int requiredUid = mRequiredVerifierPackage == null ? -1 10542 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 10543 if (!origin.existing && requiredUid != -1 10544 && isVerificationEnabled(userIdentifier, installFlags)) { 10545 final Intent verification = new Intent( 10546 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 10547 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 10548 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 10549 PACKAGE_MIME_TYPE); 10550 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10551 10552 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 10553 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 10554 0 /* TODO: Which userId? */); 10555 10556 if (DEBUG_VERIFY) { 10557 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 10558 + verification.toString() + " with " + pkgLite.verifiers.length 10559 + " optional verifiers"); 10560 } 10561 10562 final int verificationId = mPendingVerificationToken++; 10563 10564 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10565 10566 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 10567 installerPackageName); 10568 10569 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 10570 installFlags); 10571 10572 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 10573 pkgLite.packageName); 10574 10575 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 10576 pkgLite.versionCode); 10577 10578 if (verificationParams != null) { 10579 if (verificationParams.getVerificationURI() != null) { 10580 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 10581 verificationParams.getVerificationURI()); 10582 } 10583 if (verificationParams.getOriginatingURI() != null) { 10584 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 10585 verificationParams.getOriginatingURI()); 10586 } 10587 if (verificationParams.getReferrer() != null) { 10588 verification.putExtra(Intent.EXTRA_REFERRER, 10589 verificationParams.getReferrer()); 10590 } 10591 if (verificationParams.getOriginatingUid() >= 0) { 10592 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 10593 verificationParams.getOriginatingUid()); 10594 } 10595 if (verificationParams.getInstallerUid() >= 0) { 10596 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 10597 verificationParams.getInstallerUid()); 10598 } 10599 } 10600 10601 final PackageVerificationState verificationState = new PackageVerificationState( 10602 requiredUid, args); 10603 10604 mPendingVerification.append(verificationId, verificationState); 10605 10606 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 10607 receivers, verificationState); 10608 10609 /* 10610 * If any sufficient verifiers were listed in the package 10611 * manifest, attempt to ask them. 10612 */ 10613 if (sufficientVerifiers != null) { 10614 final int N = sufficientVerifiers.size(); 10615 if (N == 0) { 10616 Slog.i(TAG, "Additional verifiers required, but none installed."); 10617 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 10618 } else { 10619 for (int i = 0; i < N; i++) { 10620 final ComponentName verifierComponent = sufficientVerifiers.get(i); 10621 10622 final Intent sufficientIntent = new Intent(verification); 10623 sufficientIntent.setComponent(verifierComponent); 10624 10625 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 10626 } 10627 } 10628 } 10629 10630 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 10631 mRequiredVerifierPackage, receivers); 10632 if (ret == PackageManager.INSTALL_SUCCEEDED 10633 && mRequiredVerifierPackage != null) { 10634 /* 10635 * Send the intent to the required verification agent, 10636 * but only start the verification timeout after the 10637 * target BroadcastReceivers have run. 10638 */ 10639 verification.setComponent(requiredVerifierComponent); 10640 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 10641 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10642 new BroadcastReceiver() { 10643 @Override 10644 public void onReceive(Context context, Intent intent) { 10645 final Message msg = mHandler 10646 .obtainMessage(CHECK_PENDING_VERIFICATION); 10647 msg.arg1 = verificationId; 10648 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 10649 } 10650 }, null, 0, null, null); 10651 10652 /* 10653 * We don't want the copy to proceed until verification 10654 * succeeds, so null out this field. 10655 */ 10656 mArgs = null; 10657 } 10658 } else { 10659 /* 10660 * No package verification is enabled, so immediately start 10661 * the remote call to initiate copy using temporary file. 10662 */ 10663 ret = args.copyApk(mContainerService, true); 10664 } 10665 } 10666 10667 mRet = ret; 10668 } 10669 10670 @Override 10671 void handleReturnCode() { 10672 // If mArgs is null, then MCS couldn't be reached. When it 10673 // reconnects, it will try again to install. At that point, this 10674 // will succeed. 10675 if (mArgs != null) { 10676 processPendingInstall(mArgs, mRet); 10677 } 10678 } 10679 10680 @Override 10681 void handleServiceError() { 10682 mArgs = createInstallArgs(this); 10683 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10684 } 10685 10686 public boolean isForwardLocked() { 10687 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10688 } 10689 } 10690 10691 /** 10692 * Used during creation of InstallArgs 10693 * 10694 * @param installFlags package installation flags 10695 * @return true if should be installed on external storage 10696 */ 10697 private static boolean installOnExternalAsec(int installFlags) { 10698 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 10699 return false; 10700 } 10701 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 10702 return true; 10703 } 10704 return false; 10705 } 10706 10707 /** 10708 * Used during creation of InstallArgs 10709 * 10710 * @param installFlags package installation flags 10711 * @return true if should be installed as forward locked 10712 */ 10713 private static boolean installForwardLocked(int installFlags) { 10714 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10715 } 10716 10717 private InstallArgs createInstallArgs(InstallParams params) { 10718 if (params.move != null) { 10719 return new MoveInstallArgs(params); 10720 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 10721 return new AsecInstallArgs(params); 10722 } else { 10723 return new FileInstallArgs(params); 10724 } 10725 } 10726 10727 /** 10728 * Create args that describe an existing installed package. Typically used 10729 * when cleaning up old installs, or used as a move source. 10730 */ 10731 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 10732 String resourcePath, String[] instructionSets) { 10733 final boolean isInAsec; 10734 if (installOnExternalAsec(installFlags)) { 10735 /* Apps on SD card are always in ASEC containers. */ 10736 isInAsec = true; 10737 } else if (installForwardLocked(installFlags) 10738 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 10739 /* 10740 * Forward-locked apps are only in ASEC containers if they're the 10741 * new style 10742 */ 10743 isInAsec = true; 10744 } else { 10745 isInAsec = false; 10746 } 10747 10748 if (isInAsec) { 10749 return new AsecInstallArgs(codePath, instructionSets, 10750 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 10751 } else { 10752 return new FileInstallArgs(codePath, resourcePath, instructionSets); 10753 } 10754 } 10755 10756 static abstract class InstallArgs { 10757 /** @see InstallParams#origin */ 10758 final OriginInfo origin; 10759 /** @see InstallParams#move */ 10760 final MoveInfo move; 10761 10762 final IPackageInstallObserver2 observer; 10763 // Always refers to PackageManager flags only 10764 final int installFlags; 10765 final String installerPackageName; 10766 final String volumeUuid; 10767 final ManifestDigest manifestDigest; 10768 final UserHandle user; 10769 final String abiOverride; 10770 10771 // The list of instruction sets supported by this app. This is currently 10772 // only used during the rmdex() phase to clean up resources. We can get rid of this 10773 // if we move dex files under the common app path. 10774 /* nullable */ String[] instructionSets; 10775 10776 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10777 int installFlags, String installerPackageName, String volumeUuid, 10778 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 10779 String abiOverride) { 10780 this.origin = origin; 10781 this.move = move; 10782 this.installFlags = installFlags; 10783 this.observer = observer; 10784 this.installerPackageName = installerPackageName; 10785 this.volumeUuid = volumeUuid; 10786 this.manifestDigest = manifestDigest; 10787 this.user = user; 10788 this.instructionSets = instructionSets; 10789 this.abiOverride = abiOverride; 10790 } 10791 10792 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 10793 abstract int doPreInstall(int status); 10794 10795 /** 10796 * Rename package into final resting place. All paths on the given 10797 * scanned package should be updated to reflect the rename. 10798 */ 10799 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 10800 abstract int doPostInstall(int status, int uid); 10801 10802 /** @see PackageSettingBase#codePathString */ 10803 abstract String getCodePath(); 10804 /** @see PackageSettingBase#resourcePathString */ 10805 abstract String getResourcePath(); 10806 10807 // Need installer lock especially for dex file removal. 10808 abstract void cleanUpResourcesLI(); 10809 abstract boolean doPostDeleteLI(boolean delete); 10810 10811 /** 10812 * Called before the source arguments are copied. This is used mostly 10813 * for MoveParams when it needs to read the source file to put it in the 10814 * destination. 10815 */ 10816 int doPreCopy() { 10817 return PackageManager.INSTALL_SUCCEEDED; 10818 } 10819 10820 /** 10821 * Called after the source arguments are copied. This is used mostly for 10822 * MoveParams when it needs to read the source file to put it in the 10823 * destination. 10824 * 10825 * @return 10826 */ 10827 int doPostCopy(int uid) { 10828 return PackageManager.INSTALL_SUCCEEDED; 10829 } 10830 10831 protected boolean isFwdLocked() { 10832 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10833 } 10834 10835 protected boolean isExternalAsec() { 10836 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10837 } 10838 10839 UserHandle getUser() { 10840 return user; 10841 } 10842 } 10843 10844 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 10845 if (!allCodePaths.isEmpty()) { 10846 if (instructionSets == null) { 10847 throw new IllegalStateException("instructionSet == null"); 10848 } 10849 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 10850 for (String codePath : allCodePaths) { 10851 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 10852 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 10853 if (retCode < 0) { 10854 Slog.w(TAG, "Couldn't remove dex file for package: " 10855 + " at location " + codePath + ", retcode=" + retCode); 10856 // we don't consider this to be a failure of the core package deletion 10857 } 10858 } 10859 } 10860 } 10861 } 10862 10863 /** 10864 * Logic to handle installation of non-ASEC applications, including copying 10865 * and renaming logic. 10866 */ 10867 class FileInstallArgs extends InstallArgs { 10868 private File codeFile; 10869 private File resourceFile; 10870 10871 // Example topology: 10872 // /data/app/com.example/base.apk 10873 // /data/app/com.example/split_foo.apk 10874 // /data/app/com.example/lib/arm/libfoo.so 10875 // /data/app/com.example/lib/arm64/libfoo.so 10876 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 10877 10878 /** New install */ 10879 FileInstallArgs(InstallParams params) { 10880 super(params.origin, params.move, params.observer, params.installFlags, 10881 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10882 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10883 if (isFwdLocked()) { 10884 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 10885 } 10886 } 10887 10888 /** Existing install */ 10889 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 10890 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 10891 null); 10892 this.codeFile = (codePath != null) ? new File(codePath) : null; 10893 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 10894 } 10895 10896 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10897 if (origin.staged) { 10898 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 10899 codeFile = origin.file; 10900 resourceFile = origin.file; 10901 return PackageManager.INSTALL_SUCCEEDED; 10902 } 10903 10904 try { 10905 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 10906 codeFile = tempDir; 10907 resourceFile = tempDir; 10908 } catch (IOException e) { 10909 Slog.w(TAG, "Failed to create copy file: " + e); 10910 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10911 } 10912 10913 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 10914 @Override 10915 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 10916 if (!FileUtils.isValidExtFilename(name)) { 10917 throw new IllegalArgumentException("Invalid filename: " + name); 10918 } 10919 try { 10920 final File file = new File(codeFile, name); 10921 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 10922 O_RDWR | O_CREAT, 0644); 10923 Os.chmod(file.getAbsolutePath(), 0644); 10924 return new ParcelFileDescriptor(fd); 10925 } catch (ErrnoException e) { 10926 throw new RemoteException("Failed to open: " + e.getMessage()); 10927 } 10928 } 10929 }; 10930 10931 int ret = PackageManager.INSTALL_SUCCEEDED; 10932 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 10933 if (ret != PackageManager.INSTALL_SUCCEEDED) { 10934 Slog.e(TAG, "Failed to copy package"); 10935 return ret; 10936 } 10937 10938 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 10939 NativeLibraryHelper.Handle handle = null; 10940 try { 10941 handle = NativeLibraryHelper.Handle.create(codeFile); 10942 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 10943 abiOverride); 10944 } catch (IOException e) { 10945 Slog.e(TAG, "Copying native libraries failed", e); 10946 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10947 } finally { 10948 IoUtils.closeQuietly(handle); 10949 } 10950 10951 return ret; 10952 } 10953 10954 int doPreInstall(int status) { 10955 if (status != PackageManager.INSTALL_SUCCEEDED) { 10956 cleanUp(); 10957 } 10958 return status; 10959 } 10960 10961 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10962 if (status != PackageManager.INSTALL_SUCCEEDED) { 10963 cleanUp(); 10964 return false; 10965 } 10966 10967 final File targetDir = codeFile.getParentFile(); 10968 final File beforeCodeFile = codeFile; 10969 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 10970 10971 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 10972 try { 10973 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 10974 } catch (ErrnoException e) { 10975 Slog.w(TAG, "Failed to rename", e); 10976 return false; 10977 } 10978 10979 if (!SELinux.restoreconRecursive(afterCodeFile)) { 10980 Slog.w(TAG, "Failed to restorecon"); 10981 return false; 10982 } 10983 10984 // Reflect the rename internally 10985 codeFile = afterCodeFile; 10986 resourceFile = afterCodeFile; 10987 10988 // Reflect the rename in scanned details 10989 pkg.codePath = afterCodeFile.getAbsolutePath(); 10990 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10991 pkg.baseCodePath); 10992 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10993 pkg.splitCodePaths); 10994 10995 // Reflect the rename in app info 10996 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10997 pkg.applicationInfo.setCodePath(pkg.codePath); 10998 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10999 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11000 pkg.applicationInfo.setResourcePath(pkg.codePath); 11001 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11002 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11003 11004 return true; 11005 } 11006 11007 int doPostInstall(int status, int uid) { 11008 if (status != PackageManager.INSTALL_SUCCEEDED) { 11009 cleanUp(); 11010 } 11011 return status; 11012 } 11013 11014 @Override 11015 String getCodePath() { 11016 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11017 } 11018 11019 @Override 11020 String getResourcePath() { 11021 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11022 } 11023 11024 private boolean cleanUp() { 11025 if (codeFile == null || !codeFile.exists()) { 11026 return false; 11027 } 11028 11029 if (codeFile.isDirectory()) { 11030 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11031 } else { 11032 codeFile.delete(); 11033 } 11034 11035 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 11036 resourceFile.delete(); 11037 } 11038 11039 return true; 11040 } 11041 11042 void cleanUpResourcesLI() { 11043 // Try enumerating all code paths before deleting 11044 List<String> allCodePaths = Collections.EMPTY_LIST; 11045 if (codeFile != null && codeFile.exists()) { 11046 try { 11047 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11048 allCodePaths = pkg.getAllCodePaths(); 11049 } catch (PackageParserException e) { 11050 // Ignored; we tried our best 11051 } 11052 } 11053 11054 cleanUp(); 11055 removeDexFiles(allCodePaths, instructionSets); 11056 } 11057 11058 boolean doPostDeleteLI(boolean delete) { 11059 // XXX err, shouldn't we respect the delete flag? 11060 cleanUpResourcesLI(); 11061 return true; 11062 } 11063 } 11064 11065 private boolean isAsecExternal(String cid) { 11066 final String asecPath = PackageHelper.getSdFilesystem(cid); 11067 return !asecPath.startsWith(mAsecInternalPath); 11068 } 11069 11070 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 11071 PackageManagerException { 11072 if (copyRet < 0) { 11073 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 11074 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 11075 throw new PackageManagerException(copyRet, message); 11076 } 11077 } 11078 } 11079 11080 /** 11081 * Extract the MountService "container ID" from the full code path of an 11082 * .apk. 11083 */ 11084 static String cidFromCodePath(String fullCodePath) { 11085 int eidx = fullCodePath.lastIndexOf("/"); 11086 String subStr1 = fullCodePath.substring(0, eidx); 11087 int sidx = subStr1.lastIndexOf("/"); 11088 return subStr1.substring(sidx+1, eidx); 11089 } 11090 11091 /** 11092 * Logic to handle installation of ASEC applications, including copying and 11093 * renaming logic. 11094 */ 11095 class AsecInstallArgs extends InstallArgs { 11096 static final String RES_FILE_NAME = "pkg.apk"; 11097 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 11098 11099 String cid; 11100 String packagePath; 11101 String resourcePath; 11102 11103 /** New install */ 11104 AsecInstallArgs(InstallParams params) { 11105 super(params.origin, params.move, params.observer, params.installFlags, 11106 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11107 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 11108 } 11109 11110 /** Existing install */ 11111 AsecInstallArgs(String fullCodePath, String[] instructionSets, 11112 boolean isExternal, boolean isForwardLocked) { 11113 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 11114 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11115 instructionSets, null); 11116 // Hackily pretend we're still looking at a full code path 11117 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 11118 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 11119 } 11120 11121 // Extract cid from fullCodePath 11122 int eidx = fullCodePath.lastIndexOf("/"); 11123 String subStr1 = fullCodePath.substring(0, eidx); 11124 int sidx = subStr1.lastIndexOf("/"); 11125 cid = subStr1.substring(sidx+1, eidx); 11126 setMountPath(subStr1); 11127 } 11128 11129 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 11130 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 11131 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11132 instructionSets, null); 11133 this.cid = cid; 11134 setMountPath(PackageHelper.getSdDir(cid)); 11135 } 11136 11137 void createCopyFile() { 11138 cid = mInstallerService.allocateExternalStageCidLegacy(); 11139 } 11140 11141 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11142 if (origin.staged) { 11143 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 11144 cid = origin.cid; 11145 setMountPath(PackageHelper.getSdDir(cid)); 11146 return PackageManager.INSTALL_SUCCEEDED; 11147 } 11148 11149 if (temp) { 11150 createCopyFile(); 11151 } else { 11152 /* 11153 * Pre-emptively destroy the container since it's destroyed if 11154 * copying fails due to it existing anyway. 11155 */ 11156 PackageHelper.destroySdDir(cid); 11157 } 11158 11159 final String newMountPath = imcs.copyPackageToContainer( 11160 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 11161 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 11162 11163 if (newMountPath != null) { 11164 setMountPath(newMountPath); 11165 return PackageManager.INSTALL_SUCCEEDED; 11166 } else { 11167 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11168 } 11169 } 11170 11171 @Override 11172 String getCodePath() { 11173 return packagePath; 11174 } 11175 11176 @Override 11177 String getResourcePath() { 11178 return resourcePath; 11179 } 11180 11181 int doPreInstall(int status) { 11182 if (status != PackageManager.INSTALL_SUCCEEDED) { 11183 // Destroy container 11184 PackageHelper.destroySdDir(cid); 11185 } else { 11186 boolean mounted = PackageHelper.isContainerMounted(cid); 11187 if (!mounted) { 11188 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 11189 Process.SYSTEM_UID); 11190 if (newMountPath != null) { 11191 setMountPath(newMountPath); 11192 } else { 11193 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11194 } 11195 } 11196 } 11197 return status; 11198 } 11199 11200 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11201 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 11202 String newMountPath = null; 11203 if (PackageHelper.isContainerMounted(cid)) { 11204 // Unmount the container 11205 if (!PackageHelper.unMountSdDir(cid)) { 11206 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 11207 return false; 11208 } 11209 } 11210 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11211 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 11212 " which might be stale. Will try to clean up."); 11213 // Clean up the stale container and proceed to recreate. 11214 if (!PackageHelper.destroySdDir(newCacheId)) { 11215 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 11216 return false; 11217 } 11218 // Successfully cleaned up stale container. Try to rename again. 11219 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11220 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 11221 + " inspite of cleaning it up."); 11222 return false; 11223 } 11224 } 11225 if (!PackageHelper.isContainerMounted(newCacheId)) { 11226 Slog.w(TAG, "Mounting container " + newCacheId); 11227 newMountPath = PackageHelper.mountSdDir(newCacheId, 11228 getEncryptKey(), Process.SYSTEM_UID); 11229 } else { 11230 newMountPath = PackageHelper.getSdDir(newCacheId); 11231 } 11232 if (newMountPath == null) { 11233 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 11234 return false; 11235 } 11236 Log.i(TAG, "Succesfully renamed " + cid + 11237 " to " + newCacheId + 11238 " at new path: " + newMountPath); 11239 cid = newCacheId; 11240 11241 final File beforeCodeFile = new File(packagePath); 11242 setMountPath(newMountPath); 11243 final File afterCodeFile = new File(packagePath); 11244 11245 // Reflect the rename in scanned details 11246 pkg.codePath = afterCodeFile.getAbsolutePath(); 11247 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11248 pkg.baseCodePath); 11249 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11250 pkg.splitCodePaths); 11251 11252 // Reflect the rename in app info 11253 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11254 pkg.applicationInfo.setCodePath(pkg.codePath); 11255 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11256 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11257 pkg.applicationInfo.setResourcePath(pkg.codePath); 11258 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11259 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11260 11261 return true; 11262 } 11263 11264 private void setMountPath(String mountPath) { 11265 final File mountFile = new File(mountPath); 11266 11267 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 11268 if (monolithicFile.exists()) { 11269 packagePath = monolithicFile.getAbsolutePath(); 11270 if (isFwdLocked()) { 11271 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 11272 } else { 11273 resourcePath = packagePath; 11274 } 11275 } else { 11276 packagePath = mountFile.getAbsolutePath(); 11277 resourcePath = packagePath; 11278 } 11279 } 11280 11281 int doPostInstall(int status, int uid) { 11282 if (status != PackageManager.INSTALL_SUCCEEDED) { 11283 cleanUp(); 11284 } else { 11285 final int groupOwner; 11286 final String protectedFile; 11287 if (isFwdLocked()) { 11288 groupOwner = UserHandle.getSharedAppGid(uid); 11289 protectedFile = RES_FILE_NAME; 11290 } else { 11291 groupOwner = -1; 11292 protectedFile = null; 11293 } 11294 11295 if (uid < Process.FIRST_APPLICATION_UID 11296 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 11297 Slog.e(TAG, "Failed to finalize " + cid); 11298 PackageHelper.destroySdDir(cid); 11299 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11300 } 11301 11302 boolean mounted = PackageHelper.isContainerMounted(cid); 11303 if (!mounted) { 11304 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 11305 } 11306 } 11307 return status; 11308 } 11309 11310 private void cleanUp() { 11311 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 11312 11313 // Destroy secure container 11314 PackageHelper.destroySdDir(cid); 11315 } 11316 11317 private List<String> getAllCodePaths() { 11318 final File codeFile = new File(getCodePath()); 11319 if (codeFile != null && codeFile.exists()) { 11320 try { 11321 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11322 return pkg.getAllCodePaths(); 11323 } catch (PackageParserException e) { 11324 // Ignored; we tried our best 11325 } 11326 } 11327 return Collections.EMPTY_LIST; 11328 } 11329 11330 void cleanUpResourcesLI() { 11331 // Enumerate all code paths before deleting 11332 cleanUpResourcesLI(getAllCodePaths()); 11333 } 11334 11335 private void cleanUpResourcesLI(List<String> allCodePaths) { 11336 cleanUp(); 11337 removeDexFiles(allCodePaths, instructionSets); 11338 } 11339 11340 String getPackageName() { 11341 return getAsecPackageName(cid); 11342 } 11343 11344 boolean doPostDeleteLI(boolean delete) { 11345 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 11346 final List<String> allCodePaths = getAllCodePaths(); 11347 boolean mounted = PackageHelper.isContainerMounted(cid); 11348 if (mounted) { 11349 // Unmount first 11350 if (PackageHelper.unMountSdDir(cid)) { 11351 mounted = false; 11352 } 11353 } 11354 if (!mounted && delete) { 11355 cleanUpResourcesLI(allCodePaths); 11356 } 11357 return !mounted; 11358 } 11359 11360 @Override 11361 int doPreCopy() { 11362 if (isFwdLocked()) { 11363 if (!PackageHelper.fixSdPermissions(cid, 11364 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 11365 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11366 } 11367 } 11368 11369 return PackageManager.INSTALL_SUCCEEDED; 11370 } 11371 11372 @Override 11373 int doPostCopy(int uid) { 11374 if (isFwdLocked()) { 11375 if (uid < Process.FIRST_APPLICATION_UID 11376 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 11377 RES_FILE_NAME)) { 11378 Slog.e(TAG, "Failed to finalize " + cid); 11379 PackageHelper.destroySdDir(cid); 11380 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11381 } 11382 } 11383 11384 return PackageManager.INSTALL_SUCCEEDED; 11385 } 11386 } 11387 11388 /** 11389 * Logic to handle movement of existing installed applications. 11390 */ 11391 class MoveInstallArgs extends InstallArgs { 11392 private File codeFile; 11393 private File resourceFile; 11394 11395 /** New install */ 11396 MoveInstallArgs(InstallParams params) { 11397 super(params.origin, params.move, params.observer, params.installFlags, 11398 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11399 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 11400 } 11401 11402 int copyApk(IMediaContainerService imcs, boolean temp) { 11403 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 11404 + move.fromUuid + " to " + move.toUuid); 11405 synchronized (mInstaller) { 11406 if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName, 11407 move.dataAppName, move.appId, move.seinfo) != 0) { 11408 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11409 } 11410 } 11411 11412 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 11413 resourceFile = codeFile; 11414 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 11415 11416 return PackageManager.INSTALL_SUCCEEDED; 11417 } 11418 11419 int doPreInstall(int status) { 11420 if (status != PackageManager.INSTALL_SUCCEEDED) { 11421 cleanUp(move.toUuid); 11422 } 11423 return status; 11424 } 11425 11426 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11427 if (status != PackageManager.INSTALL_SUCCEEDED) { 11428 cleanUp(move.toUuid); 11429 return false; 11430 } 11431 11432 // Reflect the move in app info 11433 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11434 pkg.applicationInfo.setCodePath(pkg.codePath); 11435 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11436 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11437 pkg.applicationInfo.setResourcePath(pkg.codePath); 11438 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11439 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11440 11441 return true; 11442 } 11443 11444 int doPostInstall(int status, int uid) { 11445 if (status == PackageManager.INSTALL_SUCCEEDED) { 11446 cleanUp(move.fromUuid); 11447 } else { 11448 cleanUp(move.toUuid); 11449 } 11450 return status; 11451 } 11452 11453 @Override 11454 String getCodePath() { 11455 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11456 } 11457 11458 @Override 11459 String getResourcePath() { 11460 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11461 } 11462 11463 private boolean cleanUp(String volumeUuid) { 11464 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 11465 move.dataAppName); 11466 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 11467 synchronized (mInstallLock) { 11468 // Clean up both app data and code 11469 removeDataDirsLI(volumeUuid, move.packageName); 11470 if (codeFile.isDirectory()) { 11471 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11472 } else { 11473 codeFile.delete(); 11474 } 11475 } 11476 return true; 11477 } 11478 11479 void cleanUpResourcesLI() { 11480 throw new UnsupportedOperationException(); 11481 } 11482 11483 boolean doPostDeleteLI(boolean delete) { 11484 throw new UnsupportedOperationException(); 11485 } 11486 } 11487 11488 static String getAsecPackageName(String packageCid) { 11489 int idx = packageCid.lastIndexOf("-"); 11490 if (idx == -1) { 11491 return packageCid; 11492 } 11493 return packageCid.substring(0, idx); 11494 } 11495 11496 // Utility method used to create code paths based on package name and available index. 11497 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 11498 String idxStr = ""; 11499 int idx = 1; 11500 // Fall back to default value of idx=1 if prefix is not 11501 // part of oldCodePath 11502 if (oldCodePath != null) { 11503 String subStr = oldCodePath; 11504 // Drop the suffix right away 11505 if (suffix != null && subStr.endsWith(suffix)) { 11506 subStr = subStr.substring(0, subStr.length() - suffix.length()); 11507 } 11508 // If oldCodePath already contains prefix find out the 11509 // ending index to either increment or decrement. 11510 int sidx = subStr.lastIndexOf(prefix); 11511 if (sidx != -1) { 11512 subStr = subStr.substring(sidx + prefix.length()); 11513 if (subStr != null) { 11514 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 11515 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 11516 } 11517 try { 11518 idx = Integer.parseInt(subStr); 11519 if (idx <= 1) { 11520 idx++; 11521 } else { 11522 idx--; 11523 } 11524 } catch(NumberFormatException e) { 11525 } 11526 } 11527 } 11528 } 11529 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 11530 return prefix + idxStr; 11531 } 11532 11533 private File getNextCodePath(File targetDir, String packageName) { 11534 int suffix = 1; 11535 File result; 11536 do { 11537 result = new File(targetDir, packageName + "-" + suffix); 11538 suffix++; 11539 } while (result.exists()); 11540 return result; 11541 } 11542 11543 // Utility method that returns the relative package path with respect 11544 // to the installation directory. Like say for /data/data/com.test-1.apk 11545 // string com.test-1 is returned. 11546 static String deriveCodePathName(String codePath) { 11547 if (codePath == null) { 11548 return null; 11549 } 11550 final File codeFile = new File(codePath); 11551 final String name = codeFile.getName(); 11552 if (codeFile.isDirectory()) { 11553 return name; 11554 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 11555 final int lastDot = name.lastIndexOf('.'); 11556 return name.substring(0, lastDot); 11557 } else { 11558 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 11559 return null; 11560 } 11561 } 11562 11563 class PackageInstalledInfo { 11564 String name; 11565 int uid; 11566 // The set of users that originally had this package installed. 11567 int[] origUsers; 11568 // The set of users that now have this package installed. 11569 int[] newUsers; 11570 PackageParser.Package pkg; 11571 int returnCode; 11572 String returnMsg; 11573 PackageRemovedInfo removedInfo; 11574 11575 public void setError(int code, String msg) { 11576 returnCode = code; 11577 returnMsg = msg; 11578 Slog.w(TAG, msg); 11579 } 11580 11581 public void setError(String msg, PackageParserException e) { 11582 returnCode = e.error; 11583 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11584 Slog.w(TAG, msg, e); 11585 } 11586 11587 public void setError(String msg, PackageManagerException e) { 11588 returnCode = e.error; 11589 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11590 Slog.w(TAG, msg, e); 11591 } 11592 11593 // In some error cases we want to convey more info back to the observer 11594 String origPackage; 11595 String origPermission; 11596 } 11597 11598 /* 11599 * Install a non-existing package. 11600 */ 11601 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11602 UserHandle user, String installerPackageName, String volumeUuid, 11603 PackageInstalledInfo res) { 11604 // Remember this for later, in case we need to rollback this install 11605 String pkgName = pkg.packageName; 11606 11607 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 11608 final boolean dataDirExists = Environment 11609 .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists(); 11610 synchronized(mPackages) { 11611 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 11612 // A package with the same name is already installed, though 11613 // it has been renamed to an older name. The package we 11614 // are trying to install should be installed as an update to 11615 // the existing one, but that has not been requested, so bail. 11616 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11617 + " without first uninstalling package running as " 11618 + mSettings.mRenamedPackages.get(pkgName)); 11619 return; 11620 } 11621 if (mPackages.containsKey(pkgName)) { 11622 // Don't allow installation over an existing package with the same name. 11623 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11624 + " without first uninstalling."); 11625 return; 11626 } 11627 } 11628 11629 try { 11630 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 11631 System.currentTimeMillis(), user); 11632 11633 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 11634 // delete the partially installed application. the data directory will have to be 11635 // restored if it was already existing 11636 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11637 // remove package from internal structures. Note that we want deletePackageX to 11638 // delete the package data and cache directories that it created in 11639 // scanPackageLocked, unless those directories existed before we even tried to 11640 // install. 11641 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 11642 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 11643 res.removedInfo, true); 11644 } 11645 11646 } catch (PackageManagerException e) { 11647 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11648 } 11649 } 11650 11651 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 11652 // Can't rotate keys during boot or if sharedUser. 11653 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 11654 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 11655 return false; 11656 } 11657 // app is using upgradeKeySets; make sure all are valid 11658 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11659 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 11660 for (int i = 0; i < upgradeKeySets.length; i++) { 11661 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 11662 Slog.wtf(TAG, "Package " 11663 + (oldPs.name != null ? oldPs.name : "<null>") 11664 + " contains upgrade-key-set reference to unknown key-set: " 11665 + upgradeKeySets[i] 11666 + " reverting to signatures check."); 11667 return false; 11668 } 11669 } 11670 return true; 11671 } 11672 11673 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 11674 // Upgrade keysets are being used. Determine if new package has a superset of the 11675 // required keys. 11676 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 11677 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11678 for (int i = 0; i < upgradeKeySets.length; i++) { 11679 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 11680 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 11681 return true; 11682 } 11683 } 11684 return false; 11685 } 11686 11687 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11688 UserHandle user, String installerPackageName, String volumeUuid, 11689 PackageInstalledInfo res) { 11690 final PackageParser.Package oldPackage; 11691 final String pkgName = pkg.packageName; 11692 final int[] allUsers; 11693 final boolean[] perUserInstalled; 11694 final boolean weFroze; 11695 11696 // First find the old package info and check signatures 11697 synchronized(mPackages) { 11698 oldPackage = mPackages.get(pkgName); 11699 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 11700 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11701 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 11702 if(!checkUpgradeKeySetLP(ps, pkg)) { 11703 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11704 "New package not signed by keys specified by upgrade-keysets: " 11705 + pkgName); 11706 return; 11707 } 11708 } else { 11709 // default to original signature matching 11710 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 11711 != PackageManager.SIGNATURE_MATCH) { 11712 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11713 "New package has a different signature: " + pkgName); 11714 return; 11715 } 11716 } 11717 11718 // In case of rollback, remember per-user/profile install state 11719 allUsers = sUserManager.getUserIds(); 11720 perUserInstalled = new boolean[allUsers.length]; 11721 for (int i = 0; i < allUsers.length; i++) { 11722 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11723 } 11724 11725 // Mark the app as frozen to prevent launching during the upgrade 11726 // process, and then kill all running instances 11727 if (!ps.frozen) { 11728 ps.frozen = true; 11729 weFroze = true; 11730 } else { 11731 weFroze = false; 11732 } 11733 } 11734 11735 // Now that we're guarded by frozen state, kill app during upgrade 11736 killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg"); 11737 11738 try { 11739 boolean sysPkg = (isSystemApp(oldPackage)); 11740 if (sysPkg) { 11741 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11742 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11743 } else { 11744 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11745 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11746 } 11747 } finally { 11748 // Regardless of success or failure of upgrade steps above, always 11749 // unfreeze the package if we froze it 11750 if (weFroze) { 11751 unfreezePackage(pkgName); 11752 } 11753 } 11754 } 11755 11756 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 11757 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11758 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11759 String volumeUuid, PackageInstalledInfo res) { 11760 String pkgName = deletedPackage.packageName; 11761 boolean deletedPkg = true; 11762 boolean updatedSettings = false; 11763 11764 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 11765 + deletedPackage); 11766 long origUpdateTime; 11767 if (pkg.mExtras != null) { 11768 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 11769 } else { 11770 origUpdateTime = 0; 11771 } 11772 11773 // First delete the existing package while retaining the data directory 11774 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 11775 res.removedInfo, true)) { 11776 // If the existing package wasn't successfully deleted 11777 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 11778 deletedPkg = false; 11779 } else { 11780 // Successfully deleted the old package; proceed with replace. 11781 11782 // If deleted package lived in a container, give users a chance to 11783 // relinquish resources before killing. 11784 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 11785 if (DEBUG_INSTALL) { 11786 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 11787 } 11788 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 11789 final ArrayList<String> pkgList = new ArrayList<String>(1); 11790 pkgList.add(deletedPackage.applicationInfo.packageName); 11791 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 11792 } 11793 11794 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 11795 try { 11796 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 11797 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 11798 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11799 perUserInstalled, res, user); 11800 updatedSettings = true; 11801 } catch (PackageManagerException e) { 11802 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11803 } 11804 } 11805 11806 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11807 // remove package from internal structures. Note that we want deletePackageX to 11808 // delete the package data and cache directories that it created in 11809 // scanPackageLocked, unless those directories existed before we even tried to 11810 // install. 11811 if(updatedSettings) { 11812 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 11813 deletePackageLI( 11814 pkgName, null, true, allUsers, perUserInstalled, 11815 PackageManager.DELETE_KEEP_DATA, 11816 res.removedInfo, true); 11817 } 11818 // Since we failed to install the new package we need to restore the old 11819 // package that we deleted. 11820 if (deletedPkg) { 11821 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 11822 File restoreFile = new File(deletedPackage.codePath); 11823 // Parse old package 11824 boolean oldExternal = isExternal(deletedPackage); 11825 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 11826 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 11827 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11828 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 11829 try { 11830 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 11831 } catch (PackageManagerException e) { 11832 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 11833 + e.getMessage()); 11834 return; 11835 } 11836 // Restore of old package succeeded. Update permissions. 11837 // writer 11838 synchronized (mPackages) { 11839 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 11840 UPDATE_PERMISSIONS_ALL); 11841 // can downgrade to reader 11842 mSettings.writeLPr(); 11843 } 11844 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 11845 } 11846 } 11847 } 11848 11849 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 11850 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11851 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11852 String volumeUuid, PackageInstalledInfo res) { 11853 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 11854 + ", old=" + deletedPackage); 11855 boolean disabledSystem = false; 11856 boolean updatedSettings = false; 11857 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 11858 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 11859 != 0) { 11860 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11861 } 11862 String packageName = deletedPackage.packageName; 11863 if (packageName == null) { 11864 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11865 "Attempt to delete null packageName."); 11866 return; 11867 } 11868 PackageParser.Package oldPkg; 11869 PackageSetting oldPkgSetting; 11870 // reader 11871 synchronized (mPackages) { 11872 oldPkg = mPackages.get(packageName); 11873 oldPkgSetting = mSettings.mPackages.get(packageName); 11874 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 11875 (oldPkgSetting == null)) { 11876 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11877 "Couldn't find package:" + packageName + " information"); 11878 return; 11879 } 11880 } 11881 11882 res.removedInfo.uid = oldPkg.applicationInfo.uid; 11883 res.removedInfo.removedPackage = packageName; 11884 // Remove existing system package 11885 removePackageLI(oldPkgSetting, true); 11886 // writer 11887 synchronized (mPackages) { 11888 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 11889 if (!disabledSystem && deletedPackage != null) { 11890 // We didn't need to disable the .apk as a current system package, 11891 // which means we are replacing another update that is already 11892 // installed. We need to make sure to delete the older one's .apk. 11893 res.removedInfo.args = createInstallArgsForExisting(0, 11894 deletedPackage.applicationInfo.getCodePath(), 11895 deletedPackage.applicationInfo.getResourcePath(), 11896 getAppDexInstructionSets(deletedPackage.applicationInfo)); 11897 } else { 11898 res.removedInfo.args = null; 11899 } 11900 } 11901 11902 // Successfully disabled the old package. Now proceed with re-installation 11903 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 11904 11905 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11906 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 11907 11908 PackageParser.Package newPackage = null; 11909 try { 11910 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 11911 if (newPackage.mExtras != null) { 11912 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 11913 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 11914 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 11915 11916 // is the update attempting to change shared user? that isn't going to work... 11917 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 11918 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 11919 "Forbidding shared user change from " + oldPkgSetting.sharedUser 11920 + " to " + newPkgSetting.sharedUser); 11921 updatedSettings = true; 11922 } 11923 } 11924 11925 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11926 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11927 perUserInstalled, res, user); 11928 updatedSettings = true; 11929 } 11930 11931 } catch (PackageManagerException e) { 11932 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11933 } 11934 11935 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11936 // Re installation failed. Restore old information 11937 // Remove new pkg information 11938 if (newPackage != null) { 11939 removeInstalledPackageLI(newPackage, true); 11940 } 11941 // Add back the old system package 11942 try { 11943 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 11944 } catch (PackageManagerException e) { 11945 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 11946 } 11947 // Restore the old system information in Settings 11948 synchronized (mPackages) { 11949 if (disabledSystem) { 11950 mSettings.enableSystemPackageLPw(packageName); 11951 } 11952 if (updatedSettings) { 11953 mSettings.setInstallerPackageName(packageName, 11954 oldPkgSetting.installerPackageName); 11955 } 11956 mSettings.writeLPr(); 11957 } 11958 } 11959 } 11960 11961 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 11962 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 11963 UserHandle user) { 11964 String pkgName = newPackage.packageName; 11965 synchronized (mPackages) { 11966 //write settings. the installStatus will be incomplete at this stage. 11967 //note that the new package setting would have already been 11968 //added to mPackages. It hasn't been persisted yet. 11969 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 11970 mSettings.writeLPr(); 11971 } 11972 11973 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 11974 11975 synchronized (mPackages) { 11976 updatePermissionsLPw(newPackage.packageName, newPackage, 11977 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 11978 ? UPDATE_PERMISSIONS_ALL : 0)); 11979 // For system-bundled packages, we assume that installing an upgraded version 11980 // of the package implies that the user actually wants to run that new code, 11981 // so we enable the package. 11982 PackageSetting ps = mSettings.mPackages.get(pkgName); 11983 if (ps != null) { 11984 if (isSystemApp(newPackage)) { 11985 // NB: implicit assumption that system package upgrades apply to all users 11986 if (DEBUG_INSTALL) { 11987 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 11988 } 11989 if (res.origUsers != null) { 11990 for (int userHandle : res.origUsers) { 11991 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 11992 userHandle, installerPackageName); 11993 } 11994 } 11995 // Also convey the prior install/uninstall state 11996 if (allUsers != null && perUserInstalled != null) { 11997 for (int i = 0; i < allUsers.length; i++) { 11998 if (DEBUG_INSTALL) { 11999 Slog.d(TAG, " user " + allUsers[i] 12000 + " => " + perUserInstalled[i]); 12001 } 12002 ps.setInstalled(perUserInstalled[i], allUsers[i]); 12003 } 12004 // these install state changes will be persisted in the 12005 // upcoming call to mSettings.writeLPr(). 12006 } 12007 } 12008 // It's implied that when a user requests installation, they want the app to be 12009 // installed and enabled. 12010 int userId = user.getIdentifier(); 12011 if (userId != UserHandle.USER_ALL) { 12012 ps.setInstalled(true, userId); 12013 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 12014 } 12015 } 12016 res.name = pkgName; 12017 res.uid = newPackage.applicationInfo.uid; 12018 res.pkg = newPackage; 12019 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 12020 mSettings.setInstallerPackageName(pkgName, installerPackageName); 12021 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12022 //to update install status 12023 mSettings.writeLPr(); 12024 } 12025 } 12026 12027 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 12028 final int installFlags = args.installFlags; 12029 final String installerPackageName = args.installerPackageName; 12030 final String volumeUuid = args.volumeUuid; 12031 final File tmpPackageFile = new File(args.getCodePath()); 12032 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 12033 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 12034 || (args.volumeUuid != null)); 12035 boolean replace = false; 12036 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 12037 if (args.move != null) { 12038 // moving a complete application; perfom an initial scan on the new install location 12039 scanFlags |= SCAN_INITIAL; 12040 } 12041 // Result object to be returned 12042 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12043 12044 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 12045 // Retrieve PackageSettings and parse package 12046 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 12047 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 12048 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 12049 PackageParser pp = new PackageParser(); 12050 pp.setSeparateProcesses(mSeparateProcesses); 12051 pp.setDisplayMetrics(mMetrics); 12052 12053 final PackageParser.Package pkg; 12054 try { 12055 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 12056 } catch (PackageParserException e) { 12057 res.setError("Failed parse during installPackageLI", e); 12058 return; 12059 } 12060 12061 // Mark that we have an install time CPU ABI override. 12062 pkg.cpuAbiOverride = args.abiOverride; 12063 12064 String pkgName = res.name = pkg.packageName; 12065 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 12066 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 12067 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 12068 return; 12069 } 12070 } 12071 12072 try { 12073 pp.collectCertificates(pkg, parseFlags); 12074 pp.collectManifestDigest(pkg); 12075 } catch (PackageParserException e) { 12076 res.setError("Failed collect during installPackageLI", e); 12077 return; 12078 } 12079 12080 /* If the installer passed in a manifest digest, compare it now. */ 12081 if (args.manifestDigest != null) { 12082 if (DEBUG_INSTALL) { 12083 final String parsedManifest = pkg.manifestDigest == null ? "null" 12084 : pkg.manifestDigest.toString(); 12085 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 12086 + parsedManifest); 12087 } 12088 12089 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 12090 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 12091 return; 12092 } 12093 } else if (DEBUG_INSTALL) { 12094 final String parsedManifest = pkg.manifestDigest == null 12095 ? "null" : pkg.manifestDigest.toString(); 12096 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 12097 } 12098 12099 // Get rid of all references to package scan path via parser. 12100 pp = null; 12101 String oldCodePath = null; 12102 boolean systemApp = false; 12103 synchronized (mPackages) { 12104 // Check if installing already existing package 12105 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12106 String oldName = mSettings.mRenamedPackages.get(pkgName); 12107 if (pkg.mOriginalPackages != null 12108 && pkg.mOriginalPackages.contains(oldName) 12109 && mPackages.containsKey(oldName)) { 12110 // This package is derived from an original package, 12111 // and this device has been updating from that original 12112 // name. We must continue using the original name, so 12113 // rename the new package here. 12114 pkg.setPackageName(oldName); 12115 pkgName = pkg.packageName; 12116 replace = true; 12117 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 12118 + oldName + " pkgName=" + pkgName); 12119 } else if (mPackages.containsKey(pkgName)) { 12120 // This package, under its official name, already exists 12121 // on the device; we should replace it. 12122 replace = true; 12123 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 12124 } 12125 12126 // Prevent apps opting out from runtime permissions 12127 if (replace) { 12128 PackageParser.Package oldPackage = mPackages.get(pkgName); 12129 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 12130 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 12131 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 12132 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 12133 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 12134 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 12135 + " doesn't support runtime permissions but the old" 12136 + " target SDK " + oldTargetSdk + " does."); 12137 return; 12138 } 12139 } 12140 } 12141 12142 PackageSetting ps = mSettings.mPackages.get(pkgName); 12143 if (ps != null) { 12144 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 12145 12146 // Quick sanity check that we're signed correctly if updating; 12147 // we'll check this again later when scanning, but we want to 12148 // bail early here before tripping over redefined permissions. 12149 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12150 if (!checkUpgradeKeySetLP(ps, pkg)) { 12151 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 12152 + pkg.packageName + " upgrade keys do not match the " 12153 + "previously installed version"); 12154 return; 12155 } 12156 } else { 12157 try { 12158 verifySignaturesLP(ps, pkg); 12159 } catch (PackageManagerException e) { 12160 res.setError(e.error, e.getMessage()); 12161 return; 12162 } 12163 } 12164 12165 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 12166 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 12167 systemApp = (ps.pkg.applicationInfo.flags & 12168 ApplicationInfo.FLAG_SYSTEM) != 0; 12169 } 12170 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12171 } 12172 12173 // Check whether the newly-scanned package wants to define an already-defined perm 12174 int N = pkg.permissions.size(); 12175 for (int i = N-1; i >= 0; i--) { 12176 PackageParser.Permission perm = pkg.permissions.get(i); 12177 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 12178 if (bp != null) { 12179 // If the defining package is signed with our cert, it's okay. This 12180 // also includes the "updating the same package" case, of course. 12181 // "updating same package" could also involve key-rotation. 12182 final boolean sigsOk; 12183 if (bp.sourcePackage.equals(pkg.packageName) 12184 && (bp.packageSetting instanceof PackageSetting) 12185 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 12186 scanFlags))) { 12187 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 12188 } else { 12189 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 12190 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 12191 } 12192 if (!sigsOk) { 12193 // If the owning package is the system itself, we log but allow 12194 // install to proceed; we fail the install on all other permission 12195 // redefinitions. 12196 if (!bp.sourcePackage.equals("android")) { 12197 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 12198 + pkg.packageName + " attempting to redeclare permission " 12199 + perm.info.name + " already owned by " + bp.sourcePackage); 12200 res.origPermission = perm.info.name; 12201 res.origPackage = bp.sourcePackage; 12202 return; 12203 } else { 12204 Slog.w(TAG, "Package " + pkg.packageName 12205 + " attempting to redeclare system permission " 12206 + perm.info.name + "; ignoring new declaration"); 12207 pkg.permissions.remove(i); 12208 } 12209 } 12210 } 12211 } 12212 12213 } 12214 12215 if (systemApp && onExternal) { 12216 // Disable updates to system apps on sdcard 12217 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 12218 "Cannot install updates to system apps on sdcard"); 12219 return; 12220 } 12221 12222 if (args.move != null) { 12223 // We did an in-place move, so dex is ready to roll 12224 scanFlags |= SCAN_NO_DEX; 12225 scanFlags |= SCAN_MOVE; 12226 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 12227 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 12228 scanFlags |= SCAN_NO_DEX; 12229 12230 try { 12231 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 12232 true /* extract libs */); 12233 } catch (PackageManagerException pme) { 12234 Slog.e(TAG, "Error deriving application ABI", pme); 12235 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 12236 return; 12237 } 12238 12239 // Run dexopt before old package gets removed, to minimize time when app is unavailable 12240 int result = mPackageDexOptimizer 12241 .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */, 12242 false /* defer */, false /* inclDependencies */); 12243 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 12244 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 12245 return; 12246 } 12247 } 12248 12249 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 12250 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 12251 return; 12252 } 12253 12254 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 12255 12256 if (replace) { 12257 replacePackageLI(pkg, parseFlags, scanFlags, args.user, 12258 installerPackageName, volumeUuid, res); 12259 } else { 12260 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 12261 args.user, installerPackageName, volumeUuid, res); 12262 } 12263 synchronized (mPackages) { 12264 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12265 if (ps != null) { 12266 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12267 } 12268 } 12269 } 12270 12271 private void startIntentFilterVerifications(int userId, boolean replacing, 12272 PackageParser.Package pkg) { 12273 if (mIntentFilterVerifierComponent == null) { 12274 Slog.w(TAG, "No IntentFilter verification will not be done as " 12275 + "there is no IntentFilterVerifier available!"); 12276 return; 12277 } 12278 12279 final int verifierUid = getPackageUid( 12280 mIntentFilterVerifierComponent.getPackageName(), 12281 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 12282 12283 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 12284 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 12285 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 12286 mHandler.sendMessage(msg); 12287 } 12288 12289 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 12290 PackageParser.Package pkg) { 12291 int size = pkg.activities.size(); 12292 if (size == 0) { 12293 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12294 "No activity, so no need to verify any IntentFilter!"); 12295 return; 12296 } 12297 12298 final boolean hasDomainURLs = hasDomainURLs(pkg); 12299 if (!hasDomainURLs) { 12300 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12301 "No domain URLs, so no need to verify any IntentFilter!"); 12302 return; 12303 } 12304 12305 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 12306 + " if any IntentFilter from the " + size 12307 + " Activities needs verification ..."); 12308 12309 int count = 0; 12310 final String packageName = pkg.packageName; 12311 12312 synchronized (mPackages) { 12313 // If this is a new install and we see that we've already run verification for this 12314 // package, we have nothing to do: it means the state was restored from backup. 12315 if (!replacing) { 12316 IntentFilterVerificationInfo ivi = 12317 mSettings.getIntentFilterVerificationLPr(packageName); 12318 if (ivi != null) { 12319 if (DEBUG_DOMAIN_VERIFICATION) { 12320 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 12321 + ivi.getStatusString()); 12322 } 12323 return; 12324 } 12325 } 12326 12327 // If any filters need to be verified, then all need to be. 12328 boolean needToVerify = false; 12329 for (PackageParser.Activity a : pkg.activities) { 12330 for (ActivityIntentInfo filter : a.intents) { 12331 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 12332 if (DEBUG_DOMAIN_VERIFICATION) { 12333 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 12334 } 12335 needToVerify = true; 12336 break; 12337 } 12338 } 12339 } 12340 12341 if (needToVerify) { 12342 final int verificationId = mIntentFilterVerificationToken++; 12343 for (PackageParser.Activity a : pkg.activities) { 12344 for (ActivityIntentInfo filter : a.intents) { 12345 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 12346 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12347 "Verification needed for IntentFilter:" + filter.toString()); 12348 mIntentFilterVerifier.addOneIntentFilterVerification( 12349 verifierUid, userId, verificationId, filter, packageName); 12350 count++; 12351 } 12352 } 12353 } 12354 } 12355 } 12356 12357 if (count > 0) { 12358 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 12359 + " IntentFilter verification" + (count > 1 ? "s" : "") 12360 + " for userId:" + userId); 12361 mIntentFilterVerifier.startVerifications(userId); 12362 } else { 12363 if (DEBUG_DOMAIN_VERIFICATION) { 12364 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 12365 } 12366 } 12367 } 12368 12369 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 12370 final ComponentName cn = filter.activity.getComponentName(); 12371 final String packageName = cn.getPackageName(); 12372 12373 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 12374 packageName); 12375 if (ivi == null) { 12376 return true; 12377 } 12378 int status = ivi.getStatus(); 12379 switch (status) { 12380 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 12381 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 12382 return true; 12383 12384 default: 12385 // Nothing to do 12386 return false; 12387 } 12388 } 12389 12390 private static boolean isMultiArch(PackageSetting ps) { 12391 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12392 } 12393 12394 private static boolean isMultiArch(ApplicationInfo info) { 12395 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12396 } 12397 12398 private static boolean isExternal(PackageParser.Package pkg) { 12399 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12400 } 12401 12402 private static boolean isExternal(PackageSetting ps) { 12403 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12404 } 12405 12406 private static boolean isExternal(ApplicationInfo info) { 12407 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12408 } 12409 12410 private static boolean isSystemApp(PackageParser.Package pkg) { 12411 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 12412 } 12413 12414 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 12415 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 12416 } 12417 12418 private static boolean hasDomainURLs(PackageParser.Package pkg) { 12419 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 12420 } 12421 12422 private static boolean isSystemApp(PackageSetting ps) { 12423 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 12424 } 12425 12426 private static boolean isUpdatedSystemApp(PackageSetting ps) { 12427 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 12428 } 12429 12430 private int packageFlagsToInstallFlags(PackageSetting ps) { 12431 int installFlags = 0; 12432 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 12433 // This existing package was an external ASEC install when we have 12434 // the external flag without a UUID 12435 installFlags |= PackageManager.INSTALL_EXTERNAL; 12436 } 12437 if (ps.isForwardLocked()) { 12438 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12439 } 12440 return installFlags; 12441 } 12442 12443 private void deleteTempPackageFiles() { 12444 final FilenameFilter filter = new FilenameFilter() { 12445 public boolean accept(File dir, String name) { 12446 return name.startsWith("vmdl") && name.endsWith(".tmp"); 12447 } 12448 }; 12449 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 12450 file.delete(); 12451 } 12452 } 12453 12454 @Override 12455 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 12456 int flags) { 12457 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 12458 flags); 12459 } 12460 12461 @Override 12462 public void deletePackage(final String packageName, 12463 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 12464 mContext.enforceCallingOrSelfPermission( 12465 android.Manifest.permission.DELETE_PACKAGES, null); 12466 Preconditions.checkNotNull(packageName); 12467 Preconditions.checkNotNull(observer); 12468 final int uid = Binder.getCallingUid(); 12469 if (UserHandle.getUserId(uid) != userId) { 12470 mContext.enforceCallingPermission( 12471 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 12472 "deletePackage for user " + userId); 12473 } 12474 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 12475 try { 12476 observer.onPackageDeleted(packageName, 12477 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 12478 } catch (RemoteException re) { 12479 } 12480 return; 12481 } 12482 12483 boolean uninstallBlocked = false; 12484 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 12485 int[] users = sUserManager.getUserIds(); 12486 for (int i = 0; i < users.length; ++i) { 12487 if (getBlockUninstallForUser(packageName, users[i])) { 12488 uninstallBlocked = true; 12489 break; 12490 } 12491 } 12492 } else { 12493 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 12494 } 12495 if (uninstallBlocked) { 12496 try { 12497 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 12498 null); 12499 } catch (RemoteException re) { 12500 } 12501 return; 12502 } 12503 12504 if (DEBUG_REMOVE) { 12505 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 12506 } 12507 // Queue up an async operation since the package deletion may take a little while. 12508 mHandler.post(new Runnable() { 12509 public void run() { 12510 mHandler.removeCallbacks(this); 12511 final int returnCode = deletePackageX(packageName, userId, flags); 12512 if (observer != null) { 12513 try { 12514 observer.onPackageDeleted(packageName, returnCode, null); 12515 } catch (RemoteException e) { 12516 Log.i(TAG, "Observer no longer exists."); 12517 } //end catch 12518 } //end if 12519 } //end run 12520 }); 12521 } 12522 12523 private boolean isPackageDeviceAdmin(String packageName, int userId) { 12524 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 12525 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 12526 try { 12527 if (dpm != null) { 12528 if (dpm.isDeviceOwner(packageName)) { 12529 return true; 12530 } 12531 int[] users; 12532 if (userId == UserHandle.USER_ALL) { 12533 users = sUserManager.getUserIds(); 12534 } else { 12535 users = new int[]{userId}; 12536 } 12537 for (int i = 0; i < users.length; ++i) { 12538 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 12539 return true; 12540 } 12541 } 12542 } 12543 } catch (RemoteException e) { 12544 } 12545 return false; 12546 } 12547 12548 /** 12549 * This method is an internal method that could be get invoked either 12550 * to delete an installed package or to clean up a failed installation. 12551 * After deleting an installed package, a broadcast is sent to notify any 12552 * listeners that the package has been installed. For cleaning up a failed 12553 * installation, the broadcast is not necessary since the package's 12554 * installation wouldn't have sent the initial broadcast either 12555 * The key steps in deleting a package are 12556 * deleting the package information in internal structures like mPackages, 12557 * deleting the packages base directories through installd 12558 * updating mSettings to reflect current status 12559 * persisting settings for later use 12560 * sending a broadcast if necessary 12561 */ 12562 private int deletePackageX(String packageName, int userId, int flags) { 12563 final PackageRemovedInfo info = new PackageRemovedInfo(); 12564 final boolean res; 12565 12566 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 12567 ? UserHandle.ALL : new UserHandle(userId); 12568 12569 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 12570 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 12571 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 12572 } 12573 12574 boolean removedForAllUsers = false; 12575 boolean systemUpdate = false; 12576 12577 // for the uninstall-updates case and restricted profiles, remember the per- 12578 // userhandle installed state 12579 int[] allUsers; 12580 boolean[] perUserInstalled; 12581 synchronized (mPackages) { 12582 PackageSetting ps = mSettings.mPackages.get(packageName); 12583 allUsers = sUserManager.getUserIds(); 12584 perUserInstalled = new boolean[allUsers.length]; 12585 for (int i = 0; i < allUsers.length; i++) { 12586 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12587 } 12588 } 12589 12590 synchronized (mInstallLock) { 12591 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 12592 res = deletePackageLI(packageName, removeForUser, 12593 true, allUsers, perUserInstalled, 12594 flags | REMOVE_CHATTY, info, true); 12595 systemUpdate = info.isRemovedPackageSystemUpdate; 12596 if (res && !systemUpdate && mPackages.get(packageName) == null) { 12597 removedForAllUsers = true; 12598 } 12599 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 12600 + " removedForAllUsers=" + removedForAllUsers); 12601 } 12602 12603 if (res) { 12604 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 12605 12606 // If the removed package was a system update, the old system package 12607 // was re-enabled; we need to broadcast this information 12608 if (systemUpdate) { 12609 Bundle extras = new Bundle(1); 12610 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 12611 ? info.removedAppId : info.uid); 12612 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12613 12614 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 12615 extras, null, null, null); 12616 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 12617 extras, null, null, null); 12618 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 12619 null, packageName, null, null); 12620 } 12621 } 12622 // Force a gc here. 12623 Runtime.getRuntime().gc(); 12624 // Delete the resources here after sending the broadcast to let 12625 // other processes clean up before deleting resources. 12626 if (info.args != null) { 12627 synchronized (mInstallLock) { 12628 info.args.doPostDeleteLI(true); 12629 } 12630 } 12631 12632 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 12633 } 12634 12635 class PackageRemovedInfo { 12636 String removedPackage; 12637 int uid = -1; 12638 int removedAppId = -1; 12639 int[] removedUsers = null; 12640 boolean isRemovedPackageSystemUpdate = false; 12641 // Clean up resources deleted packages. 12642 InstallArgs args = null; 12643 12644 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 12645 Bundle extras = new Bundle(1); 12646 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 12647 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 12648 if (replacing) { 12649 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12650 } 12651 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 12652 if (removedPackage != null) { 12653 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 12654 extras, null, null, removedUsers); 12655 if (fullRemove && !replacing) { 12656 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 12657 extras, null, null, removedUsers); 12658 } 12659 } 12660 if (removedAppId >= 0) { 12661 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 12662 removedUsers); 12663 } 12664 } 12665 } 12666 12667 /* 12668 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 12669 * flag is not set, the data directory is removed as well. 12670 * make sure this flag is set for partially installed apps. If not its meaningless to 12671 * delete a partially installed application. 12672 */ 12673 private void removePackageDataLI(PackageSetting ps, 12674 int[] allUserHandles, boolean[] perUserInstalled, 12675 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 12676 String packageName = ps.name; 12677 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 12678 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 12679 // Retrieve object to delete permissions for shared user later on 12680 final PackageSetting deletedPs; 12681 // reader 12682 synchronized (mPackages) { 12683 deletedPs = mSettings.mPackages.get(packageName); 12684 if (outInfo != null) { 12685 outInfo.removedPackage = packageName; 12686 outInfo.removedUsers = deletedPs != null 12687 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 12688 : null; 12689 } 12690 } 12691 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12692 removeDataDirsLI(ps.volumeUuid, packageName); 12693 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 12694 } 12695 // writer 12696 synchronized (mPackages) { 12697 if (deletedPs != null) { 12698 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12699 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 12700 clearDefaultBrowserIfNeeded(packageName); 12701 if (outInfo != null) { 12702 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 12703 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 12704 } 12705 updatePermissionsLPw(deletedPs.name, null, 0); 12706 if (deletedPs.sharedUser != null) { 12707 // Remove permissions associated with package. Since runtime 12708 // permissions are per user we have to kill the removed package 12709 // or packages running under the shared user of the removed 12710 // package if revoking the permissions requested only by the removed 12711 // package is successful and this causes a change in gids. 12712 for (int userId : UserManagerService.getInstance().getUserIds()) { 12713 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 12714 userId); 12715 if (userIdToKill == UserHandle.USER_ALL 12716 || userIdToKill >= UserHandle.USER_OWNER) { 12717 // If gids changed for this user, kill all affected packages. 12718 mHandler.post(new Runnable() { 12719 @Override 12720 public void run() { 12721 // This has to happen with no lock held. 12722 killSettingPackagesForUser(deletedPs, userIdToKill, 12723 KILL_APP_REASON_GIDS_CHANGED); 12724 } 12725 }); 12726 break; 12727 } 12728 } 12729 } 12730 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 12731 } 12732 // make sure to preserve per-user disabled state if this removal was just 12733 // a downgrade of a system app to the factory package 12734 if (allUserHandles != null && perUserInstalled != null) { 12735 if (DEBUG_REMOVE) { 12736 Slog.d(TAG, "Propagating install state across downgrade"); 12737 } 12738 for (int i = 0; i < allUserHandles.length; i++) { 12739 if (DEBUG_REMOVE) { 12740 Slog.d(TAG, " user " + allUserHandles[i] 12741 + " => " + perUserInstalled[i]); 12742 } 12743 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12744 } 12745 } 12746 } 12747 // can downgrade to reader 12748 if (writeSettings) { 12749 // Save settings now 12750 mSettings.writeLPr(); 12751 } 12752 } 12753 if (outInfo != null) { 12754 // A user ID was deleted here. Go through all users and remove it 12755 // from KeyStore. 12756 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 12757 } 12758 } 12759 12760 static boolean locationIsPrivileged(File path) { 12761 try { 12762 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 12763 .getCanonicalPath(); 12764 return path.getCanonicalPath().startsWith(privilegedAppDir); 12765 } catch (IOException e) { 12766 Slog.e(TAG, "Unable to access code path " + path); 12767 } 12768 return false; 12769 } 12770 12771 /* 12772 * Tries to delete system package. 12773 */ 12774 private boolean deleteSystemPackageLI(PackageSetting newPs, 12775 int[] allUserHandles, boolean[] perUserInstalled, 12776 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 12777 final boolean applyUserRestrictions 12778 = (allUserHandles != null) && (perUserInstalled != null); 12779 PackageSetting disabledPs = null; 12780 // Confirm if the system package has been updated 12781 // An updated system app can be deleted. This will also have to restore 12782 // the system pkg from system partition 12783 // reader 12784 synchronized (mPackages) { 12785 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 12786 } 12787 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 12788 + " disabledPs=" + disabledPs); 12789 if (disabledPs == null) { 12790 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 12791 return false; 12792 } else if (DEBUG_REMOVE) { 12793 Slog.d(TAG, "Deleting system pkg from data partition"); 12794 } 12795 if (DEBUG_REMOVE) { 12796 if (applyUserRestrictions) { 12797 Slog.d(TAG, "Remembering install states:"); 12798 for (int i = 0; i < allUserHandles.length; i++) { 12799 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 12800 } 12801 } 12802 } 12803 // Delete the updated package 12804 outInfo.isRemovedPackageSystemUpdate = true; 12805 if (disabledPs.versionCode < newPs.versionCode) { 12806 // Delete data for downgrades 12807 flags &= ~PackageManager.DELETE_KEEP_DATA; 12808 } else { 12809 // Preserve data by setting flag 12810 flags |= PackageManager.DELETE_KEEP_DATA; 12811 } 12812 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 12813 allUserHandles, perUserInstalled, outInfo, writeSettings); 12814 if (!ret) { 12815 return false; 12816 } 12817 // writer 12818 synchronized (mPackages) { 12819 // Reinstate the old system package 12820 mSettings.enableSystemPackageLPw(newPs.name); 12821 // Remove any native libraries from the upgraded package. 12822 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 12823 } 12824 // Install the system package 12825 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 12826 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 12827 if (locationIsPrivileged(disabledPs.codePath)) { 12828 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12829 } 12830 12831 final PackageParser.Package newPkg; 12832 try { 12833 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 12834 } catch (PackageManagerException e) { 12835 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 12836 return false; 12837 } 12838 12839 // writer 12840 synchronized (mPackages) { 12841 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 12842 12843 // Propagate the permissions state as we do want to drop on the floor 12844 // runtime permissions. The update permissions method below will take 12845 // care of removing obsolete permissions and grant install permissions. 12846 ps.getPermissionsState().copyFrom(disabledPs.getPermissionsState()); 12847 updatePermissionsLPw(newPkg.packageName, newPkg, 12848 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 12849 12850 if (applyUserRestrictions) { 12851 if (DEBUG_REMOVE) { 12852 Slog.d(TAG, "Propagating install state across reinstall"); 12853 } 12854 for (int i = 0; i < allUserHandles.length; i++) { 12855 if (DEBUG_REMOVE) { 12856 Slog.d(TAG, " user " + allUserHandles[i] 12857 + " => " + perUserInstalled[i]); 12858 } 12859 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12860 } 12861 // Regardless of writeSettings we need to ensure that this restriction 12862 // state propagation is persisted 12863 mSettings.writeAllUsersPackageRestrictionsLPr(); 12864 } 12865 // can downgrade to reader here 12866 if (writeSettings) { 12867 mSettings.writeLPr(); 12868 } 12869 } 12870 return true; 12871 } 12872 12873 private boolean deleteInstalledPackageLI(PackageSetting ps, 12874 boolean deleteCodeAndResources, int flags, 12875 int[] allUserHandles, boolean[] perUserInstalled, 12876 PackageRemovedInfo outInfo, boolean writeSettings) { 12877 if (outInfo != null) { 12878 outInfo.uid = ps.appId; 12879 } 12880 12881 // Delete package data from internal structures and also remove data if flag is set 12882 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 12883 12884 // Delete application code and resources 12885 if (deleteCodeAndResources && (outInfo != null)) { 12886 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 12887 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 12888 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 12889 } 12890 return true; 12891 } 12892 12893 @Override 12894 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 12895 int userId) { 12896 mContext.enforceCallingOrSelfPermission( 12897 android.Manifest.permission.DELETE_PACKAGES, null); 12898 synchronized (mPackages) { 12899 PackageSetting ps = mSettings.mPackages.get(packageName); 12900 if (ps == null) { 12901 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 12902 return false; 12903 } 12904 if (!ps.getInstalled(userId)) { 12905 // Can't block uninstall for an app that is not installed or enabled. 12906 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 12907 return false; 12908 } 12909 ps.setBlockUninstall(blockUninstall, userId); 12910 mSettings.writePackageRestrictionsLPr(userId); 12911 } 12912 return true; 12913 } 12914 12915 @Override 12916 public boolean getBlockUninstallForUser(String packageName, int userId) { 12917 synchronized (mPackages) { 12918 PackageSetting ps = mSettings.mPackages.get(packageName); 12919 if (ps == null) { 12920 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 12921 return false; 12922 } 12923 return ps.getBlockUninstall(userId); 12924 } 12925 } 12926 12927 /* 12928 * This method handles package deletion in general 12929 */ 12930 private boolean deletePackageLI(String packageName, UserHandle user, 12931 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 12932 int flags, PackageRemovedInfo outInfo, 12933 boolean writeSettings) { 12934 if (packageName == null) { 12935 Slog.w(TAG, "Attempt to delete null packageName."); 12936 return false; 12937 } 12938 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 12939 PackageSetting ps; 12940 boolean dataOnly = false; 12941 int removeUser = -1; 12942 int appId = -1; 12943 synchronized (mPackages) { 12944 ps = mSettings.mPackages.get(packageName); 12945 if (ps == null) { 12946 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12947 return false; 12948 } 12949 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 12950 && user.getIdentifier() != UserHandle.USER_ALL) { 12951 // The caller is asking that the package only be deleted for a single 12952 // user. To do this, we just mark its uninstalled state and delete 12953 // its data. If this is a system app, we only allow this to happen if 12954 // they have set the special DELETE_SYSTEM_APP which requests different 12955 // semantics than normal for uninstalling system apps. 12956 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 12957 ps.setUserState(user.getIdentifier(), 12958 COMPONENT_ENABLED_STATE_DEFAULT, 12959 false, //installed 12960 true, //stopped 12961 true, //notLaunched 12962 false, //hidden 12963 null, null, null, 12964 false, // blockUninstall 12965 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 12966 if (!isSystemApp(ps)) { 12967 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 12968 // Other user still have this package installed, so all 12969 // we need to do is clear this user's data and save that 12970 // it is uninstalled. 12971 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 12972 removeUser = user.getIdentifier(); 12973 appId = ps.appId; 12974 scheduleWritePackageRestrictionsLocked(removeUser); 12975 } else { 12976 // We need to set it back to 'installed' so the uninstall 12977 // broadcasts will be sent correctly. 12978 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 12979 ps.setInstalled(true, user.getIdentifier()); 12980 } 12981 } else { 12982 // This is a system app, so we assume that the 12983 // other users still have this package installed, so all 12984 // we need to do is clear this user's data and save that 12985 // it is uninstalled. 12986 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 12987 removeUser = user.getIdentifier(); 12988 appId = ps.appId; 12989 scheduleWritePackageRestrictionsLocked(removeUser); 12990 } 12991 } 12992 } 12993 12994 if (removeUser >= 0) { 12995 // From above, we determined that we are deleting this only 12996 // for a single user. Continue the work here. 12997 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 12998 if (outInfo != null) { 12999 outInfo.removedPackage = packageName; 13000 outInfo.removedAppId = appId; 13001 outInfo.removedUsers = new int[] {removeUser}; 13002 } 13003 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 13004 removeKeystoreDataIfNeeded(removeUser, appId); 13005 schedulePackageCleaning(packageName, removeUser, false); 13006 synchronized (mPackages) { 13007 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 13008 scheduleWritePackageRestrictionsLocked(removeUser); 13009 } 13010 resetUserChangesToRuntimePermissionsAndFlagsLocked(ps, removeUser); 13011 } 13012 return true; 13013 } 13014 13015 if (dataOnly) { 13016 // Delete application data first 13017 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 13018 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 13019 return true; 13020 } 13021 13022 boolean ret = false; 13023 if (isSystemApp(ps)) { 13024 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 13025 // When an updated system application is deleted we delete the existing resources as well and 13026 // fall back to existing code in system partition 13027 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 13028 flags, outInfo, writeSettings); 13029 } else { 13030 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 13031 // Kill application pre-emptively especially for apps on sd. 13032 killApplication(packageName, ps.appId, "uninstall pkg"); 13033 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 13034 allUserHandles, perUserInstalled, 13035 outInfo, writeSettings); 13036 } 13037 13038 return ret; 13039 } 13040 13041 private final class ClearStorageConnection implements ServiceConnection { 13042 IMediaContainerService mContainerService; 13043 13044 @Override 13045 public void onServiceConnected(ComponentName name, IBinder service) { 13046 synchronized (this) { 13047 mContainerService = IMediaContainerService.Stub.asInterface(service); 13048 notifyAll(); 13049 } 13050 } 13051 13052 @Override 13053 public void onServiceDisconnected(ComponentName name) { 13054 } 13055 } 13056 13057 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 13058 final boolean mounted; 13059 if (Environment.isExternalStorageEmulated()) { 13060 mounted = true; 13061 } else { 13062 final String status = Environment.getExternalStorageState(); 13063 13064 mounted = status.equals(Environment.MEDIA_MOUNTED) 13065 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 13066 } 13067 13068 if (!mounted) { 13069 return; 13070 } 13071 13072 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 13073 int[] users; 13074 if (userId == UserHandle.USER_ALL) { 13075 users = sUserManager.getUserIds(); 13076 } else { 13077 users = new int[] { userId }; 13078 } 13079 final ClearStorageConnection conn = new ClearStorageConnection(); 13080 if (mContext.bindServiceAsUser( 13081 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 13082 try { 13083 for (int curUser : users) { 13084 long timeout = SystemClock.uptimeMillis() + 5000; 13085 synchronized (conn) { 13086 long now = SystemClock.uptimeMillis(); 13087 while (conn.mContainerService == null && now < timeout) { 13088 try { 13089 conn.wait(timeout - now); 13090 } catch (InterruptedException e) { 13091 } 13092 } 13093 } 13094 if (conn.mContainerService == null) { 13095 return; 13096 } 13097 13098 final UserEnvironment userEnv = new UserEnvironment(curUser); 13099 clearDirectory(conn.mContainerService, 13100 userEnv.buildExternalStorageAppCacheDirs(packageName)); 13101 if (allData) { 13102 clearDirectory(conn.mContainerService, 13103 userEnv.buildExternalStorageAppDataDirs(packageName)); 13104 clearDirectory(conn.mContainerService, 13105 userEnv.buildExternalStorageAppMediaDirs(packageName)); 13106 } 13107 } 13108 } finally { 13109 mContext.unbindService(conn); 13110 } 13111 } 13112 } 13113 13114 @Override 13115 public void clearApplicationUserData(final String packageName, 13116 final IPackageDataObserver observer, final int userId) { 13117 mContext.enforceCallingOrSelfPermission( 13118 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 13119 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 13120 // Queue up an async operation since the package deletion may take a little while. 13121 mHandler.post(new Runnable() { 13122 public void run() { 13123 mHandler.removeCallbacks(this); 13124 final boolean succeeded; 13125 synchronized (mInstallLock) { 13126 succeeded = clearApplicationUserDataLI(packageName, userId); 13127 } 13128 clearExternalStorageDataSync(packageName, userId, true); 13129 if (succeeded) { 13130 // invoke DeviceStorageMonitor's update method to clear any notifications 13131 DeviceStorageMonitorInternal 13132 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13133 if (dsm != null) { 13134 dsm.checkMemory(); 13135 } 13136 } 13137 if(observer != null) { 13138 try { 13139 observer.onRemoveCompleted(packageName, succeeded); 13140 } catch (RemoteException e) { 13141 Log.i(TAG, "Observer no longer exists."); 13142 } 13143 } //end if observer 13144 } //end run 13145 }); 13146 } 13147 13148 private boolean clearApplicationUserDataLI(String packageName, int userId) { 13149 if (packageName == null) { 13150 Slog.w(TAG, "Attempt to delete null packageName."); 13151 return false; 13152 } 13153 13154 // Try finding details about the requested package 13155 PackageParser.Package pkg; 13156 synchronized (mPackages) { 13157 pkg = mPackages.get(packageName); 13158 if (pkg == null) { 13159 final PackageSetting ps = mSettings.mPackages.get(packageName); 13160 if (ps != null) { 13161 pkg = ps.pkg; 13162 } 13163 } 13164 13165 if (pkg == null) { 13166 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13167 return false; 13168 } 13169 13170 PackageSetting ps = (PackageSetting) pkg.mExtras; 13171 resetUserChangesToRuntimePermissionsAndFlagsLocked(ps, userId); 13172 } 13173 13174 // Always delete data directories for package, even if we found no other 13175 // record of app. This helps users recover from UID mismatches without 13176 // resorting to a full data wipe. 13177 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 13178 if (retCode < 0) { 13179 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 13180 return false; 13181 } 13182 13183 final int appId = pkg.applicationInfo.uid; 13184 removeKeystoreDataIfNeeded(userId, appId); 13185 13186 // Create a native library symlink only if we have native libraries 13187 // and if the native libraries are 32 bit libraries. We do not provide 13188 // this symlink for 64 bit libraries. 13189 if (pkg.applicationInfo.primaryCpuAbi != null && 13190 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 13191 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 13192 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 13193 nativeLibPath, userId) < 0) { 13194 Slog.w(TAG, "Failed linking native library dir"); 13195 return false; 13196 } 13197 } 13198 13199 return true; 13200 } 13201 13202 /** 13203 * Reverts user permission state changes (permissions and flags). 13204 * 13205 * @param ps The package for which to reset. 13206 * @param userId The device user for which to do a reset. 13207 */ 13208 private void resetUserChangesToRuntimePermissionsAndFlagsLocked( 13209 final PackageSetting ps, final int userId) { 13210 if (ps.pkg == null) { 13211 return; 13212 } 13213 13214 final int userSettableFlags = FLAG_PERMISSION_USER_SET 13215 | FLAG_PERMISSION_USER_FIXED 13216 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 13217 13218 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 13219 | FLAG_PERMISSION_POLICY_FIXED; 13220 13221 boolean writeInstallPermissions = false; 13222 boolean writeRuntimePermissions = false; 13223 13224 final int permissionCount = ps.pkg.requestedPermissions.size(); 13225 for (int i = 0; i < permissionCount; i++) { 13226 String permission = ps.pkg.requestedPermissions.get(i); 13227 13228 BasePermission bp = mSettings.mPermissions.get(permission); 13229 if (bp == null) { 13230 continue; 13231 } 13232 13233 // If shared user we just reset the state to which only this app contributed. 13234 if (ps.sharedUser != null) { 13235 boolean used = false; 13236 final int packageCount = ps.sharedUser.packages.size(); 13237 for (int j = 0; j < packageCount; j++) { 13238 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 13239 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 13240 && pkg.pkg.requestedPermissions.contains(permission)) { 13241 used = true; 13242 break; 13243 } 13244 } 13245 if (used) { 13246 continue; 13247 } 13248 } 13249 13250 PermissionsState permissionsState = ps.getPermissionsState(); 13251 13252 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 13253 13254 // Always clear the user settable flags. 13255 final boolean hasInstallState = permissionsState.getInstallPermissionState( 13256 bp.name) != null; 13257 if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) { 13258 if (hasInstallState) { 13259 writeInstallPermissions = true; 13260 } else { 13261 writeRuntimePermissions = true; 13262 } 13263 } 13264 13265 // Below is only runtime permission handling. 13266 if (!bp.isRuntime()) { 13267 continue; 13268 } 13269 13270 // Never clobber system or policy. 13271 if ((oldFlags & policyOrSystemFlags) != 0) { 13272 continue; 13273 } 13274 13275 // If this permission was granted by default, make sure it is. 13276 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 13277 if (permissionsState.grantRuntimePermission(bp, userId) 13278 != PERMISSION_OPERATION_FAILURE) { 13279 writeRuntimePermissions = true; 13280 } 13281 } else { 13282 // Otherwise, reset the permission. 13283 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 13284 switch (revokeResult) { 13285 case PERMISSION_OPERATION_SUCCESS: { 13286 writeRuntimePermissions = true; 13287 } break; 13288 13289 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 13290 writeRuntimePermissions = true; 13291 // If gids changed for this user, kill all affected packages. 13292 mHandler.post(new Runnable() { 13293 @Override 13294 public void run() { 13295 // This has to happen with no lock held. 13296 killSettingPackagesForUser(ps, userId, 13297 KILL_APP_REASON_GIDS_CHANGED); 13298 } 13299 }); 13300 } break; 13301 } 13302 } 13303 } 13304 13305 // Synchronously write as we are taking permissions away. 13306 if (writeRuntimePermissions) { 13307 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 13308 } 13309 13310 // Synchronously write as we are taking permissions away. 13311 if (writeInstallPermissions) { 13312 mSettings.writeLPr(); 13313 } 13314 } 13315 13316 /** 13317 * Remove entries from the keystore daemon. Will only remove it if the 13318 * {@code appId} is valid. 13319 */ 13320 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 13321 if (appId < 0) { 13322 return; 13323 } 13324 13325 final KeyStore keyStore = KeyStore.getInstance(); 13326 if (keyStore != null) { 13327 if (userId == UserHandle.USER_ALL) { 13328 for (final int individual : sUserManager.getUserIds()) { 13329 keyStore.clearUid(UserHandle.getUid(individual, appId)); 13330 } 13331 } else { 13332 keyStore.clearUid(UserHandle.getUid(userId, appId)); 13333 } 13334 } else { 13335 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 13336 } 13337 } 13338 13339 @Override 13340 public void deleteApplicationCacheFiles(final String packageName, 13341 final IPackageDataObserver observer) { 13342 mContext.enforceCallingOrSelfPermission( 13343 android.Manifest.permission.DELETE_CACHE_FILES, null); 13344 // Queue up an async operation since the package deletion may take a little while. 13345 final int userId = UserHandle.getCallingUserId(); 13346 mHandler.post(new Runnable() { 13347 public void run() { 13348 mHandler.removeCallbacks(this); 13349 final boolean succeded; 13350 synchronized (mInstallLock) { 13351 succeded = deleteApplicationCacheFilesLI(packageName, userId); 13352 } 13353 clearExternalStorageDataSync(packageName, userId, false); 13354 if (observer != null) { 13355 try { 13356 observer.onRemoveCompleted(packageName, succeded); 13357 } catch (RemoteException e) { 13358 Log.i(TAG, "Observer no longer exists."); 13359 } 13360 } //end if observer 13361 } //end run 13362 }); 13363 } 13364 13365 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 13366 if (packageName == null) { 13367 Slog.w(TAG, "Attempt to delete null packageName."); 13368 return false; 13369 } 13370 PackageParser.Package p; 13371 synchronized (mPackages) { 13372 p = mPackages.get(packageName); 13373 } 13374 if (p == null) { 13375 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13376 return false; 13377 } 13378 final ApplicationInfo applicationInfo = p.applicationInfo; 13379 if (applicationInfo == null) { 13380 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13381 return false; 13382 } 13383 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 13384 if (retCode < 0) { 13385 Slog.w(TAG, "Couldn't remove cache files for package: " 13386 + packageName + " u" + userId); 13387 return false; 13388 } 13389 return true; 13390 } 13391 13392 @Override 13393 public void getPackageSizeInfo(final String packageName, int userHandle, 13394 final IPackageStatsObserver observer) { 13395 mContext.enforceCallingOrSelfPermission( 13396 android.Manifest.permission.GET_PACKAGE_SIZE, null); 13397 if (packageName == null) { 13398 throw new IllegalArgumentException("Attempt to get size of null packageName"); 13399 } 13400 13401 PackageStats stats = new PackageStats(packageName, userHandle); 13402 13403 /* 13404 * Queue up an async operation since the package measurement may take a 13405 * little while. 13406 */ 13407 Message msg = mHandler.obtainMessage(INIT_COPY); 13408 msg.obj = new MeasureParams(stats, observer); 13409 mHandler.sendMessage(msg); 13410 } 13411 13412 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 13413 PackageStats pStats) { 13414 if (packageName == null) { 13415 Slog.w(TAG, "Attempt to get size of null packageName."); 13416 return false; 13417 } 13418 PackageParser.Package p; 13419 boolean dataOnly = false; 13420 String libDirRoot = null; 13421 String asecPath = null; 13422 PackageSetting ps = null; 13423 synchronized (mPackages) { 13424 p = mPackages.get(packageName); 13425 ps = mSettings.mPackages.get(packageName); 13426 if(p == null) { 13427 dataOnly = true; 13428 if((ps == null) || (ps.pkg == null)) { 13429 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13430 return false; 13431 } 13432 p = ps.pkg; 13433 } 13434 if (ps != null) { 13435 libDirRoot = ps.legacyNativeLibraryPathString; 13436 } 13437 if (p != null && (isExternal(p) || p.isForwardLocked())) { 13438 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 13439 if (secureContainerId != null) { 13440 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 13441 } 13442 } 13443 } 13444 String publicSrcDir = null; 13445 if(!dataOnly) { 13446 final ApplicationInfo applicationInfo = p.applicationInfo; 13447 if (applicationInfo == null) { 13448 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13449 return false; 13450 } 13451 if (p.isForwardLocked()) { 13452 publicSrcDir = applicationInfo.getBaseResourcePath(); 13453 } 13454 } 13455 // TODO: extend to measure size of split APKs 13456 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 13457 // not just the first level. 13458 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 13459 // just the primary. 13460 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 13461 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath, 13462 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 13463 if (res < 0) { 13464 return false; 13465 } 13466 13467 // Fix-up for forward-locked applications in ASEC containers. 13468 if (!isExternal(p)) { 13469 pStats.codeSize += pStats.externalCodeSize; 13470 pStats.externalCodeSize = 0L; 13471 } 13472 13473 return true; 13474 } 13475 13476 13477 @Override 13478 public void addPackageToPreferred(String packageName) { 13479 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 13480 } 13481 13482 @Override 13483 public void removePackageFromPreferred(String packageName) { 13484 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 13485 } 13486 13487 @Override 13488 public List<PackageInfo> getPreferredPackages(int flags) { 13489 return new ArrayList<PackageInfo>(); 13490 } 13491 13492 private int getUidTargetSdkVersionLockedLPr(int uid) { 13493 Object obj = mSettings.getUserIdLPr(uid); 13494 if (obj instanceof SharedUserSetting) { 13495 final SharedUserSetting sus = (SharedUserSetting) obj; 13496 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 13497 final Iterator<PackageSetting> it = sus.packages.iterator(); 13498 while (it.hasNext()) { 13499 final PackageSetting ps = it.next(); 13500 if (ps.pkg != null) { 13501 int v = ps.pkg.applicationInfo.targetSdkVersion; 13502 if (v < vers) vers = v; 13503 } 13504 } 13505 return vers; 13506 } else if (obj instanceof PackageSetting) { 13507 final PackageSetting ps = (PackageSetting) obj; 13508 if (ps.pkg != null) { 13509 return ps.pkg.applicationInfo.targetSdkVersion; 13510 } 13511 } 13512 return Build.VERSION_CODES.CUR_DEVELOPMENT; 13513 } 13514 13515 @Override 13516 public void addPreferredActivity(IntentFilter filter, int match, 13517 ComponentName[] set, ComponentName activity, int userId) { 13518 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13519 "Adding preferred"); 13520 } 13521 13522 private void addPreferredActivityInternal(IntentFilter filter, int match, 13523 ComponentName[] set, ComponentName activity, boolean always, int userId, 13524 String opname) { 13525 // writer 13526 int callingUid = Binder.getCallingUid(); 13527 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 13528 if (filter.countActions() == 0) { 13529 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13530 return; 13531 } 13532 synchronized (mPackages) { 13533 if (mContext.checkCallingOrSelfPermission( 13534 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13535 != PackageManager.PERMISSION_GRANTED) { 13536 if (getUidTargetSdkVersionLockedLPr(callingUid) 13537 < Build.VERSION_CODES.FROYO) { 13538 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 13539 + callingUid); 13540 return; 13541 } 13542 mContext.enforceCallingOrSelfPermission( 13543 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13544 } 13545 13546 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 13547 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 13548 + userId + ":"); 13549 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13550 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 13551 scheduleWritePackageRestrictionsLocked(userId); 13552 } 13553 } 13554 13555 @Override 13556 public void replacePreferredActivity(IntentFilter filter, int match, 13557 ComponentName[] set, ComponentName activity, int userId) { 13558 if (filter.countActions() != 1) { 13559 throw new IllegalArgumentException( 13560 "replacePreferredActivity expects filter to have only 1 action."); 13561 } 13562 if (filter.countDataAuthorities() != 0 13563 || filter.countDataPaths() != 0 13564 || filter.countDataSchemes() > 1 13565 || filter.countDataTypes() != 0) { 13566 throw new IllegalArgumentException( 13567 "replacePreferredActivity expects filter to have no data authorities, " + 13568 "paths, or types; and at most one scheme."); 13569 } 13570 13571 final int callingUid = Binder.getCallingUid(); 13572 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 13573 synchronized (mPackages) { 13574 if (mContext.checkCallingOrSelfPermission( 13575 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13576 != PackageManager.PERMISSION_GRANTED) { 13577 if (getUidTargetSdkVersionLockedLPr(callingUid) 13578 < Build.VERSION_CODES.FROYO) { 13579 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 13580 + Binder.getCallingUid()); 13581 return; 13582 } 13583 mContext.enforceCallingOrSelfPermission( 13584 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13585 } 13586 13587 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13588 if (pir != null) { 13589 // Get all of the existing entries that exactly match this filter. 13590 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 13591 if (existing != null && existing.size() == 1) { 13592 PreferredActivity cur = existing.get(0); 13593 if (DEBUG_PREFERRED) { 13594 Slog.i(TAG, "Checking replace of preferred:"); 13595 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13596 if (!cur.mPref.mAlways) { 13597 Slog.i(TAG, " -- CUR; not mAlways!"); 13598 } else { 13599 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 13600 Slog.i(TAG, " -- CUR: mSet=" 13601 + Arrays.toString(cur.mPref.mSetComponents)); 13602 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 13603 Slog.i(TAG, " -- NEW: mMatch=" 13604 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 13605 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 13606 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 13607 } 13608 } 13609 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 13610 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 13611 && cur.mPref.sameSet(set)) { 13612 // Setting the preferred activity to what it happens to be already 13613 if (DEBUG_PREFERRED) { 13614 Slog.i(TAG, "Replacing with same preferred activity " 13615 + cur.mPref.mShortComponent + " for user " 13616 + userId + ":"); 13617 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13618 } 13619 return; 13620 } 13621 } 13622 13623 if (existing != null) { 13624 if (DEBUG_PREFERRED) { 13625 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 13626 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13627 } 13628 for (int i = 0; i < existing.size(); i++) { 13629 PreferredActivity pa = existing.get(i); 13630 if (DEBUG_PREFERRED) { 13631 Slog.i(TAG, "Removing existing preferred activity " 13632 + pa.mPref.mComponent + ":"); 13633 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 13634 } 13635 pir.removeFilter(pa); 13636 } 13637 } 13638 } 13639 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13640 "Replacing preferred"); 13641 } 13642 } 13643 13644 @Override 13645 public void clearPackagePreferredActivities(String packageName) { 13646 final int uid = Binder.getCallingUid(); 13647 // writer 13648 synchronized (mPackages) { 13649 PackageParser.Package pkg = mPackages.get(packageName); 13650 if (pkg == null || pkg.applicationInfo.uid != uid) { 13651 if (mContext.checkCallingOrSelfPermission( 13652 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13653 != PackageManager.PERMISSION_GRANTED) { 13654 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 13655 < Build.VERSION_CODES.FROYO) { 13656 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 13657 + Binder.getCallingUid()); 13658 return; 13659 } 13660 mContext.enforceCallingOrSelfPermission( 13661 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13662 } 13663 } 13664 13665 int user = UserHandle.getCallingUserId(); 13666 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 13667 scheduleWritePackageRestrictionsLocked(user); 13668 } 13669 } 13670 } 13671 13672 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13673 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 13674 ArrayList<PreferredActivity> removed = null; 13675 boolean changed = false; 13676 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13677 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 13678 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13679 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 13680 continue; 13681 } 13682 Iterator<PreferredActivity> it = pir.filterIterator(); 13683 while (it.hasNext()) { 13684 PreferredActivity pa = it.next(); 13685 // Mark entry for removal only if it matches the package name 13686 // and the entry is of type "always". 13687 if (packageName == null || 13688 (pa.mPref.mComponent.getPackageName().equals(packageName) 13689 && pa.mPref.mAlways)) { 13690 if (removed == null) { 13691 removed = new ArrayList<PreferredActivity>(); 13692 } 13693 removed.add(pa); 13694 } 13695 } 13696 if (removed != null) { 13697 for (int j=0; j<removed.size(); j++) { 13698 PreferredActivity pa = removed.get(j); 13699 pir.removeFilter(pa); 13700 } 13701 changed = true; 13702 } 13703 } 13704 return changed; 13705 } 13706 13707 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13708 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 13709 if (userId == UserHandle.USER_ALL) { 13710 if (mSettings.removeIntentFilterVerificationLPw(packageName, 13711 sUserManager.getUserIds())) { 13712 for (int oneUserId : sUserManager.getUserIds()) { 13713 scheduleWritePackageRestrictionsLocked(oneUserId); 13714 } 13715 } 13716 } else { 13717 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 13718 scheduleWritePackageRestrictionsLocked(userId); 13719 } 13720 } 13721 } 13722 13723 13724 void clearDefaultBrowserIfNeeded(String packageName) { 13725 for (int oneUserId : sUserManager.getUserIds()) { 13726 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 13727 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 13728 if (packageName.equals(defaultBrowserPackageName)) { 13729 setDefaultBrowserPackageName(null, oneUserId); 13730 } 13731 } 13732 } 13733 13734 @Override 13735 public void resetPreferredActivities(int userId) { 13736 mContext.enforceCallingOrSelfPermission( 13737 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13738 // writer 13739 synchronized (mPackages) { 13740 clearPackagePreferredActivitiesLPw(null, userId); 13741 mSettings.applyDefaultPreferredAppsLPw(this, userId); 13742 applyFactoryDefaultBrowserLPw(userId); 13743 primeDomainVerificationsLPw(userId); 13744 13745 scheduleWritePackageRestrictionsLocked(userId); 13746 } 13747 } 13748 13749 @Override 13750 public int getPreferredActivities(List<IntentFilter> outFilters, 13751 List<ComponentName> outActivities, String packageName) { 13752 13753 int num = 0; 13754 final int userId = UserHandle.getCallingUserId(); 13755 // reader 13756 synchronized (mPackages) { 13757 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13758 if (pir != null) { 13759 final Iterator<PreferredActivity> it = pir.filterIterator(); 13760 while (it.hasNext()) { 13761 final PreferredActivity pa = it.next(); 13762 if (packageName == null 13763 || (pa.mPref.mComponent.getPackageName().equals(packageName) 13764 && pa.mPref.mAlways)) { 13765 if (outFilters != null) { 13766 outFilters.add(new IntentFilter(pa)); 13767 } 13768 if (outActivities != null) { 13769 outActivities.add(pa.mPref.mComponent); 13770 } 13771 } 13772 } 13773 } 13774 } 13775 13776 return num; 13777 } 13778 13779 @Override 13780 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 13781 int userId) { 13782 int callingUid = Binder.getCallingUid(); 13783 if (callingUid != Process.SYSTEM_UID) { 13784 throw new SecurityException( 13785 "addPersistentPreferredActivity can only be run by the system"); 13786 } 13787 if (filter.countActions() == 0) { 13788 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13789 return; 13790 } 13791 synchronized (mPackages) { 13792 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 13793 " :"); 13794 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13795 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 13796 new PersistentPreferredActivity(filter, activity)); 13797 scheduleWritePackageRestrictionsLocked(userId); 13798 } 13799 } 13800 13801 @Override 13802 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 13803 int callingUid = Binder.getCallingUid(); 13804 if (callingUid != Process.SYSTEM_UID) { 13805 throw new SecurityException( 13806 "clearPackagePersistentPreferredActivities can only be run by the system"); 13807 } 13808 ArrayList<PersistentPreferredActivity> removed = null; 13809 boolean changed = false; 13810 synchronized (mPackages) { 13811 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 13812 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 13813 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 13814 .valueAt(i); 13815 if (userId != thisUserId) { 13816 continue; 13817 } 13818 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 13819 while (it.hasNext()) { 13820 PersistentPreferredActivity ppa = it.next(); 13821 // Mark entry for removal only if it matches the package name. 13822 if (ppa.mComponent.getPackageName().equals(packageName)) { 13823 if (removed == null) { 13824 removed = new ArrayList<PersistentPreferredActivity>(); 13825 } 13826 removed.add(ppa); 13827 } 13828 } 13829 if (removed != null) { 13830 for (int j=0; j<removed.size(); j++) { 13831 PersistentPreferredActivity ppa = removed.get(j); 13832 ppir.removeFilter(ppa); 13833 } 13834 changed = true; 13835 } 13836 } 13837 13838 if (changed) { 13839 scheduleWritePackageRestrictionsLocked(userId); 13840 } 13841 } 13842 } 13843 13844 /** 13845 * Common machinery for picking apart a restored XML blob and passing 13846 * it to a caller-supplied functor to be applied to the running system. 13847 */ 13848 private void restoreFromXml(XmlPullParser parser, int userId, 13849 String expectedStartTag, BlobXmlRestorer functor) 13850 throws IOException, XmlPullParserException { 13851 int type; 13852 while ((type = parser.next()) != XmlPullParser.START_TAG 13853 && type != XmlPullParser.END_DOCUMENT) { 13854 } 13855 if (type != XmlPullParser.START_TAG) { 13856 // oops didn't find a start tag?! 13857 if (DEBUG_BACKUP) { 13858 Slog.e(TAG, "Didn't find start tag during restore"); 13859 } 13860 return; 13861 } 13862 13863 // this is supposed to be TAG_PREFERRED_BACKUP 13864 if (!expectedStartTag.equals(parser.getName())) { 13865 if (DEBUG_BACKUP) { 13866 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 13867 } 13868 return; 13869 } 13870 13871 // skip interfering stuff, then we're aligned with the backing implementation 13872 while ((type = parser.next()) == XmlPullParser.TEXT) { } 13873 functor.apply(parser, userId); 13874 } 13875 13876 private interface BlobXmlRestorer { 13877 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 13878 } 13879 13880 /** 13881 * Non-Binder method, support for the backup/restore mechanism: write the 13882 * full set of preferred activities in its canonical XML format. Returns the 13883 * XML output as a byte array, or null if there is none. 13884 */ 13885 @Override 13886 public byte[] getPreferredActivityBackup(int userId) { 13887 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13888 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 13889 } 13890 13891 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13892 try { 13893 final XmlSerializer serializer = new FastXmlSerializer(); 13894 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13895 serializer.startDocument(null, true); 13896 serializer.startTag(null, TAG_PREFERRED_BACKUP); 13897 13898 synchronized (mPackages) { 13899 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 13900 } 13901 13902 serializer.endTag(null, TAG_PREFERRED_BACKUP); 13903 serializer.endDocument(); 13904 serializer.flush(); 13905 } catch (Exception e) { 13906 if (DEBUG_BACKUP) { 13907 Slog.e(TAG, "Unable to write preferred activities for backup", e); 13908 } 13909 return null; 13910 } 13911 13912 return dataStream.toByteArray(); 13913 } 13914 13915 @Override 13916 public void restorePreferredActivities(byte[] backup, int userId) { 13917 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13918 throw new SecurityException("Only the system may call restorePreferredActivities()"); 13919 } 13920 13921 try { 13922 final XmlPullParser parser = Xml.newPullParser(); 13923 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13924 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 13925 new BlobXmlRestorer() { 13926 @Override 13927 public void apply(XmlPullParser parser, int userId) 13928 throws XmlPullParserException, IOException { 13929 synchronized (mPackages) { 13930 mSettings.readPreferredActivitiesLPw(parser, userId); 13931 } 13932 } 13933 } ); 13934 } catch (Exception e) { 13935 if (DEBUG_BACKUP) { 13936 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 13937 } 13938 } 13939 } 13940 13941 /** 13942 * Non-Binder method, support for the backup/restore mechanism: write the 13943 * default browser (etc) settings in its canonical XML format. Returns the default 13944 * browser XML representation as a byte array, or null if there is none. 13945 */ 13946 @Override 13947 public byte[] getDefaultAppsBackup(int userId) { 13948 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13949 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 13950 } 13951 13952 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13953 try { 13954 final XmlSerializer serializer = new FastXmlSerializer(); 13955 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13956 serializer.startDocument(null, true); 13957 serializer.startTag(null, TAG_DEFAULT_APPS); 13958 13959 synchronized (mPackages) { 13960 mSettings.writeDefaultAppsLPr(serializer, userId); 13961 } 13962 13963 serializer.endTag(null, TAG_DEFAULT_APPS); 13964 serializer.endDocument(); 13965 serializer.flush(); 13966 } catch (Exception e) { 13967 if (DEBUG_BACKUP) { 13968 Slog.e(TAG, "Unable to write default apps for backup", e); 13969 } 13970 return null; 13971 } 13972 13973 return dataStream.toByteArray(); 13974 } 13975 13976 @Override 13977 public void restoreDefaultApps(byte[] backup, int userId) { 13978 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13979 throw new SecurityException("Only the system may call restoreDefaultApps()"); 13980 } 13981 13982 try { 13983 final XmlPullParser parser = Xml.newPullParser(); 13984 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13985 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 13986 new BlobXmlRestorer() { 13987 @Override 13988 public void apply(XmlPullParser parser, int userId) 13989 throws XmlPullParserException, IOException { 13990 synchronized (mPackages) { 13991 mSettings.readDefaultAppsLPw(parser, userId); 13992 } 13993 } 13994 } ); 13995 } catch (Exception e) { 13996 if (DEBUG_BACKUP) { 13997 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 13998 } 13999 } 14000 } 14001 14002 @Override 14003 public byte[] getIntentFilterVerificationBackup(int userId) { 14004 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14005 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 14006 } 14007 14008 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14009 try { 14010 final XmlSerializer serializer = new FastXmlSerializer(); 14011 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14012 serializer.startDocument(null, true); 14013 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 14014 14015 synchronized (mPackages) { 14016 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 14017 } 14018 14019 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 14020 serializer.endDocument(); 14021 serializer.flush(); 14022 } catch (Exception e) { 14023 if (DEBUG_BACKUP) { 14024 Slog.e(TAG, "Unable to write default apps for backup", e); 14025 } 14026 return null; 14027 } 14028 14029 return dataStream.toByteArray(); 14030 } 14031 14032 @Override 14033 public void restoreIntentFilterVerification(byte[] backup, int userId) { 14034 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14035 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14036 } 14037 14038 try { 14039 final XmlPullParser parser = Xml.newPullParser(); 14040 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14041 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 14042 new BlobXmlRestorer() { 14043 @Override 14044 public void apply(XmlPullParser parser, int userId) 14045 throws XmlPullParserException, IOException { 14046 synchronized (mPackages) { 14047 mSettings.readAllDomainVerificationsLPr(parser, userId); 14048 mSettings.writeLPr(); 14049 } 14050 } 14051 } ); 14052 } catch (Exception e) { 14053 if (DEBUG_BACKUP) { 14054 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14055 } 14056 } 14057 } 14058 14059 @Override 14060 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 14061 int sourceUserId, int targetUserId, int flags) { 14062 mContext.enforceCallingOrSelfPermission( 14063 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14064 int callingUid = Binder.getCallingUid(); 14065 enforceOwnerRights(ownerPackage, callingUid); 14066 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14067 if (intentFilter.countActions() == 0) { 14068 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 14069 return; 14070 } 14071 synchronized (mPackages) { 14072 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 14073 ownerPackage, targetUserId, flags); 14074 CrossProfileIntentResolver resolver = 14075 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14076 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 14077 // We have all those whose filter is equal. Now checking if the rest is equal as well. 14078 if (existing != null) { 14079 int size = existing.size(); 14080 for (int i = 0; i < size; i++) { 14081 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 14082 return; 14083 } 14084 } 14085 } 14086 resolver.addFilter(newFilter); 14087 scheduleWritePackageRestrictionsLocked(sourceUserId); 14088 } 14089 } 14090 14091 @Override 14092 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 14093 mContext.enforceCallingOrSelfPermission( 14094 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14095 int callingUid = Binder.getCallingUid(); 14096 enforceOwnerRights(ownerPackage, callingUid); 14097 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14098 synchronized (mPackages) { 14099 CrossProfileIntentResolver resolver = 14100 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14101 ArraySet<CrossProfileIntentFilter> set = 14102 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 14103 for (CrossProfileIntentFilter filter : set) { 14104 if (filter.getOwnerPackage().equals(ownerPackage)) { 14105 resolver.removeFilter(filter); 14106 } 14107 } 14108 scheduleWritePackageRestrictionsLocked(sourceUserId); 14109 } 14110 } 14111 14112 // Enforcing that callingUid is owning pkg on userId 14113 private void enforceOwnerRights(String pkg, int callingUid) { 14114 // The system owns everything. 14115 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 14116 return; 14117 } 14118 int callingUserId = UserHandle.getUserId(callingUid); 14119 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 14120 if (pi == null) { 14121 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 14122 + callingUserId); 14123 } 14124 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 14125 throw new SecurityException("Calling uid " + callingUid 14126 + " does not own package " + pkg); 14127 } 14128 } 14129 14130 @Override 14131 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 14132 Intent intent = new Intent(Intent.ACTION_MAIN); 14133 intent.addCategory(Intent.CATEGORY_HOME); 14134 14135 final int callingUserId = UserHandle.getCallingUserId(); 14136 List<ResolveInfo> list = queryIntentActivities(intent, null, 14137 PackageManager.GET_META_DATA, callingUserId); 14138 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 14139 true, false, false, callingUserId); 14140 14141 allHomeCandidates.clear(); 14142 if (list != null) { 14143 for (ResolveInfo ri : list) { 14144 allHomeCandidates.add(ri); 14145 } 14146 } 14147 return (preferred == null || preferred.activityInfo == null) 14148 ? null 14149 : new ComponentName(preferred.activityInfo.packageName, 14150 preferred.activityInfo.name); 14151 } 14152 14153 @Override 14154 public void setApplicationEnabledSetting(String appPackageName, 14155 int newState, int flags, int userId, String callingPackage) { 14156 if (!sUserManager.exists(userId)) return; 14157 if (callingPackage == null) { 14158 callingPackage = Integer.toString(Binder.getCallingUid()); 14159 } 14160 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 14161 } 14162 14163 @Override 14164 public void setComponentEnabledSetting(ComponentName componentName, 14165 int newState, int flags, int userId) { 14166 if (!sUserManager.exists(userId)) return; 14167 setEnabledSetting(componentName.getPackageName(), 14168 componentName.getClassName(), newState, flags, userId, null); 14169 } 14170 14171 private void setEnabledSetting(final String packageName, String className, int newState, 14172 final int flags, int userId, String callingPackage) { 14173 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 14174 || newState == COMPONENT_ENABLED_STATE_ENABLED 14175 || newState == COMPONENT_ENABLED_STATE_DISABLED 14176 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 14177 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 14178 throw new IllegalArgumentException("Invalid new component state: " 14179 + newState); 14180 } 14181 PackageSetting pkgSetting; 14182 final int uid = Binder.getCallingUid(); 14183 final int permission = mContext.checkCallingOrSelfPermission( 14184 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14185 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 14186 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14187 boolean sendNow = false; 14188 boolean isApp = (className == null); 14189 String componentName = isApp ? packageName : className; 14190 int packageUid = -1; 14191 ArrayList<String> components; 14192 14193 // writer 14194 synchronized (mPackages) { 14195 pkgSetting = mSettings.mPackages.get(packageName); 14196 if (pkgSetting == null) { 14197 if (className == null) { 14198 throw new IllegalArgumentException( 14199 "Unknown package: " + packageName); 14200 } 14201 throw new IllegalArgumentException( 14202 "Unknown component: " + packageName 14203 + "/" + className); 14204 } 14205 // Allow root and verify that userId is not being specified by a different user 14206 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 14207 throw new SecurityException( 14208 "Permission Denial: attempt to change component state from pid=" 14209 + Binder.getCallingPid() 14210 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 14211 } 14212 if (className == null) { 14213 // We're dealing with an application/package level state change 14214 if (pkgSetting.getEnabled(userId) == newState) { 14215 // Nothing to do 14216 return; 14217 } 14218 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 14219 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 14220 // Don't care about who enables an app. 14221 callingPackage = null; 14222 } 14223 pkgSetting.setEnabled(newState, userId, callingPackage); 14224 // pkgSetting.pkg.mSetEnabled = newState; 14225 } else { 14226 // We're dealing with a component level state change 14227 // First, verify that this is a valid class name. 14228 PackageParser.Package pkg = pkgSetting.pkg; 14229 if (pkg == null || !pkg.hasComponentClassName(className)) { 14230 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 14231 throw new IllegalArgumentException("Component class " + className 14232 + " does not exist in " + packageName); 14233 } else { 14234 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 14235 + className + " does not exist in " + packageName); 14236 } 14237 } 14238 switch (newState) { 14239 case COMPONENT_ENABLED_STATE_ENABLED: 14240 if (!pkgSetting.enableComponentLPw(className, userId)) { 14241 return; 14242 } 14243 break; 14244 case COMPONENT_ENABLED_STATE_DISABLED: 14245 if (!pkgSetting.disableComponentLPw(className, userId)) { 14246 return; 14247 } 14248 break; 14249 case COMPONENT_ENABLED_STATE_DEFAULT: 14250 if (!pkgSetting.restoreComponentLPw(className, userId)) { 14251 return; 14252 } 14253 break; 14254 default: 14255 Slog.e(TAG, "Invalid new component state: " + newState); 14256 return; 14257 } 14258 } 14259 scheduleWritePackageRestrictionsLocked(userId); 14260 components = mPendingBroadcasts.get(userId, packageName); 14261 final boolean newPackage = components == null; 14262 if (newPackage) { 14263 components = new ArrayList<String>(); 14264 } 14265 if (!components.contains(componentName)) { 14266 components.add(componentName); 14267 } 14268 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 14269 sendNow = true; 14270 // Purge entry from pending broadcast list if another one exists already 14271 // since we are sending one right away. 14272 mPendingBroadcasts.remove(userId, packageName); 14273 } else { 14274 if (newPackage) { 14275 mPendingBroadcasts.put(userId, packageName, components); 14276 } 14277 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 14278 // Schedule a message 14279 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 14280 } 14281 } 14282 } 14283 14284 long callingId = Binder.clearCallingIdentity(); 14285 try { 14286 if (sendNow) { 14287 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 14288 sendPackageChangedBroadcast(packageName, 14289 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 14290 } 14291 } finally { 14292 Binder.restoreCallingIdentity(callingId); 14293 } 14294 } 14295 14296 private void sendPackageChangedBroadcast(String packageName, 14297 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 14298 if (DEBUG_INSTALL) 14299 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 14300 + componentNames); 14301 Bundle extras = new Bundle(4); 14302 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 14303 String nameList[] = new String[componentNames.size()]; 14304 componentNames.toArray(nameList); 14305 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 14306 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 14307 extras.putInt(Intent.EXTRA_UID, packageUid); 14308 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 14309 new int[] {UserHandle.getUserId(packageUid)}); 14310 } 14311 14312 @Override 14313 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 14314 if (!sUserManager.exists(userId)) return; 14315 final int uid = Binder.getCallingUid(); 14316 final int permission = mContext.checkCallingOrSelfPermission( 14317 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14318 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14319 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 14320 // writer 14321 synchronized (mPackages) { 14322 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 14323 allowedByPermission, uid, userId)) { 14324 scheduleWritePackageRestrictionsLocked(userId); 14325 } 14326 } 14327 } 14328 14329 @Override 14330 public String getInstallerPackageName(String packageName) { 14331 // reader 14332 synchronized (mPackages) { 14333 return mSettings.getInstallerPackageNameLPr(packageName); 14334 } 14335 } 14336 14337 @Override 14338 public int getApplicationEnabledSetting(String packageName, int userId) { 14339 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14340 int uid = Binder.getCallingUid(); 14341 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 14342 // reader 14343 synchronized (mPackages) { 14344 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 14345 } 14346 } 14347 14348 @Override 14349 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 14350 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14351 int uid = Binder.getCallingUid(); 14352 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 14353 // reader 14354 synchronized (mPackages) { 14355 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 14356 } 14357 } 14358 14359 @Override 14360 public void enterSafeMode() { 14361 enforceSystemOrRoot("Only the system can request entering safe mode"); 14362 14363 if (!mSystemReady) { 14364 mSafeMode = true; 14365 } 14366 } 14367 14368 @Override 14369 public void systemReady() { 14370 mSystemReady = true; 14371 14372 // Read the compatibilty setting when the system is ready. 14373 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 14374 mContext.getContentResolver(), 14375 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 14376 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 14377 if (DEBUG_SETTINGS) { 14378 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 14379 } 14380 14381 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 14382 14383 synchronized (mPackages) { 14384 // Verify that all of the preferred activity components actually 14385 // exist. It is possible for applications to be updated and at 14386 // that point remove a previously declared activity component that 14387 // had been set as a preferred activity. We try to clean this up 14388 // the next time we encounter that preferred activity, but it is 14389 // possible for the user flow to never be able to return to that 14390 // situation so here we do a sanity check to make sure we haven't 14391 // left any junk around. 14392 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 14393 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14394 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14395 removed.clear(); 14396 for (PreferredActivity pa : pir.filterSet()) { 14397 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 14398 removed.add(pa); 14399 } 14400 } 14401 if (removed.size() > 0) { 14402 for (int r=0; r<removed.size(); r++) { 14403 PreferredActivity pa = removed.get(r); 14404 Slog.w(TAG, "Removing dangling preferred activity: " 14405 + pa.mPref.mComponent); 14406 pir.removeFilter(pa); 14407 } 14408 mSettings.writePackageRestrictionsLPr( 14409 mSettings.mPreferredActivities.keyAt(i)); 14410 } 14411 } 14412 14413 for (int userId : UserManagerService.getInstance().getUserIds()) { 14414 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 14415 grantPermissionsUserIds = ArrayUtils.appendInt( 14416 grantPermissionsUserIds, userId); 14417 } 14418 } 14419 } 14420 sUserManager.systemReady(); 14421 14422 // If we upgraded grant all default permissions before kicking off. 14423 for (int userId : grantPermissionsUserIds) { 14424 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 14425 } 14426 14427 // Kick off any messages waiting for system ready 14428 if (mPostSystemReadyMessages != null) { 14429 for (Message msg : mPostSystemReadyMessages) { 14430 msg.sendToTarget(); 14431 } 14432 mPostSystemReadyMessages = null; 14433 } 14434 14435 // Watch for external volumes that come and go over time 14436 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14437 storage.registerListener(mStorageListener); 14438 14439 mInstallerService.systemReady(); 14440 mPackageDexOptimizer.systemReady(); 14441 } 14442 14443 @Override 14444 public boolean isSafeMode() { 14445 return mSafeMode; 14446 } 14447 14448 @Override 14449 public boolean hasSystemUidErrors() { 14450 return mHasSystemUidErrors; 14451 } 14452 14453 static String arrayToString(int[] array) { 14454 StringBuffer buf = new StringBuffer(128); 14455 buf.append('['); 14456 if (array != null) { 14457 for (int i=0; i<array.length; i++) { 14458 if (i > 0) buf.append(", "); 14459 buf.append(array[i]); 14460 } 14461 } 14462 buf.append(']'); 14463 return buf.toString(); 14464 } 14465 14466 static class DumpState { 14467 public static final int DUMP_LIBS = 1 << 0; 14468 public static final int DUMP_FEATURES = 1 << 1; 14469 public static final int DUMP_RESOLVERS = 1 << 2; 14470 public static final int DUMP_PERMISSIONS = 1 << 3; 14471 public static final int DUMP_PACKAGES = 1 << 4; 14472 public static final int DUMP_SHARED_USERS = 1 << 5; 14473 public static final int DUMP_MESSAGES = 1 << 6; 14474 public static final int DUMP_PROVIDERS = 1 << 7; 14475 public static final int DUMP_VERIFIERS = 1 << 8; 14476 public static final int DUMP_PREFERRED = 1 << 9; 14477 public static final int DUMP_PREFERRED_XML = 1 << 10; 14478 public static final int DUMP_KEYSETS = 1 << 11; 14479 public static final int DUMP_VERSION = 1 << 12; 14480 public static final int DUMP_INSTALLS = 1 << 13; 14481 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 14482 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 14483 14484 public static final int OPTION_SHOW_FILTERS = 1 << 0; 14485 14486 private int mTypes; 14487 14488 private int mOptions; 14489 14490 private boolean mTitlePrinted; 14491 14492 private SharedUserSetting mSharedUser; 14493 14494 public boolean isDumping(int type) { 14495 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 14496 return true; 14497 } 14498 14499 return (mTypes & type) != 0; 14500 } 14501 14502 public void setDump(int type) { 14503 mTypes |= type; 14504 } 14505 14506 public boolean isOptionEnabled(int option) { 14507 return (mOptions & option) != 0; 14508 } 14509 14510 public void setOptionEnabled(int option) { 14511 mOptions |= option; 14512 } 14513 14514 public boolean onTitlePrinted() { 14515 final boolean printed = mTitlePrinted; 14516 mTitlePrinted = true; 14517 return printed; 14518 } 14519 14520 public boolean getTitlePrinted() { 14521 return mTitlePrinted; 14522 } 14523 14524 public void setTitlePrinted(boolean enabled) { 14525 mTitlePrinted = enabled; 14526 } 14527 14528 public SharedUserSetting getSharedUser() { 14529 return mSharedUser; 14530 } 14531 14532 public void setSharedUser(SharedUserSetting user) { 14533 mSharedUser = user; 14534 } 14535 } 14536 14537 @Override 14538 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 14539 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 14540 != PackageManager.PERMISSION_GRANTED) { 14541 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 14542 + Binder.getCallingPid() 14543 + ", uid=" + Binder.getCallingUid() 14544 + " without permission " 14545 + android.Manifest.permission.DUMP); 14546 return; 14547 } 14548 14549 DumpState dumpState = new DumpState(); 14550 boolean fullPreferred = false; 14551 boolean checkin = false; 14552 14553 String packageName = null; 14554 ArraySet<String> permissionNames = null; 14555 14556 int opti = 0; 14557 while (opti < args.length) { 14558 String opt = args[opti]; 14559 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 14560 break; 14561 } 14562 opti++; 14563 14564 if ("-a".equals(opt)) { 14565 // Right now we only know how to print all. 14566 } else if ("-h".equals(opt)) { 14567 pw.println("Package manager dump options:"); 14568 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 14569 pw.println(" --checkin: dump for a checkin"); 14570 pw.println(" -f: print details of intent filters"); 14571 pw.println(" -h: print this help"); 14572 pw.println(" cmd may be one of:"); 14573 pw.println(" l[ibraries]: list known shared libraries"); 14574 pw.println(" f[ibraries]: list device features"); 14575 pw.println(" k[eysets]: print known keysets"); 14576 pw.println(" r[esolvers]: dump intent resolvers"); 14577 pw.println(" perm[issions]: dump permissions"); 14578 pw.println(" permission [name ...]: dump declaration and use of given permission"); 14579 pw.println(" pref[erred]: print preferred package settings"); 14580 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 14581 pw.println(" prov[iders]: dump content providers"); 14582 pw.println(" p[ackages]: dump installed packages"); 14583 pw.println(" s[hared-users]: dump shared user IDs"); 14584 pw.println(" m[essages]: print collected runtime messages"); 14585 pw.println(" v[erifiers]: print package verifier info"); 14586 pw.println(" version: print database version info"); 14587 pw.println(" write: write current settings now"); 14588 pw.println(" <package.name>: info about given package"); 14589 pw.println(" installs: details about install sessions"); 14590 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 14591 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 14592 return; 14593 } else if ("--checkin".equals(opt)) { 14594 checkin = true; 14595 } else if ("-f".equals(opt)) { 14596 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14597 } else { 14598 pw.println("Unknown argument: " + opt + "; use -h for help"); 14599 } 14600 } 14601 14602 // Is the caller requesting to dump a particular piece of data? 14603 if (opti < args.length) { 14604 String cmd = args[opti]; 14605 opti++; 14606 // Is this a package name? 14607 if ("android".equals(cmd) || cmd.contains(".")) { 14608 packageName = cmd; 14609 // When dumping a single package, we always dump all of its 14610 // filter information since the amount of data will be reasonable. 14611 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14612 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 14613 dumpState.setDump(DumpState.DUMP_LIBS); 14614 } else if ("f".equals(cmd) || "features".equals(cmd)) { 14615 dumpState.setDump(DumpState.DUMP_FEATURES); 14616 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 14617 dumpState.setDump(DumpState.DUMP_RESOLVERS); 14618 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 14619 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 14620 } else if ("permission".equals(cmd)) { 14621 if (opti >= args.length) { 14622 pw.println("Error: permission requires permission name"); 14623 return; 14624 } 14625 permissionNames = new ArraySet<>(); 14626 while (opti < args.length) { 14627 permissionNames.add(args[opti]); 14628 opti++; 14629 } 14630 dumpState.setDump(DumpState.DUMP_PERMISSIONS 14631 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 14632 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 14633 dumpState.setDump(DumpState.DUMP_PREFERRED); 14634 } else if ("preferred-xml".equals(cmd)) { 14635 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 14636 if (opti < args.length && "--full".equals(args[opti])) { 14637 fullPreferred = true; 14638 opti++; 14639 } 14640 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 14641 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 14642 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 14643 dumpState.setDump(DumpState.DUMP_PACKAGES); 14644 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 14645 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 14646 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 14647 dumpState.setDump(DumpState.DUMP_PROVIDERS); 14648 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 14649 dumpState.setDump(DumpState.DUMP_MESSAGES); 14650 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 14651 dumpState.setDump(DumpState.DUMP_VERIFIERS); 14652 } else if ("i".equals(cmd) || "ifv".equals(cmd) 14653 || "intent-filter-verifiers".equals(cmd)) { 14654 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 14655 } else if ("version".equals(cmd)) { 14656 dumpState.setDump(DumpState.DUMP_VERSION); 14657 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 14658 dumpState.setDump(DumpState.DUMP_KEYSETS); 14659 } else if ("installs".equals(cmd)) { 14660 dumpState.setDump(DumpState.DUMP_INSTALLS); 14661 } else if ("write".equals(cmd)) { 14662 synchronized (mPackages) { 14663 mSettings.writeLPr(); 14664 pw.println("Settings written."); 14665 return; 14666 } 14667 } 14668 } 14669 14670 if (checkin) { 14671 pw.println("vers,1"); 14672 } 14673 14674 // reader 14675 synchronized (mPackages) { 14676 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 14677 if (!checkin) { 14678 if (dumpState.onTitlePrinted()) 14679 pw.println(); 14680 pw.println("Database versions:"); 14681 pw.print(" SDK Version:"); 14682 pw.print(" internal="); 14683 pw.print(mSettings.mInternalSdkPlatform); 14684 pw.print(" external="); 14685 pw.println(mSettings.mExternalSdkPlatform); 14686 pw.print(" DB Version:"); 14687 pw.print(" internal="); 14688 pw.print(mSettings.mInternalDatabaseVersion); 14689 pw.print(" external="); 14690 pw.println(mSettings.mExternalDatabaseVersion); 14691 } 14692 } 14693 14694 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 14695 if (!checkin) { 14696 if (dumpState.onTitlePrinted()) 14697 pw.println(); 14698 pw.println("Verifiers:"); 14699 pw.print(" Required: "); 14700 pw.print(mRequiredVerifierPackage); 14701 pw.print(" (uid="); 14702 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 14703 pw.println(")"); 14704 } else if (mRequiredVerifierPackage != null) { 14705 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 14706 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 14707 } 14708 } 14709 14710 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 14711 packageName == null) { 14712 if (mIntentFilterVerifierComponent != null) { 14713 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 14714 if (!checkin) { 14715 if (dumpState.onTitlePrinted()) 14716 pw.println(); 14717 pw.println("Intent Filter Verifier:"); 14718 pw.print(" Using: "); 14719 pw.print(verifierPackageName); 14720 pw.print(" (uid="); 14721 pw.print(getPackageUid(verifierPackageName, 0)); 14722 pw.println(")"); 14723 } else if (verifierPackageName != null) { 14724 pw.print("ifv,"); pw.print(verifierPackageName); 14725 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 14726 } 14727 } else { 14728 pw.println(); 14729 pw.println("No Intent Filter Verifier available!"); 14730 } 14731 } 14732 14733 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 14734 boolean printedHeader = false; 14735 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 14736 while (it.hasNext()) { 14737 String name = it.next(); 14738 SharedLibraryEntry ent = mSharedLibraries.get(name); 14739 if (!checkin) { 14740 if (!printedHeader) { 14741 if (dumpState.onTitlePrinted()) 14742 pw.println(); 14743 pw.println("Libraries:"); 14744 printedHeader = true; 14745 } 14746 pw.print(" "); 14747 } else { 14748 pw.print("lib,"); 14749 } 14750 pw.print(name); 14751 if (!checkin) { 14752 pw.print(" -> "); 14753 } 14754 if (ent.path != null) { 14755 if (!checkin) { 14756 pw.print("(jar) "); 14757 pw.print(ent.path); 14758 } else { 14759 pw.print(",jar,"); 14760 pw.print(ent.path); 14761 } 14762 } else { 14763 if (!checkin) { 14764 pw.print("(apk) "); 14765 pw.print(ent.apk); 14766 } else { 14767 pw.print(",apk,"); 14768 pw.print(ent.apk); 14769 } 14770 } 14771 pw.println(); 14772 } 14773 } 14774 14775 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 14776 if (dumpState.onTitlePrinted()) 14777 pw.println(); 14778 if (!checkin) { 14779 pw.println("Features:"); 14780 } 14781 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 14782 while (it.hasNext()) { 14783 String name = it.next(); 14784 if (!checkin) { 14785 pw.print(" "); 14786 } else { 14787 pw.print("feat,"); 14788 } 14789 pw.println(name); 14790 } 14791 } 14792 14793 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 14794 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 14795 : "Activity Resolver Table:", " ", packageName, 14796 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14797 dumpState.setTitlePrinted(true); 14798 } 14799 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 14800 : "Receiver Resolver Table:", " ", packageName, 14801 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14802 dumpState.setTitlePrinted(true); 14803 } 14804 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 14805 : "Service Resolver Table:", " ", packageName, 14806 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14807 dumpState.setTitlePrinted(true); 14808 } 14809 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 14810 : "Provider Resolver Table:", " ", packageName, 14811 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14812 dumpState.setTitlePrinted(true); 14813 } 14814 } 14815 14816 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 14817 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14818 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14819 int user = mSettings.mPreferredActivities.keyAt(i); 14820 if (pir.dump(pw, 14821 dumpState.getTitlePrinted() 14822 ? "\nPreferred Activities User " + user + ":" 14823 : "Preferred Activities User " + user + ":", " ", 14824 packageName, true, false)) { 14825 dumpState.setTitlePrinted(true); 14826 } 14827 } 14828 } 14829 14830 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 14831 pw.flush(); 14832 FileOutputStream fout = new FileOutputStream(fd); 14833 BufferedOutputStream str = new BufferedOutputStream(fout); 14834 XmlSerializer serializer = new FastXmlSerializer(); 14835 try { 14836 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 14837 serializer.startDocument(null, true); 14838 serializer.setFeature( 14839 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 14840 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 14841 serializer.endDocument(); 14842 serializer.flush(); 14843 } catch (IllegalArgumentException e) { 14844 pw.println("Failed writing: " + e); 14845 } catch (IllegalStateException e) { 14846 pw.println("Failed writing: " + e); 14847 } catch (IOException e) { 14848 pw.println("Failed writing: " + e); 14849 } 14850 } 14851 14852 if (!checkin 14853 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 14854 && packageName == null) { 14855 pw.println(); 14856 int count = mSettings.mPackages.size(); 14857 if (count == 0) { 14858 pw.println("No applications!"); 14859 pw.println(); 14860 } else { 14861 final String prefix = " "; 14862 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 14863 if (allPackageSettings.size() == 0) { 14864 pw.println("No domain preferred apps!"); 14865 pw.println(); 14866 } else { 14867 pw.println("App verification status:"); 14868 pw.println(); 14869 count = 0; 14870 for (PackageSetting ps : allPackageSettings) { 14871 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 14872 if (ivi == null || ivi.getPackageName() == null) continue; 14873 pw.println(prefix + "Package: " + ivi.getPackageName()); 14874 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 14875 pw.println(prefix + "Status: " + ivi.getStatusString()); 14876 pw.println(); 14877 count++; 14878 } 14879 if (count == 0) { 14880 pw.println(prefix + "No app verification established."); 14881 pw.println(); 14882 } 14883 for (int userId : sUserManager.getUserIds()) { 14884 pw.println("App linkages for user " + userId + ":"); 14885 pw.println(); 14886 count = 0; 14887 for (PackageSetting ps : allPackageSettings) { 14888 final int status = ps.getDomainVerificationStatusForUser(userId); 14889 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 14890 continue; 14891 } 14892 pw.println(prefix + "Package: " + ps.name); 14893 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 14894 String statusStr = IntentFilterVerificationInfo. 14895 getStatusStringFromValue(status); 14896 pw.println(prefix + "Status: " + statusStr); 14897 pw.println(); 14898 count++; 14899 } 14900 if (count == 0) { 14901 pw.println(prefix + "No configured app linkages."); 14902 pw.println(); 14903 } 14904 } 14905 } 14906 } 14907 } 14908 14909 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 14910 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 14911 if (packageName == null && permissionNames == null) { 14912 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 14913 if (iperm == 0) { 14914 if (dumpState.onTitlePrinted()) 14915 pw.println(); 14916 pw.println("AppOp Permissions:"); 14917 } 14918 pw.print(" AppOp Permission "); 14919 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 14920 pw.println(":"); 14921 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 14922 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 14923 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 14924 } 14925 } 14926 } 14927 } 14928 14929 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 14930 boolean printedSomething = false; 14931 for (PackageParser.Provider p : mProviders.mProviders.values()) { 14932 if (packageName != null && !packageName.equals(p.info.packageName)) { 14933 continue; 14934 } 14935 if (!printedSomething) { 14936 if (dumpState.onTitlePrinted()) 14937 pw.println(); 14938 pw.println("Registered ContentProviders:"); 14939 printedSomething = true; 14940 } 14941 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 14942 pw.print(" "); pw.println(p.toString()); 14943 } 14944 printedSomething = false; 14945 for (Map.Entry<String, PackageParser.Provider> entry : 14946 mProvidersByAuthority.entrySet()) { 14947 PackageParser.Provider p = entry.getValue(); 14948 if (packageName != null && !packageName.equals(p.info.packageName)) { 14949 continue; 14950 } 14951 if (!printedSomething) { 14952 if (dumpState.onTitlePrinted()) 14953 pw.println(); 14954 pw.println("ContentProvider Authorities:"); 14955 printedSomething = true; 14956 } 14957 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 14958 pw.print(" "); pw.println(p.toString()); 14959 if (p.info != null && p.info.applicationInfo != null) { 14960 final String appInfo = p.info.applicationInfo.toString(); 14961 pw.print(" applicationInfo="); pw.println(appInfo); 14962 } 14963 } 14964 } 14965 14966 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 14967 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 14968 } 14969 14970 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 14971 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 14972 } 14973 14974 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 14975 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 14976 } 14977 14978 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 14979 // XXX should handle packageName != null by dumping only install data that 14980 // the given package is involved with. 14981 if (dumpState.onTitlePrinted()) pw.println(); 14982 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 14983 } 14984 14985 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 14986 if (dumpState.onTitlePrinted()) pw.println(); 14987 mSettings.dumpReadMessagesLPr(pw, dumpState); 14988 14989 pw.println(); 14990 pw.println("Package warning messages:"); 14991 BufferedReader in = null; 14992 String line = null; 14993 try { 14994 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 14995 while ((line = in.readLine()) != null) { 14996 if (line.contains("ignored: updated version")) continue; 14997 pw.println(line); 14998 } 14999 } catch (IOException ignored) { 15000 } finally { 15001 IoUtils.closeQuietly(in); 15002 } 15003 } 15004 15005 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 15006 BufferedReader in = null; 15007 String line = null; 15008 try { 15009 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15010 while ((line = in.readLine()) != null) { 15011 if (line.contains("ignored: updated version")) continue; 15012 pw.print("msg,"); 15013 pw.println(line); 15014 } 15015 } catch (IOException ignored) { 15016 } finally { 15017 IoUtils.closeQuietly(in); 15018 } 15019 } 15020 } 15021 } 15022 15023 private String dumpDomainString(String packageName) { 15024 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName); 15025 List<IntentFilter> filters = getAllIntentFilters(packageName); 15026 15027 ArraySet<String> result = new ArraySet<>(); 15028 if (iviList.size() > 0) { 15029 for (IntentFilterVerificationInfo ivi : iviList) { 15030 for (String host : ivi.getDomains()) { 15031 result.add(host); 15032 } 15033 } 15034 } 15035 if (filters != null && filters.size() > 0) { 15036 for (IntentFilter filter : filters) { 15037 if (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 15038 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)) { 15039 result.addAll(filter.getHostsList()); 15040 } 15041 } 15042 } 15043 15044 StringBuilder sb = new StringBuilder(result.size() * 16); 15045 for (String domain : result) { 15046 if (sb.length() > 0) sb.append(" "); 15047 sb.append(domain); 15048 } 15049 return sb.toString(); 15050 } 15051 15052 // ------- apps on sdcard specific code ------- 15053 static final boolean DEBUG_SD_INSTALL = false; 15054 15055 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 15056 15057 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 15058 15059 private boolean mMediaMounted = false; 15060 15061 static String getEncryptKey() { 15062 try { 15063 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 15064 SD_ENCRYPTION_KEYSTORE_NAME); 15065 if (sdEncKey == null) { 15066 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 15067 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 15068 if (sdEncKey == null) { 15069 Slog.e(TAG, "Failed to create encryption keys"); 15070 return null; 15071 } 15072 } 15073 return sdEncKey; 15074 } catch (NoSuchAlgorithmException nsae) { 15075 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 15076 return null; 15077 } catch (IOException ioe) { 15078 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 15079 return null; 15080 } 15081 } 15082 15083 /* 15084 * Update media status on PackageManager. 15085 */ 15086 @Override 15087 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 15088 int callingUid = Binder.getCallingUid(); 15089 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 15090 throw new SecurityException("Media status can only be updated by the system"); 15091 } 15092 // reader; this apparently protects mMediaMounted, but should probably 15093 // be a different lock in that case. 15094 synchronized (mPackages) { 15095 Log.i(TAG, "Updating external media status from " 15096 + (mMediaMounted ? "mounted" : "unmounted") + " to " 15097 + (mediaStatus ? "mounted" : "unmounted")); 15098 if (DEBUG_SD_INSTALL) 15099 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 15100 + ", mMediaMounted=" + mMediaMounted); 15101 if (mediaStatus == mMediaMounted) { 15102 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 15103 : 0, -1); 15104 mHandler.sendMessage(msg); 15105 return; 15106 } 15107 mMediaMounted = mediaStatus; 15108 } 15109 // Queue up an async operation since the package installation may take a 15110 // little while. 15111 mHandler.post(new Runnable() { 15112 public void run() { 15113 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 15114 } 15115 }); 15116 } 15117 15118 /** 15119 * Called by MountService when the initial ASECs to scan are available. 15120 * Should block until all the ASEC containers are finished being scanned. 15121 */ 15122 public void scanAvailableAsecs() { 15123 updateExternalMediaStatusInner(true, false, false); 15124 if (mShouldRestoreconData) { 15125 SELinuxMMAC.setRestoreconDone(); 15126 mShouldRestoreconData = false; 15127 } 15128 } 15129 15130 /* 15131 * Collect information of applications on external media, map them against 15132 * existing containers and update information based on current mount status. 15133 * Please note that we always have to report status if reportStatus has been 15134 * set to true especially when unloading packages. 15135 */ 15136 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 15137 boolean externalStorage) { 15138 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 15139 int[] uidArr = EmptyArray.INT; 15140 15141 final String[] list = PackageHelper.getSecureContainerList(); 15142 if (ArrayUtils.isEmpty(list)) { 15143 Log.i(TAG, "No secure containers found"); 15144 } else { 15145 // Process list of secure containers and categorize them 15146 // as active or stale based on their package internal state. 15147 15148 // reader 15149 synchronized (mPackages) { 15150 for (String cid : list) { 15151 // Leave stages untouched for now; installer service owns them 15152 if (PackageInstallerService.isStageName(cid)) continue; 15153 15154 if (DEBUG_SD_INSTALL) 15155 Log.i(TAG, "Processing container " + cid); 15156 String pkgName = getAsecPackageName(cid); 15157 if (pkgName == null) { 15158 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 15159 continue; 15160 } 15161 if (DEBUG_SD_INSTALL) 15162 Log.i(TAG, "Looking for pkg : " + pkgName); 15163 15164 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15165 if (ps == null) { 15166 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 15167 continue; 15168 } 15169 15170 /* 15171 * Skip packages that are not external if we're unmounting 15172 * external storage. 15173 */ 15174 if (externalStorage && !isMounted && !isExternal(ps)) { 15175 continue; 15176 } 15177 15178 final AsecInstallArgs args = new AsecInstallArgs(cid, 15179 getAppDexInstructionSets(ps), ps.isForwardLocked()); 15180 // The package status is changed only if the code path 15181 // matches between settings and the container id. 15182 if (ps.codePathString != null 15183 && ps.codePathString.startsWith(args.getCodePath())) { 15184 if (DEBUG_SD_INSTALL) { 15185 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 15186 + " at code path: " + ps.codePathString); 15187 } 15188 15189 // We do have a valid package installed on sdcard 15190 processCids.put(args, ps.codePathString); 15191 final int uid = ps.appId; 15192 if (uid != -1) { 15193 uidArr = ArrayUtils.appendInt(uidArr, uid); 15194 } 15195 } else { 15196 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 15197 + ps.codePathString); 15198 } 15199 } 15200 } 15201 15202 Arrays.sort(uidArr); 15203 } 15204 15205 // Process packages with valid entries. 15206 if (isMounted) { 15207 if (DEBUG_SD_INSTALL) 15208 Log.i(TAG, "Loading packages"); 15209 loadMediaPackages(processCids, uidArr); 15210 startCleaningPackages(); 15211 mInstallerService.onSecureContainersAvailable(); 15212 } else { 15213 if (DEBUG_SD_INSTALL) 15214 Log.i(TAG, "Unloading packages"); 15215 unloadMediaPackages(processCids, uidArr, reportStatus); 15216 } 15217 } 15218 15219 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15220 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 15221 final int size = infos.size(); 15222 final String[] packageNames = new String[size]; 15223 final int[] packageUids = new int[size]; 15224 for (int i = 0; i < size; i++) { 15225 final ApplicationInfo info = infos.get(i); 15226 packageNames[i] = info.packageName; 15227 packageUids[i] = info.uid; 15228 } 15229 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 15230 finishedReceiver); 15231 } 15232 15233 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15234 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15235 sendResourcesChangedBroadcast(mediaStatus, replacing, 15236 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 15237 } 15238 15239 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15240 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15241 int size = pkgList.length; 15242 if (size > 0) { 15243 // Send broadcasts here 15244 Bundle extras = new Bundle(); 15245 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 15246 if (uidArr != null) { 15247 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 15248 } 15249 if (replacing) { 15250 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 15251 } 15252 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 15253 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 15254 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 15255 } 15256 } 15257 15258 /* 15259 * Look at potentially valid container ids from processCids If package 15260 * information doesn't match the one on record or package scanning fails, 15261 * the cid is added to list of removeCids. We currently don't delete stale 15262 * containers. 15263 */ 15264 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 15265 ArrayList<String> pkgList = new ArrayList<String>(); 15266 Set<AsecInstallArgs> keys = processCids.keySet(); 15267 15268 for (AsecInstallArgs args : keys) { 15269 String codePath = processCids.get(args); 15270 if (DEBUG_SD_INSTALL) 15271 Log.i(TAG, "Loading container : " + args.cid); 15272 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15273 try { 15274 // Make sure there are no container errors first. 15275 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 15276 Slog.e(TAG, "Failed to mount cid : " + args.cid 15277 + " when installing from sdcard"); 15278 continue; 15279 } 15280 // Check code path here. 15281 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 15282 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 15283 + " does not match one in settings " + codePath); 15284 continue; 15285 } 15286 // Parse package 15287 int parseFlags = mDefParseFlags; 15288 if (args.isExternalAsec()) { 15289 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 15290 } 15291 if (args.isFwdLocked()) { 15292 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 15293 } 15294 15295 synchronized (mInstallLock) { 15296 PackageParser.Package pkg = null; 15297 try { 15298 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 15299 } catch (PackageManagerException e) { 15300 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 15301 } 15302 // Scan the package 15303 if (pkg != null) { 15304 /* 15305 * TODO why is the lock being held? doPostInstall is 15306 * called in other places without the lock. This needs 15307 * to be straightened out. 15308 */ 15309 // writer 15310 synchronized (mPackages) { 15311 retCode = PackageManager.INSTALL_SUCCEEDED; 15312 pkgList.add(pkg.packageName); 15313 // Post process args 15314 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 15315 pkg.applicationInfo.uid); 15316 } 15317 } else { 15318 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 15319 } 15320 } 15321 15322 } finally { 15323 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 15324 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 15325 } 15326 } 15327 } 15328 // writer 15329 synchronized (mPackages) { 15330 // If the platform SDK has changed since the last time we booted, 15331 // we need to re-grant app permission to catch any new ones that 15332 // appear. This is really a hack, and means that apps can in some 15333 // cases get permissions that the user didn't initially explicitly 15334 // allow... it would be nice to have some better way to handle 15335 // this situation. 15336 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 15337 if (regrantPermissions) 15338 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 15339 + mSdkVersion + "; regranting permissions for external storage"); 15340 mSettings.mExternalSdkPlatform = mSdkVersion; 15341 15342 // Make sure group IDs have been assigned, and any permission 15343 // changes in other apps are accounted for 15344 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 15345 | (regrantPermissions 15346 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 15347 : 0)); 15348 15349 mSettings.updateExternalDatabaseVersion(); 15350 15351 // can downgrade to reader 15352 // Persist settings 15353 mSettings.writeLPr(); 15354 } 15355 // Send a broadcast to let everyone know we are done processing 15356 if (pkgList.size() > 0) { 15357 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 15358 } 15359 } 15360 15361 /* 15362 * Utility method to unload a list of specified containers 15363 */ 15364 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 15365 // Just unmount all valid containers. 15366 for (AsecInstallArgs arg : cidArgs) { 15367 synchronized (mInstallLock) { 15368 arg.doPostDeleteLI(false); 15369 } 15370 } 15371 } 15372 15373 /* 15374 * Unload packages mounted on external media. This involves deleting package 15375 * data from internal structures, sending broadcasts about diabled packages, 15376 * gc'ing to free up references, unmounting all secure containers 15377 * corresponding to packages on external media, and posting a 15378 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 15379 * that we always have to post this message if status has been requested no 15380 * matter what. 15381 */ 15382 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 15383 final boolean reportStatus) { 15384 if (DEBUG_SD_INSTALL) 15385 Log.i(TAG, "unloading media packages"); 15386 ArrayList<String> pkgList = new ArrayList<String>(); 15387 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 15388 final Set<AsecInstallArgs> keys = processCids.keySet(); 15389 for (AsecInstallArgs args : keys) { 15390 String pkgName = args.getPackageName(); 15391 if (DEBUG_SD_INSTALL) 15392 Log.i(TAG, "Trying to unload pkg : " + pkgName); 15393 // Delete package internally 15394 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15395 synchronized (mInstallLock) { 15396 boolean res = deletePackageLI(pkgName, null, false, null, null, 15397 PackageManager.DELETE_KEEP_DATA, outInfo, false); 15398 if (res) { 15399 pkgList.add(pkgName); 15400 } else { 15401 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 15402 failedList.add(args); 15403 } 15404 } 15405 } 15406 15407 // reader 15408 synchronized (mPackages) { 15409 // We didn't update the settings after removing each package; 15410 // write them now for all packages. 15411 mSettings.writeLPr(); 15412 } 15413 15414 // We have to absolutely send UPDATED_MEDIA_STATUS only 15415 // after confirming that all the receivers processed the ordered 15416 // broadcast when packages get disabled, force a gc to clean things up. 15417 // and unload all the containers. 15418 if (pkgList.size() > 0) { 15419 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 15420 new IIntentReceiver.Stub() { 15421 public void performReceive(Intent intent, int resultCode, String data, 15422 Bundle extras, boolean ordered, boolean sticky, 15423 int sendingUser) throws RemoteException { 15424 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 15425 reportStatus ? 1 : 0, 1, keys); 15426 mHandler.sendMessage(msg); 15427 } 15428 }); 15429 } else { 15430 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 15431 keys); 15432 mHandler.sendMessage(msg); 15433 } 15434 } 15435 15436 private void loadPrivatePackages(VolumeInfo vol) { 15437 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 15438 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 15439 synchronized (mInstallLock) { 15440 synchronized (mPackages) { 15441 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15442 for (PackageSetting ps : packages) { 15443 final PackageParser.Package pkg; 15444 try { 15445 pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null); 15446 loaded.add(pkg.applicationInfo); 15447 } catch (PackageManagerException e) { 15448 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 15449 } 15450 } 15451 15452 // TODO: regrant any permissions that changed based since original install 15453 15454 mSettings.writeLPr(); 15455 } 15456 } 15457 15458 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 15459 sendResourcesChangedBroadcast(true, false, loaded, null); 15460 } 15461 15462 private void unloadPrivatePackages(VolumeInfo vol) { 15463 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 15464 synchronized (mInstallLock) { 15465 synchronized (mPackages) { 15466 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15467 for (PackageSetting ps : packages) { 15468 if (ps.pkg == null) continue; 15469 15470 final ApplicationInfo info = ps.pkg.applicationInfo; 15471 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15472 if (deletePackageLI(ps.name, null, false, null, null, 15473 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 15474 unloaded.add(info); 15475 } else { 15476 Slog.w(TAG, "Failed to unload " + ps.codePath); 15477 } 15478 } 15479 15480 mSettings.writeLPr(); 15481 } 15482 } 15483 15484 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 15485 sendResourcesChangedBroadcast(false, false, unloaded, null); 15486 } 15487 15488 /** 15489 * Examine all users present on given mounted volume, and destroy data 15490 * belonging to users that are no longer valid, or whose user ID has been 15491 * recycled. 15492 */ 15493 private void reconcileUsers(String volumeUuid) { 15494 final File[] files = Environment.getDataUserDirectory(volumeUuid).listFiles(); 15495 if (ArrayUtils.isEmpty(files)) { 15496 Slog.d(TAG, "No users found on " + volumeUuid); 15497 return; 15498 } 15499 15500 for (File file : files) { 15501 if (!file.isDirectory()) continue; 15502 15503 final int userId; 15504 final UserInfo info; 15505 try { 15506 userId = Integer.parseInt(file.getName()); 15507 info = sUserManager.getUserInfo(userId); 15508 } catch (NumberFormatException e) { 15509 Slog.w(TAG, "Invalid user directory " + file); 15510 continue; 15511 } 15512 15513 boolean destroyUser = false; 15514 if (info == null) { 15515 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15516 + " because no matching user was found"); 15517 destroyUser = true; 15518 } else { 15519 try { 15520 UserManagerService.enforceSerialNumber(file, info.serialNumber); 15521 } catch (IOException e) { 15522 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15523 + " because we failed to enforce serial number: " + e); 15524 destroyUser = true; 15525 } 15526 } 15527 15528 if (destroyUser) { 15529 synchronized (mInstallLock) { 15530 mInstaller.removeUserDataDirs(volumeUuid, userId); 15531 } 15532 } 15533 } 15534 15535 final UserManager um = mContext.getSystemService(UserManager.class); 15536 for (UserInfo user : um.getUsers()) { 15537 final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id); 15538 if (userDir.exists()) continue; 15539 15540 try { 15541 UserManagerService.prepareUserDirectory(mContext, volumeUuid, user.id); 15542 UserManagerService.enforceSerialNumber(userDir, user.serialNumber); 15543 } catch (IOException e) { 15544 Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e); 15545 } 15546 } 15547 } 15548 15549 /** 15550 * Examine all apps present on given mounted volume, and destroy apps that 15551 * aren't expected, either due to uninstallation or reinstallation on 15552 * another volume. 15553 */ 15554 private void reconcileApps(String volumeUuid) { 15555 final File[] files = Environment.getDataAppDirectory(volumeUuid).listFiles(); 15556 if (ArrayUtils.isEmpty(files)) { 15557 Slog.d(TAG, "No apps found on " + volumeUuid); 15558 return; 15559 } 15560 15561 for (File file : files) { 15562 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 15563 && !PackageInstallerService.isStageName(file.getName()); 15564 if (!isPackage) { 15565 // Ignore entries which are not packages 15566 continue; 15567 } 15568 15569 boolean destroyApp = false; 15570 String packageName = null; 15571 try { 15572 final PackageLite pkg = PackageParser.parsePackageLite(file, 15573 PackageParser.PARSE_MUST_BE_APK); 15574 packageName = pkg.packageName; 15575 15576 synchronized (mPackages) { 15577 final PackageSetting ps = mSettings.mPackages.get(packageName); 15578 if (ps == null) { 15579 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + " 15580 + volumeUuid + " because we found no install record"); 15581 destroyApp = true; 15582 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 15583 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on " 15584 + volumeUuid + " because we expected it on " + ps.volumeUuid); 15585 destroyApp = true; 15586 } 15587 } 15588 15589 } catch (PackageParserException e) { 15590 logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e); 15591 destroyApp = true; 15592 } 15593 15594 if (destroyApp) { 15595 synchronized (mInstallLock) { 15596 if (packageName != null) { 15597 removeDataDirsLI(volumeUuid, packageName); 15598 } 15599 if (file.isDirectory()) { 15600 mInstaller.rmPackageDir(file.getAbsolutePath()); 15601 } else { 15602 file.delete(); 15603 } 15604 } 15605 } 15606 } 15607 } 15608 15609 private void unfreezePackage(String packageName) { 15610 synchronized (mPackages) { 15611 final PackageSetting ps = mSettings.mPackages.get(packageName); 15612 if (ps != null) { 15613 ps.frozen = false; 15614 } 15615 } 15616 } 15617 15618 @Override 15619 public int movePackage(final String packageName, final String volumeUuid) { 15620 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15621 15622 final int moveId = mNextMoveId.getAndIncrement(); 15623 try { 15624 movePackageInternal(packageName, volumeUuid, moveId); 15625 } catch (PackageManagerException e) { 15626 Slog.w(TAG, "Failed to move " + packageName, e); 15627 mMoveCallbacks.notifyStatusChanged(moveId, 15628 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15629 } 15630 return moveId; 15631 } 15632 15633 private void movePackageInternal(final String packageName, final String volumeUuid, 15634 final int moveId) throws PackageManagerException { 15635 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 15636 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15637 final PackageManager pm = mContext.getPackageManager(); 15638 15639 final boolean currentAsec; 15640 final String currentVolumeUuid; 15641 final File codeFile; 15642 final String installerPackageName; 15643 final String packageAbiOverride; 15644 final int appId; 15645 final String seinfo; 15646 final String label; 15647 15648 // reader 15649 synchronized (mPackages) { 15650 final PackageParser.Package pkg = mPackages.get(packageName); 15651 final PackageSetting ps = mSettings.mPackages.get(packageName); 15652 if (pkg == null || ps == null) { 15653 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 15654 } 15655 15656 if (pkg.applicationInfo.isSystemApp()) { 15657 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 15658 "Cannot move system application"); 15659 } 15660 15661 if (Objects.equals(ps.volumeUuid, volumeUuid)) { 15662 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15663 "Package already moved to " + volumeUuid); 15664 } 15665 15666 final File probe = new File(pkg.codePath); 15667 final File probeOat = new File(probe, "oat"); 15668 if (!probe.isDirectory() || !probeOat.isDirectory()) { 15669 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15670 "Move only supported for modern cluster style installs"); 15671 } 15672 15673 if (ps.frozen) { 15674 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 15675 "Failed to move already frozen package"); 15676 } 15677 ps.frozen = true; 15678 15679 currentAsec = pkg.applicationInfo.isForwardLocked() 15680 || pkg.applicationInfo.isExternalAsec(); 15681 currentVolumeUuid = ps.volumeUuid; 15682 codeFile = new File(pkg.codePath); 15683 installerPackageName = ps.installerPackageName; 15684 packageAbiOverride = ps.cpuAbiOverrideString; 15685 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 15686 seinfo = pkg.applicationInfo.seinfo; 15687 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 15688 } 15689 15690 // Now that we're guarded by frozen state, kill app during move 15691 killApplication(packageName, appId, "move pkg"); 15692 15693 final Bundle extras = new Bundle(); 15694 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 15695 extras.putString(Intent.EXTRA_TITLE, label); 15696 mMoveCallbacks.notifyCreated(moveId, extras); 15697 15698 int installFlags; 15699 final boolean moveCompleteApp; 15700 final File measurePath; 15701 15702 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 15703 installFlags = INSTALL_INTERNAL; 15704 moveCompleteApp = !currentAsec; 15705 measurePath = Environment.getDataAppDirectory(volumeUuid); 15706 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 15707 installFlags = INSTALL_EXTERNAL; 15708 moveCompleteApp = false; 15709 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 15710 } else { 15711 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 15712 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 15713 || !volume.isMountedWritable()) { 15714 unfreezePackage(packageName); 15715 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15716 "Move location not mounted private volume"); 15717 } 15718 15719 Preconditions.checkState(!currentAsec); 15720 15721 installFlags = INSTALL_INTERNAL; 15722 moveCompleteApp = true; 15723 measurePath = Environment.getDataAppDirectory(volumeUuid); 15724 } 15725 15726 final PackageStats stats = new PackageStats(null, -1); 15727 synchronized (mInstaller) { 15728 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 15729 unfreezePackage(packageName); 15730 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15731 "Failed to measure package size"); 15732 } 15733 } 15734 15735 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 15736 + stats.dataSize); 15737 15738 final long startFreeBytes = measurePath.getFreeSpace(); 15739 final long sizeBytes; 15740 if (moveCompleteApp) { 15741 sizeBytes = stats.codeSize + stats.dataSize; 15742 } else { 15743 sizeBytes = stats.codeSize; 15744 } 15745 15746 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 15747 unfreezePackage(packageName); 15748 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15749 "Not enough free space to move"); 15750 } 15751 15752 mMoveCallbacks.notifyStatusChanged(moveId, 10); 15753 15754 final CountDownLatch installedLatch = new CountDownLatch(1); 15755 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 15756 @Override 15757 public void onUserActionRequired(Intent intent) throws RemoteException { 15758 throw new IllegalStateException(); 15759 } 15760 15761 @Override 15762 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 15763 Bundle extras) throws RemoteException { 15764 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 15765 + PackageManager.installStatusToString(returnCode, msg)); 15766 15767 installedLatch.countDown(); 15768 15769 // Regardless of success or failure of the move operation, 15770 // always unfreeze the package 15771 unfreezePackage(packageName); 15772 15773 final int status = PackageManager.installStatusToPublicStatus(returnCode); 15774 switch (status) { 15775 case PackageInstaller.STATUS_SUCCESS: 15776 mMoveCallbacks.notifyStatusChanged(moveId, 15777 PackageManager.MOVE_SUCCEEDED); 15778 break; 15779 case PackageInstaller.STATUS_FAILURE_STORAGE: 15780 mMoveCallbacks.notifyStatusChanged(moveId, 15781 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 15782 break; 15783 default: 15784 mMoveCallbacks.notifyStatusChanged(moveId, 15785 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15786 break; 15787 } 15788 } 15789 }; 15790 15791 final MoveInfo move; 15792 if (moveCompleteApp) { 15793 // Kick off a thread to report progress estimates 15794 new Thread() { 15795 @Override 15796 public void run() { 15797 while (true) { 15798 try { 15799 if (installedLatch.await(1, TimeUnit.SECONDS)) { 15800 break; 15801 } 15802 } catch (InterruptedException ignored) { 15803 } 15804 15805 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 15806 final int progress = 10 + (int) MathUtils.constrain( 15807 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 15808 mMoveCallbacks.notifyStatusChanged(moveId, progress); 15809 } 15810 } 15811 }.start(); 15812 15813 final String dataAppName = codeFile.getName(); 15814 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 15815 dataAppName, appId, seinfo); 15816 } else { 15817 move = null; 15818 } 15819 15820 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 15821 15822 final Message msg = mHandler.obtainMessage(INIT_COPY); 15823 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 15824 msg.obj = new InstallParams(origin, move, installObserver, installFlags, 15825 installerPackageName, volumeUuid, null, user, packageAbiOverride); 15826 mHandler.sendMessage(msg); 15827 } 15828 15829 @Override 15830 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 15831 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15832 15833 final int realMoveId = mNextMoveId.getAndIncrement(); 15834 final Bundle extras = new Bundle(); 15835 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 15836 mMoveCallbacks.notifyCreated(realMoveId, extras); 15837 15838 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 15839 @Override 15840 public void onCreated(int moveId, Bundle extras) { 15841 // Ignored 15842 } 15843 15844 @Override 15845 public void onStatusChanged(int moveId, int status, long estMillis) { 15846 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 15847 } 15848 }; 15849 15850 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15851 storage.setPrimaryStorageUuid(volumeUuid, callback); 15852 return realMoveId; 15853 } 15854 15855 @Override 15856 public int getMoveStatus(int moveId) { 15857 mContext.enforceCallingOrSelfPermission( 15858 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15859 return mMoveCallbacks.mLastStatus.get(moveId); 15860 } 15861 15862 @Override 15863 public void registerMoveCallback(IPackageMoveObserver callback) { 15864 mContext.enforceCallingOrSelfPermission( 15865 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15866 mMoveCallbacks.register(callback); 15867 } 15868 15869 @Override 15870 public void unregisterMoveCallback(IPackageMoveObserver callback) { 15871 mContext.enforceCallingOrSelfPermission( 15872 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15873 mMoveCallbacks.unregister(callback); 15874 } 15875 15876 @Override 15877 public boolean setInstallLocation(int loc) { 15878 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 15879 null); 15880 if (getInstallLocation() == loc) { 15881 return true; 15882 } 15883 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 15884 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 15885 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 15886 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 15887 return true; 15888 } 15889 return false; 15890 } 15891 15892 @Override 15893 public int getInstallLocation() { 15894 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 15895 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 15896 PackageHelper.APP_INSTALL_AUTO); 15897 } 15898 15899 /** Called by UserManagerService */ 15900 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 15901 mDirtyUsers.remove(userHandle); 15902 mSettings.removeUserLPw(userHandle); 15903 mPendingBroadcasts.remove(userHandle); 15904 if (mInstaller != null) { 15905 // Technically, we shouldn't be doing this with the package lock 15906 // held. However, this is very rare, and there is already so much 15907 // other disk I/O going on, that we'll let it slide for now. 15908 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15909 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 15910 final String volumeUuid = vol.getFsUuid(); 15911 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 15912 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 15913 } 15914 } 15915 mUserNeedsBadging.delete(userHandle); 15916 removeUnusedPackagesLILPw(userManager, userHandle); 15917 } 15918 15919 /** 15920 * We're removing userHandle and would like to remove any downloaded packages 15921 * that are no longer in use by any other user. 15922 * @param userHandle the user being removed 15923 */ 15924 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 15925 final boolean DEBUG_CLEAN_APKS = false; 15926 int [] users = userManager.getUserIdsLPr(); 15927 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 15928 while (psit.hasNext()) { 15929 PackageSetting ps = psit.next(); 15930 if (ps.pkg == null) { 15931 continue; 15932 } 15933 final String packageName = ps.pkg.packageName; 15934 // Skip over if system app 15935 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 15936 continue; 15937 } 15938 if (DEBUG_CLEAN_APKS) { 15939 Slog.i(TAG, "Checking package " + packageName); 15940 } 15941 boolean keep = false; 15942 for (int i = 0; i < users.length; i++) { 15943 if (users[i] != userHandle && ps.getInstalled(users[i])) { 15944 keep = true; 15945 if (DEBUG_CLEAN_APKS) { 15946 Slog.i(TAG, " Keeping package " + packageName + " for user " 15947 + users[i]); 15948 } 15949 break; 15950 } 15951 } 15952 if (!keep) { 15953 if (DEBUG_CLEAN_APKS) { 15954 Slog.i(TAG, " Removing package " + packageName); 15955 } 15956 mHandler.post(new Runnable() { 15957 public void run() { 15958 deletePackageX(packageName, userHandle, 0); 15959 } //end run 15960 }); 15961 } 15962 } 15963 } 15964 15965 /** Called by UserManagerService */ 15966 void createNewUserLILPw(int userHandle) { 15967 if (mInstaller != null) { 15968 mInstaller.createUserConfig(userHandle); 15969 mSettings.createNewUserLILPw(this, mInstaller, userHandle); 15970 applyFactoryDefaultBrowserLPw(userHandle); 15971 primeDomainVerificationsLPw(userHandle); 15972 } 15973 } 15974 15975 void newUserCreated(final int userHandle) { 15976 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 15977 } 15978 15979 @Override 15980 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 15981 mContext.enforceCallingOrSelfPermission( 15982 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 15983 "Only package verification agents can read the verifier device identity"); 15984 15985 synchronized (mPackages) { 15986 return mSettings.getVerifierDeviceIdentityLPw(); 15987 } 15988 } 15989 15990 @Override 15991 public void setPermissionEnforced(String permission, boolean enforced) { 15992 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 15993 if (READ_EXTERNAL_STORAGE.equals(permission)) { 15994 synchronized (mPackages) { 15995 if (mSettings.mReadExternalStorageEnforced == null 15996 || mSettings.mReadExternalStorageEnforced != enforced) { 15997 mSettings.mReadExternalStorageEnforced = enforced; 15998 mSettings.writeLPr(); 15999 } 16000 } 16001 // kill any non-foreground processes so we restart them and 16002 // grant/revoke the GID. 16003 final IActivityManager am = ActivityManagerNative.getDefault(); 16004 if (am != null) { 16005 final long token = Binder.clearCallingIdentity(); 16006 try { 16007 am.killProcessesBelowForeground("setPermissionEnforcement"); 16008 } catch (RemoteException e) { 16009 } finally { 16010 Binder.restoreCallingIdentity(token); 16011 } 16012 } 16013 } else { 16014 throw new IllegalArgumentException("No selective enforcement for " + permission); 16015 } 16016 } 16017 16018 @Override 16019 @Deprecated 16020 public boolean isPermissionEnforced(String permission) { 16021 return true; 16022 } 16023 16024 @Override 16025 public boolean isStorageLow() { 16026 final long token = Binder.clearCallingIdentity(); 16027 try { 16028 final DeviceStorageMonitorInternal 16029 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 16030 if (dsm != null) { 16031 return dsm.isMemoryLow(); 16032 } else { 16033 return false; 16034 } 16035 } finally { 16036 Binder.restoreCallingIdentity(token); 16037 } 16038 } 16039 16040 @Override 16041 public IPackageInstaller getPackageInstaller() { 16042 return mInstallerService; 16043 } 16044 16045 private boolean userNeedsBadging(int userId) { 16046 int index = mUserNeedsBadging.indexOfKey(userId); 16047 if (index < 0) { 16048 final UserInfo userInfo; 16049 final long token = Binder.clearCallingIdentity(); 16050 try { 16051 userInfo = sUserManager.getUserInfo(userId); 16052 } finally { 16053 Binder.restoreCallingIdentity(token); 16054 } 16055 final boolean b; 16056 if (userInfo != null && userInfo.isManagedProfile()) { 16057 b = true; 16058 } else { 16059 b = false; 16060 } 16061 mUserNeedsBadging.put(userId, b); 16062 return b; 16063 } 16064 return mUserNeedsBadging.valueAt(index); 16065 } 16066 16067 @Override 16068 public KeySet getKeySetByAlias(String packageName, String alias) { 16069 if (packageName == null || alias == null) { 16070 return null; 16071 } 16072 synchronized(mPackages) { 16073 final PackageParser.Package pkg = mPackages.get(packageName); 16074 if (pkg == null) { 16075 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16076 throw new IllegalArgumentException("Unknown package: " + packageName); 16077 } 16078 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16079 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 16080 } 16081 } 16082 16083 @Override 16084 public KeySet getSigningKeySet(String packageName) { 16085 if (packageName == null) { 16086 return null; 16087 } 16088 synchronized(mPackages) { 16089 final PackageParser.Package pkg = mPackages.get(packageName); 16090 if (pkg == null) { 16091 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16092 throw new IllegalArgumentException("Unknown package: " + packageName); 16093 } 16094 if (pkg.applicationInfo.uid != Binder.getCallingUid() 16095 && Process.SYSTEM_UID != Binder.getCallingUid()) { 16096 throw new SecurityException("May not access signing KeySet of other apps."); 16097 } 16098 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16099 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 16100 } 16101 } 16102 16103 @Override 16104 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 16105 if (packageName == null || ks == null) { 16106 return false; 16107 } 16108 synchronized(mPackages) { 16109 final PackageParser.Package pkg = mPackages.get(packageName); 16110 if (pkg == null) { 16111 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16112 throw new IllegalArgumentException("Unknown package: " + packageName); 16113 } 16114 IBinder ksh = ks.getToken(); 16115 if (ksh instanceof KeySetHandle) { 16116 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16117 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 16118 } 16119 return false; 16120 } 16121 } 16122 16123 @Override 16124 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 16125 if (packageName == null || ks == null) { 16126 return false; 16127 } 16128 synchronized(mPackages) { 16129 final PackageParser.Package pkg = mPackages.get(packageName); 16130 if (pkg == null) { 16131 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16132 throw new IllegalArgumentException("Unknown package: " + packageName); 16133 } 16134 IBinder ksh = ks.getToken(); 16135 if (ksh instanceof KeySetHandle) { 16136 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16137 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 16138 } 16139 return false; 16140 } 16141 } 16142 16143 public void getUsageStatsIfNoPackageUsageInfo() { 16144 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 16145 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 16146 if (usm == null) { 16147 throw new IllegalStateException("UsageStatsManager must be initialized"); 16148 } 16149 long now = System.currentTimeMillis(); 16150 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 16151 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 16152 String packageName = entry.getKey(); 16153 PackageParser.Package pkg = mPackages.get(packageName); 16154 if (pkg == null) { 16155 continue; 16156 } 16157 UsageStats usage = entry.getValue(); 16158 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 16159 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 16160 } 16161 } 16162 } 16163 16164 /** 16165 * Check and throw if the given before/after packages would be considered a 16166 * downgrade. 16167 */ 16168 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 16169 throws PackageManagerException { 16170 if (after.versionCode < before.mVersionCode) { 16171 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16172 "Update version code " + after.versionCode + " is older than current " 16173 + before.mVersionCode); 16174 } else if (after.versionCode == before.mVersionCode) { 16175 if (after.baseRevisionCode < before.baseRevisionCode) { 16176 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16177 "Update base revision code " + after.baseRevisionCode 16178 + " is older than current " + before.baseRevisionCode); 16179 } 16180 16181 if (!ArrayUtils.isEmpty(after.splitNames)) { 16182 for (int i = 0; i < after.splitNames.length; i++) { 16183 final String splitName = after.splitNames[i]; 16184 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 16185 if (j != -1) { 16186 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 16187 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16188 "Update split " + splitName + " revision code " 16189 + after.splitRevisionCodes[i] + " is older than current " 16190 + before.splitRevisionCodes[j]); 16191 } 16192 } 16193 } 16194 } 16195 } 16196 } 16197 16198 private static class MoveCallbacks extends Handler { 16199 private static final int MSG_CREATED = 1; 16200 private static final int MSG_STATUS_CHANGED = 2; 16201 16202 private final RemoteCallbackList<IPackageMoveObserver> 16203 mCallbacks = new RemoteCallbackList<>(); 16204 16205 private final SparseIntArray mLastStatus = new SparseIntArray(); 16206 16207 public MoveCallbacks(Looper looper) { 16208 super(looper); 16209 } 16210 16211 public void register(IPackageMoveObserver callback) { 16212 mCallbacks.register(callback); 16213 } 16214 16215 public void unregister(IPackageMoveObserver callback) { 16216 mCallbacks.unregister(callback); 16217 } 16218 16219 @Override 16220 public void handleMessage(Message msg) { 16221 final SomeArgs args = (SomeArgs) msg.obj; 16222 final int n = mCallbacks.beginBroadcast(); 16223 for (int i = 0; i < n; i++) { 16224 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 16225 try { 16226 invokeCallback(callback, msg.what, args); 16227 } catch (RemoteException ignored) { 16228 } 16229 } 16230 mCallbacks.finishBroadcast(); 16231 args.recycle(); 16232 } 16233 16234 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 16235 throws RemoteException { 16236 switch (what) { 16237 case MSG_CREATED: { 16238 callback.onCreated(args.argi1, (Bundle) args.arg2); 16239 break; 16240 } 16241 case MSG_STATUS_CHANGED: { 16242 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 16243 break; 16244 } 16245 } 16246 } 16247 16248 private void notifyCreated(int moveId, Bundle extras) { 16249 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 16250 16251 final SomeArgs args = SomeArgs.obtain(); 16252 args.argi1 = moveId; 16253 args.arg2 = extras; 16254 obtainMessage(MSG_CREATED, args).sendToTarget(); 16255 } 16256 16257 private void notifyStatusChanged(int moveId, int status) { 16258 notifyStatusChanged(moveId, status, -1); 16259 } 16260 16261 private void notifyStatusChanged(int moveId, int status, long estMillis) { 16262 Slog.v(TAG, "Move " + moveId + " status " + status); 16263 16264 final SomeArgs args = SomeArgs.obtain(); 16265 args.argi1 = moveId; 16266 args.argi2 = status; 16267 args.arg3 = estMillis; 16268 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 16269 16270 synchronized (mLastStatus) { 16271 mLastStatus.put(moveId, status); 16272 } 16273 } 16274 } 16275 16276 private final class OnPermissionChangeListeners extends Handler { 16277 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 16278 16279 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 16280 new RemoteCallbackList<>(); 16281 16282 public OnPermissionChangeListeners(Looper looper) { 16283 super(looper); 16284 } 16285 16286 @Override 16287 public void handleMessage(Message msg) { 16288 switch (msg.what) { 16289 case MSG_ON_PERMISSIONS_CHANGED: { 16290 final int uid = msg.arg1; 16291 handleOnPermissionsChanged(uid); 16292 } break; 16293 } 16294 } 16295 16296 public void addListenerLocked(IOnPermissionsChangeListener listener) { 16297 mPermissionListeners.register(listener); 16298 16299 } 16300 16301 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 16302 mPermissionListeners.unregister(listener); 16303 } 16304 16305 public void onPermissionsChanged(int uid) { 16306 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 16307 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 16308 } 16309 } 16310 16311 private void handleOnPermissionsChanged(int uid) { 16312 final int count = mPermissionListeners.beginBroadcast(); 16313 try { 16314 for (int i = 0; i < count; i++) { 16315 IOnPermissionsChangeListener callback = mPermissionListeners 16316 .getBroadcastItem(i); 16317 try { 16318 callback.onPermissionsChanged(uid); 16319 } catch (RemoteException e) { 16320 Log.e(TAG, "Permission listener is dead", e); 16321 } 16322 } 16323 } finally { 16324 mPermissionListeners.finishBroadcast(); 16325 } 16326 } 16327 } 16328 16329 private class PackageManagerInternalImpl extends PackageManagerInternal { 16330 @Override 16331 public void setLocationPackagesProvider(PackagesProvider provider) { 16332 synchronized (mPackages) { 16333 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 16334 } 16335 } 16336 16337 @Override 16338 public void setImePackagesProvider(PackagesProvider provider) { 16339 synchronized (mPackages) { 16340 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 16341 } 16342 } 16343 16344 @Override 16345 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 16346 synchronized (mPackages) { 16347 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 16348 } 16349 } 16350 16351 @Override 16352 public void setSmsAppPackagesProvider(PackagesProvider provider) { 16353 synchronized (mPackages) { 16354 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 16355 } 16356 } 16357 16358 @Override 16359 public void setDialerAppPackagesProvider(PackagesProvider provider) { 16360 synchronized (mPackages) { 16361 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 16362 } 16363 } 16364 16365 @Override 16366 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 16367 synchronized (mPackages) { 16368 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderrLPw(provider); 16369 } 16370 } 16371 16372 @Override 16373 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 16374 synchronized (mPackages) { 16375 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 16376 packageName, userId); 16377 } 16378 } 16379 16380 @Override 16381 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 16382 synchronized (mPackages) { 16383 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 16384 packageName, userId); 16385 } 16386 } 16387 } 16388 16389 @Override 16390 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 16391 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 16392 synchronized (mPackages) { 16393 final long identity = Binder.clearCallingIdentity(); 16394 try { 16395 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 16396 packageNames, userId); 16397 } finally { 16398 Binder.restoreCallingIdentity(identity); 16399 } 16400 } 16401 } 16402 16403 private static void enforceSystemOrPhoneCaller(String tag) { 16404 int callingUid = Binder.getCallingUid(); 16405 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 16406 throw new SecurityException( 16407 "Cannot call " + tag + " from UID " + callingUid); 16408 } 16409 } 16410} 16411